text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { TranslateService } from '@ngx-translate/core';
import { Observable, Subject } from 'rxjs/Rx';
import { SimpleChanges, OnDestroy } from '@angular/core/src/metadata/lifecycle_hooks';
import { DeploymentData, Deployment } from '../../Models/deployment-data';
import { Component, Input, OnChanges } from '@angular/core';
import { LogCategories, SiteTabIds, DeploymentCenterConstants } from '../../../../shared/models/constants';
import { BusyStateScopeManager } from '../../../../busy-state/busy-state-scope-manager';
import { BroadcastService } from '../../../../shared/services/broadcast.service';
import { DeploymentDashboard } from '../deploymentDashboard';
import { SiteService } from '../../../../shared/services/site.service';
import { LogService } from '../../../../shared/services/log.service';
import { BroadcastEvent } from '../../../../shared/models/broadcast-event';
import { PortalResources } from '../../../../shared/models/portal-resources';
import { PortalService } from '../../../../shared/services/portal.service';
import * as moment from 'moment-mini-ts';
import { dateTimeComparatorReverse } from '../../../../shared/Utilities/comparators';
import { TableItem, GetTableHash } from 'app/controls/tbl/tbl.component';
import { ArmObj } from 'app/shared/models/arm/arm-obj';
import { GithubService } from '../../deployment-center-setup/wizard-logic/github.service';
import { ArmSiteDescriptor } from '../../../../shared/resourceDescriptors';
import { GitHubCommit, FileContent } from '../../Models/github';
import { ProviderService } from '../../../../shared/services/provider.service';
import { SourceControl } from '../../../../shared/models/arm/provider';
enum DeployStatus {
Pending,
Building,
Deploying,
Failed,
Success,
}
enum DeployDisconnectStep {
DeleteWorkflowFile = 'DeleteWorkflowFile',
ClearSCMSettings = 'ClearSCMSettings',
}
interface DeploymentDisconnectStatus {
step: DeployDisconnectStep;
isSuccessful: boolean;
errorMessage?: string;
error?: any;
}
class GithubActionTableItem implements TableItem {
public type: 'row' | 'group';
public time: Date;
public date: string;
public status: string;
public checkinMessage: string;
public commit: string;
public author: string;
public deploymentObj: ArmObj<Deployment>;
public active?: boolean;
}
@Component({
selector: 'app-github-action-dashboard',
templateUrl: './github-action-dashboard.component.html',
styleUrls: ['./github-action-dashboard.component.scss'],
providers: [GithubService, ProviderService],
})
export class GithubActionDashboardComponent extends DeploymentDashboard implements OnChanges, OnDestroy {
@Input()
resourceId: string;
public deploymentObject: DeploymentData;
public repositoryText: string;
public branchText: string;
public githubActionLink: string;
public sidePanelOpened = false;
public hideCreds = false;
public showDisconnectModal = false;
public githubActionDisconnectDeleteWorkflowText = '';
public errorMessage = '';
public rightPaneItem: ArmObj<Deployment>;
private _viewInfoStream$ = new Subject<string>();
private _repositoryStatusStream$ = new Subject<boolean>();
private _ngUnsubscribe$ = new Subject();
private _busyManager: BusyStateScopeManager;
private _forceLoad = false;
private _oldTableHash = 0;
private _tableItems: GithubActionTableItem[];
private _deleteWorkflowDuringDisconnect = false;
private _actionWorkflowFileName = '';
private _repoName = '';
private _gitHubToken = '';
constructor(
private _portalService: PortalService,
private _logService: LogService,
private _siteService: SiteService,
private _broadcastService: BroadcastService,
private _githubService: GithubService,
private _providerService: ProviderService,
translateService: TranslateService
) {
super(translateService);
this._busyManager = new BusyStateScopeManager(_broadcastService, SiteTabIds.continuousDeployment);
this._setupRepositoryStatusStream();
this._setupViewInfoStream();
}
public ngOnChanges(changes: SimpleChanges): void {
if (changes['resourceId']) {
this._busyManager.setBusy();
this._viewInfoStream$.next(this.resourceId);
}
}
public ngOnDestroy(): void {
this._ngUnsubscribe$.next();
}
public showDeploymentCredentials() {
this._broadcastService.broadcastEvent(BroadcastEvent.ReloadDeploymentCenter, 'credentials-dashboard');
}
public browseToSite() {
this._browseToSite(this.deploymentObject);
}
public refresh() {
this._forceLoad = true;
this._resetValues();
this._viewInfoStream$.next(this.resourceId);
}
public disconnect() {
this._disconnectDeployment();
}
public githubActionOnClick() {
if (this.githubActionLink) {
const win = window.open(this.githubActionLink, '_blank');
win.focus();
}
}
public repositoryOnClick() {
const repoUrl = this.deploymentObject && this.deploymentObject.sourceControls.properties.repoUrl;
if (repoUrl) {
const win = window.open(repoUrl, '_blank');
win.focus();
}
}
public branchOnClick() {
const repoUrl = this.deploymentObject && this.deploymentObject.sourceControls.properties.repoUrl;
const branchUrl = `${repoUrl}/tree/${this.branchText}`;
if (branchUrl) {
const win = window.open(branchUrl, '_blank');
win.focus();
}
}
public showDisconnectPrompt() {
this.showDisconnectModal = true;
}
public cancelDisconnectPrompt() {
this._deleteWorkflowDuringDisconnect = false;
this._hideDisconnectPrompt();
}
public toggleDeleteWorkflowState() {
this._deleteWorkflowDuringDisconnect = !this._deleteWorkflowDuringDisconnect;
}
get tableItems() {
if (this._deploymentFetchTries > 10) {
this.tableMessages.emptyMessage = this._translateService.instant(PortalResources.noDeploymentDataAvailable);
}
return this._tableItems || [];
}
public _hideDisconnectPrompt() {
this.showDisconnectModal = false;
}
public details(item: GithubActionTableItem) {
this.hideCreds = false;
this.rightPaneItem = item.deploymentObj;
this.sidePanelOpened = true;
}
private _disconnectDeployment() {
let notificationId = null;
this._busyManager.setBusy();
this._portalService
.startNotification(
this._translateService.instant(PortalResources.disconnectingDeployment),
this._translateService.instant(PortalResources.disconnectingDeployment)
)
.take(1)
.do(notification => {
notificationId = notification.id;
})
// NOTE (michinoy): First try to delete the workflow file.
.switchMap(() => this._deleteWorkflowFileIfNeeded())
// NOTE (michinoy): Next try to clear the SCM settings.
.switchMap(result => this._clearSCMSettings(result))
.switchMap(r => {
if (!r.isSuccessful) {
return this._deleteWorkflowDuringDisconnect
? Observable.throw({
step: DeployDisconnectStep.ClearSCMSettings,
isSuccessful: false,
errorMessage: this._translateService.instant(PortalResources.disconnectingDeploymentFailWorkflowFileDeleteSucceeded),
error: r.error,
})
: Observable.throw({
step: DeployDisconnectStep.ClearSCMSettings,
isSuccessful: false,
errorMessage: this._translateService.instant(PortalResources.disconnectingDeploymentFail),
error: r.error,
});
} else {
return Observable.of(r);
}
})
.subscribe(
r => {
this._busyManager.clearBusy();
this._deleteWorkflowDuringDisconnect = false;
this._portalService.stopNotification(
notificationId,
true,
this._translateService.instant(PortalResources.disconnectingDeploymentSuccess)
);
this._broadcastService.broadcastEvent(BroadcastEvent.ReloadDeploymentCenter);
},
err => {
this._deleteWorkflowDuringDisconnect = false;
this._portalService.stopNotification(notificationId, false, err.errorMessage);
this._logService.error(LogCategories.cicd, '/github-action-dashboard-disconnect', { resourceId: this.resourceId, error: err });
}
);
}
private _clearSCMSettings(deploymentDisconnectStatus: DeploymentDisconnectStatus) {
if (deploymentDisconnectStatus.isSuccessful) {
this._logService.trace(LogCategories.cicd, '/github-action-dashboard-disconnect-scm', { resourceId: this.resourceId });
return this._siteService.deleteSiteSourceControlConfig(this.resourceId);
} else {
return Observable.throw(deploymentDisconnectStatus);
}
}
private _deleteWorkflowFileIfNeeded(): Observable<DeploymentDisconnectStatus> {
this._hideDisconnectPrompt();
const errorMessage = this._translateService
.instant(PortalResources.githubActionDisconnectWorkflowDeleteFailed)
.format(this._actionWorkflowFileName, this.branchText, this.repositoryText);
const successStatus: DeploymentDisconnectStatus = {
step: DeployDisconnectStep.DeleteWorkflowFile,
isSuccessful: true,
errorMessage: null,
};
const failedStatus: DeploymentDisconnectStatus = {
step: DeployDisconnectStep.DeleteWorkflowFile,
isSuccessful: false,
errorMessage: errorMessage,
};
if (!this._deleteWorkflowDuringDisconnect) {
// NOTE(michinoy): In this case, the user has opted not to delete the file, it should not block any dependent actions.
return Observable.of(successStatus);
} else {
this._logService.trace(LogCategories.cicd, '/github-action-dashboard-disconnect-workflow', { resourceId: this.resourceId });
const workflowFilePath = `.github/workflows/${this._actionWorkflowFileName}`;
return this._githubService
.fetchWorkflowConfiguration(this._gitHubToken, this.repositoryText, this._repoName, this.branchText, workflowFilePath)
.switchMap(result => this._deleteWorkflowFile(workflowFilePath, result))
.do(_ => successStatus)
.catch(err => {
// Something failed on the fetch action
failedStatus.error = err;
return Observable.of(failedStatus);
});
}
}
private _deleteWorkflowFile(workflowFilePath: string, fileContent: FileContent) {
if (fileContent) {
const deleteCommitInfo: GitHubCommit = {
repoName: this._repoName,
branchName: this.branchText,
filePath: workflowFilePath,
message: this._translateService.instant(PortalResources.githubActionWorkflowDeleteCommitMessage),
committer: {
name: 'Azure App Service',
email: 'donotreply@microsoft.com',
},
sha: fileContent.sha,
};
return this._githubService.deleteActionWorkflow(this._gitHubToken, deleteCommitInfo);
} else {
// NOTE (michinoy): fetchWorkflowConfiguration return null if the file is not found.
return Observable.throw({
errorMessage: `Workflow file '${workflowFilePath}' not found in branch '${this.branchText}' from repo '${this._repoName}'`,
});
}
}
private _setupViewInfoStream() {
this._viewInfoStream$
.takeUntil(this._ngUnsubscribe$)
.switchMap(resourceId => {
if (resourceId !== this.resourceId) {
this._logService.trace(LogCategories.cicd, '/github-action-dashboard', { resourceId });
}
return Observable.zip(
this._siteService.getSite(resourceId, this._forceLoad),
this._siteService.getSiteConfig(resourceId, this._forceLoad),
this._siteService.getPublishingCredentials(resourceId, this._forceLoad),
this._siteService.getSiteSourceControlConfig(resourceId, this._forceLoad),
this._siteService.getSiteDeployments(resourceId),
this._siteService.getPublishingUser(),
this._providerService.getUserSourceControl('github'),
(site, siteConfig, pubCreds, sourceControl, deployments, publishingUser, gitHubUserSourceControl) => ({
site: site.result,
siteConfig: siteConfig.result,
pubCreds: pubCreds.result,
sourceControl: sourceControl.result,
deployments: deployments.result,
publishingUser: publishingUser.result,
gitHubToken: gitHubUserSourceControl.result,
})
);
})
.subscribe(
r => {
this._busyManager.clearBusy();
this._forceLoad = false;
this._gitHubToken = (r.gitHubToken as ArmObj<SourceControl>).properties.token;
this.deploymentObject = {
site: r.site,
siteConfig: r.siteConfig,
sourceControls: r.sourceControl,
publishingCredentials: r.pubCreds,
deployments: r.deployments,
publishingUser: r.publishingUser,
};
if (this.deploymentObject.sourceControls && this.deploymentObject.sourceControls.properties) {
if (
this.repositoryText !== this.deploymentObject.sourceControls.properties.repoUrl ||
this.branchText !== this.deploymentObject.sourceControls.properties.branch
) {
this.errorMessage = '';
this.repositoryText = this.deploymentObject.sourceControls.properties.repoUrl;
this._repoName = this.repositoryText.toLocaleLowerCase().replace(`${DeploymentCenterConstants.githubUri}/`, '');
this.branchText = this.deploymentObject.sourceControls.properties.branch;
this.githubActionLink = `${this.repositoryText}/actions?query=event%3Apush+branch%3A${this.branchText}`;
this._repositoryStatusStream$.next(true);
}
const siteDescriptor = <ArmSiteDescriptor>ArmSiteDescriptor.getSiteDescriptor(this.deploymentObject.site.id);
this._actionWorkflowFileName = this._githubService.getWorkflowFileName(
this.branchText,
siteDescriptor.site,
siteDescriptor.slot
);
this.githubActionDisconnectDeleteWorkflowText = this._translateService
.instant(PortalResources.githubActionDisconnectDeleteWorkflow)
.format(this._actionWorkflowFileName, this.branchText, this.repositoryText);
}
if (this.deploymentObject.deployments) {
this._populateTable();
}
},
err => {
this._busyManager.clearBusy();
this._forceLoad = false;
this.deploymentObject = null;
this._logService.error(LogCategories.cicd, '/github-action-dashboard', { resourceId: this.resourceId, error: err });
}
);
// refresh automatically every 5 seconds
Observable.timer(5000, 5000)
.takeUntil(this._ngUnsubscribe$)
.subscribe(() => {
this._deploymentFetchTries++;
this._viewInfoStream$.next(this.resourceId);
});
}
private _setupRepositoryStatusStream() {
this._repositoryStatusStream$
.takeUntil(this._ngUnsubscribe$)
.switchMap(_ =>
Observable.zip(
this._githubService.fetchRepo(this._gitHubToken, this.repositoryText, this._repoName).catch(r => Observable.of(r)),
this._githubService
.fetchBranch(this._gitHubToken, this.repositoryText, this._repoName, this.branchText)
.catch(r => Observable.of(r))
)
)
.subscribe(responses => {
const [repoResponse, branchResponse] = responses;
if (repoResponse && repoResponse.status === 404) {
this.errorMessage = this._translateService
.instant(PortalResources.githubActionDashboardRepositoryMissingError)
.format(this.repositoryText);
} else if (branchResponse && branchResponse.status === 404) {
this.errorMessage = this._translateService
.instant(PortalResources.githubActionDashboardBranchMissingError)
.format(this.branchText, this.repositoryText);
} else {
this.errorMessage = '';
}
});
}
private _resetValues() {
this.repositoryText = null;
this.branchText = null;
}
private _populateTable() {
const deployments = this.deploymentObject.deployments.value;
const tableItems = deployments.map(value => {
const item = value.properties;
const date: moment.Moment = moment(item.received_time);
const t = moment(date);
const commitId = item.id.substr(0, 7);
const author = item.author;
const row: GithubActionTableItem = {
type: 'row',
time: date.toDate(),
date: t.format('M/D/YY'),
commit: commitId,
checkinMessage: item.message,
status: this._getStatusString(item.status, item.progress),
active: item.active,
author: author,
deploymentObj: value,
};
return row;
});
const newHash = GetTableHash(tableItems);
if (this._oldTableHash !== newHash) {
this._tableItems = tableItems.sort(dateTimeComparatorReverse);
this._oldTableHash = newHash;
}
}
private _getStatusString(status: DeployStatus, progressString: string): string {
switch (status) {
case DeployStatus.Building:
case DeployStatus.Deploying:
return progressString;
case DeployStatus.Pending:
return this._translateService.instant(PortalResources.pending);
case DeployStatus.Failed:
return this._translateService.instant(PortalResources.failed);
case DeployStatus.Success:
return this._translateService.instant(PortalResources.success);
default:
return '';
}
}
} | the_stack |
import { debugLogger } from './logger';
import { toHumanTime } from './dates';
import {
isRetryableError,
TSError,
parseError,
isFatalError
} from './errors';
const logger = debugLogger('utils:promises');
/** promisified setTimeout */
export function pDelay<T = undefined>(delay = 0, arg?: T): Promise<T> {
return new Promise<T>((resolve) => {
setTimeout(resolve, delay, arg);
});
}
let supportsSetImmediate = false;
try {
if (typeof globalThis.setImmediate === 'function') {
supportsSetImmediate = true;
}
} catch (err) {
supportsSetImmediate = false;
}
let supportsNextTick = false;
try {
if (typeof globalThis.process.nextTick === 'function') {
supportsNextTick = true;
}
} catch (err) {
supportsNextTick = false;
}
/** promisified process.nextTick,setImmediate or setTimeout depending on your environment */
export function pImmediate<T = undefined>(arg?: T): Promise<T> {
return new Promise<T>((resolve) => {
if (supportsNextTick) {
process.nextTick(resolve, arg);
} else if (supportsSetImmediate) {
if (arg != null) setImmediate(resolve, arg);
else setImmediate(resolve as () => void);
} else {
setTimeout(resolve, 0, arg);
}
});
}
export interface PRetryConfig {
/**
* The number of retries to attempt before failing.
* This does not include the initial attempt
*
* @default 3
*/
retries: number;
/**
* The initial time to delay before retrying the function
*
* @default 500
*/
delay: number;
/**
* The maximum time to delay when retrying in milliseconds
*
* @default 60000
*/
maxDelay: number;
/**
* The backoff multiplier
*
* @default 2
*/
backoff: number;
/**
* If set to true, this will set fail with fatalError to true
*/
endWithFatal: boolean;
/**
* Set a error message prefix
*/
reason?: string;
/**
* Log function for logging any errors that occurred
*/
logError: (...args: any[]) => void;
/**
* If this not specified or is empty, all errors will be treated as retryable.
* If any of the items in the array match the error message,
* it will be considered retryable
*/
matches?: (string | RegExp)[];
}
/**
* A promise retry fn.
*/
export async function pRetry<T = any>(
fn: PromiseFn<T>,
options?: Partial<PRetryConfig>
): Promise<T> {
const config = Object.assign(
{
retries: 3,
delay: 500,
maxDelay: 60000,
backoff: 2,
matches: [],
_currentDelay: 0,
// @ts-expect-error
_context: undefined as PRetryContext,
},
options
);
if (!config._currentDelay) {
config._currentDelay = config.delay;
}
config._context = config._context || {
startTime: Date.now(),
attempts: 0,
};
config._context.attempts++;
try {
return await fn();
} catch (_err) {
let matches = true;
if (config.matches?.length) {
const rawErr = parseError(_err);
matches = config.matches.some((match) => {
const reg = new RegExp(match);
return reg.test(rawErr);
});
}
const context = {
...config._context,
duration: Date.now() - config._context.startTime,
};
const err = new TSError(_err, {
reason: config.reason,
context,
});
if (_err && _err.stack) {
err.stack += `\n${_err.stack
.split('\n')
.slice(1)
.join('\n')}`;
}
if (!isFatalError(err) && err.retryable == null) {
err.retryable = matches;
}
if (isRetryableError(err) && config.retries > 1) {
config.retries--;
config._currentDelay = getBackoffDelay(
config._currentDelay,
config.backoff,
config.maxDelay,
config.delay
);
await pDelay(config._currentDelay);
if (config.logError) {
config.logError(err, 'retry error, retrying...', {
...config,
_context: null,
});
}
return pRetry(fn, config);
}
err.retryable = false;
if (config.endWithFatal) {
err.fatalError = true;
}
throw err;
}
}
export type PWhileOptions = {
/** @defaults to -1 which is never */
timeoutMs?: number;
/** @defaults to "Request" */
name?: string;
/** enable jitter to stagger requests */
enabledJitter?: boolean;
/** the minimum the jitter wait time will be (in milliseconds),
* defaults to 100ms */
minJitter?: number
/** the maximum the jitter wait time will be (in milliseconds),
* defaults to 3x the minJitter setting, but less than timeoutMs
* */
maxJitter?: number
};
/**
* Run a function until it returns true or throws an error
*/
export async function pWhile(fn: PromiseFn, options: PWhileOptions = {}): Promise<void> {
const {
timeoutMs = -1,
name = 'Request',
enabledJitter = false,
minJitter = 100,
} = options;
const maxJitter = options.maxJitter ?? minJitter * 3;
if (timeoutMs <= 2 && options.enabledJitter) {
throw new Error('Jitter cannot be enabled whe timeout is <=2');
}
const startTime = Date.now();
const endTime = timeoutMs > 0 ? startTime + timeoutMs : Number.POSITIVE_INFINITY;
let running = false;
let interval: any;
const promise = new Promise<void>((resolve, reject) => {
interval = setInterval(async () => {
if (running) return;
running = true;
const remaining = endTime - Date.now();
if (remaining <= 0) {
reject(
new TSError(`${name} timeout after ${toHumanTime(timeoutMs)}`, {
statusCode: 503,
})
);
return;
}
try {
if (enabledJitter) {
const jitterDelay = getBackoffDelay(
minJitter, 3, maxJitter, minJitter
);
// ensure we don't exceed the remaing time
const delay = Math.min(jitterDelay, remaining - 2);
if (delay > 2) {
await pDelay(delay);
}
}
const result = await fn();
if (result) {
resolve();
return;
}
running = false;
} catch (err) {
reject(err);
}
}, 1);
});
try {
await promise;
} finally {
clearInterval(interval);
}
}
/**
* Get backoff delay that will safe to retry and is slightly staggered
*/
export function getBackoffDelay(
current: number,
factor = 2,
max = 60000,
min = 500
): number {
// jitter is a floating point number between -0.2 and 0.8
const jitter = Math.random() * 0.8 + -0.2;
let n = current;
// ensure the number does not go below the min val
if (n < min) n = min;
// multiple the current backoff value by input factor and jitter
n *= factor + jitter;
// ensure the number does not exceed the max val
if (n > max) n = max;
// round it so it remains a whole number
return Math.round(n);
}
type PRetryContext = {
attempts: number;
startTime: number;
};
interface PromiseFn<T = any> {
(...args: any[]): Promise<T>;
}
/** Async waterfall function */
export function waterfall(input: unknown, fns: PromiseFn[], addBreak = false): Promise<any> {
let i = 0;
return fns.reduce(async (last, fn) => {
if (i++ === 0 && addBreak) await pImmediate();
return fn(await last);
}, input) as any;
}
/**
* Run multiple promises at once, and resolve/reject when the first completes
*/
export function pRace(promises: Promise<any>[], logError?: (err: any) => void): Promise<any> {
if (!promises || !Array.isArray(promises)) {
throw new Error('Invalid promises argument, must be an array');
}
return new Promise((resolve, reject) => {
let done = false;
promises.forEach(async (promise) => {
try {
const result = await promise;
resolve(result);
done = true;
} catch (err) {
if (done) {
if (logError) logError(err);
else logger.error(err, 'pRace reject with an error after complete');
}
reject(err);
}
});
});
}
/**
* Similar to pRace but with
*/
export async function pRaceWithTimeout(
promises: Promise<any>[] | Promise<any>,
timeout: number,
logError?: (err: any) => void
): Promise<any> {
if (!timeout || typeof timeout !== 'number') {
throw new Error('Invalid timeout argument, must be a number');
}
let timeoutId: any;
try {
const pTimeout = new Promise((resolve) => {
// add unref to avoid keeping the process open
timeoutId = setTimeout(resolve, timeout);
timeoutId.unref();
});
const _promises = Array.isArray(promises) ? promises : [promises];
await pRace([..._promises, pTimeout], logError);
} catch (err) {
if (logError) logError(err);
else console.error(err);
} finally {
clearTimeout(timeoutId);
}
}
/**
* An alternative to Bluebird.defer: http://bluebirdjs.com/docs/api/deferred-migration.html
* Considered bad practice in most cases, use the Promise constructor
*/
export function pDefer(): {
resolve: (value?: unknown) => void,
reject: (reason?: any) => void,
promise: Promise<any>
} {
let resolve: (value?: unknown) => void;
let reject: (reason?: any) => void;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
return {
resolve: resolve!,
reject: reject!,
promise
};
} | the_stack |
import { CfnResource, IConstruct } from '@aws-cdk/core';
import { NagPack, NagMessageLevel, NagPackProps } from '../nag-pack';
import {
APIGWCacheEnabledAndEncrypted,
APIGWExecutionLoggingEnabled,
} from '../rules/apigw';
import { AutoScalingGroupELBHealthCheckRequired } from '../rules/autoscaling';
import {
CloudTrailCloudWatchLogsEnabled,
CloudTrailEncryptionEnabled,
CloudTrailLogFileValidationEnabled,
} from '../rules/cloudtrail';
import {
CloudWatchAlarmAction,
CloudWatchLogGroupEncrypted,
CloudWatchLogGroupRetentionPeriod,
} from '../rules/cloudwatch';
import {
CodeBuildProjectEnvVarAwsCred,
CodeBuildProjectSourceRepoUrl,
} from '../rules/codebuild';
import { DMSReplicationNotPublic } from '../rules/dms';
import {
DynamoDBAutoScalingEnabled,
DynamoDBInBackupPlan,
DynamoDBPITREnabled,
} from '../rules/dynamodb';
import {
EC2EBSInBackupPlan,
EC2InstanceDetailedMonitoringEnabled,
EC2InstancesInVPC,
EC2InstanceNoPublicIp,
EC2RestrictedCommonPorts,
EC2RestrictedSSH,
} from '../rules/ec2';
import { EFSEncrypted, EFSInBackupPlan } from '../rules/efs';
import { ElastiCacheRedisClusterAutomaticBackup } from '../rules/elasticache';
import {
ALBHttpDropInvalidHeaderEnabled,
ALBHttpToHttpsRedirection,
ALBWAFEnabled,
ELBACMCertificateRequired,
ELBCrossZoneLoadBalancingEnabled,
ELBDeletionProtectionEnabled,
ELBLoggingEnabled,
ELBTlsHttpsListenersOnly,
} from '../rules/elb';
import { EMRKerberosEnabled } from '../rules/emr';
import {
IAMGroupHasUsers,
IAMNoInlinePolicy,
IAMPolicyNoStatementsWithAdminAccess,
IAMUserGroupMembership,
IAMUserNoPolicies,
} from '../rules/iam';
import { KMSBackingKeyRotationEnabled } from '../rules/kms';
import { LambdaInsideVPC } from '../rules/lambda';
import {
OpenSearchEncryptedAtRest,
OpenSearchInVPCOnly,
OpenSearchNodeToNodeEncryption,
} from '../rules/opensearch';
import {
RDSEnhancedMonitoringEnabled,
RDSInBackupPlan,
RDSInstanceBackupEnabled,
RDSInstanceDeletionProtectionEnabled,
RDSInstancePublicAccess,
RDSLoggingEnabled,
RDSMultiAZSupport,
RDSStorageEncrypted,
} from '../rules/rds';
import {
RedshiftClusterConfiguration,
RedshiftClusterPublicAccess,
RedshiftRequireTlsSSL,
} from '../rules/redshift';
import {
S3BucketDefaultLockEnabled,
S3BucketLoggingEnabled,
S3BucketPublicReadProhibited,
S3BucketPublicWriteProhibited,
S3BucketReplicationEnabled,
S3BucketServerSideEncryptionEnabled,
S3BucketSSLRequestsOnly,
S3BucketVersioningEnabled,
} from '../rules/s3';
import {
SageMakerEndpointConfigurationKMSKeyConfigured,
SageMakerNotebookInstanceKMSKeyConfigured,
SageMakerNotebookNoDirectInternetAccess,
} from '../rules/sagemaker';
import { SNSEncryptedKMS } from '../rules/sns';
import {
VPCDefaultSecurityGroupClosed,
VPCFlowLogsEnabled,
} from '../rules/vpc';
import { WAFv2LoggingEnabled } from '../rules/waf';
/**
* Check for NIST 800-53 rev 4 compliance.
* Based on the NIST 800-53 rev 4 AWS operational best practices: https://docs.aws.amazon.com/config/latest/developerguide/operational-best-practices-for-nist-800-53_rev_4.html
*/
export class NIST80053R4Checks extends NagPack {
constructor(props?: NagPackProps) {
super(props);
this.packName = 'NIST.800.53.R4';
}
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.checkDynamoDB(node);
this.checkEC2(node);
this.checkEFS(node);
this.checkElastiCache(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.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 API Gateway stage does not have caching enabled and encrypted for all methods - (Control IDs: SC-13, SC-28).',
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: AU-2(a)(d), AU-3, AU-12(a)(c)).',
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,
});
}
/**
* Check Auto Scaling Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkAutoScaling(node: CfnResource) {
this.applyRule({
info: 'The Auto Scaling group utilizes a load balancer and does not have an ELB health check configured - (Control IDs: SC-5).',
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.',
level: NagMessageLevel.ERROR,
rule: AutoScalingGroupELBHealthCheckRequired,
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: AC-2(4), AC-2(g), AU-2(a)(d), AU-3, AU-6(1)(3), AU-7(1), AU-12(a)(c), CA-7(a)(b), SI-4(2), SI-4(4), SI-4(5), SI-4(a)(b)(c)).',
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 a KMS key ID or have encryption enabled - (Control ID: AU-9).',
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 ID: AC-6).',
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 alarm does not have at least one alarm action, one INSUFFICIENT_DATA action, or one OK action enabled - (Control IDs: AC-2(4), AU-6(1)(3), AU-7(1), CA-7(a)(b), IR-4(1), SI-4(2), SI-4(4), SI-4(5), SI-4(a)(b)(c)).',
explanation:
'Amazon CloudWatch alarms alert when a metric breaches the threshold for a specified number of evaluation periods. The alarm performs one or more actions based on the value of the metric or expression relative to a threshold over a number of time periods.',
level: NagMessageLevel.ERROR,
rule: CloudWatchAlarmAction,
node: node,
});
this.applyRule({
info: 'The CloudWatch Log Group is not encrypted with an AWS KMS key - (Control IDs: AU-9, SC-13, SC-28).',
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: AU-11, SI-12).',
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) {
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 IDs: AC-6, IA-5(7), SA-3(a)).',
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: SA-3(a)).',
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: AC-3).',
explanation:
'DMS replication instances can contain sensitive information and access control is required for such accounts.',
level: NagMessageLevel.ERROR,
rule: DMSReplicationNotPublic,
node: node,
});
}
/**
* Check DynamoDB Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkDynamoDB(node: CfnResource) {
this.applyRule({
info: "The provisioned capacity DynamoDB table does not have Auto Scaling enabled on it's indexes - (Control IDs: CP-10, SC-5).",
explanation:
'Amazon DynamoDB auto scaling uses the AWS Application Auto Scaling service to adjust provisioned throughput capacity that automatically responds to actual traffic patterns. This enables a table or a global secondary index to increase its provisioned read/write capacity to handle sudden increases in traffic, without throttling.',
level: NagMessageLevel.ERROR,
rule: DynamoDBAutoScalingEnabled,
node: node,
});
this.applyRule({
info: 'The DynamoDB table is not in an AWS Backup plan - (Control IDs: CP-9(b), CP-10, SI-12).',
explanation:
'To help with data back-up processes, ensure your Amazon DynamoDB tables are a part of an AWS Backup plan. AWS Backup is a fully managed backup service with a policy-based backup solution. This solution simplifies your backup management and enables you to meet your business and regulatory backup compliance requirements.',
level: NagMessageLevel.ERROR,
rule: DynamoDBInBackupPlan,
node: node,
});
this.applyRule({
info: 'The DynamoDB table does not have Point-in-time Recovery enabled - (Control IDs: CP-9(b), CP-10, SI-12).',
explanation:
'The recovery maintains continuous backups of your table for the last 35 days.',
level: NagMessageLevel.ERROR,
rule: DynamoDBPITREnabled,
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 EBS volume is not in an AWS Backup plan - (Control IDs: CP-9(b), CP-10, SI-12).',
explanation:
'To help with data back-up processes, ensure your Amazon Elastic Block Store (Amazon EBS) volumes are a part of an AWS Backup plan. AWS Backup is a fully managed backup service with a policy-based backup solution. This solution simplifies your backup management and enables you to meet your business and regulatory backup compliance requirements.',
level: NagMessageLevel.ERROR,
rule: EC2EBSInBackupPlan,
node: node,
});
this.applyRule({
info: 'The EC2 instance does not have detailed monitoring enabled - (Control IDs: CA-7(a)(b), SI-4(2), SI-4(a)(b)(c)).',
explanation:
'Detailed monitoring provides additional monitoring information (such as 1-minute period graphs) on the AWS console.',
level: NagMessageLevel.ERROR,
rule: EC2InstanceDetailedMonitoringEnabled,
node: node,
});
this.applyRule({
info: 'The EC2 instance is not within a VPC - (Control IDs: AC-4, SC-7, SC-7(3)).',
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: EC2InstancesInVPC,
node: node,
});
this.applyRule({
info: 'The EC2 instance is associated with a public IP address - (Control IDs: AC-4, AC-6, AC-21(b), SC-7, SC-7(3)). ',
explanation:
'Amazon EC2 instances can contain sensitive information and access control is required for such resources.',
level: NagMessageLevel.ERROR,
rule: EC2InstanceNoPublicIp,
node: node,
});
this.applyRule({
info: 'The EC2 instance allows unrestricted inbound IPv4 TCP traffic on common ports (20, 21, 3389, 3306, 4333) - (Control IDs: AC-4, CM-2, SC-7, SC-7(3)).',
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: AC-4, SC-7, SC-7(3)).',
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 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 is not in an AWS Backup plan - (Control IDs: CP-9(b), CP-10, SI-12).',
explanation:
'To help with data back-up processes, ensure your Amazon Elastic File System (Amazon EFS) file systems are a part of an AWS Backup plan. AWS Backup is a fully managed backup service with a policy-based backup solution. This solution simplifies your backup management and enables you to meet your business and regulatory backup compliance requirements.',
level: NagMessageLevel.ERROR,
rule: EFSInBackupPlan,
node: node,
});
this.applyRule({
info: 'The EFS does not have encryption at rest enabled - (Control IDs: SC-13, SC-28).',
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 ElastiCache Resources
* @param node the CfnResource to check
* @param ignores list of ignores for the resource
*/
private checkElastiCache(node: CfnResource) {
this.applyRule({
info: 'The ElastiCache Redis cluster does not retain automatic backups for at least 15 days - (Control IDs: CP-9(b), CP-10, SI-12).',
explanation:
'Automatic backups can help guard against data loss. If a failure occurs, you can create a new cluster, which restores your data from the most recent backup.',
level: NagMessageLevel.ERROR,
rule: ElastiCacheRedisClusterAutomaticBackup,
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 ID: AC-17(2)).',
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: AC-17(2), SC-7, SC-8, SC-8(1), SC-13, SC-23).",
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 IDs: SC-7, SI-4(a)(b)(c)).',
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: AC-17(2), SC-7, SC-8, SC-8(1), SC-13).',
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 CLB does not balance traffic between at least 2 Availability Zones - (Control IDs: SC-5, CP-10).',
explanation:
'The cross-zone load balancing reduces the need to maintain equivalent numbers of instances in each enabled availability zone.',
level: NagMessageLevel.ERROR,
rule: ELBCrossZoneLoadBalancingEnabled,
node: node,
});
this.applyRule({
info: 'The ALB, NLB, or GLB does not have deletion protection enabled - (Control IDs: CM-2, CP-10).',
explanation:
'Use this feature to prevent your load balancer from being accidentally or maliciously deleted, which can lead to loss of availability for your applications.',
level: NagMessageLevel.ERROR,
rule: ELBDeletionProtectionEnabled,
node: node,
});
this.applyRule({
info: 'The ELB does not have logging enabled - (Control ID: AU-2(a)(d)).',
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: AC-17(2), SC-7, SC-8, SC-8(1), SC-23).',
explanation:
'Because sensitive data can exist, enable encryption in transit to help protect that data.',
level: NagMessageLevel.ERROR,
rule: ELBTlsHttpsListenersOnly,
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 EMR cluster does not have Kerberos enabled - (Control IDs: AC-2(j), AC-3, AC-5c, AC-6).',
explanation:
'The access permissions and authorizations can be managed and incorporated with the principles of least privilege and separation of duties, by enabling Kerberos for Amazon EMR clusters.',
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 ID: AC-2(j)).',
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 ID: AC-6).',
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: AC-2(1), AC-2(j), AC-3, AC-6).',
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, restricting policies from containing "Effect": "Allow" with "Action": "*" over "Resource": "*". 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: IAMPolicyNoStatementsWithAdminAccess,
node: node,
});
this.applyRule({
info: 'The IAM user does not belong to any group(s) - (Control IDs: AC-2(1), AC-2(j), AC-3, AC-6).',
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: AC-2(j), AC-3, AC-5c, AC-6).',
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 ID: SC-12).',
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: AC-4, SC-7, SC-7(3)).',
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: SC-13, SC-28).',
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: AC-4, SC-7, SC-7(3)).',
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 have node-to-node encryption enabled - (Control IDs: SC-7, SC-8, SC-8(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 Amazon 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 RDS DB instance does not enhanced monitoring enabled - (Control ID: CA-7(a)(b)).',
explanation:
'Enable enhanced monitoring to help monitor Amazon RDS availability. This provides detailed visibility into the health of your Amazon RDS database instances.',
level: NagMessageLevel.ERROR,
rule: RDSEnhancedMonitoringEnabled,
node: node,
});
this.applyRule({
info: 'The RDS DB instance is not in an AWS Backup plan - (Control IDs: CP-9(b), CP-10, SI-12).',
explanation:
'To help with data back-up processes, ensure your Amazon Relational Database Service (Amazon RDS) instances are a part of an AWS Backup plan. AWS Backup is a fully managed backup service with a policy-based backup solution. This solution simplifies your backup management and enables you to meet your business and regulatory backup compliance requirements.',
level: NagMessageLevel.ERROR,
rule: RDSInBackupPlan,
node: node,
});
this.applyRule({
info: 'The RDS DB instance does not have backups enabled - (Control IDs: CP-9(b), CP-10, SI-12).',
explanation:
'The backup feature of Amazon RDS creates backups of your databases and transaction logs.',
level: NagMessageLevel.ERROR,
rule: RDSInstanceBackupEnabled,
node: node,
});
this.applyRule({
info: 'The RDS DB instance or Aurora DB cluster does not have deletion protection enabled - (Control ID: SC-5).',
explanation:
'Ensure Amazon Relational Database Service (Amazon RDS) instances and clusters have deletion protection enabled. Use deletion protection to prevent your Amazon RDS DB instances and clusters from being accidentally or maliciously deleted, which can lead to loss of availability for your applications.',
level: NagMessageLevel.ERROR,
rule: RDSInstanceDeletionProtectionEnabled,
node: node,
});
this.applyRule({
info: 'The RDS DB instance allows public access - (Control IDs: AC-4, AC-6, AC-21(b), SC-7, SC-7(3)).',
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: AC-2(4), AC-2(g), AU-2(a)(d), AU-3, AU-12(a)(c)).',
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 non-Aurora RDS DB instance does not have multi-AZ support enabled - (Control IDs: CP-10, SC-5, SC-36).',
explanation:
'Multi-AZ support in Amazon Relational Database Service (Amazon RDS) provides enhanced availability and durability for database instances. When you provision a Multi-AZ database instance, Amazon RDS automatically creates a primary database instance, and synchronously replicates the data to a standby instance in a different Availability Zone. In case of an infrastructure failure, Amazon RDS performs an automatic failover to the standby so that you can resume database operations as soon as the failover is complete.',
level: NagMessageLevel.ERROR,
rule: RDSMultiAZSupport,
node: node,
});
this.applyRule({
info: 'The RDS DB instance or Aurora DB cluster does not have storage encrypted - (Control IDs: SC-13, SC-28).',
explanation:
'Because sensitive data can exist at rest in Amazon RDS DB instances and clusters, 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: AC-2(4), AC-2(g), AU-2(a)(d), AU-3, AU-12(a)(c), SC-13).',
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 allows public access - (Control IDs: AC-3, AC-4, AC-6, AC-21(b), SC-7, SC-7(3)).',
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 require TLS/SSL encryption - (Control IDs: AC-17(2), SC-7, SC-8, SC-8(1), SC-13).',
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 have object lock enabled - (Control ID: SC-28).',
explanation:
'Because sensitive data can exist at rest in S3 buckets, enforce object locks at rest to help protect that data.',
level: NagMessageLevel.ERROR,
rule: S3BucketDefaultLockEnabled,
node: node,
});
this.applyRule({
info: 'The S3 Bucket does not have server access logs enabled - (Control IDs: AC-2(g), AU-2(a)(d), AU-3, AU-12(a)(c)).',
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: AC-3, AC-4, AC-6, AC-21(b), SC-7, SC-7(3)).',
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: AC-3, AC-4, AC-6, AC-21(b), SC-7, SC-7(3)).',
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: AU-9(2), CP-9(b), CP-10, SC-5, SC-36).',
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: AU-9(2), CP-9(b), CP-10, SC-5, SC-36).',
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: AC-17(2), SC-7, SC-8, SC-8(1), SC-13).',
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 IDs: CP-10, SI-12).',
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,
});
}
/**
* 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 endpoint is not encrypted with a KMS key - (Control IDs: SC-13, SC-28).',
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: SC-13, SC-28).',
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: AC-3, AC-4, AC-6, AC-21(b), SC-7, SC-7(3)).',
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 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 IDs: SC-13, SC-28).',
explanation:
'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: AC-4, SC-7, SC-7(3)).",
explanation:
'When creating a VPC through CloudFormation, the default security group will always be open. Therefore it is important to always close the default security group after stack creation whenever a VPC is created. 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: AU-2(a)(d), AU-3, AU-12(a)(c)).',
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,
});
}
/**
* 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: AU-2(a)(d), AU-3, AU-12(a)(c), SC-7, SI-4(a)(b)(c)).',
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 { isAbsolute, join } from 'path';
import * as vscode from 'vscode';
import { Telemetry, APPMAP_OPEN, APPMAP_UPLOAD } from './telemetry';
import { getNonce, getRecords, workspaceFolderForDocument } from './util';
import { version } from '../package.json';
import AppMapProperties from './appmapProperties';
import { AppmapUploader } from './appmapUploader';
/**
* Provider for AppLand scenario files.
*/
export class ScenarioProvider implements vscode.CustomTextEditorProvider {
public static register(context: vscode.ExtensionContext, properties: AppMapProperties): void {
const provider = new ScenarioProvider(context, properties);
const providerRegistration = vscode.window.registerCustomEditorProvider(
ScenarioProvider.viewType,
provider
);
context.subscriptions.push(providerRegistration);
context.subscriptions.push(
vscode.commands.registerCommand('appmap.getAppmapState', () => {
if (provider.currentWebView) {
provider.currentWebView.webview.postMessage({
type: 'requestAppmapState',
});
}
})
);
context.subscriptions.push(
vscode.commands.registerCommand('appmap.setAppmapState', async () => {
if (provider.currentWebView) {
const state = await vscode.window.showInputBox({
placeHolder: 'AppMap state serialized string',
});
if (state) {
provider.currentWebView.webview.postMessage({
type: 'setAppmapState',
state: state,
});
}
}
})
);
context.subscriptions.push(
vscode.commands.registerCommand('appmap.setAppmapStateNoPrompt', async (state) => {
if (provider.currentWebView) {
provider.currentWebView.webview.postMessage({
type: 'setAppmapState',
state: state,
});
}
})
);
}
private static readonly viewType = 'appmap.views.appMapFile';
private static readonly INSTRUCTIONS_VIEWED = 'APPMAP_INSTRUCTIONS_VIEWED';
private static readonly RELEASE_KEY = 'APPMAP_RELEASE_KEY';
public static readonly APPMAP_OPENED = 'APPMAP_OPENED';
public static readonly INITIAL_STATE = 'INITIAL_STATE';
public currentWebView;
constructor(
private readonly context: vscode.ExtensionContext,
private readonly properties: AppMapProperties
) {}
/**
* Called when our custom editor is opened.
*/
public async resolveCustomTextEditor(
document: vscode.TextDocument,
webviewPanel: vscode.WebviewPanel
/* _token: vscode.CancellationToken */
): Promise<void> {
this.currentWebView = webviewPanel;
webviewPanel.onDidChangeViewState((e) => {
if (e.webviewPanel.active) {
this.currentWebView = e.webviewPanel;
}
});
const updateWebview = () => {
webviewPanel.webview.postMessage({
type: 'update',
text: document.getText(),
});
const workspaceFolder = workspaceFolderForDocument(document);
if (workspaceFolder) {
this.properties.setWorkspaceOpenedAppMap(workspaceFolder, true);
}
const lastVersion = this.context.globalState.get(ScenarioProvider.RELEASE_KEY);
if (!lastVersion) {
this.context.globalState.update(ScenarioProvider.RELEASE_KEY, version);
} else if (lastVersion !== version) {
webviewPanel.webview.postMessage({
type: 'displayUpdateNotification',
version,
});
}
// get initial state and apply to opened webview
const initialState = this.context.globalState.get(ScenarioProvider.INITIAL_STATE);
if (initialState) {
vscode.commands.executeCommand('appmap.setAppmapStateNoPrompt', initialState);
}
this.context.globalState.update(ScenarioProvider.INITIAL_STATE, null);
};
// Handle messages from the webview.
// Note: this has to be set before setting the HTML to avoid a race.
webviewPanel.webview.onDidReceiveMessage(async (message) => {
switch (message.command) {
case 'viewSource':
viewSource(message.text);
break;
case 'ready':
updateWebview();
break;
case 'appmapStateResult':
vscode.env.clipboard.writeText(message.state);
vscode.window.setStatusBarMessage('AppMap state was copied to clipboard', 5000);
break;
case 'onLoadComplete':
Telemetry.sendEvent(APPMAP_OPEN, {
rootDirectory: workspaceFolderForDocument(document)?.uri.fsPath,
uri: document.uri,
metadata: JSON.parse(document.getText()).metadata,
metrics: message.metrics,
});
break;
case 'performAction':
Telemetry.reportAction(
message.action,
getRecords(message.data, `appmap.${message.action}`)
);
break;
case 'reportError':
Telemetry.reportWebviewError(message.error);
break;
case 'closeUpdateNotification':
this.context.globalState.update(ScenarioProvider.RELEASE_KEY, version);
break;
case 'appmapOpenUrl':
vscode.env.openExternal(message.url);
Telemetry.reportOpenUri(message.url);
break;
case 'uploadAppmap':
{
const uploadResult = await AppmapUploader.upload(document, this.context);
if (uploadResult) {
Telemetry.sendEvent(APPMAP_UPLOAD, {
rootDirectory: workspaceFolderForDocument(document)?.uri.fsPath,
uri: document.uri,
metadata: JSON.parse(document.getText()).metadata,
metrics: message.metrics,
});
}
}
break;
}
});
// Setup initial content for the webview
webviewPanel.webview.options = {
enableScripts: true,
};
webviewPanel.webview.html = this.getHtmlForWebview(webviewPanel.webview);
// Hook up event handlers so that we can synchronize the webview with the text document.
//
// The text document acts as our model, so we have to sync change in the document to our
// editor and sync changes in the editor back to the document.
//
// Remember that a single text document can also be shared between multiple custom
// editors (this happens for example when you split a custom editor)
const changeDocumentSubscription = vscode.workspace.onDidChangeTextDocument((e) => {
if (e.document.uri.toString() === document.uri.toString()) {
updateWebview();
}
});
// Make sure we get rid of the listener when our editor is closed.
webviewPanel.onDidDispose(() => {
changeDocumentSubscription.dispose();
this.currentWebView = null;
});
function openFile(uri: vscode.Uri, lineNumber: number) {
const showOptions = {
viewColumn: vscode.ViewColumn.Beside,
selection: new vscode.Range(
new vscode.Position(lineNumber - 1, 0),
new vscode.Position(lineNumber - 1, 0)
),
};
vscode.commands.executeCommand('vscode.open', uri, showOptions);
}
function viewSource(location: string) {
const tokens = location.split(':', 2);
const path = tokens[0];
const lineNumberStr = tokens[1];
let lineNumber = 1;
if (lineNumberStr) {
lineNumber = Number.parseInt(lineNumberStr, 10);
}
let searchPath;
if (vscode.workspace.workspaceFolders) {
for (let i = 0; !searchPath && i < vscode.workspace.workspaceFolders?.length; ++i) {
const folder = vscode.workspace.workspaceFolders[i];
// findFiles is not tolerant of absolute paths, even if the absolute path matches the
// path of the file in the workspace.
if (folder.uri.scheme === 'file' && path.startsWith(folder.uri.path)) {
searchPath = path.slice(folder.uri.path.length + 1);
}
}
}
searchPath = searchPath || path;
if (!isAbsolute(path)) {
searchPath = join('**', path);
}
vscode.workspace.findFiles(searchPath).then((uris) => {
if (uris.length === 0) {
return;
} else if (uris.length === 1) {
openFile(uris[0], lineNumber);
} else {
const options: vscode.QuickPickOptions = {
canPickMany: false,
placeHolder: 'Choose file to open',
};
vscode.window
.showQuickPick(
uris.map((uri) => uri.toString()),
options
)
.then((fileName) => {
if (!fileName) {
return false;
}
openFile(vscode.Uri.parse(fileName), lineNumber);
});
}
});
}
}
/**
* Get the static html used for the editor webviews.
*/
private getHtmlForWebview(webview: vscode.Webview): string {
// Local path to script and css for the webview
const scriptUri = webview.asWebviewUri(
vscode.Uri.file(join(this.context.extensionPath, 'out', 'app.js'))
);
// Use a nonce to whitelist which scripts can be run
const nonce = getNonce();
return /* html */ `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AppLand Scenario</title>
</head>
<body>
<div id="app">
</div>
<script nonce="${nonce}" src="${scriptUri}"></script>
<script type="text/javascript" nonce="${nonce}">
AppLandWeb.mountApp();
</script>
</body>
</html>`;
}
private getDocumentAsJson(document: vscode.TextDocument): Record<string, unknown> {
const text = document.getText();
if (text.trim().length === 0) {
return {};
}
try {
return JSON.parse(text);
} catch {
throw new Error('Could not get document as json. Content is not valid json');
}
}
//forget usage state set by this class
public static resetState(context: vscode.ExtensionContext): void {
context.globalState.update(ScenarioProvider.INSTRUCTIONS_VIEWED, null);
context.globalState.update(ScenarioProvider.RELEASE_KEY, null);
context.globalState.update(ScenarioProvider.APPMAP_OPENED, null);
context.globalState.update(ScenarioProvider.INITIAL_STATE, null);
}
} | the_stack |
import supertest from "supertest";
import { should } from "chai";
import { expect } from "chai";
import * as express from "../src/functions/express";
import * as test_helper from "./test_helper";
import * as test_db_helper from "./test_db_helper";
should();
const adminDB = test_db_helper.adminDB();
express.updateDb(adminDB);
const app = express.app;
const request = supertest(app);
test_db_helper.initHook();
const good_cafe_data = {
restProfilePhoto: "https://example.com/images",
images: {
profile: {
resizedImages: {
"600": "https://example.com/images600",
},
},
},
restaurantName: "Good cafe",
introduction: "こんにちは",
streetAddress: "NY",
city: "NY",
state: "NY",
zip: "123",
phoneNumber: "+01-0000-0000",
url: "https://example.com",
uid: "123123",
defaultTaxRate: 10,
publicFlag: true,
deletedFlag: false,
inclusiveTax: true,
};
const ownerData = {
images: {
cover: {
resizedImages: {
"600": "https://example.com/images600",
},
},
},
name: "Good cafe owner",
introduction: "こんにちは",
description: "hello",
};
describe("express function", () => {
before(async () => {
await adminDB.doc(`restaurants/testbar`).set(good_cafe_data);
await adminDB.doc(`restaurants/testbar/menus/hoge`).set({
images: { item: { resizedImages: { "600": "123.jpg" } } },
itemDescription: "hello from menu",
price: 1000,
itemName: "good menu",
});
await adminDB.doc(`restaurants/testbar/menus/VbXMnx4wdTgh1VBpBRIr`).set({
images: { item: { resizedImages: { "600": "123.jpg" } } },
itemDescription: "hello from menu",
price: 1000,
itemName: "good menu",
});
await adminDB.doc(`restaurants/testbar/menus/DJHHNW17WqhT7O51lhxB`).set({
images: { item: { resizedImages: { "600": "123.jpg" } } },
itemDescription: "hello from menu",
price: 1000,
itemName: "good menu",
itemOptionCheckbox: [
"大盛り (+150),大盛り (+150),大盛り (+150),大盛り (+150),大盛り (+150),大盛り (+150),大盛り (+150),大盛り (+150),大盛り (0),大盛り (-150),",
"豆(+150), +ーAZaz09, 割引(ー130)",
"ひき肉 (+10), チーズ, コーヒー",
],
});
await adminDB.doc(`restaurants/testbar/private/apikey`).set({
apikey: "apiKeyMaster",
});
await adminDB.doc(`restaurants/testbar/orders/1212`).set({
payment: { stripe: "confirmed" },
timePlaced: { seconds: 1611631800, nanoseconds: 904000000 },
totalCharge: 1080,
uid: "hdLfvObioAWvymcZsGlq5PKL0CX2",
updatedAt: { seconds: 1611624589, nanoseconds: 130000000 },
timeConfirmed: { seconds: 1611624580, nanoseconds: 857000000 },
number: 372,
tip: 0,
orderAcceptedAt: { seconds: 1611624568, nanoseconds: 883000000 },
status: 650,
accounting: {
food: { tax: 80, revenue: 1000 },
alcohol: { tax: 0, revenue: 0 },
},
memo: "",
rawOptions: { VbXMnx4wdTgh1VBpBRIr: { "0": [] } },
tax: 80,
orderPlacedAt: { seconds: 1611624550, nanoseconds: 383000000 },
phoneNumber: "+819011111111",
timeEstimated: { seconds: 1611631800, nanoseconds: 904000000 },
options: { VbXMnx4wdTgh1VBpBRIr: { "0": [] } },
order: { VbXMnx4wdTgh1VBpBRIr: [1] },
prices: { VbXMnx4wdTgh1VBpBRIr: [1212] },
inclusiveTax: false,
name: "😃",
sendSMS: true,
timeCreated: { seconds: 1611624532, nanoseconds: 267000000 },
description: "#372 Test good fave 0333333333 ETsB5oBUQNMG53zA8K8P",
menuItems: { VbXMnx4wdTgh1VBpBRIr: { price: 1000, itemName: "1212" } },
transactionCompletedAt: { seconds: 1611624589, nanoseconds: 130000000 },
total: 1080,
sub_total: 1000,
});
await adminDB.doc(`restaurants/testbar/orders/12123`).set({
sendSMS: true,
tax: 84,
sub_total: 1051,
accounting: {
alcohol: { revenue: 0, tax: 0 },
food: { revenue: 1051, tax: 84 },
},
updatedAt: { seconds: 1611624733, nanoseconds: 407000000 },
menuItems: {
DJHHNW17WqhT7O51lhxB: {
itemName: "aaa 炒めももの",
price: 741,
category1: "222",
},
},
memo: "",
timePlaced: { seconds: 1611631800, nanoseconds: 996000000 },
totalCharge: 1135,
phoneNumber: "+819011111111",
options: {
DJHHNW17WqhT7O51lhxB: {
"0": ["大盛り (+150)", "豆(+150)", "ひき肉 (+10)"],
},
},
name: "😃",
timeCreated: { seconds: 1611624725, nanoseconds: 303000000 },
order: { DJHHNW17WqhT7O51lhxB: [1] },
prices: { DJHHNW17WqhT7O51lhxB: [1222] },
inclusiveTax: false,
number: 374,
status: 300,
total: 1135,
rawOptions: { DJHHNW17WqhT7O51lhxB: { "0": [0, 0, 0] } },
uid: "hdLfvObioAWvymcZsGlq5PKL0CX2",
tip: 0,
orderPlacedAt: { seconds: 1611624733, nanoseconds: 407000000 },
});
await adminDB.doc('owners/123').set(ownerData);
});
it("express simple test", async function () {
const response = await request.get("/users");
response.status.should.equal(404);
const restaurant_response = await request.get("/r/testbar");
restaurant_response.status.should.equal(200);
const meta_tag = test_helper.parse_meta(restaurant_response.text);
meta_tag["og:title"].should.not.empty;
meta_tag["og:title"].should.equal("Good cafe / テイクアウト・お持ち帰り / おもちかえり.com");
meta_tag["og:site_name"].should.not.empty;
meta_tag["og:type"].should.not.empty;
meta_tag["og:image"].should.equal("https://example.com/images600");
const restaurant_menu_response = await request.get("/r/testbar/menus/hoge");
restaurant_menu_response.status.should.equal(200);
const meta_menu_tag = test_helper.parse_meta(restaurant_menu_response.text);
meta_menu_tag["og:title"].should.not.empty;
meta_menu_tag["og:title"].should.equal("good menu / Good cafe");
meta_menu_tag["og:site_name"].should.not.empty;
meta_menu_tag["og:type"].should.not.empty;
meta_menu_tag["og:image"].should.equal("123.jpg");
meta_menu_tag["og:description"].should.equal("hello from menu");
const restaurant_error_response = await request.get("/r/testbar2");
restaurant_error_response.status.should.equal(404);
});
it("express simple test", async function () {
// const db_data = await adminDB.doc(`restaurants/testbar`).get();
const response = await request.get("/users");
response.status.should.equal(404);
const restaurant_response = await request.get("/r/testbar");
restaurant_response.status.should.equal(200);
const meta_tag = test_helper.parse_meta(restaurant_response.text);
meta_tag["og:title"].should.not.empty;
meta_tag["og:title"].should.equal(good_cafe_data.restaurantName + " / テイクアウト・お持ち帰り / おもちかえり.com");
meta_tag["og:site_name"].should.not.empty;
meta_tag["og:type"].should.not.empty;
meta_tag["og:image"].should.equal("https://example.com/images600");
});
it("express sitemape test", async function () {
const response = await request.get("/sitemap.xml");
response.status.should.equal(200);
// console.log(response.text);
});
it("express api test", async function () {
const response = await request.get("/api/1.0/restaurants").set("Origin", "http://localhost:3000");
response.status.should.equal(200);
console.log(response.headers["access-control-allow-origin"]);
});
it("express api cors test", async function () {
const response = await request.get("/api/1.0/restaurants").set("Origin", "http://localhost:3000");
response.status.should.equal(200);
response.headers["access-control-allow-origin"].should.equal("http://localhost:3000");
});
it("express api cors test", async function () {
const response = await request.get("/api/1.0/restaurants").set("Origin", "http://localhost:8000");
response.status.should.equal(200);
response.headers["access-control-allow-origin"].should.equal("http://localhost:8000");
});
it("express api cors test", async function () {
const response = await request.get("/api/1.0/restaurants").set("Origin", "http://localhost:8000.example.com");
response.status.should.equal(200);
expect(response.headers["access-control-allow-origin"]).equal(undefined);
});
it("express api cors test", async function () {
const response = await request.get("/api/1.0/restaurants").set("Origin", "http://localhostname:8000");
response.status.should.equal(200);
expect(response.headers["access-control-allow-origin"]).equal(undefined);
});
it("express api cors test", async function () {
const response = await request.get("/api/1.0/restaurants").set("Origin", "https://test-aa.firebaseapp.com");
response.status.should.equal(200);
response.headers["access-control-allow-origin"].should.equal("https://test-aa.firebaseapp.com");
});
it("express api cors test", async function () {
const response = await request.get("/api/1.0/restaurants").set("Origin", "https://test-aa.vvv.firebaseapp.com");
response.status.should.equal(200);
expect(response.headers["access-control-allow-origin"]).equal(undefined);
});
it("express api cors test", async function () {
const response = await request.get("/api/1.0/restaurants").set("Origin", "https://test.firebaseapp.com.hoge.com");
response.status.should.equal(200);
expect(response.headers["access-control-allow-origin"]).equal(undefined);
});
it("express api cors test", async function () {
const response = await request.get("/api/1.0/restaurants").set("Origin", "https://test-aa.web.app");
response.status.should.equal(200);
response.headers["access-control-allow-origin"].should.equal("https://test-aa.web.app");
});
it("express api key test", async function () {
const response = await request.get("/api/2.0/restaurants/testbar/orders").set("Authorization", "Bearer 123");
response.status.should.equal(401);
});
it("express api key test", async function () {
const response = await request.get("/api/2.0/restaurants/testbar/orders");
response.status.should.equal(401);
});
it("express api key test", async function () {
const response = await request.get("/api/2.0/restaurants/testbar/orders").set("Authorization", "Bearer apiKeyMaster");
response.status.should.equal(200);
console.log(JSON.stringify(JSON.parse(response.text), undefined, 1));
});
it("owner test", async function () {
const response = await request.get("/o/123");
response.status.should.equal(200);
console.log(response.text);
});
/*
it ('express smaregi webhook test', async function() {
const response = await request.post('/smaregi/1.0/webhook')
.send({action: "created"})
.set("Content-Type", "application/json")
.set("Smaregi-Contract-Id", "123")
.set("Smaregi-Event", "abc");
response.status.should.equal(200);
console.log(JSON.stringify(JSON.parse(response.text), undefined, 1));
});
*/
}); | the_stack |
export namespace Contacts {
// Default Application
export interface Application {}
// Class
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* Address for the given record.
*/
export interface Address {
/**
* City part of the address.
*/
city(): any;
/**
* properly formatted string for this address.
*/
formattedAddress(): any;
/**
* Street part of the address, multiple lines separated by carriage returns.
*/
street(): any;
/**
* unique identifier for this address.
*/
id(): any;
/**
* Zip or postal code of the address.
*/
zip(): any;
/**
* Country part of the address.
*/
country(): any;
/**
* Label.
*/
label(): any;
/**
* Country code part of the address (should be a two character iso country code).
*/
countryCode(): any;
/**
* State, Province, or Region part of the address.
*/
state(): any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* User name for America Online (AOL) instant messaging.
*/
export interface AIMHandle {}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* Container object in the database, holds a key and a value
*/
export interface ContactInfo {
/**
* Label is the label associated with value like "work", "home", etc.
*/
label(): any;
/**
* Value.
*/
value(): any;
/**
* unique identifier for this entry, this is persistent, and stays with the record.
*/
id(): any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* Arbitrary date associated with this person.
*/
export interface CustomDate {}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* Email address for a person.
*/
export interface Email {}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* An entry in the address book database
*/
export interface Entry {
/**
* when the contact was last modified.
*/
modificationDate(): any;
/**
* when the contact was created.
*/
creationDate(): any;
/**
* unique and persistent identifier for this record.
*/
id(): any;
/**
* Is the entry selected?
*/
selected(): boolean;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* A Group Record in the address book database
*/
export interface Group {
/**
* The name of this group.
*/
name(): any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* User name for ICQ instant messaging.
*/
export interface ICQHandle {}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* Address for instant messaging.
*/
export interface InstantMessage {
/**
* The service name of this instant message address.
*/
serviceName(): any;
/**
* The service type of this instant message address.
*/
serviceType(): any;
/**
* The user name of this instant message address.
*/
userName(): any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* User name for Jabber instant messaging.
*/
export interface JabberHandle {}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* User name for Microsoft Network (MSN) instant messaging.
*/
export interface MSNHandle {}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* A person in the address book database.
*/
export interface Person {
/**
* The Nickname of this person.
*/
nickname(): any;
/**
* Organization that employs this person.
*/
organization(): any;
/**
* The Maiden name of this person.
*/
maidenName(): any;
/**
* The Suffix of this person.
*/
suffix(): any;
/**
* Person information in vCard format, this always returns a card in version 3.0 format.
*/
vcard(): any;
/**
* The home page of this person.
*/
homePage(): any;
/**
* The birth date of this person.
*/
birthDate(): any;
/**
* The phonetic version of the Last name of this person.
*/
phoneticLastName(): any;
/**
* The title of this person.
*/
title(): any;
/**
* The Phonetic version of the Middle name of this person.
*/
phoneticMiddleName(): any;
/**
* Department that this person works for.
*/
department(): any;
/**
* Image for person.
*/
image(): any;
/**
* First/Last name of the person, uses the name display order preference setting in Address Book.
*/
name(): any;
/**
* Notes for this person.
*/
note(): any;
/**
* Is the current record a company or a person.
*/
company(): boolean;
/**
* The Middle name of this person.
*/
middleName(): any;
/**
* The phonetic version of the First name of this person.
*/
phoneticFirstName(): any;
/**
* The job title of this person.
*/
jobTitle(): any;
/**
* The Last name of this person.
*/
lastName(): any;
/**
* The First name of this person.
*/
firstName(): any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* Phone number for a person.
*/
export interface Phone {}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* Other names related to this person.
*/
export interface RelatedName {}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* Profile for social networks.
*/
export interface SocialProfile {
/**
* The persistent unique identifier for this profile.
*/
id(): any;
/**
* The service name of this social profile.
*/
serviceName(): any;
/**
* The username used with this social profile.
*/
userName(): any;
/**
* A service-specific identifier used with this social profile.
*/
userIdentifier(): any;
/**
* The URL of this social profile.
*/
url(): any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* URLs for this person.
*/
export interface Url {}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* User name for Yahoo instant messaging.
*/
export interface YahooHandle {}
// CLass Extension
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface Application {
/**
* Returns my Address Book card.
*/
myCard(): any;
/**
* Does Address Book have any unsaved changes?
*/
unsaved(): boolean;
/**
* Currently selected entries
*/
selection(): any;
/**
* Returns the default country code for addresses.
*/
defaultCountryCode(): any;
}
// Records
// Function options
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface MakeOptionalParameter {
/**
* The class of the new object.
*/
new: any;
/**
* The location at which to insert the object.
*/
at?: any;
/**
* The initial contents of the object.
*/
withData?: any;
/**
* The initial values for properties of the object.
*/
withProperties?: any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface AddOptionalParameter {
/**
* where to add this child to.
*/
to: any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface RemoveOptionalParameter {
/**
* where to remove this child from.
*/
from: any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface ActionTitleOptionalParameter {
/**
* property that that was returned from the "action property" handler.
*/
with: any;
/**
* Currently selected person.
*/
for: any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface PerformActionOptionalParameter {
/**
* property that that was returned from the "action property" handler.
*/
with: any;
/**
* Currently selected person.
*/
for: any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface ShouldEnableActionOptionalParameter {
/**
* property that that was returned from the "action property" handler.
*/
with: any;
/**
* Currently selected person.
*/
for: any;
}
}
export interface Contacts extends Contacts.Application {
// Functions
/**
* Create a new object.
* @param option
* @return The new object.
*/
make(option?: Contacts.MakeOptionalParameter): any;
/**
* Add a child object.
* @param directParameter object to add.
* @param option
* @return undefined
*/
add(directParameter: Contacts.Entry, option?: Contacts.AddOptionalParameter): Contacts.Person;
/**
* Remove a child object.
* @param directParameter object to remove.
* @param option
* @return undefined
*/
remove(directParameter: Contacts.Entry, option?: Contacts.RemoveOptionalParameter): Contacts.Person;
/**
* Save all Address Book changes. Also see the unsaved property for the application class.
* @return undefined
*/
save(): any;
/**
* RollOver - Which property this roll over is associated with (Properties can be one of maiden name, phone, email, url, birth date, custom date, related name, aim, icq, jabber, msn, yahoo, address.)
* @return undefined
*/
actionProperty(): string;
/**
* RollOver - Returns the title that will be placed in the menu for this roll over
* @param option
* @return undefined
*/
actionTitle(option?: Contacts.ActionTitleOptionalParameter): string;
/**
* RollOver - Performs the action on the given person and value
* @param option
* @return undefined
*/
performAction(option?: Contacts.PerformActionOptionalParameter): boolean;
/**
* RollOver - Determines if the rollover action should be enabled for the given person and value
* @param option
* @return undefined
*/
shouldEnableAction(option?: Contacts.ShouldEnableActionOptionalParameter): boolean;
} | the_stack |
import EC2, { DescribeRegionsRequest } from 'aws-sdk/clients/ec2';
import S3, { CreateBucketRequest, PutBucketEncryptionRequest, PutBucketPolicyRequest } from 'aws-sdk/clients/s3';
import SecretsManager from 'aws-sdk/clients/secretsmanager';
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { createHash } from 'crypto';
import moment from 'moment';
import { v4 } from 'uuid';
import { getOptions } from '../solution-utils/get-options';
import { isNullOrWhiteSpace } from '../solution-utils/helpers';
import {
CheckFallbackImageRequestProperties,
CheckSecretManagerRequestProperties,
CheckSourceBucketsRequestProperties,
CompletionStatus,
CopyS3AssetsRequestProperties,
CreateLoggingBucketRequestProperties,
CustomResourceActions,
CustomResourceError,
CustomResourceRequest,
CustomResourceRequestTypes,
ErrorCodes,
LambdaContext,
MetricPayload,
PutConfigRequestProperties,
SendMetricsRequestProperties,
StatusTypes
} from './lib';
const awsSdkOptions = getOptions();
const s3Client = new S3(awsSdkOptions);
const ec2Client = new EC2(awsSdkOptions);
const secretsManager = new SecretsManager(awsSdkOptions);
const { SOLUTION_ID, SOLUTION_VERSION, AWS_REGION, RETRY_SECONDS } = process.env;
const METRICS_ENDPOINT = 'https://metrics.awssolutionsbuilder.com/generic';
const RETRY_COUNT = 3;
/**
* Custom resource Lambda handler.
* @param event The custom resource request.
* @param context The custom resource context.
* @returns Processed request response.
*/
export async function handler(event: CustomResourceRequest, context: LambdaContext) {
console.info('Received event:', JSON.stringify(event, null, 2));
const { RequestType, ResourceProperties } = event;
const response: CompletionStatus = {
Status: StatusTypes.SUCCESS,
Data: {}
};
try {
switch (ResourceProperties.CustomAction) {
case CustomResourceActions.SEND_ANONYMOUS_METRIC: {
const requestProperties: SendMetricsRequestProperties = ResourceProperties as SendMetricsRequestProperties;
if (requestProperties.AnonymousData === 'Yes') {
response.Data = await sendAnonymousMetric(requestProperties, RequestType);
}
break;
}
case CustomResourceActions.PUT_CONFIG_FILE:
if ([CustomResourceRequestTypes.CREATE, CustomResourceRequestTypes.UPDATE].includes(RequestType)) {
response.Data = await putConfigFile(ResourceProperties as PutConfigRequestProperties);
}
break;
case CustomResourceActions.COPY_S3_ASSETS:
if ([CustomResourceRequestTypes.CREATE, CustomResourceRequestTypes.UPDATE].includes(RequestType)) {
response.Data = await copyS3Assets(ResourceProperties as CopyS3AssetsRequestProperties);
}
break;
case CustomResourceActions.CREATE_UUID:
if ([CustomResourceRequestTypes.CREATE].includes(RequestType)) {
response.Data = await generateUUID();
}
break;
case CustomResourceActions.CHECK_SOURCE_BUCKETS:
if ([CustomResourceRequestTypes.CREATE, CustomResourceRequestTypes.UPDATE].includes(RequestType)) {
response.Data = await validateBuckets(ResourceProperties as CheckSourceBucketsRequestProperties);
}
break;
case CustomResourceActions.CHECK_SECRETS_MANAGER:
if ([CustomResourceRequestTypes.CREATE, CustomResourceRequestTypes.UPDATE].includes(RequestType)) {
response.Data = await checkSecretsManager(ResourceProperties as CheckSecretManagerRequestProperties);
}
break;
case CustomResourceActions.CHECK_FALLBACK_IMAGE:
if ([CustomResourceRequestTypes.CREATE, CustomResourceRequestTypes.UPDATE].includes(RequestType)) {
response.Data = await checkFallbackImage(ResourceProperties as CheckFallbackImageRequestProperties);
}
break;
case CustomResourceActions.CREATE_LOGGING_BUCKET:
if ([CustomResourceRequestTypes.CREATE].includes(RequestType)) {
response.Data = await createCloudFrontLoggingBucket(ResourceProperties as CreateLoggingBucketRequestProperties);
}
break;
default:
break;
}
} catch (error) {
console.error(`Error occurred at ${event.RequestType}::${ResourceProperties.CustomAction}`, error);
response.Status = StatusTypes.FAILED;
response.Data.Error = {
Code: error.code ?? 'CustomResourceError',
Message: error.message ?? 'Custom resource error occurred.'
};
} finally {
await sendCloudFormationResponse(event, context.logStreamName, response);
}
return response;
}
/**
* Suspends for the specified amount of seconds.
* @param timeOut The number of seconds for which the call is suspended.
* @returns Sleep promise.
*/
async function sleep(timeOut: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, timeOut));
}
/**
* Gets retry timeout based on the current retry attempt in seconds.
* @param attempt Retry attempt.
* @returns Timeout in seconds.
*/
function getRetryTimeout(attempt: number): number {
const retrySeconds = Number(RETRY_SECONDS);
return retrySeconds * 1000 * attempt;
}
/**
* Get content type by file name.
* @param filename File name.
* @returns Content type.
*/
function getContentType(filename: string): string {
let contentType = '';
if (filename.endsWith('.html')) {
contentType = 'text/html';
} else if (filename.endsWith('.css')) {
contentType = 'text/css';
} else if (filename.endsWith('.png')) {
contentType = 'image/png';
} else if (filename.endsWith('.svg')) {
contentType = 'image/svg+xml';
} else if (filename.endsWith('.jpg')) {
contentType = 'image/jpeg';
} else if (filename.endsWith('.js')) {
contentType = 'application/javascript';
} else {
contentType = 'binary/octet-stream';
}
return contentType;
}
/**
* Send custom resource response.
* @param event Custom resource event.
* @param logStreamName Custom resource log stream name.
* @param response Response completion status.
* @returns The promise of the sent request.
*/
async function sendCloudFormationResponse(event: CustomResourceRequest, logStreamName: string, response: CompletionStatus): Promise<AxiosResponse> {
const responseBody = JSON.stringify({
Status: response.Status,
Reason: `See the details in CloudWatch Log Stream: ${logStreamName}`,
PhysicalResourceId: event.LogicalResourceId,
StackId: event.StackId,
RequestId: event.RequestId,
LogicalResourceId: event.LogicalResourceId,
Data: response.Data
});
const config: AxiosRequestConfig = {
headers: {
'Content-Type': '',
'Content-Length': responseBody.length
}
};
return axios.put(event.ResponseURL, responseBody, config);
}
/**
* Sends anonymous metrics.
* @param requestProperties The send metrics request properties.
* @param requestType The request type.
* @returns Promise message object.
*/
async function sendAnonymousMetric(requestProperties: SendMetricsRequestProperties, requestType: CustomResourceRequestTypes): Promise<{ Message: string; Data: MetricPayload }> {
const result: { Message: string; Data: MetricPayload } = { Message: '', Data: undefined };
try {
const numberOfSourceBuckets =
requestProperties.SourceBuckets?.split(',')
.map(x => x.trim())
.filter(x => !isNullOrWhiteSpace(x)).length || 0;
const payload: MetricPayload = {
Solution: SOLUTION_ID,
Version: SOLUTION_VERSION,
UUID: requestProperties.UUID,
TimeStamp: moment.utc().format('YYYY-MM-DD HH:mm:ss.S'),
Data: {
Region: AWS_REGION,
Type: requestType,
CorsEnabled: requestProperties.CorsEnabled,
NumberOfSourceBuckets: numberOfSourceBuckets,
DeployDemoUi: requestProperties.DeployDemoUi,
LogRetentionPeriod: requestProperties.LogRetentionPeriod,
AutoWebP: requestProperties.AutoWebP,
EnableSignature: requestProperties.EnableSignature,
EnableDefaultFallbackImage: requestProperties.EnableDefaultFallbackImage
}
};
result.Data = payload;
const payloadStr = JSON.stringify(payload);
const config: AxiosRequestConfig = {
headers: {
'content-type': 'application/json',
'content-length': payloadStr.length
}
};
console.info('Sending anonymous metric', payloadStr);
const response = await axios.post(METRICS_ENDPOINT, payloadStr, config);
console.info(`Anonymous metric response: ${response.statusText} (${response.status})`);
result.Message = 'Anonymous data was sent successfully.';
} catch (err) {
console.error('Error sending anonymous metric');
console.error(err);
result.Message = 'Anonymous data was sent failed.';
}
return result;
}
/**
* Puts the config file into S3 bucket.
* @param requestProperties The request properties.
* @returns Result of the putting config file.
*/
async function putConfigFile(requestProperties: PutConfigRequestProperties): Promise<{ Message: string; Content: string }> {
const { ConfigItem, DestS3Bucket, DestS3key } = requestProperties;
console.info(`Attempting to save content blob destination location: ${DestS3Bucket}/${DestS3key}`);
console.info(JSON.stringify(ConfigItem, null, 2));
const configFieldValues = Object.entries(ConfigItem)
.map(([key, value]) => `${key}: '${value}'`)
.join(',\n');
const content = `'use strict';\n\nconst appVariables = {\n${configFieldValues}\n};`;
// In case getting object fails due to asynchronous IAM permission creation, it retries.
const params = {
Bucket: DestS3Bucket,
Body: content,
Key: DestS3key,
ContentType: getContentType(DestS3key)
};
for (let retry = 1; retry <= RETRY_COUNT; retry++) {
try {
console.info(`Putting ${DestS3key}... Try count: ${retry}`);
await s3Client.putObject(params).promise();
console.info(`Putting ${DestS3key} completed.`);
break;
} catch (error) {
if (retry === RETRY_COUNT || error.code !== ErrorCodes.ACCESS_DENIED) {
console.info(`Error occurred while putting ${DestS3key} into ${DestS3Bucket} bucket.`, error);
throw new CustomResourceError('ConfigFileCreationFailure', `Saving config file to ${DestS3Bucket}/${DestS3key} failed.`);
} else {
console.info('Waiting for retry...');
await sleep(getRetryTimeout(retry));
}
}
}
return {
Message: 'Config file uploaded.',
Content: content
};
}
/**
* Copies assets from the source S3 bucket to the destination S3 bucket.
* @param requestProperties The request properties.
* @returns The result of copying assets.
*/
async function copyS3Assets(requestProperties: CopyS3AssetsRequestProperties): Promise<{ Message: string; Manifest: { Files: string[] } }> {
const { ManifestKey, SourceS3Bucket, SourceS3key, DestS3Bucket } = requestProperties;
console.info(`Source bucket: ${SourceS3Bucket}`);
console.info(`Source prefix: ${SourceS3key}`);
console.info(`Destination bucket: ${DestS3Bucket}`);
let manifest: { files: string[] };
// Download manifest
for (let retry = 1; retry <= RETRY_COUNT; retry++) {
try {
const getParams = {
Bucket: SourceS3Bucket,
Key: ManifestKey
};
const response = await s3Client.getObject(getParams).promise();
manifest = JSON.parse(response.Body.toString());
break;
} catch (error) {
if (retry === RETRY_COUNT || error.code !== ErrorCodes.ACCESS_DENIED) {
console.error('Error occurred while getting manifest file.');
console.error(error);
throw new CustomResourceError('GetManifestFailure', 'Copy of website assets failed.');
} else {
console.info('Waiting for retry...');
await sleep(getRetryTimeout(retry));
}
}
}
// Copy asset files
try {
await Promise.all(
manifest.files.map(async (fileName: string) => {
const copyObjectParams = {
Bucket: DestS3Bucket,
CopySource: `${SourceS3Bucket}/${SourceS3key}/${fileName}`,
Key: fileName,
ContentType: getContentType(fileName)
};
console.debug(`Copying ${fileName} to ${DestS3Bucket}`);
return s3Client.copyObject(copyObjectParams).promise();
})
);
return {
Message: 'Copy assets completed.',
Manifest: { Files: manifest.files }
};
} catch (error) {
console.error('Error occurred while copying assets.');
console.error(error);
throw new CustomResourceError('CopyAssetsFailure', 'Copy of website assets failed.');
}
}
/**
* Generates UUID.
* @returns Generated UUID.
*/
async function generateUUID(): Promise<{ UUID: string }> {
return Promise.resolve({ UUID: v4() });
}
/**
* Validates if buckets exist in the account.
* @param requestProperties The request properties.
* @returns The result of validation.
*/
async function validateBuckets(requestProperties: CheckSourceBucketsRequestProperties): Promise<{ Message: string }> {
const { SourceBuckets } = requestProperties;
const buckets = SourceBuckets.replace(/\s/g, '');
console.info(`Attempting to check if the following buckets exist: ${buckets}`);
const checkBuckets = buckets.split(',');
const errorBuckets = [];
for (const bucket of checkBuckets) {
const params = { Bucket: bucket };
try {
await s3Client.headBucket(params).promise();
console.info(`Found bucket: ${bucket}`);
} catch (error) {
console.error(`Could not find bucket: ${bucket}`);
console.error(error);
errorBuckets.push(bucket);
}
}
if (errorBuckets.length === 0) {
return { Message: 'Buckets validated.' };
} else {
const commaSeparatedErrors = errorBuckets.join(',');
throw new CustomResourceError(
'BucketNotFound',
`Could not find the following source bucket(s) in your account: ${commaSeparatedErrors}. Please specify at least one source bucket that exists within your account and try again. If specifying multiple source buckets, please ensure that they are comma-separated.`
);
}
}
/**
* Checks if AWS Secrets Manager secret is valid.
* @param requestProperties The request properties.
* @returns ARN of the AWS Secrets Manager secret.
*/
async function checkSecretsManager(requestProperties: CheckSecretManagerRequestProperties): Promise<{ Message: string; ARN: string }> {
const { SecretsManagerName, SecretsManagerKey } = requestProperties;
if (isNullOrWhiteSpace(SecretsManagerName)) {
throw new CustomResourceError('SecretNotProvided', 'You need to provide AWS Secrets Manager secret.');
}
if (isNullOrWhiteSpace(SecretsManagerKey)) {
throw new CustomResourceError('SecretKeyNotProvided', 'You need to provide AWS Secrets Manager secret key.');
}
let arn = '';
for (let retry = 1; retry <= RETRY_COUNT; retry++) {
try {
const response = await secretsManager.getSecretValue({ SecretId: SecretsManagerName }).promise();
const secretString = JSON.parse(response.SecretString);
if (!Object.prototype.hasOwnProperty.call(secretString, SecretsManagerKey)) {
throw new CustomResourceError('SecretKeyNotFound', `AWS Secrets Manager secret requires ${SecretsManagerKey} key.`);
}
arn = response.ARN;
break;
} catch (error) {
if (retry === RETRY_COUNT) {
console.error(`AWS Secrets Manager secret or signature might not exist: ${SecretsManagerName}/${SecretsManagerKey}`);
throw error;
} else {
console.info('Waiting for retry...');
await sleep(getRetryTimeout(retry));
}
}
}
return {
Message: 'Secrets Manager validated.',
ARN: arn
};
}
/**
* Checks fallback image.
* @param requestProperties The request properties.
* @returns The result of validation.
*/
async function checkFallbackImage(requestProperties: CheckFallbackImageRequestProperties): Promise<{ Message: string; Data: unknown }> {
const { FallbackImageS3Bucket, FallbackImageS3Key } = requestProperties as CheckFallbackImageRequestProperties;
if (isNullOrWhiteSpace(FallbackImageS3Bucket)) {
throw new CustomResourceError('S3BucketNotProvided', 'You need to provide the default fallback image bucket.');
}
if (isNullOrWhiteSpace(FallbackImageS3Key)) {
throw new CustomResourceError('S3KeyNotProvided', 'You need to provide the default fallback image object key.');
}
let data = {};
for (let retry = 1; retry <= RETRY_COUNT; retry++) {
try {
data = await s3Client.headObject({ Bucket: FallbackImageS3Bucket, Key: FallbackImageS3Key }).promise();
break;
} catch (error) {
if (retry === RETRY_COUNT || ![ErrorCodes.ACCESS_DENIED, ErrorCodes.FORBIDDEN].includes(error.code)) {
console.error(`Either the object does not exist or you don't have permission to access the object: ${FallbackImageS3Bucket}/${FallbackImageS3Key}`);
throw new CustomResourceError(
'FallbackImageError',
`Either the object does not exist or you don't have permission to access the object: ${FallbackImageS3Bucket}/${FallbackImageS3Key}`
);
} else {
console.info('Waiting for retry...');
await sleep(getRetryTimeout(retry));
}
}
}
return {
Message: 'The default fallback image validated.',
Data: data
};
}
/**
* Creates a bucket with settings for cloudfront logging.
* @param requestProperties The request properties.
* @returns Bucket name of the created bucket.
*/
async function createCloudFrontLoggingBucket(requestProperties: CreateLoggingBucketRequestProperties) {
const logBucketSuffix = createHash('md5').update(`${requestProperties.BucketSuffix}${moment.utc().valueOf()}`).digest('hex');
const bucketName = `serverless-image-handler-logs-${logBucketSuffix.substring(0, 8)}`.toLowerCase();
// the S3 bucket will be created in 'us-east-1' if the current region is in opt-in regions,
// because CloudFront does not currently deliver access logs to opt-in region buckets
const isOptInRegion = await checkRegionOptInStatus(AWS_REGION);
const targetRegion = isOptInRegion ? 'us-east-1' : AWS_REGION;
console.info(`The opt-in status of the '${AWS_REGION}' region is '${isOptInRegion ? 'opted-in' : 'opt-in-not-required'}'`);
// create bucket
try {
const s3Client = new S3({ ...awsSdkOptions, apiVersion: '2006-03-01', region: targetRegion });
const createBucketRequestParams: CreateBucketRequest = { Bucket: bucketName, ACL: 'log-delivery-write' };
await s3Client.createBucket(createBucketRequestParams).promise();
console.info(`Successfully created bucket '${bucketName}' in '${targetRegion}' region`);
} catch (error) {
console.error(`Could not create bucket '${bucketName}'`);
console.error(error);
throw error;
}
// add encryption to bucket
console.info('Adding Encryption...');
try {
const putBucketEncryptionRequestParams: PutBucketEncryptionRequest = {
Bucket: bucketName,
ServerSideEncryptionConfiguration: { Rules: [{ ApplyServerSideEncryptionByDefault: { SSEAlgorithm: 'AES256' } }] }
};
await s3Client.putBucketEncryption(putBucketEncryptionRequestParams).promise();
console.info(`Successfully enabled encryption on bucket '${bucketName}'`);
} catch (error) {
console.error(`Failed to add encryption to bucket '${bucketName}'`);
console.error(error);
throw error;
}
// add policy to bucket
try {
console.info('Adding policy...');
const bucketPolicyStatement = {
Resource: `arn:aws:s3:::${bucketName}/*`,
Action: '*',
Effect: 'Deny',
Principal: '*',
Sid: 'HttpsOnly',
Condition: { Bool: { 'aws:SecureTransport': 'false' } }
};
const bucketPolicy = { Version: '2012-10-17', Statement: [bucketPolicyStatement] };
const putBucketPolicyRequestParams: PutBucketPolicyRequest = { Bucket: bucketName, Policy: JSON.stringify(bucketPolicy) };
await s3Client.putBucketPolicy(putBucketPolicyRequestParams).promise();
console.info(`Successfully added policy added to bucket '${bucketName}'`);
} catch (error) {
console.error(`Failed to add policy to bucket '${bucketName}'`);
console.error(error);
throw error;
}
return { BucketName: bucketName, Region: targetRegion };
}
/**
* Checks if the region is opted-in or not.
* @param region The region to check.
* @returns The result of check.
*/
async function checkRegionOptInStatus(region: string): Promise<boolean> {
const describeRegionsRequestParams: DescribeRegionsRequest = {
RegionNames: [region],
Filters: [{ Name: 'opt-in-status', Values: ['opted-in'] }]
};
const describeRegionsResponse = await ec2Client.describeRegions(describeRegionsRequestParams).promise();
return describeRegionsResponse.Regions.length > 0;
} | the_stack |
import tc from '@spaceavocado/type-check';
import pathToRegexp from 'path-to-regexp';
import createHistory, {
HISTORY_MODE,
HISTORY_ACTION,
HASH_TYPE,
} from './history';
import {
Location,
RawLocation,
createLocation,
} from './location';
import {
HistoryLocation,
joinPath,
fullURL,
historyFullURL,
hasPrefix,
trimPrefix,
} from './utils';
import {
Route,
Record,
RouteConfig,
RouteConfigPrefab,
routeRedirect,
componentModule,
createRouteConfig,
createRouteRecord,
createRoute,
cloneRoute,
} from './route';
type historyModule = {
action: HISTORY_ACTION;
location: HistoryLocation;
push: (path: string) => void;
replace: (path: string) => void;
go: (n: number) => void;
goBack: () => void;
goForward: () => void;
listen: (listener:
(location: HistoryLocation, action: HISTORY_ACTION) => void
) => () => void;
};
/**
* History lib configuration.
*/
interface HistoryOptions {
/** The base URL of the app, defaults to ''. */
basename?: string;
/** Hash type. */
hashType?: string;
}
/**
* Router configuration.
*/
export interface RouterConfig {
/** History mode */
mode?: HISTORY_MODE;
/** The base URL of the app, defaults to ''. */
basename?: string;
/** Hash type. */
hashType?: HASH_TYPE;
/** Router routes. */
routes: RouteConfigPrefab[];
/** CSS class applied on the active route link. Defaults to "active". */
activeClass?: string;
/** History options */
historyOpts?: HistoryOptions;
}
/**
* Possible actions:
* * fn() or fn(true) = Continue.
* * fn(false) = Abort the navigation.
* * fn(Error) = Abort the navigation and trigger navigation error.
* * fn(url) or fn(RawLocation) = Break the navigation
* and resolve the new navigation.
*/
type navigationGuardNextAction = undefined | boolean | Error | string | object;
type navigationGuardFunction = (from: Route | null, to: Route | null,
next: (action: navigationGuardNextAction) => void) => void;
/**
* Navigation Guard entry.
*/
interface NavigationGuard {
key: symbol;
guard: navigationGuardFunction;
}
type onErrorCallback = (e: Error) => void;
type onNavigationCallback = (from: Route, to: Route) => void;
/**
* Router event listeners collection.
*/
interface EventListeners {
onError: Map<symbol, onErrorCallback>;
onBeforeNavigation: Map<symbol, onNavigationCallback>;
onNavigationChanged: Map<symbol, onNavigationCallback>;
}
/**
* Svelte Router core class.
*/
export class Router {
private _mode: HISTORY_MODE;
private _basename: string;
private _routes: RouteConfig[];
private _activeClass: string;
private _history: historyModule;
private _historyListener: () => void;
private _navigationGuards: NavigationGuard[];
private _listeners: EventListeners;
private _currentRoute: Route | null = null;
private _pendingRoute: Route | null = null;
private _asyncViews: Map<symbol, () => object>;
/**
* @constructor
* @param {RouterConfig} opts
*/
constructor(opts: RouterConfig) {
opts = opts || {};
opts.historyOpts = {};
opts.mode = opts.mode || HISTORY_MODE.HISTORY;
if (tc.not.isEnumKey(opts.mode, HISTORY_MODE)) {
throw new Error(`invalid router mode, "${opts.mode}"`);
}
opts.historyOpts.basename = opts.basename || '';
if (tc.not.isString(opts.historyOpts.basename)) {
throw new Error(`invalid basename, "${opts.historyOpts.basename}"`);
}
if (opts.historyOpts.basename.length > 0
&& hasPrefix(opts.historyOpts.basename, '/') == false) {
opts.historyOpts.basename = '/' + opts.historyOpts.basename;
}
if (opts.mode == HISTORY_MODE.HASH) {
opts.historyOpts.hashType = opts.hashType || HASH_TYPE.SLASH;
if (tc.not.isEnumKey(opts.historyOpts.hashType, HASH_TYPE)) {
throw new Error(`invalid hash type, "${opts.historyOpts.hashType}"`);
}
opts.historyOpts.hashType = opts.historyOpts.hashType.toLowerCase();
}
this._mode = opts.mode;
this._basename = opts.historyOpts.basename;
this._routes = [];
this._activeClass = opts.activeClass || 'active';
this._history = createHistory(
this._mode, opts.historyOpts || {}
) as historyModule;
this._historyListener = this._history.listen(
this.onHistoryChange.bind(this)
);
// Navigation guards and listeners
this._navigationGuards = [];
this._listeners = {
onError: new Map(),
onBeforeNavigation: new Map(),
onNavigationChanged: new Map(),
};
// Current resolved route and resolved pending route
this._currentRoute = null;
this._pendingRoute = null;
// Async views
this._asyncViews = new Map();
// Preprocess routes
this.preprocessRoutes(this._routes, opts.routes);
}
/**
* Trigger the on load history change.
*/
start(): void {
this.onHistoryChange(this._history.location, HISTORY_ACTION.POP);
}
/**
* Get router mode
*/
get mode(): HISTORY_MODE {
return this._mode;
}
/**
* Get router basename
*/
get basename(): string {
return this._basename;
}
/**
* Get routes
*/
get routes(): RouteConfig[] {
return this._routes;
}
/**
* Get current resolved route
*/
get currentRoute(): Route | null {
return this._currentRoute;
}
/**
* Get router link active class
*/
get activeClass(): string {
return this._activeClass;
}
/**
* Register a navigation guard which will be called
* whenever a navigation is triggered.
* All registered navigation guards are resolved in sequence.
* Navigation guard must call the next() function to continue
* the execution of navigation change.
* @param {function} guard Guard callback function.
* @return {function} Unregister guard function.
*/
navigationGuard(guard: navigationGuardFunction): () => void {
const key = Symbol();
this._navigationGuards.push({
key,
guard,
});
return (): void => {
this.removeNavigationGuard(key);
};
}
/**
* Register a callback which will be called before
* execution of navigation guards.
* @param {function} callback callback function.
* @return {function} Unregister listener function.
*/
onBeforeNavigation(callback: onNavigationCallback): () => void {
const key = Symbol();
this._listeners.onBeforeNavigation.set(key, callback);
return (): void => {
this._listeners.onBeforeNavigation.delete(key);
};
}
/**
* Register a callback which will be called when
* all navigation guards are resolved, and the final
* navigation change is resolved.
* @param {function} callback callback function.
* @return {function} Unregister listener function.
*/
onNavigationChanged(callback: onNavigationCallback): () => void {
const key = Symbol();
this._listeners.onNavigationChanged.set(key, callback);
return (): void => {
this._listeners.onNavigationChanged.delete(key);
};
}
/**
* Register a callback which will be called when an error
* is caught during a route navigation.
* @param {function} callback Callback function.
* @return {function} Unregister callback function.
*/
onError(callback: onErrorCallback): () => void {
const key = Symbol();
this._listeners.onError.set(key, callback);
return (): void => {
this._listeners.onError.delete(key);
};
}
/**
* Push to navigation.
* @param {RawLocation|string} rawLocation raw path or location object.
* @param {function?} onComplete On complete callback function.
* @param {function?} onAbort On abort callback function.
* @throws When the rawLocation is invalid or when the path is invalid.
*/
push(
rawLocation: RawLocation | string,
onComplete?: () => void,
onAbort?: () => void): void {
let location;
try {
location = this.rawLocationToLocation(rawLocation, false);
} catch (e) {
if (onAbort && tc.isFunction(onAbort)) {
onAbort();
}
this.notifyOnError(
new Error(`invalid location, ${e.toString()}`)
);
return;
}
this.resolveRoute(location,
tc.isFunction(onComplete) ? onComplete : undefined,
tc.isFunction(onAbort) ? onAbort : undefined,
);
}
/**
* Replace in navigation
* @param {RawLocation|string} rawLocation raw path or location object.
* @param {function?} onComplete On complete callback function.
* @param {function?} onAbort On abort callback function.
* @throws when the rawLocation is invalid or when the path is invalid.
*/
replace(
rawLocation: RawLocation | string,
onComplete?: () => void,
onAbort?: () => void): void {
let location;
try {
location = this.rawLocationToLocation(rawLocation, true);
} catch (e) {
if (onAbort && tc.isFunction(onAbort)) {
onAbort();
}
this.notifyOnError(
new Error(`invalid location, ${e.toString()}`)
);
return;
}
this.resolveRoute(location,
tc.isFunction(onComplete) ? onComplete : undefined,
tc.isFunction(onAbort) ? onAbort : undefined,
);
}
/**
* Go to a specific history position in the navigation history.
* @param {number} n number of steps to forward
* or backwards (negative number).
*/
go(n: number): void {
this._history.go(n);
}
/**
* Go one step back in the navigation history.
*/
back(): void {
this._history.goBack();
}
/**
* Go one step forward in the navigation history.
*/
forward(): void {
this._history.goForward();
}
/**
* Generate route URL from the the raw location.
* @param {RawLocation} rawLocation raw location object.
* @throws when the route is not found or the route params are not valid.
* @return {string}
*/
routeURL(rawLocation: RawLocation): string {
if (tc.isNullOrUndefined(rawLocation)) {
throw new Error('invalid rawLocation');
}
if (tc.isNullOrUndefined(rawLocation.name)
|| tc.not.isString(rawLocation.name)) {
throw new Error('missing or invalid route name');
}
if (tc.not.isNullOrUndefined(rawLocation.params)
&& tc.not.isObject(rawLocation.params)) {
throw new Error('invalid params property, expected object.');
}
if (tc.not.isNullOrUndefined(rawLocation.query)
&& tc.not.isObject(rawLocation.query)) {
throw new Error('invalid query property, expected object.');
}
if (tc.not.isNullOrUndefined(rawLocation.hash)
&& tc.not.isString(rawLocation.hash)) {
throw new Error('invalid hash property');
}
rawLocation.params = rawLocation.params || {};
rawLocation.query = rawLocation.query || {};
rawLocation.hash = rawLocation.hash || '';
// Try to find the route
const match = this.findRouteByName(
rawLocation.name as string,
this._routes);
if (match == null) {
throw new Error(`no matching route found for name:${rawLocation.name}`);
}
// Try to generate the route URL with the given params
// to validate the route and to get the params
let url = '';
try {
url = match.generator(rawLocation.params || {});
} catch (e) {
throw new Error(`invalid route parameters, :${e.toString()}`);
}
// Resolve query params
url = fullURL(url, rawLocation.query, rawLocation.hash);
// Basename
if (this._basename.length > 0) {
url = joinPath(this._basename, url);
}
return url;
}
/**
* Convert routes prefabs into route configs, recursively.
* @param {RouteConfig[]} routes Routes reference collection.
* @param {RouteConfigPrefab[]} prefabs Collection of route prefabs.
* @param {RouteConfig|null} parent Parent route.
*/
private preprocessRoutes(
routes: RouteConfig[],
prefabs: RouteConfigPrefab[],
parent: RouteConfig | null = null): void {
for (let i = 0; i < prefabs.length; i++) {
let route: RouteConfig;
try {
prefabs[i].children = prefabs[i].children || [];
route = createRouteConfig(prefabs[i]);
route.parent = null;
routes.push(route);
} catch (e) {
console.error(new Error(`invalid route, ${e.toString()}`));
continue;
}
// Append parent path prefix
if (parent != null) {
route.parent = parent;
if (route.path.length > 0) {
route.path = joinPath(parent.path, route.path);
} else {
route.path = parent.path;
}
}
// Generate the regex matcher and params keys
route.paramKeys = [];
// Any URL
if (route.path == '*') {
route.matcher = /.*/i;
route.generator = (): string => '/';
// Regex based
} else {
route.matcher = pathToRegexp(
route.path,
route.paramKeys as pathToRegexp.Key[], {
end: (prefabs[i].children as RouteConfigPrefab[]).length == 0,
});
route.generator = pathToRegexp.compile(route.path);
}
// Process children
if ((prefabs[i].children as RouteConfigPrefab[]).length > 0) {
this.preprocessRoutes(
route.children,
prefabs[i].children as RouteConfigPrefab[],
route
);
}
}
}
/**
* On history change event.
* @param {HistoryLocation} location
* @param {HISTORY_ACTION} action
*/
private onHistoryChange(
location: HistoryLocation,
action: HISTORY_ACTION): void {
// Resolve route when the history is popped.
if (action == HISTORY_ACTION.POP) {
this.push(historyFullURL(location));
}
}
/**
* Convert raw Location to Location.
* @param {RawLocation | string} rawLocation raw path or location object.
* @param {boolean} replace history replace flag.
* @throws when the rawLocation is invalid or when the path is invalid.
* @return {Location}
*/
private rawLocationToLocation(
rawLocation: RawLocation | string,
replace: boolean): Location {
if (tc.isNullOrUndefined(rawLocation)) {
throw new Error('invalid rawLocation');
}
if (tc.isString(rawLocation)) {
rawLocation = {
path: rawLocation,
} as RawLocation;
}
rawLocation.replace = replace;
let location;
try {
location = createLocation(rawLocation as RawLocation);
} catch (e) {
throw e;
}
return location;
}
/**
* Resolve route from the requested location.
* @param {Location} location
* @param {function?} onComplete On complete request callback.
* @param {function?} onAbort On abort request callback.
*/
private resolveRoute(
location: Location,
onComplete?: () => void,
onAbort?: () => void): void {
let matches: Record[] = [];
if (this._basename.length > 0) {
location.path = trimPrefix(location.path, this._basename);
}
// Resolve named route
if (location.name) {
let match = this.findRouteByName(location.name, this._routes);
if (match == null) {
if (onAbort != null) {
onAbort();
}
this.notifyOnError(
new Error(`no matching route found for name:${location.name}`)
);
return;
}
// Try to generate the route URL with the given params
// to validate the route and to get the params
try {
location.path = match.generator(location.params);
} catch (e) {
if (onAbort != null) {
onAbort();
}
this.notifyOnError(
new Error(`invalid route parameters, :${e.toString()}`)
);
return;
}
// Generate the route records
matches.push(createRouteRecord(match, location.params));
while (match.parent != null) {
match = match.parent;
matches.push(createRouteRecord(match, location.params));
}
if (matches.length > 1) {
matches = matches.reverse();
}
// Resolved route by path
// and generate the route records
} else {
if (this.matchRoute(location.path, this._routes, matches) == false) {
if (onAbort != null) {
onAbort();
}
this.notifyOnError(
new Error(`no matching route found for path:${location.path}`)
);
return;
}
}
// Create new pending route
this._pendingRoute = createRoute(location, matches);
// Resolve redirect
if (this._pendingRoute.redirect != null) {
this.resolveRedirect(this._pendingRoute.redirect, onComplete, onAbort);
return;
}
// Skip the same location
if (this._currentRoute
&& this._pendingRoute.fullPath == this._currentRoute.fullPath) {
this._pendingRoute = null;
if (onComplete != null) {
onComplete();
}
return;
}
Object.freeze(this._currentRoute);
Object.freeze(this._pendingRoute);
// Notify all before navigation listeners
this.notifyOnBeforeNavigation(
Object.freeze(cloneRoute(this._currentRoute as Route)),
Object.freeze(cloneRoute(this._pendingRoute as Route))
);
// Resolve navigation guards
this.resolveNavigationGuard(0, onComplete, onAbort);
}
/**
* Match route by path, recursively.
* @param {string} path Base path without query or hash.
* @param {RouteConfig[]} routes All routes.
* @param {Record[]} matches Matched routes.
* @return {boolean}
*/
private matchRoute(
path: string,
routes: RouteConfig[],
matches: Record[]): boolean {
for (let i = 0; i < routes.length; i++) {
const match = routes[i].matcher.exec(path);
if (match) {
matches.push(createRouteRecord(routes[i], match));
// Final route
if (routes[i].children.length == 0) {
return true;
}
// Segment
if (this.matchRoute(path, routes[i].children, matches)) {
return true;
} else {
matches.pop();
}
}
}
return false;
}
/**
* Find route by name, recursively.
* @param {string} name Name of the route.
* @param {RouteConfig[]} routes Route config collection.
* @return {RouteConfig|null}
*/
private findRouteByName(
name: string,
routes: RouteConfig[]): RouteConfig | null {
for (let i = 0; i < routes.length; i++) {
if (routes[i].name == name) {
return routes[i];
}
const match = this.findRouteByName(name, routes[i].children);
if (match != null) {
return match;
}
}
return null;
}
/**
* Resolve pending route redirect.
* @param {function|object|string} redirect Redirect resolver.
* @param {function?} onComplete On complete callback.
* @param {function?} onAbort On abort callback.
*/
private resolveRedirect(
redirect: routeRedirect,
onComplete: undefined | (() => void),
onAbort: undefined | (() => void)): void {
// Function
if (tc.isFunction(redirect)) {
redirect =
(redirect as (to: Route) => string)(this._pendingRoute as Route);
}
// External
if (tc.isString(redirect) && hasPrefix(redirect as string, 'http')) {
window.location.replace(redirect as string);
return;
}
// URL or Route object
this._pendingRoute = null;
this.push(tc.isString(redirect)
? redirect as string
: redirect as RawLocation,
onComplete, onAbort);
}
/**
* Resolve each navigation guard on the given index
* It executes the navigation guard function, chained by calling of
* the next function.
* @param {number} index Index of the navigation guard, defaults to 0.
* @param {function?} onComplete On complete callback.
* @param {function?} onAbort On abort callback.
*/
private resolveNavigationGuard(
index = 0,
onComplete: undefined | (() => void),
onAbort: undefined | (() => void)): void {
// There are no other guards
// finish the navigation change
if (index >= this._navigationGuards.length) {
this.finishNavigationChange(onComplete, onAbort);
return;
}
// Abort the pending route
const abort = (err: Error | null = null): void => {
this._pendingRoute = null;
if (onAbort) {
onAbort();
}
if (err != null) {
this.notifyOnError(
new Error(`navigation guard error, ${err.toString()}`)
);
}
// Revert history if needed
if (this._currentRoute != null &&
(historyFullURL(this._history.location) != this._currentRoute.fullPath)) {
this._history.push(this._currentRoute.fullPath);
}
};
// Execute the navigation guard and wait for the next callback
this._navigationGuards[index].guard(
this._currentRoute,
this._pendingRoute,
(next: navigationGuardNextAction) => {
// Continue to next guard
if (next == undefined) {
this.resolveNavigationGuard(++index, onComplete, onAbort);
// Cancel the route change
} else if (next === false) {
abort();
// Error
} else if (tc.isError(next)) {
abort(next as Error);
// Go to different route
} else if (tc.isString(next) || tc.isObject(next)) {
this._pendingRoute = null;
this.push(next as string, onComplete, onAbort);
// Unexpected next
} else {
abort(new Error(`unexpected next(val) value.`));
}
});
}
/**
* Notify all onError listeners
* @param {Error} error
*/
private notifyOnError(error: Error): void {
for (const callback of this._listeners.onError.values()) {
callback(error);
}
}
/**
* Notify all onBeforeNavigation listeners
* @param {Route} from Current route.
* @param {Route} to Resolved route.
*/
private notifyOnBeforeNavigation(from: Route, to: Route): void {
for (const callback of this._listeners.onBeforeNavigation.values()) {
callback(from, to);
}
}
/**
* Notify all onNavigationChanged listeners
* @param {Route} from Current route.
* @param {Route} to Resolved route.
*/
private notifyOnNavigationChanged(from: Route, to: Route): void {
for (const callback of this._listeners.onNavigationChanged.values()) {
callback(from, to);
}
}
/**
* Update the current route and update the navigation history
* to complete the route change.
* @param {function?} onComplete On complete callback.
* @param {function?} onAbort On abort callback.
*/
private finishNavigationChange(
onComplete?: () => void,
onAbort?: () => void): void {
if (this._pendingRoute == null) {
throw new Error('navigation cannot be finished, missing pending route');
}
const asyncPending: object[] = [];
for (const r of this._pendingRoute.matched) {
if (r.async == false) {
continue;
}
if (this._asyncViews.has(r.id) == false) {
asyncPending.push(new Promise((resolve, reject): void => {
(r.component as Promise<componentModule>)
.then((m) => resolve({id: r.id, component: m.default}))
.catch((e) => reject(e));
}));
}
}
// After all components are resolved.
const afterResolved = (): void => {
if (this._pendingRoute == null) {
throw new Error('navigation cannot be finished, missing pending route');
}
// Get the resolved components for async views
for (const r of this._pendingRoute.matched) {
if (r.async == false) {
continue;
}
r.component = this._asyncViews.get(r.id) as () => object;
}
// notify all listeners and update the history
this.notifyOnNavigationChanged(
Object.freeze(cloneRoute(this._currentRoute as Route)),
Object.freeze(cloneRoute(this._pendingRoute as Route))
);
this._currentRoute = cloneRoute(this._pendingRoute as Route);
this._pendingRoute = null;
// Resolve history update if needed
if (historyFullURL(this._history.location)
!= this._currentRoute.fullPath) {
// Push
if (this._currentRoute.action == HISTORY_ACTION.PUSH) {
this._history.push(this._currentRoute.fullPath);
// Replace
} else if (this._currentRoute.action == HISTORY_ACTION.REPLACE) {
this._history.replace(this._currentRoute.fullPath);
}
}
if (onComplete != null) {
onComplete();
}
};
// Resolve lazy loaded async components
if (asyncPending.length > 0) {
Promise.all(asyncPending).then((views) => {
for (const v of views) {
const view = v as {id: symbol; component: () => object};
this._asyncViews.set(view.id, view.component);
}
afterResolved();
}).catch((e) => {
this.notifyOnError(
new Error(`failed to load async error, ${e.toString()}`)
);
if (onAbort != null) {
onAbort();
}
});
// No pending async components
} else {
afterResolved();
}
}
/**
* Remove navigation guard.
* @param {symbol} key Navigation guard key.
*/
private removeNavigationGuard(key: symbol): void {
for (let i = 0; i < this._navigationGuards.length; i++) {
if (this._navigationGuards[i].key === key) {
this._navigationGuards.splice(i, 1);
break;
}
}
}
}
export default Router; | the_stack |
import Heap from 'qheap'
import {
Capability,
FeeMarketEIP1559Transaction,
Transaction,
TypedTransaction,
} from '@ethereumjs/tx'
import { Address, BN } from 'ethereumjs-util'
import { Config } from '../config'
import { Peer } from '../net/peer'
import { EthProtocolMethods } from '../net/protocol'
import type { PeerPool } from '../net/peerpool'
import type { Block } from '@ethereumjs/block'
import type { StateManager } from '@ethereumjs/vm/dist/state'
export interface TxPoolOptions {
/* Config */
config: Config
/* Return number of connected peers for stats logging */
getPeerCount?: () => number
}
type TxPoolObject = {
tx: TypedTransaction
hash: UnprefixedHash
added: number
}
type HandledObject = {
address: UnprefixedAddress
added: number
}
type SentObject = {
hash: UnprefixedHash
added: number
}
type UnprefixedAddress = string
type UnprefixedHash = string
type PeerId = string
/**
* @module service
*/
/**
* Tx pool (mempool)
* @memberof module:service
*/
export class TxPool {
public config: Config
public running: boolean
private opened: boolean
private getPeerCount?: () => number
/* global NodeJS */
private _logInterval: NodeJS.Timeout | undefined
/**
* List of pending tx hashes to avoid double requests
*/
private pending: UnprefixedHash[] = []
/**
* The central pool dataset.
*
* Maps an address to a `TxPoolObject`
*/
public pool: Map<UnprefixedAddress, TxPoolObject[]>
/**
* Map for handled tx hashes
* (have been added to the pool at some point)
*
* This is meant to be a superset of the tx pool
* so at any point it time containing minimally
* all txs from the pool.
*/
private handled: Map<UnprefixedHash, HandledObject>
/**
* Map for tx hashes a peer is already aware of
* (so no need to re-broadcast)
*/
private knownByPeer: Map<PeerId, SentObject[]>
/**
* Activate before chain head is reached to start
* tx pool preparation (sorting out included txs)
*/
public BLOCKS_BEFORE_TARGET_HEIGHT_ACTIVATION = 20
/**
* Max number of txs to request
*/
private TX_RETRIEVAL_LIMIT = 256
/**
* Number of minutes to keep txs in the pool
*/
public POOLED_STORAGE_TIME_LIMIT = 20
/**
* Number of minutes to forget about handled
* txs (for cleanup/memory reasons)
*/
public HANDLED_CLEANUP_TIME_LIMIT = 60
/**
* Rebroadcast full txs and new blocks to a fraction
* of peers by doing
* `min(1, floor(NUM_PEERS/NUM_PEERS_REBROADCAST_QUOTIENT))`
*/
public NUM_PEERS_REBROADCAST_QUOTIENT = 4
/**
* Log pool statistics on the given interval
*/
private LOG_STATISTICS_INTERVAL = 10000 // ms
/**
* Create new tx pool
* @param options constructor parameters
*/
constructor(options: TxPoolOptions) {
this.config = options.config
this.getPeerCount = options.getPeerCount
this.pool = new Map<UnprefixedAddress, TxPoolObject[]>()
this.handled = new Map<UnprefixedHash, HandledObject>()
this.knownByPeer = new Map<PeerId, SentObject[]>()
this.opened = false
this.running = false
}
/**
* Open pool
*/
open(): boolean {
if (this.opened) {
return false
}
this.opened = true
return true
}
/**
* Start tx processing
*/
start(): boolean {
if (this.running) {
return false
}
this._logInterval = setInterval(this._logPoolStats.bind(this), this.LOG_STATISTICS_INTERVAL)
this.running = true
this.config.logger.info('TxPool started.')
return true
}
/**
* Adds a tx to the pool.
*
* If there is a tx in the pool with the same address and
* nonce it will be replaced by the new tx.
* @param tx Transaction
*/
add(tx: TypedTransaction) {
const sender: UnprefixedAddress = tx.getSenderAddress().toString().slice(2)
const inPool = this.pool.get(sender)
let add: TxPoolObject[] = []
if (inPool) {
// Replace pooled txs with the same nonce
add = inPool.filter((poolObj) => !poolObj.tx.nonce.eq(tx.nonce))
}
const address: UnprefixedAddress = tx.getSenderAddress().toString().slice(2)
const hash: UnprefixedHash = tx.hash().toString('hex')
const added = Date.now()
add.push({ tx, added, hash })
this.pool.set(address, add)
this.handled.set(hash, { address, added })
}
/**
* Returns the available txs from the pool
* @param txHashes
* @returns Array with tx objects
*/
getByHash(txHashes: Buffer[]): TypedTransaction[] {
const found = []
for (const txHash of txHashes) {
const txHashStr = txHash.toString('hex')
const handled = this.handled.get(txHashStr)
if (!handled) {
continue
}
const inPool = this.pool.get(handled.address)?.filter((poolObj) => poolObj.hash === txHashStr)
if (inPool && inPool.length === 1) {
found.push(inPool[0].tx)
}
}
return found
}
/**
* Removes the given tx from the pool
* @param txHash Hash of the transaction
*/
removeByHash(txHash: UnprefixedHash) {
if (!this.handled.has(txHash)) {
return
}
const address = this.handled.get(txHash)!.address
if (!this.pool.has(address)) {
return
}
const newPoolObjects = this.pool.get(address)!.filter((poolObj) => poolObj.hash !== txHash)
if (newPoolObjects.length === 0) {
// List of txs for address is now empty, can delete
this.pool.delete(address)
} else {
// There are more txs from this address
this.pool.set(address, newPoolObjects)
}
}
/**
* Adds passed in txs to the map keeping track
* of tx hashes known by a peer.
* @param txHashes
* @param peer
* @returns Array with txs which are new to the list
*/
addToKnownByPeer(txHashes: Buffer[], peer: Peer): Buffer[] {
// Make sure data structure is initialized
if (!this.knownByPeer.has(peer.id)) {
this.knownByPeer.set(peer.id, [])
}
const newHashes: Buffer[] = []
for (const hash of txHashes) {
const inSent = this.knownByPeer
.get(peer.id)!
.filter((sentObject) => sentObject.hash === hash.toString('hex')).length
if (inSent === 0) {
const added = Date.now()
const add = {
hash: hash.toString('hex'),
added,
}
this.knownByPeer.get(peer.id)!.push(add)
newHashes.push(hash)
}
}
return newHashes
}
/**
* Send (broadcast) tx hashes from the pool to connected
* peers.
*
* Double sending is avoided by compare towards the
* `SentTxHashes` map.
* @param txHashes Array with transactions to send
* @param peers
*/
async sendNewTxHashes(txHashes: Buffer[], peers: Peer[]) {
for (const peer of peers) {
// Make sure data structure is initialized
if (!this.knownByPeer.has(peer.id)) {
this.knownByPeer.set(peer.id, [])
}
// Add to known tx hashes and get hashes still to send to peer
const hashesToSend = this.addToKnownByPeer(txHashes, peer)
// Broadcast to peer if at least 1 new tx hash to announce
if (hashesToSend.length > 0) {
peer.eth?.send('NewPooledTransactionHashes', hashesToSend)
}
}
}
/**
* Send transactions to other peers in the peer pool
*
* Note that there is currently no data structure to avoid
* double sending to a peer, so this has to be made sure
* by checking on the context the sending is performed.
* @param txs Array with transactions to send
* @param peers
*/
sendTransactions(txs: TypedTransaction[], peers: Peer[]) {
if (txs.length > 0) {
const hashes = txs.map((tx) => tx.hash())
for (const peer of peers) {
// This is used to avoid re-sending along pooledTxHashes
// announcements/re-broadcasts
this.addToKnownByPeer(hashes, peer)
peer.eth?.send('Transactions', txs)
}
}
}
/**
* Include new announced txs in the pool
* and re-broadcast to other peers
* @param txs
* @param peer Announcing peer
* @param peerPool Reference to the {@link PeerPool}
*/
async handleAnnouncedTxs(txs: TypedTransaction[], peer: Peer, peerPool: PeerPool) {
if (!this.running || txs.length === 0) {
return
}
this.config.logger.debug(`TxPool: received new transactions number=${txs.length}`)
this.addToKnownByPeer(
txs.map((tx) => tx.hash()),
peer
)
this.cleanup()
const newTxHashes = []
for (const tx of txs) {
this.add(tx)
newTxHashes.push(tx.hash())
}
const peers = peerPool.peers
const numPeers = peers.length
const sendFull = Math.min(1, Math.floor(numPeers / this.NUM_PEERS_REBROADCAST_QUOTIENT))
this.sendTransactions(txs, peers.slice(0, sendFull))
await this.sendNewTxHashes(newTxHashes, peers.slice(sendFull))
}
/**
* Request new pooled txs from tx hashes announced and include them in the pool
* and re-broadcast to other peers
* @param txHashes new tx hashes announced
* @param peer Announcing peer
* @param peerPool Reference to the peer pool
*/
async handleAnnouncedTxHashes(txHashes: Buffer[], peer: Peer, peerPool: PeerPool) {
if (!this.running || txHashes.length === 0) {
return
}
this.config.logger.debug(`TxPool: received new pooled hashes number=${txHashes.length}`)
this.addToKnownByPeer(txHashes, peer)
this.cleanup()
const reqHashes = []
for (const txHash of txHashes) {
const txHashStr: UnprefixedHash = txHash.toString('hex')
if (this.pending.includes(txHashStr) || this.handled.has(txHashStr)) {
continue
}
reqHashes.push(txHash)
}
if (reqHashes.length === 0) {
return
}
const reqHashesStr: UnprefixedHash[] = reqHashes.map((hash) => hash.toString('hex'))
this.pending.concat(reqHashesStr)
this.config.logger.debug(
`TxPool: requesting txs number=${reqHashes.length} pending=${this.pending.length}`
)
const [_, txs] = await (peer!.eth as EthProtocolMethods).getPooledTransactions({
hashes: reqHashes.slice(0, this.TX_RETRIEVAL_LIMIT),
})
this.config.logger.debug(`TxPool: received requested txs number=${txs.length}`)
// Remove from pending list regardless if tx is in result
for (const reqHashStr of reqHashesStr) {
this.pending = this.pending.filter((hash) => hash !== reqHashStr)
}
const newTxHashes = []
for (const tx of txs) {
this.add(tx)
newTxHashes.push(tx.hash())
}
await this.sendNewTxHashes(newTxHashes, peerPool.peers)
}
/**
* Remove txs included in the latest blocks from the tx pool
*/
removeNewBlockTxs(newBlocks: Block[]) {
if (!this.running) {
return
}
for (const block of newBlocks) {
for (const tx of block.transactions) {
const txHash: UnprefixedHash = tx.hash().toString('hex')
this.removeByHash(txHash)
}
}
}
/**
* Regular tx pool cleanup
*/
cleanup() {
// Remove txs older than POOLED_STORAGE_TIME_LIMIT from the pool
// as well as the list of txs being known by a peer
let compDate = Date.now() - this.POOLED_STORAGE_TIME_LIMIT * 60
for (const mapToClean of [this.pool, this.knownByPeer]) {
mapToClean.forEach((objects, key) => {
const updatedObjects = objects.filter((obj) => obj.added >= compDate)
if (updatedObjects.length < objects.length) {
if (updatedObjects.length === 0) {
mapToClean.delete(key)
} else {
mapToClean.set(key, updatedObjects)
}
}
})
}
// Cleanup handled txs
compDate = Date.now() - this.HANDLED_CLEANUP_TIME_LIMIT * 60
this.handled.forEach((handleObj, address) => {
if (handleObj.added < compDate) {
this.handled.delete(address)
}
})
}
/**
* Helper to return a normalized gas price across different
* transaction types. Providing the baseFee param returns the
* priority tip, and omitting it returns the max total fee.
* @param tx The tx
* @param baseFee Provide a baseFee to subtract from the legacy
* gasPrice to determine the leftover priority tip.
*/
private txGasPrice(tx: TypedTransaction, baseFee?: BN) {
const supports1559 = tx.supports(Capability.EIP1559FeeMarket)
if (baseFee) {
if (supports1559) {
return (tx as FeeMarketEIP1559Transaction).maxPriorityFeePerGas
} else {
return (tx as Transaction).gasPrice.sub(baseFee)
}
} else {
if (supports1559) {
return (tx as FeeMarketEIP1559Transaction).maxFeePerGas
} else {
return (tx as Transaction).gasPrice
}
}
}
/**
* Returns eligible txs to be mined sorted by price in such a way that the
* nonce orderings within a single account are maintained.
*
* Note, this is not as trivial as it seems from the first look as there are three
* different criteria that need to be taken into account (price, nonce, account
* match), which cannot be done with any plain sorting method, as certain items
* cannot be compared without context.
*
* This method first sorts the separates the list of transactions into individual
* sender accounts and sorts them by nonce. After the account nonce ordering is
* satisfied, the results are merged back together by price, always comparing only
* the head transaction from each account. This is done via a heap to keep it fast.
*
* @param stateManager Account nonces are queried to only include executable txs
* @param baseFee Provide a baseFee to exclude txs with a lower gasPrice
*/
async txsByPriceAndNonce(stateManager: StateManager, baseFee?: BN) {
const txs: TypedTransaction[] = []
// Separate the transactions by account and sort by nonce
const byNonce = new Map<string, TypedTransaction[]>()
for (const [address, poolObjects] of this.pool) {
let txsSortedByNonce = poolObjects
.map((obj) => obj.tx)
.sort((a, b) => a.nonce.sub(b.nonce).toNumber())
// Check if the account nonce matches the lowest known tx nonce
const { nonce } = await stateManager.getAccount(new Address(Buffer.from(address, 'hex')))
if (!txsSortedByNonce[0].nonce.eq(nonce)) {
// Account nonce does not match the lowest known tx nonce,
// therefore no txs from this address are currently exectuable
continue
}
if (baseFee) {
// If any tx has an insiffucient gasPrice,
// remove all txs after that since they cannot be executed
const found = txsSortedByNonce.findIndex((tx) => this.txGasPrice(tx).lt(baseFee))
if (found > -1) {
txsSortedByNonce = txsSortedByNonce.slice(0, found)
}
}
byNonce.set(address, txsSortedByNonce)
}
// Initialize a price based heap with the head transactions
const byPrice = new Heap<TypedTransaction>({
comparBefore: (a: TypedTransaction, b: TypedTransaction) =>
this.txGasPrice(b, baseFee).sub(this.txGasPrice(a, baseFee)).ltn(0),
})
byNonce.forEach((txs, address) => {
byPrice.insert(txs[0])
byNonce.set(address, txs.slice(1))
})
// Merge by replacing the best with the next from the same account
while (byPrice.length > 0) {
// Retrieve the next best transaction by price
const best = byPrice.remove()
if (!best) break
// Push in its place the next transaction from the same account
const address = best.getSenderAddress().toString().slice(2)
const accTxs = byNonce.get(address)!
if (accTxs.length > 0) {
byPrice.insert(accTxs[0])
byNonce.set(address, accTxs.slice(1))
}
// Accumulate the best priced transaction
txs.push(best)
}
return txs
}
/**
* Stop pool execution
*/
stop(): boolean {
if (!this.running) {
return false
}
clearInterval(this._logInterval as NodeJS.Timeout)
this.running = false
this.config.logger.info('TxPool stopped.')
return true
}
/**
* Close pool
*/
close() {
this.pool.clear()
this.opened = false
}
_logPoolStats() {
let count = 0
this.pool.forEach((poolObjects) => {
count += poolObjects.length
})
this.config.logger.info(
`TxPool Statistics txs=${count} senders=${this.pool.size} peers=${this.getPeerCount?.() ?? 0}`
)
}
} | the_stack |
import { createElement } from '@syncfusion/ej2-base';
import { Diagram } from '../../../src/diagram/diagram';
import { DiagramElement } from '../../../src/diagram/core/elements/diagram-element';
import { ConnectorModel } from '../../../src/diagram/objects/connector-model';
import {profile , inMB, getMemoryProfile} from '../../../spec/common.spec';
/**
* Connector Annotations
*/
describe('Diagram Control', () => {
describe('Straight segment annotation with offset 0', () => {
let diagram: Diagram;
let ele: HTMLElement;
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagramk1' });
document.body.appendChild(ele);
let connector1: ConnectorModel = {
id: 'connector1',
type: 'Straight',
sourcePoint: { x: 100, y: 100 },
targetPoint: { x: 200, y: 100 },
annotations: [{ 'content': 'label', 'offset': 0, 'alignment': 'Center' }]
};
let connector2: ConnectorModel = {
id: 'connector2',
type: 'Straight',
sourcePoint: { x: 300, y: 100 },
targetPoint: { x: 400, y: 100 },
annotations: [{ 'content': 'label', 'offset': 0, 'alignment': 'Before' }]
};
let connector3: ConnectorModel = {
id: 'connector3',
type: 'Straight',
sourcePoint: { x: 500, y: 100 },
targetPoint: { x: 600, y: 100 },
annotations: [{ 'content': 'label', 'offset': 0, 'alignment': 'After' }]
};
diagram = new Diagram({ width: 1000, height: 1000, connectors: [connector1, connector2, connector3] });
diagram.appendTo('#diagramk1');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Checking annotation alignment with offset 0', (done: Function) => {
let element1: DiagramElement = diagram.connectors[0].wrapper.children[3];
let element2: DiagramElement = diagram.connectors[1].wrapper.children[3];
let element3: DiagramElement = diagram.connectors[2].wrapper.children[3];
expect((Math.round(element1.offsetX) === 113 || Math.round(element1.offsetX) >= 111 || Math.round(element1.offsetX) <= 116) && Math.round(element1.offsetY) === 100 &&
(Math.round(element2.offsetX) === 313 || Math.round(element2.offsetX) >= 311 || Math.round(element2.offsetX) <= 316) && Math.round(element2.offsetY) === 93 &&
(Math.round(element3.offsetX) === 513 || Math.round(element3.offsetX) >= 511 || Math.round(element3.offsetX) <= 516) && Math.round(element3.offsetY) === 107).toBe(true);
done();
});
it('Checking annotation alignment with offset 0.5', (done: Function) => {
diagram.connectors[0].annotations[0].offset = 0.5;
diagram.connectors[1].annotations[0].offset = 0.5;
diagram.connectors[2].annotations[0].offset = 0.5;
diagram.dataBind();
let element1: DiagramElement = diagram.connectors[0].wrapper.children[3];
let element2: DiagramElement = diagram.connectors[1].wrapper.children[3];
let element3: DiagramElement = diagram.connectors[2].wrapper.children[3];
expect(Math.round(element1.offsetX) === 150 && Math.round(element1.offsetY) === 100 &&
Math.round(element2.offsetX) === 350 && Math.round(element2.offsetY) === 93 &&
Math.round(element3.offsetX) === 550 && Math.round(element3.offsetY) === 107).toBe(true);
done();
});
it('Checking annotation alignment with offset 1', (done: Function) => {
diagram.connectors[0].annotations[0].offset = 1;
diagram.connectors[1].annotations[0].offset = 1;
diagram.connectors[2].annotations[0].offset = 1;
diagram.dataBind();
let element1: DiagramElement = diagram.connectors[0].wrapper.children[3];
let element2: DiagramElement = diagram.connectors[1].wrapper.children[3];
let element3: DiagramElement = diagram.connectors[2].wrapper.children[3];
expect((Math.round(element1.offsetX) === 187 || Math.round(element1.offsetX) >= 185 || Math.round(element1.offsetX) <= 189) && Math.round(element1.offsetY) === 100 &&
(Math.round(element2.offsetX) === 387 || Math.round(element2.offsetX) >= 385 || Math.round(element2.offsetX) <= 389) && Math.round(element2.offsetY) === 93 &&
(Math.round(element3.offsetX) === 587 || Math.round(element3.offsetX) >= 585 || Math.round(element3.offsetX) <= 589) && Math.round(element3.offsetY) === 107).toBe(true);
done();
});
it('Checking alignment, offset 0, for slanting connector', (done: Function) => {
diagram.connectors[0].targetPoint = { x: 200, y: 200 };
diagram.connectors[1].targetPoint = { x: 400, y: 200 };
diagram.connectors[2].targetPoint = { x: 600, y: 200 };
diagram.connectors[0].annotations[0].offset = 0;
diagram.connectors[1].annotations[0].offset = 0;
diagram.connectors[2].annotations[0].offset = 0;
diagram.dataBind();
let element1: DiagramElement = diagram.connectors[0].wrapper.children[3];
let element2: DiagramElement = diagram.connectors[1].wrapper.children[3];
let element3: DiagramElement = diagram.connectors[2].wrapper.children[3];
expect(Math.round(element1.offsetX) === 100 && Math.round(element1.offsetY) === 107 &&
(Math.round(element2.offsetX) === 287 || Math.round(element2.offsetX) >= 285 || Math.round(element2.offsetX) <= 289) && Math.round(element2.offsetY) === 107 &&
(Math.round(element3.offsetX) === 513 || Math.round(element3.offsetX) >= 511 || Math.round(element3.offsetX) <= 515) && Math.round(element3.offsetY) === 107).toBe(true);
done();
});
it('Checking alignment, offset 0.5, for slanting connector', (done: Function) => {
diagram.connectors[0].annotations[0].offset = 0.5;
diagram.connectors[1].annotations[0].offset = 0.5;
diagram.connectors[2].annotations[0].offset = 0.5;
diagram.dataBind();
let element1: DiagramElement = diagram.connectors[0].wrapper.children[3];
let element2: DiagramElement = diagram.connectors[1].wrapper.children[3];
let element3: DiagramElement = diagram.connectors[2].wrapper.children[3];
expect(Math.round(element1.offsetX) === 150 && Math.round(element1.offsetY) === 150 &&
(Math.round(element2.offsetX) === 337 || Math.round(element2.offsetX) >= 335 || Math.round(element2.offsetX) <= 339) && Math.round(element2.offsetY) === 150 &&
(Math.round(element3.offsetX) === 563 || Math.round(element3.offsetX) >= 561 || Math.round(element3.offsetX) <= 566) && Math.round(element3.offsetY) === 150).toBe(true);
done();
});
it('Checking alignment, offset 1, for slanting connector', (done: Function) => {
diagram.connectors[0].annotations[0].offset = 1;
diagram.connectors[1].annotations[0].offset = 1;
diagram.connectors[2].annotations[0].offset = 1;
diagram.dataBind();
let element1: DiagramElement = diagram.connectors[0].wrapper.children[3];
let element2: DiagramElement = diagram.connectors[1].wrapper.children[3];
let element3: DiagramElement = diagram.connectors[2].wrapper.children[3];
expect(Math.round(element1.offsetX) === 200 && Math.round(element1.offsetY) === 193 &&
(Math.round(element2.offsetX) === 387 || Math.round(element2.offsetX) >= 385 || Math.round(element2.offsetX) <= 389) && Math.round(element2.offsetY) === 193 &&
(Math.round(element3.offsetX) === 613 || Math.round(element3.offsetX) >= 611 || Math.round(element3.offsetX) <= 617) && Math.round(element3.offsetY) === 193).toBe(true);
done();
});
it('Checking alignment, offset 0, for orthogonal connector', (done: Function) => {
diagram.connectors[0].type = 'Orthogonal';
diagram.connectors[1].type = 'Orthogonal';
diagram.connectors[2].type = 'Orthogonal';
diagram.connectors[0].annotations[0].offset = 0;
diagram.connectors[1].annotations[0].offset = 0;
diagram.connectors[2].annotations[0].offset = 0;
diagram.dataBind();
let element1: DiagramElement = diagram.connectors[0].wrapper.children[3];
let element2: DiagramElement = diagram.connectors[1].wrapper.children[3];
let element3: DiagramElement = diagram.connectors[2].wrapper.children[3];
expect(Math.round(element1.offsetX) === 100 && Math.round(element1.offsetY) === 107 &&
(Math.round(element2.offsetX) === 287 || Math.round(element2.offsetX) >= 285 || Math.round(element2.offsetX) <= 289) && Math.round(element2.offsetY) === 107 &&
(Math.round(element3.offsetX) === 513 || Math.round(element3.offsetX) >= 511 || Math.round(element3.offsetX) <= 515) && Math.round(element3.offsetY) === 107).toBe(true);
done();
});
it('Checking alignment, offset 0.5, for orthogonal connector', (done: Function) => {
diagram.connectors[0].annotations[0].offset = 0.5;
diagram.connectors[1].annotations[0].offset = 0.5;
diagram.connectors[2].annotations[0].offset = 0.5;
diagram.dataBind();
let element1: DiagramElement = diagram.connectors[0].wrapper.children[3];
let element2: DiagramElement = diagram.connectors[1].wrapper.children[3];
let element3: DiagramElement = diagram.connectors[2].wrapper.children[3];
expect(Math.round(element1.offsetX) === 180 && Math.round(element1.offsetY) === 120 &&
Math.round(element2.offsetX) === 380 && Math.round(element2.offsetY) === 113 &&
Math.round(element3.offsetX) === 580 && Math.round(element3.offsetY) === 127).toBe(true);
done();
});
it('Checking alignment, offset 1, for orthogonal connector', (done: Function) => {
diagram.connectors[0].annotations[0].offset = 1;
diagram.connectors[1].annotations[0].offset = 1;
diagram.connectors[2].annotations[0].offset = 1;
diagram.dataBind();
let element1: DiagramElement = diagram.connectors[0].wrapper.children[3];
let element2: DiagramElement = diagram.connectors[1].wrapper.children[3];
let element3: DiagramElement = diagram.connectors[2].wrapper.children[3];
expect(Math.round(element1.offsetX) === 200 && Math.round(element1.offsetY) === 193 &&
(Math.round(element2.offsetX) === 387 || Math.round(element2.offsetX) >= 385 || Math.round(element2.offsetX) <= 389) && Math.round(element2.offsetY) === 193 &&
(Math.round(element3.offsetX) === 613 || Math.round(element3.offsetX) >= 611 || Math.round(element3.offsetX) <= 615) && Math.round(element3.offsetY) === 193).toBe(true);
done();
});
it('Checking alignment, offset 0, for reverse straight connector', (done: Function) => {
diagram.connectors[0].sourcePoint = { x: 200, y: 100 };
diagram.connectors[1].sourcePoint = { x: 400, y: 100 };
diagram.connectors[2].sourcePoint = { x: 600, y: 100 };
diagram.connectors[0].targetPoint = { x: 100, y: 100 };
diagram.connectors[1].targetPoint = { x: 300, y: 100 };
diagram.connectors[2].targetPoint = { x: 500, y: 100 };
diagram.connectors[0].annotations[0].offset = 0;
diagram.connectors[1].annotations[0].offset = 0;
diagram.connectors[2].annotations[0].offset = 0;
diagram.connectors[0].type = 'Straight';
diagram.connectors[1].type = 'Straight';
diagram.connectors[2].type = 'Straight';
diagram.dataBind();
let element1: DiagramElement = diagram.connectors[0].wrapper.children[3];
let element2: DiagramElement = diagram.connectors[1].wrapper.children[3];
let element3: DiagramElement = diagram.connectors[2].wrapper.children[3];
expect((Math.round(element1.offsetX) === 187 || Math.round(element1.offsetX) >= 185 || Math.round(element1.offsetX) <= 188) && Math.round(element1.offsetY) === 100 &&
(Math.round(element2.offsetX) === 387 || Math.round(element2.offsetX) >= 385 || Math.round(element2.offsetX) <= 388) && Math.round(element2.offsetY) === 107 &&
(Math.round(element3.offsetX) === 587 || Math.round(element3.offsetX) >= 585 || Math.round(element3.offsetX) <= 588) && Math.round(element3.offsetY) === 93).toBe(true);
done();
});
it('Checking alignment, offset 0.5, for reverse straight connector', (done: Function) => {
diagram.connectors[0].annotations[0].offset = 0.5;
diagram.connectors[1].annotations[0].offset = 0.5;
diagram.connectors[2].annotations[0].offset = 0.5;
diagram.dataBind();
let element1: DiagramElement = diagram.connectors[0].wrapper.children[3];
let element2: DiagramElement = diagram.connectors[1].wrapper.children[3];
let element3: DiagramElement = diagram.connectors[2].wrapper.children[3];
expect(Math.round(element1.offsetX) === 150 && Math.round(element1.offsetY) === 100 &&
Math.round(element2.offsetX) === 350 && Math.round(element2.offsetY) === 107 &&
Math.round(element3.offsetX) === 550 && Math.round(element3.offsetY) === 93).toBe(true);
done();
});
it('Checking alignment, offset 1, for reverse straight connector', (done: Function) => {
diagram.connectors[0].annotations[0].offset = 1;
diagram.connectors[1].annotations[0].offset = 1;
diagram.connectors[2].annotations[0].offset = 1;
diagram.dataBind();
let element1: DiagramElement = diagram.connectors[0].wrapper.children[3];
let element2: DiagramElement = diagram.connectors[1].wrapper.children[3];
let element3: DiagramElement = diagram.connectors[2].wrapper.children[3];
expect(Math.round(element1.offsetX) === 113 || 112.671875 && Math.round(element1.offsetY) === 100 &&
Math.round(element2.offsetX) === 313 || 312.671875 && Math.round(element2.offsetY) === 106 || 107.2 &&
Math.round(element3.offsetX) === 513 || 512.671875 && Math.round(element3.offsetY) === 93 || 92.8).toBe(true);
done();
});
it('Checking alignment, offset 0, for reverse slanting connector', (done: Function) => {
diagram.connectors[0].sourcePoint = { x: 200, y: 200 };
diagram.connectors[1].sourcePoint = { x: 400, y: 200 };
diagram.connectors[2].sourcePoint = { x: 600, y: 200 };
diagram.connectors[0].annotations[0].offset = 0;
diagram.connectors[1].annotations[0].offset = 0;
diagram.connectors[2].annotations[0].offset = 0;
diagram.connectors[0].type = 'Straight';
diagram.connectors[1].type = 'Straight';
diagram.connectors[2].type = 'Straight';
diagram.dataBind();
let element1: DiagramElement = diagram.connectors[0].wrapper.children[3];
let element2: DiagramElement = diagram.connectors[1].wrapper.children[3];
let element3: DiagramElement = diagram.connectors[2].wrapper.children[3];
expect(Math.round(element1.offsetX) === 200 && Math.round(element1.offsetY) === 193 &&
(Math.round(element2.offsetX) === 413 || Math.round(element2.offsetX) >= 412 || Math.round(element2.offsetX) <= 416) && Math.round(element2.offsetY) === 193 &&
(Math.round(element3.offsetX) === 587 || Math.round(element3.offsetX) >= 585 || Math.round(element3.offsetX) <= 589) && Math.round(element3.offsetY) === 193).toBe(true);
done();
});
it('Checking alignment, offset 0.5, for reverse slanting connector', (done: Function) => {
diagram.connectors[0].annotations[0].offset = 0.5;
diagram.connectors[1].annotations[0].offset = 0.5;
diagram.connectors[2].annotations[0].offset = 0.5;
diagram.dataBind();
let element1: DiagramElement = diagram.connectors[0].wrapper.children[3];
let element2: DiagramElement = diagram.connectors[1].wrapper.children[3];
let element3: DiagramElement = diagram.connectors[2].wrapper.children[3];
expect(Math.round(element1.offsetX) === 150 && Math.round(element1.offsetY) === 150 &&
(Math.round(element2.offsetX) === 363 || Math.round(element2.offsetX) >= 362 || Math.round(element2.offsetX) <= 366) && Math.round(element2.offsetY) === 150 &&
(Math.round(element3.offsetX) === 537 || Math.round(element3.offsetX) >= 535 || Math.round(element3.offsetX) <= 538) && Math.round(element3.offsetY) === 150).toBe(true);
done();
});
it('Checking alignment, offset 1, for reverse slanting connector', (done: Function) => {
diagram.connectors[0].annotations[0].offset = 1;
diagram.connectors[1].annotations[0].offset = 1;
diagram.connectors[2].annotations[0].offset = 1;
diagram.dataBind();
let element1: DiagramElement = diagram.connectors[0].wrapper.children[3];
let element2: DiagramElement = diagram.connectors[1].wrapper.children[3];
let element3: DiagramElement = diagram.connectors[2].wrapper.children[3];
expect(Math.round(element1.offsetX) === 100 && Math.round(element1.offsetY) === 107 &&
(Math.round(element2.offsetX) === 313 || Math.round(element2.offsetX) >= 312 || Math.round(element2.offsetX) <= 317) && Math.round(element2.offsetY) === 107 &&
(Math.round(element3.offsetX) === 487 || Math.round(element3.offsetX) >= 485 || Math.round(element3.offsetX) <= 488) && Math.round(element3.offsetY) === 107).toBe(true);
done();
});
it('checking the displacement of the connector', (done: Function) => {
diagram.connectors[0].type = 'Orthogonal';
diagram.dataBind();
diagram.connectors[0].annotations[0].displacement.x = 15;
diagram.connectors[0].annotations[0].displacement.y = 15;
diagram.dataBind();
expect(diagram.connectors[0].wrapper.children[3].offsetX === 100 &&
diagram.connectors[0].wrapper.children[3].offsetY === 122.2).toBe(true);
done();
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
})
});
}); | the_stack |
* @packageDocumentation
* @module Voice
* @publicapi
* @internal
*/
/**
* This is a generated file. Any modifications here will be overwritten. See scripts/errors.js.
*/
import TwilioError from './twilioError';
export { TwilioError };
// TypeScript doesn't allow extending Error so we need to run constructor logic on every one of these
// individually. Ideally this logic would be run in a constructor on a TwilioError class but
// due to this limitation TwilioError is an interface.
// https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes
function construct(context: TwilioError, messageOrError?: string | Error, originalError?: Error) {
if (typeof messageOrError === 'string') {
context.message = messageOrError;
if (originalError instanceof Error) {
context.originalError = originalError;
}
} else if (messageOrError instanceof Error) {
context.originalError = messageOrError;
}
}
export namespace AuthorizationErrors {
export class AccessTokenInvalid extends Error implements TwilioError {
causes: string[] = [];
code: number = 20101;
description: string = 'Invalid access token';
explanation: string = 'Twilio was unable to validate your Access Token';
solutions: string[] = [];
constructor();
constructor(message: string);
constructor(originalError: Error);
constructor(message: string, originalError?: Error);
constructor(messageOrError?: string | Error, originalError?: Error) {
super('');
Object.setPrototypeOf(this, AuthorizationErrors.AccessTokenInvalid.prototype);
construct(this, messageOrError, originalError);
}
}
export class AccessTokenExpired extends Error implements TwilioError {
causes: string[] = [];
code: number = 20104;
description: string = 'Access token expired or expiration date invalid';
explanation: string = 'The Access Token provided to the Twilio API has expired, the expiration time specified in the token was invalid, or the expiration time specified was too far in the future';
solutions: string[] = [];
constructor();
constructor(message: string);
constructor(originalError: Error);
constructor(message: string, originalError?: Error);
constructor(messageOrError?: string | Error, originalError?: Error) {
super('');
Object.setPrototypeOf(this, AuthorizationErrors.AccessTokenExpired.prototype);
construct(this, messageOrError, originalError);
}
}
export class AuthenticationFailed extends Error implements TwilioError {
causes: string[] = [];
code: number = 20151;
description: string = 'Authentication Failed';
explanation: string = 'The Authentication with the provided JWT failed';
solutions: string[] = [];
constructor();
constructor(message: string);
constructor(originalError: Error);
constructor(message: string, originalError?: Error);
constructor(messageOrError?: string | Error, originalError?: Error) {
super('');
Object.setPrototypeOf(this, AuthorizationErrors.AuthenticationFailed.prototype);
construct(this, messageOrError, originalError);
}
}
}
export namespace ClientErrors {
export class BadRequest extends Error implements TwilioError {
causes: string[] = [];
code: number = 31400;
description: string = 'Bad Request (HTTP/SIP)';
explanation: string = 'The request could not be understood due to malformed syntax.';
solutions: string[] = [];
constructor();
constructor(message: string);
constructor(originalError: Error);
constructor(message: string, originalError?: Error);
constructor(messageOrError?: string | Error, originalError?: Error) {
super('');
Object.setPrototypeOf(this, ClientErrors.BadRequest.prototype);
construct(this, messageOrError, originalError);
}
}
}
export namespace GeneralErrors {
export class UnknownError extends Error implements TwilioError {
causes: string[] = [];
code: number = 31000;
description: string = 'Unknown Error';
explanation: string = 'An unknown error has occurred. See error details for more information.';
solutions: string[] = [];
constructor();
constructor(message: string);
constructor(originalError: Error);
constructor(message: string, originalError?: Error);
constructor(messageOrError?: string | Error, originalError?: Error) {
super('');
Object.setPrototypeOf(this, GeneralErrors.UnknownError.prototype);
construct(this, messageOrError, originalError);
}
}
export class ConnectionError extends Error implements TwilioError {
causes: string[] = [];
code: number = 31005;
description: string = 'Connection error';
explanation: string = 'A connection error occurred during the call';
solutions: string[] = [];
constructor();
constructor(message: string);
constructor(originalError: Error);
constructor(message: string, originalError?: Error);
constructor(messageOrError?: string | Error, originalError?: Error) {
super('');
Object.setPrototypeOf(this, GeneralErrors.ConnectionError.prototype);
construct(this, messageOrError, originalError);
}
}
export class TransportError extends Error implements TwilioError {
causes: string[] = [];
code: number = 31009;
description: string = 'Transport error';
explanation: string = 'No transport available to send or receive messages';
solutions: string[] = [];
constructor();
constructor(message: string);
constructor(originalError: Error);
constructor(message: string, originalError?: Error);
constructor(messageOrError?: string | Error, originalError?: Error) {
super('');
Object.setPrototypeOf(this, GeneralErrors.TransportError.prototype);
construct(this, messageOrError, originalError);
}
}
}
export namespace SignalingErrors {
export class ConnectionError extends Error implements TwilioError {
causes: string[] = [];
code: number = 53000;
description: string = 'Signaling connection error';
explanation: string = 'Raised whenever a signaling connection error occurs that is not covered by a more specific error code.';
solutions: string[] = [];
constructor();
constructor(message: string);
constructor(originalError: Error);
constructor(message: string, originalError?: Error);
constructor(messageOrError?: string | Error, originalError?: Error) {
super('');
Object.setPrototypeOf(this, SignalingErrors.ConnectionError.prototype);
construct(this, messageOrError, originalError);
}
}
export class ConnectionDisconnected extends Error implements TwilioError {
causes: string[] = [
'The device running your application lost its Internet connection.',
];
code: number = 53001;
description: string = 'Signaling connection disconnected';
explanation: string = 'Raised whenever the signaling connection is unexpectedly disconnected.';
solutions: string[] = [
'Ensure the device running your application has access to a stable Internet connection.',
];
constructor();
constructor(message: string);
constructor(originalError: Error);
constructor(message: string, originalError?: Error);
constructor(messageOrError?: string | Error, originalError?: Error) {
super('');
Object.setPrototypeOf(this, SignalingErrors.ConnectionDisconnected.prototype);
construct(this, messageOrError, originalError);
}
}
}
export namespace MediaErrors {
export class ClientLocalDescFailed extends Error implements TwilioError {
causes: string[] = [
'The Client may not be using a supported WebRTC implementation.',
'The Client may not have the necessary resources to create or apply a new media description.',
];
code: number = 53400;
description: string = 'Client is unable to create or apply a local media description';
explanation: string = 'Raised whenever a Client is unable to create or apply a local media description.';
solutions: string[] = [
'If you are experiencing this error using the JavaScript SDK, ensure you are running it with a supported WebRTC implementation.',
];
constructor();
constructor(message: string);
constructor(originalError: Error);
constructor(message: string, originalError?: Error);
constructor(messageOrError?: string | Error, originalError?: Error) {
super('');
Object.setPrototypeOf(this, MediaErrors.ClientLocalDescFailed.prototype);
construct(this, messageOrError, originalError);
}
}
export class ClientRemoteDescFailed extends Error implements TwilioError {
causes: string[] = [
'The Client may not be using a supported WebRTC implementation.',
'The Client may be connecting peer-to-peer with another Participant that is not using a supported WebRTC implementation.',
'The Client may not have the necessary resources to apply a new media description.',
];
code: number = 53402;
description: string = 'Client is unable to apply a remote media description';
explanation: string = 'Raised whenever the Client receives a remote media description but is unable to apply it.';
solutions: string[] = [
'If you are experiencing this error using the JavaScript SDK, ensure you are running it with a supported WebRTC implementation.',
];
constructor();
constructor(message: string);
constructor(originalError: Error);
constructor(message: string, originalError?: Error);
constructor(messageOrError?: string | Error, originalError?: Error) {
super('');
Object.setPrototypeOf(this, MediaErrors.ClientRemoteDescFailed.prototype);
construct(this, messageOrError, originalError);
}
}
export class ConnectionError extends Error implements TwilioError {
causes: string[] = [
'The Client was unable to establish a media connection.',
'A media connection which was active failed liveliness checks.',
];
code: number = 53405;
description: string = 'Media connection failed';
explanation: string = 'Raised by the Client or Server whenever a media connection fails.';
solutions: string[] = [
'If the problem persists, try connecting to another region.',
'Check your Client\'s network connectivity.',
'If you\'ve provided custom ICE Servers then ensure that the URLs and credentials are valid.',
];
constructor();
constructor(message: string);
constructor(originalError: Error);
constructor(message: string, originalError?: Error);
constructor(messageOrError?: string | Error, originalError?: Error) {
super('');
Object.setPrototypeOf(this, MediaErrors.ConnectionError.prototype);
construct(this, messageOrError, originalError);
}
}
}
/**
* @private
*/
export const errorsByCode: ReadonlyMap<number, any> = new Map([
[ 20101, AuthorizationErrors.AccessTokenInvalid ],
[ 20104, AuthorizationErrors.AccessTokenExpired ],
[ 20151, AuthorizationErrors.AuthenticationFailed ],
[ 31400, ClientErrors.BadRequest ],
[ 31000, GeneralErrors.UnknownError ],
[ 31005, GeneralErrors.ConnectionError ],
[ 31009, GeneralErrors.TransportError ],
[ 53000, SignalingErrors.ConnectionError ],
[ 53001, SignalingErrors.ConnectionDisconnected ],
[ 53400, MediaErrors.ClientLocalDescFailed ],
[ 53402, MediaErrors.ClientRemoteDescFailed ],
[ 53405, MediaErrors.ConnectionError ],
]);
Object.freeze(errorsByCode); | the_stack |
import {
AwsInstrumentation,
AwsSdkRequestHookInformation,
AwsSdkResponseHookInformation,
} from '../src';
import {
getTestSpans,
registerInstrumentationTesting,
} from '@opentelemetry/contrib-test-utils';
const instrumentation = registerInstrumentationTesting(
new AwsInstrumentation()
);
import * as AWS from 'aws-sdk';
import { ReadableSpan } from '@opentelemetry/sdk-trace-base';
import { SpanStatusCode, Span } from '@opentelemetry/api';
import { AttributeNames } from '../src/enums';
import { mockV2AwsSend } from './testing-utils';
import * as expect from 'expect';
describe('instrumentation-aws-sdk-v2', () => {
const responseMockSuccess = {
requestId: '0000000000000',
error: null,
};
const responseMockWithError = {
requestId: '0000000000000',
error: 'something went wrong',
};
const getAwsSpans = (): ReadableSpan[] => {
return getTestSpans().filter(s =>
s.instrumentationLibrary.name.includes('aws-sdk')
);
};
before(() => {
AWS.config.credentials = {
accessKeyId: 'test key id',
expired: false,
expireTime: new Date(),
secretAccessKey: 'test acc key',
sessionToken: 'test token',
};
});
describe('functional', () => {
describe('successful send', () => {
before(() => {
mockV2AwsSend(responseMockSuccess);
});
it('adds proper number of spans with correct attributes', async () => {
const s3 = new AWS.S3();
const bucketName = 'aws-test-bucket';
const keyName = 'aws-test-object.txt';
await new Promise(resolve => {
// span 1
s3.createBucket({ Bucket: bucketName }, async (err, data) => {
const params = {
Bucket: bucketName,
Key: keyName,
Body: 'Hello World!',
};
// span 2
s3.putObject(params, (err, data) => {
if (err) console.log(err);
resolve({});
});
});
});
const awsSpans = getAwsSpans();
expect(awsSpans.length).toBe(2);
const [spanCreateBucket, spanPutObject] = awsSpans;
expect(spanCreateBucket.attributes[AttributeNames.AWS_OPERATION]).toBe(
'createBucket'
);
expect(
spanCreateBucket.attributes[AttributeNames.AWS_SIGNATURE_VERSION]
).toBe('s3');
expect(
spanCreateBucket.attributes[AttributeNames.AWS_SERVICE_API]
).toBe('S3');
expect(
spanCreateBucket.attributes[AttributeNames.AWS_SERVICE_IDENTIFIER]
).toBe('s3');
expect(
spanCreateBucket.attributes[AttributeNames.AWS_SERVICE_NAME]
).toBe('Amazon S3');
expect(spanCreateBucket.attributes[AttributeNames.AWS_REQUEST_ID]).toBe(
responseMockSuccess.requestId
);
expect(spanCreateBucket.attributes[AttributeNames.AWS_REGION]).toBe(
'us-east-1'
);
expect(spanCreateBucket.name).toBe('S3.CreateBucket');
expect(spanPutObject.attributes[AttributeNames.AWS_OPERATION]).toBe(
'putObject'
);
expect(
spanPutObject.attributes[AttributeNames.AWS_SIGNATURE_VERSION]
).toBe('s3');
expect(spanPutObject.attributes[AttributeNames.AWS_SERVICE_API]).toBe(
'S3'
);
expect(
spanPutObject.attributes[AttributeNames.AWS_SERVICE_IDENTIFIER]
).toBe('s3');
expect(spanPutObject.attributes[AttributeNames.AWS_SERVICE_NAME]).toBe(
'Amazon S3'
);
expect(spanPutObject.attributes[AttributeNames.AWS_REQUEST_ID]).toBe(
responseMockSuccess.requestId
);
expect(spanPutObject.attributes[AttributeNames.AWS_REGION]).toBe(
'us-east-1'
);
expect(spanPutObject.name).toBe('S3.PutObject');
});
it('adds proper number of spans with correct attributes if both, promise and callback were used', async () => {
const s3 = new AWS.S3();
const bucketName = 'aws-test-bucket';
const keyName = 'aws-test-object.txt';
await new Promise(resolve => {
// span 1
s3.createBucket({ Bucket: bucketName }, async (err, data) => {
const params = {
Bucket: bucketName,
Key: keyName,
Body: 'Hello World!',
};
let reqPromise: Promise<any> | null = null;
let numberOfCalls = 0;
const cbPromise = new Promise(resolveCb => {
// span 2
const request = s3.putObject(params, (err, data) => {
if (err) console.log(err);
numberOfCalls++;
if (numberOfCalls === 2) {
resolveCb({});
}
});
// NO span
reqPromise = request.promise();
});
await Promise.all([cbPromise, reqPromise]).then(() => {
resolve({});
});
});
});
const awsSpans = getAwsSpans();
expect(awsSpans.length).toBe(2);
const [spanCreateBucket, spanPutObjectCb] = awsSpans;
expect(spanCreateBucket.attributes[AttributeNames.AWS_OPERATION]).toBe(
'createBucket'
);
expect(spanPutObjectCb.attributes[AttributeNames.AWS_OPERATION]).toBe(
'putObject'
);
expect(spanPutObjectCb.attributes[AttributeNames.AWS_REGION]).toBe(
'us-east-1'
);
});
it('adds proper number of spans with correct attributes if only promise was used', async () => {
const s3 = new AWS.S3();
const bucketName = 'aws-test-bucket';
const keyName = 'aws-test-object.txt';
await new Promise(resolve => {
// span 1
s3.createBucket({ Bucket: bucketName }, async (err, data) => {
const params = {
Bucket: bucketName,
Key: keyName,
Body: 'Hello World!',
};
// NO span
const request = s3.putObject(params);
// span 2
await request.promise();
resolve({});
});
});
const awsSpans = getAwsSpans();
expect(awsSpans.length).toBe(2);
const [spanCreateBucket, spanPutObjectCb] = awsSpans;
expect(spanCreateBucket.attributes[AttributeNames.AWS_OPERATION]).toBe(
'createBucket'
);
expect(spanPutObjectCb.attributes[AttributeNames.AWS_OPERATION]).toBe(
'putObject'
);
expect(spanPutObjectCb.attributes[AttributeNames.AWS_REGION]).toBe(
'us-east-1'
);
});
it('should create span if no callback is supplied', done => {
const s3 = new AWS.S3();
const bucketName = 'aws-test-bucket';
s3.putObject({
Bucket: bucketName,
Key: 'key name from tests',
Body: 'Hello World!',
}).send();
setImmediate(() => {
const awsSpans = getAwsSpans();
expect(awsSpans.length).toBe(1);
done();
});
});
});
describe('send return error', () => {
before(() => {
mockV2AwsSend(responseMockWithError);
});
it('adds error attribute properly', async () => {
const s3 = new AWS.S3();
const bucketName = 'aws-test-bucket';
await new Promise(resolve => {
s3.createBucket({ Bucket: bucketName }, async () => {
resolve({});
});
});
const awsSpans = getAwsSpans();
expect(awsSpans.length).toBe(1);
const [spanCreateBucket] = awsSpans;
expect(spanCreateBucket.attributes[AttributeNames.AWS_ERROR]).toBe(
responseMockWithError.error
);
});
});
});
describe('instrumentation config', () => {
it('preRequestHook called and add request attribute to span', done => {
mockV2AwsSend(responseMockSuccess, 'data returned from operation');
const config = {
preRequestHook: (
span: Span,
requestInfo: AwsSdkRequestHookInformation
) => {
span.setAttribute(
'attribute from hook',
requestInfo.request.commandInput['Bucket']
);
},
};
instrumentation.disable();
instrumentation.setConfig(config);
instrumentation.enable();
const s3 = new AWS.S3();
const bucketName = 'aws-test-bucket';
s3.createBucket({ Bucket: bucketName }, async (err, data) => {
const awsSpans = getAwsSpans();
expect(awsSpans.length).toBe(1);
expect(awsSpans[0].attributes['attribute from hook']).toStrictEqual(
bucketName
);
done();
});
});
it('preRequestHook throws does not fail span', done => {
mockV2AwsSend(responseMockSuccess, 'data returned from operation');
const config = {
preRequestHook: (span: Span, request: any) => {
throw new Error('error from request hook');
},
};
instrumentation.disable();
instrumentation.setConfig(config);
instrumentation.enable();
const s3 = new AWS.S3();
const bucketName = 'aws-test-bucket';
s3.createBucket({ Bucket: bucketName }, async (err, data) => {
const awsSpans = getAwsSpans();
expect(awsSpans.length).toBe(1);
expect(awsSpans[0].status.code).toStrictEqual(SpanStatusCode.UNSET);
done();
});
});
it('responseHook called and add response attribute to span', done => {
mockV2AwsSend(responseMockSuccess, 'data returned from operation');
const config = {
responseHook: (
span: Span,
responseInfo: AwsSdkResponseHookInformation
) => {
span.setAttribute(
'attribute from response hook',
responseInfo.response['data']
);
},
};
instrumentation.disable();
instrumentation.setConfig(config);
instrumentation.enable();
const s3 = new AWS.S3();
const bucketName = 'aws-test-bucket';
s3.createBucket({ Bucket: bucketName }, async (err, data) => {
const awsSpans = getAwsSpans();
expect(awsSpans.length).toBe(1);
expect(
awsSpans[0].attributes['attribute from response hook']
).toStrictEqual('data returned from operation');
done();
});
});
it('suppressInternalInstrumentation set to true with send()', done => {
mockV2AwsSend(responseMockSuccess, 'data returned from operation', true);
const config = {
suppressInternalInstrumentation: true,
};
instrumentation.disable();
instrumentation.setConfig(config);
instrumentation.enable();
const s3 = new AWS.S3();
s3.createBucket({ Bucket: 'aws-test-bucket' }, (err, data) => {
const awsSpans = getAwsSpans();
expect(awsSpans.length).toBe(1);
done();
});
});
it('suppressInternalInstrumentation set to true with promise()', async () => {
mockV2AwsSend(responseMockSuccess, 'data returned from operation', true);
const config = {
suppressInternalInstrumentation: true,
};
instrumentation.disable();
instrumentation.setConfig(config);
instrumentation.enable();
const s3 = new AWS.S3();
await s3.createBucket({ Bucket: 'aws-test-bucket' }).promise();
const awsSpans = getAwsSpans();
expect(awsSpans.length).toBe(1);
});
});
}); | the_stack |
import React, { FocusEvent, useCallback, useRef, useState } from 'react';
import {
useSelect,
useMultipleSelection,
A11yRemovalMessage,
A11yStatusMessageOptions,
UseMultipleSelectionStateChange,
UseMultipleSelectionStateChangeOptions,
UseMultipleSelectionState,
} from 'downshift';
import isEqual from 'lodash.isequal';
import uniqueId from 'lodash.uniqueid';
import { useVirtual } from 'react-virtual';
import 'hds-core';
import styles from './Select.module.scss';
import { FieldLabel } from '../../../internal/field-label/FieldLabel';
import classNames from '../../../utils/classNames';
import { IconAlertCircle, IconAngleDown } from '../../../icons';
import { SelectedItems } from '../../../internal/selectedItems/SelectedItems';
import { DROPDOWN_MENU_ITEM_HEIGHT, getIsInSelectedOptions } from '../dropdownUtils';
import { DropdownMenu } from '../../../internal/dropdownMenu/DropdownMenu';
import getIsElementFocused from '../../../utils/getIsElementFocused';
import getIsElementBlurred from '../../../utils/getIsElementBlurred';
import { useTheme } from '../../../hooks/useTheme';
export interface SelectCustomTheme {
'--dropdown-background-default'?: string;
'--dropdown-background-disabled'?: string;
'--dropdown-border-color-default'?: string;
'--dropdown-border-color-hover'?: string;
'--dropdown-border-color-hover-invalid'?: string;
'--dropdown-border-color-focus'?: string;
'--dropdown-border-color-invalid'?: string;
'--dropdown-border-color-disabled'?: string;
'--dropdown-color-default'?: string;
'--dropdown-color-disabled'?: string;
'--focus-outline-color'?: string;
'--helper-color-default'?: string;
'--helper-color-invalid'?: string;
'--menu-divider-color'?: string;
'--menu-item-background-default'?: string;
'--menu-item-background-hover'?: string;
'--menu-item-background-selected'?: string;
'--menu-item-background-selected-hover'?: string;
'--menu-item-background-disabled'?: string;
'--menu-item-color-default'?: string;
'--menu-item-color-hover'?: string;
'--menu-item-color-selected'?: string;
'--menu-item-color-selected-hover'?: string;
'--menu-item-color-disabled'?: string;
'--menu-item-icon-color-selected'?: string;
'--menu-item-icon-color-disabled'?: string;
'--multiselect-checkbox-background-selected'?: string;
'--multiselect-checkbox-background-disabled'?: string;
'--multiselect-checkbox-border-default'?: string;
'--multiselect-checkbox-border-hover'?: string;
'--multiselect-checkbox-border-disabled'?: string;
'--multiselect-checkbox-color-default'?: string;
'--multiselect-checkbox-color-selected'?: string;
'--multiselect-checkbox-color-selected-disabled'?: string;
'--placeholder-color'?: string;
}
export type CommonSelectProps<OptionType> = {
/**
* When `true`, allows moving from the first item to the last item with Arrow Up, and vice versa using Arrow Down.
*/
circularNavigation?: boolean;
/**
* Additional class names to apply to the select
*/
className?: string;
/**
* Flag for whether the clear selections button should be displayed
*/
clearable?: boolean;
/**
* If `true`, the dropdown will be disabled
*/
disabled?: boolean;
/**
* Function used to generate an ARIA a11y message when an item is selected. See [here](https://github.com/downshift-js/downshift/tree/master/src/hooks/useSelect#geta11yselectionmessage) for more information.
*/
getA11ySelectionMessage?: (options: A11yStatusMessageOptions<OptionType>) => string;
/**
* Function used to generate an ARIA a11y message when the status changes. See [here](https://github.com/downshift-js/downshift/tree/master/src/hooks/useSelect#geta11ystatusmessage) for more information.
*/
getA11yStatusMessage?: (options: A11yStatusMessageOptions<OptionType>) => string;
/**
* A helper text that will be shown below the dropdown
*/
helper?: React.ReactNode;
/**
* An error text that will be shown below the dropdown when `invalid` is true
*/
error?: React.ReactNode;
/**
* Used to generate the first part of the id on the elements
*/
id?: string;
/**
* If `true`, the input and `helper` will be displayed in an invalid state
*/
invalid?: boolean;
/**
* A function used to detect whether an option is disabled
*/
isOptionDisabled?: (option: OptionType, index: number) => boolean;
/**
* The label for the dropdown
*/
label: React.ReactNode;
/**
* Callback function fired when the state is changed
*/
onBlur?: () => void;
/**
* Callback function fired when the component is focused
*/
onFocus?: () => void;
/**
* Sets the data item field that represents the item label
* E.g. an `optionLabelField` value of `'foo'` and a data item `{ foo: 'Label', bar: 'value' }`, would display `Label` in the menu for that specific item
*/
optionLabelField?: string;
/**
* Array of options that should be shown in the menu
*/
options: OptionType[];
/**
* Short hint displayed in the dropdown before the user enters a value
*/
placeholder?: string;
/**
* If `true`, marks the dropdown as required
*/
required?: boolean;
/**
* Override or extend the root styles applied to the component
*/
style?: React.CSSProperties;
/**
* Custom theme styles
*/
theme?: SelectCustomTheme;
/**
* If `true`, the menu options will be virtualized. This greatly increases performance when there are a lot of options,
* but screen readers won't be able to know how many options there are.
*/
virtualized?: boolean;
/**
* Sets the number of options that are visible in the menu before it becomes scrollable
*/
visibleOptions?: number;
/**
* Aria-label text for the tooltip
*/
tooltipLabel?: string;
/**
* Aria-label text for the tooltip trigger button
*/
tooltipButtonLabel?: string;
/**
* The text content of the tooltip
*/
tooltipText?: string;
};
export type SingleSelectProps<OptionType> = CommonSelectProps<OptionType> & {
/**
* When `true`, enables selecting multiple values
*/
multiselect?: false;
/**
* Value that should be selected when the dropdown is initialized
*/
defaultValue?: OptionType;
/**
* Icon to be shown in the dropdown
*/
icon?: React.ReactNode;
/**
* Callback function fired when the state is changed
*/
onChange?: (selected: OptionType) => void;
/**
* The selected value
*/
value?: OptionType;
};
export type MultiSelectProps<OptionType> = CommonSelectProps<OptionType> & {
/**
* When `true`, enables selecting multiple values
*/
multiselect: true;
/**
* The aria-label for the clear button
*/
clearButtonAriaLabel: string;
/**
* Value(s) that should be selected when the dropdown is initialized
*/
defaultValue?: OptionType[];
/**
* Function used to generate an ARIA a11y message when an item is removed. See [here](https://github.com/downshift-js/downshift/tree/master/src/hooks/useMultipleSelection#geta11yremovalmessage) for more information.
*/
getA11yRemovalMessage?: (options: A11yRemovalMessage<OptionType>) => string;
/**
* Callback function fired when the state is changed
*/
onChange?: (selected: OptionType[]) => void;
/**
* The aria-label for the selected item remove button.
* You can use a special {value} token that will be replaced with the actual item value.
* E.g. an item with the label Foo and property value of `'Remove ${value}'` would become `aria-label="Remove Foo"`.
*/
selectedItemRemoveButtonAriaLabel: string;
/**
* A label for the selected items that is only visible to screen readers. Can be used to to give screen reader users additional information about the selected item.
* You can use a special {value} token that will be replaced with the actual item value.
* E.g. an item with the label Foo and property value of `'Selected item ${value}'` would become `aria-label="Selected item Foo"`.
*/
selectedItemSrLabel?: string;
/**
* The selected value(s)
*/
value?: OptionType[];
};
export type SelectProps<OptionType> = SingleSelectProps<OptionType> | MultiSelectProps<OptionType>;
/**
* Multi-select state change handler
* @param type
* @param activeIndex
* @param currentActiveIndex
* @param selectedItemsContainerEl
*/
export function onMultiSelectStateChange<T>(
{ type, activeIndex }: UseMultipleSelectionStateChange<T>,
currentActiveIndex,
selectedItemsContainerEl,
) {
let activeNode;
const { FunctionRemoveSelectedItem, SelectedItemKeyDownBackspace } = useMultipleSelection.stateChangeTypes;
if (type === FunctionRemoveSelectedItem || type === SelectedItemKeyDownBackspace) {
activeNode = selectedItemsContainerEl?.childNodes[currentActiveIndex] as HTMLDivElement;
if (!activeIndex && activeNode) activeNode.focus();
}
}
/**
* Multi-select reducer function
* @param state
* @param type
* @param changes
* @param controlled
*/
export function multiSelectReducer<T>(
state: UseMultipleSelectionState<T>,
{ type, changes }: UseMultipleSelectionStateChangeOptions<T>,
controlled: boolean,
) {
const { FunctionRemoveSelectedItem, SelectedItemKeyDownBackspace } = useMultipleSelection.stateChangeTypes;
if (type === FunctionRemoveSelectedItem || type === SelectedItemKeyDownBackspace) {
// get the index of the deleted item
const removedItemIndex = state.selectedItems.findIndex((item) => !changes.selectedItems.includes(item));
// activeIndex updates at a different time depending on whether the
// component is controlled. For controlled components, when 'onStateChange'
// is called, the removed item still has a SelectedItem representing
// it in the DOM. This means that the succeeding SelectedItem is at
// index n + 1 instead of n
const adjustedIndex = controlled ? removedItemIndex + 1 : removedItemIndex;
// whether the removed item was last in selectedItems
const lastItemRemoved = removedItemIndex === changes.selectedItems.length;
return {
...changes,
// set the new last item as active if the removed item was last,
// otherwise set the item succeeding the removed one active
activeIndex: lastItemRemoved ? removedItemIndex - 1 : adjustedIndex,
};
}
return changes;
}
export const Select = <OptionType,>(props: SelectProps<OptionType>) => {
// we can't destructure all the props. after destructuring, the link
// between the multiselect prop and the value, onChange etc. props would vanish
const {
circularNavigation = false,
className,
clearable = true,
disabled = false,
error,
getA11ySelectionMessage = () => '',
getA11yStatusMessage = () => '',
helper,
id = uniqueId('hds-select-') as string,
invalid,
isOptionDisabled,
label,
onBlur = () => null,
onFocus = () => null,
optionLabelField = 'label',
options = [],
placeholder,
required,
style,
theme,
virtualized = false,
visibleOptions = 5,
tooltipLabel,
tooltipButtonLabel,
tooltipText,
} = props;
// flag for whether the component is controlled
const controlled = props.multiselect && props.value !== undefined;
// custom theme class that is applied to the root element
const customThemeClass = useTheme<SelectCustomTheme>(styles.root, theme);
// selected items container ref
const selectedItemsContainerRef = useRef<HTMLDivElement>();
// menu ref
const menuRef = React.useRef<HTMLUListElement>();
// whether active focus is within the dropdown
const [hasFocus, setFocus] = useState<boolean>(false);
// virtualize menu items to increase performance
const virtualizer = useVirtual<HTMLUListElement>({
size: options.length,
parentRef: menuRef,
estimateSize: useCallback(() => DROPDOWN_MENU_ITEM_HEIGHT, []),
overscan: visibleOptions,
});
// init multi-select
const {
activeIndex,
addSelectedItem,
getDropdownProps,
getSelectedItemProps,
removeSelectedItem,
reset,
selectedItems,
setActiveIndex,
setSelectedItems,
} = useMultipleSelection<OptionType>({
// sets focus on the first selected item when the dropdown is initialized
defaultActiveIndex: 0,
initialActiveIndex: 0,
// set the default value(s) when the dropdown is initialized
...(props.multiselect && { initialSelectedItems: props.defaultValue ?? [] }),
// set the selected items when the dropdown is controlled
...(props.multiselect && props.value !== undefined && { selectedItems: props.value ?? [] }),
getA11yRemovalMessage: (props.multiselect && props.getA11yRemovalMessage) ?? (() => ''),
onSelectedItemsChange: ({ selectedItems: _selectedItems }) =>
props.multiselect && typeof props.onChange === 'function' && props.onChange(_selectedItems),
onStateChange: (changes) =>
onMultiSelectStateChange<OptionType>(changes, activeIndex, selectedItemsContainerRef.current),
stateReducer: (state, actionAndChanges) => multiSelectReducer<OptionType>(state, actionAndChanges, controlled),
});
// init select
const {
getItemProps,
getLabelProps,
getMenuProps,
getToggleButtonProps,
highlightedIndex,
isOpen,
selectedItem,
selectItem,
} = useSelect<OptionType>({
circularNavigation,
id,
items: options,
// set the default value when the dropdown is initialized
...(props.multiselect === false && { initialSelectedItem: props.defaultValue ?? null }),
// a defined value indicates that the dropdown should be controlled
// don't set selectedItem if it's not, so that downshift can handle the state
...(props.multiselect === false && props.value !== undefined && { selectedItem: props.value }),
getA11ySelectionMessage,
getA11yStatusMessage,
itemToString: (item): string => (item ? item[optionLabelField] ?? '' : ''),
onSelectedItemChange: ({ selectedItem: _selectedItem }) =>
props.multiselect === false && typeof props.onChange === 'function' && props.onChange(_selectedItem),
onStateChange({ type, selectedItem: _selectedItem }) {
const { ItemClick, MenuBlur, MenuKeyDownEnter, MenuKeyDownSpaceButton } = useSelect.stateChangeTypes;
if (
(type === ItemClick || type === MenuBlur || type === MenuKeyDownEnter || type === MenuKeyDownSpaceButton) &&
props.multiselect &&
_selectedItem
) {
getIsInSelectedOptions(selectedItems, _selectedItem)
? setSelectedItems(selectedItems.filter((item) => !isEqual(item, _selectedItem)))
: addSelectedItem(_selectedItem);
selectItem(null);
}
},
stateReducer(state, { type, changes }) {
const { ItemClick, MenuKeyDownSpaceButton } = useSelect.stateChangeTypes;
// prevent the menu from being closed when the user selects an item by clicking or pressing space
if ((type === ItemClick || type === MenuKeyDownSpaceButton) && props.multiselect) {
return {
...changes,
isOpen: state.isOpen,
highlightedIndex: state.highlightedIndex,
};
}
return changes;
},
});
const handleWrapperFocus = (e: FocusEvent<HTMLDivElement>) => {
if (getIsElementFocused(e)) {
setFocus(true);
onFocus();
}
};
const handleWrapperBlur = (e: FocusEvent<HTMLDivElement>) => {
if (getIsElementBlurred(e)) {
setFocus(false);
onBlur();
}
};
if (!props.multiselect) {
// we call the getDropdownProps getter function when multiselect isn't enabled
// in order to suppress the "You forgot to call the ..." error message thrown by downshift.
// we only need to apply the getter props to the toggle button when multiselect is enabled.
getDropdownProps({}, { suppressRefError: true });
}
// returns the toggle button label based on the dropdown mode
const getButtonLabel = (): React.ReactNode => {
let buttonLabel = selectedItem?.[optionLabelField] || placeholder;
if (props.multiselect) buttonLabel = selectedItems.length > 0 ? null : placeholder;
return buttonLabel && <span className={styles.buttonLabel}>{buttonLabel}</span>;
};
// screen readers should read the labels in the following order:
// field label > helper text > error text > toggle button label
// helper and error texts should only be read if they have been defined
// prettier-ignore
const buttonAriaLabel =
`${getLabelProps().id}${error ? ` ${id}-error` : ''}${helper ? ` ${id}-helper` : ''} ${getToggleButtonProps().id}`;
// show placeholder if no value is selected
const showPlaceholder = (props.multiselect && selectedItems.length === 0) || (!props.multiselect && !selectedItem);
return (
<div
className={classNames(
styles.root,
invalid && styles.invalid,
disabled && styles.disabled,
isOpen && styles.open,
props.multiselect && styles.multiselect,
customThemeClass,
className,
)}
style={style}
>
{/* LABEL */}
{label && (
<FieldLabel
label={label}
required={required}
{...getLabelProps()}
tooltipLabel={tooltipLabel}
tooltipButtonLabel={tooltipButtonLabel}
tooltipText={tooltipText}
/>
)}
<div className={styles.wrapper} onFocus={handleWrapperFocus} onBlur={handleWrapperBlur}>
{/* SELECTED ITEMS */}
{props.multiselect && selectedItems.length > 0 && (
<SelectedItems<OptionType>
activeIndex={activeIndex}
clearable={clearable}
clearButtonAriaLabel={props.clearButtonAriaLabel}
dropdownId={id}
getSelectedItemProps={getSelectedItemProps}
hideItems={!hasFocus}
onClear={() => reset()}
onRemove={removeSelectedItem}
optionLabelField={optionLabelField}
removeButtonAriaLabel={props.selectedItemRemoveButtonAriaLabel}
selectedItems={selectedItems}
selectedItemSrLabel={props.selectedItemSrLabel}
selectedItemsContainerRef={selectedItemsContainerRef}
setActiveIndex={setActiveIndex}
/>
)}
{/* TOGGLE BUTTON */}
<button
type="button"
{...getToggleButtonProps({
'aria-owns': getMenuProps().id,
'aria-labelledby': buttonAriaLabel,
// add downshift dropdown props when multiselect is enabled
...(props.multiselect && { ...getDropdownProps({ preventKeyAction: isOpen }) }),
...(invalid && { 'aria-invalid': true }),
disabled,
className: classNames(styles.button, showPlaceholder && styles.placeholder),
})}
>
{/* icons are only supported by single selects */}
{props.multiselect === false && props.icon && (
<span className={styles.icon} aria-hidden>
{props.icon}
</span>
)}
{getButtonLabel()}
<IconAngleDown className={styles.angleIcon} aria-hidden />
</button>
{/* MENU */}
<DropdownMenu<OptionType>
getItemProps={(item, index, selected, optionDisabled, virtualRow) =>
getItemProps({
item,
index,
disabled: optionDisabled,
className: classNames(
styles.menuItem,
highlightedIndex === index && styles.highlighted,
selected && styles.selected,
optionDisabled && styles.disabled,
virtualized && styles.virtualized,
),
// apply styles for virtualization to menu items
...(virtualRow && {
style: {
transform: `translateY(${virtualRow.start}px`,
},
ref: virtualRow.measureRef,
}),
})
}
isOptionDisabled={isOptionDisabled}
menuProps={getMenuProps({
...(props.multiselect && { 'aria-multiselectable': true }),
...(required && { 'aria-required': true }),
style: { maxHeight: DROPDOWN_MENU_ITEM_HEIGHT * visibleOptions },
ref: menuRef,
})}
menuStyles={styles}
multiselect={props.multiselect}
open={isOpen}
optionLabelField={optionLabelField}
options={options}
selectedItem={selectedItem}
selectedItems={selectedItems}
virtualizer={virtualized && virtualizer}
visibleOptions={visibleOptions}
/>
</div>
{/* INVALID TEXT */}
{invalid && error && (
<div id={`${id}-error`} className={styles.errorText} aria-hidden>
<IconAlertCircle className={styles.invalidIcon} />
{error}
</div>
)}
{/* HELPER TEXT */}
{helper && (
<div id={`${id}-helper`} className={styles.helperText} aria-hidden>
{helper}
</div>
)}
</div>
);
};
Select.defaultProps = {
multiselect: false,
}; | the_stack |
import * as kiwi from '@lume/kiwi';
import Attribute from './Attribute.js';
import Relation from './Relation.js';
import SubView from './SubView.js';
const defaultPriorityStrength = kiwi.Strength.create(0, 1000, 1000);
/**
* AutoLayoutJS API reference.
*
* ### Index
*
* |Entity|Type|Description|
* |---|---|---|
* |[AutoLayout](#autolayout)|`namespace`|Top level AutoLayout object.|
* |[VisualFormat](#autolayoutvisualformat--object)|`namespace`|Parses VFL into constraints.|
* |[View](#autolayoutview)|`class`|Main entity for adding & evaluating constraints.|
* |[SubView](#autolayoutsubview--object)|`class`|SubView's are automatically created when constraints are added to views. They give access to the evaluated results.|
* |[Attribute](#autolayoutattribute--enum)|`enum`|Attribute types that are supported when adding constraints.|
* |[Relation](#autolayoutrelation--enum)|`enum`|Relationship types that are supported when adding constraints.|
* |[Priority](#autolayoutpriority--enum)|`enum`|Default priority values for when adding constraints.|
*
* ### AutoLayout
*
* @module AutoLayout
*/
class View {
declare _solver: kiwi.Solver;
declare _subViews: {};
declare _parentSubView: SubView;
declare _spacing?: number | number[];
declare _spacingVars?: kiwi.Variable[];
declare _spacingExpr?: kiwi.Expression[];
/**
* @class View
* @param {Object} [options] Configuration options.
* @param {Number} [options.width] Initial width of the view.
* @param {Number} [options.height] Initial height of the view.
* @param {Number|Object} [options.spacing] Spacing for the view (default: 8) (see `setSpacing`).
* @param {Array} [options.constraints] One or more constraint definitions (see `addConstraints`).
*/
constructor(options) {
this._solver = new kiwi.Solver();
this._subViews = {};
this._parentSubView = new SubView({
solver: this._solver,
});
this.setSpacing(options && options.spacing !== undefined ? options.spacing : 8);
//this.constraints = [];
if (options) {
if (options.width !== undefined || options.height !== undefined) {
this.setSize(options.width, options.height);
}
if (options.constraints) {
this.addConstraints(options.constraints);
}
}
}
/**
* Sets the width and height of the view.
*
* @param {Number} width Width of the view.
* @param {Number} height Height of the view.
* @return {View} this
*/
setSize(width, height /*, depth*/) {
this._parentSubView.intrinsicWidth = width;
this._parentSubView.intrinsicHeight = height;
return this;
}
/**
* Width that was set using `setSize`.
* @readonly
* @type {Number}
*/
get width() {
return this._parentSubView.intrinsicWidth;
}
/**
* Height that was set using `setSize`.
* @readonly
* @type {Number}
*/
get height() {
return this._parentSubView.intrinsicHeight;
}
/**
* Width that is calculated from the constraints and the `.intrinsicWidth` of
* the sub-views.
*
* When the width has been explicitely set using `setSize`, the fittingWidth
* will **always** be the same as the explicitely set width. To calculate the size
* based on the content, use:
* ```javascript
* var view = new AutoLayout.View({
* constraints: VisualFormat.parse('|-[view1]-[view2]-'),
* spacing: 20
* });
* view.subViews.view1.intrinsicWidth = 100;
* view.subViews.view2.intrinsicWidth = 100;
* console.log('fittingWidth: ' + view.fittingWidth); // 260
* ```
*
* @readonly
* @type {Number}
*/
get fittingWidth() {
return this._parentSubView.width;
}
/**
* Height that is calculated from the constraints and the `.intrinsicHeight` of
* the sub-views.
*
* See `.fittingWidth`.
*
* @readonly
* @type {Number}
*/
get fittingHeight() {
return this._parentSubView.height;
}
/**
* Sets the spacing for the view.
*
* The spacing can be set for 7 different variables:
* `top`, `right`, `bottom`, `left`, `width`, `height` and `zIndex`. The `left`-spacing is
* used when a spacer is used between the parent-view and a sub-view (e.g. `|-[subView]`).
* The same is true for the `right`, `top` and `bottom` spacers. The `width` and `height` are
* used for spacers in between sub-views (e.g. `[view1]-[view2]`).
*
* Instead of using the full spacing syntax, it is also possible to use shorthand notations:
*
* |Syntax|Type|Description|
* |---|---|---|
* |`[top, right, bottom, left, width, height, zIndex]`|Array(7)|Full syntax including z-index **(clockwise order)**.|
* |`[top, right, bottom, left, width, height]`|Array(6)|Full horizontal & vertical spacing syntax (no z-index) **(clockwise order)**.|
* |`[horizontal, vertical, zIndex]`|Array(3)|Horizontal = left, right, width, vertical = top, bottom, height.|
* |`[horizontal, vertical]`|Array(2)|Horizontal = left, right, width, vertical = top, bottom, height, z-index = 1.|
* |`spacing`|Number|Horizontal & vertical spacing are all the same, z-index = 1.|
*
* Examples:
* ```javascript
* view.setSpacing(10); // horizontal & vertical spacing 10
* view.setSpacing([10, 15, 2]); // horizontal spacing 10, vertical spacing 15, z-axis spacing 2
* view.setSpacing([10, 20, 10, 20, 5, 5]); // top, right, bottom, left, horizontal, vertical
* view.setSpacing([10, 20, 10, 20, 5, 5, 1]); // top, right, bottom, left, horizontal, vertical, z
* ```
*
* @param {Number|Array} spacing
* @return {View} this
*/
setSpacing(spacing: number | number[]) {
if (!Array.isArray(spacing)) {
spacing = [spacing, spacing, spacing, spacing, spacing, spacing, 1];
} else {
// normalize spacing into array: [top, right, bottom, left, horz, vert, z-index]
switch (spacing.length) {
case 1:
spacing = [spacing[0], spacing[0], spacing[0], spacing[0], spacing[0], spacing[0], 1];
break;
case 2:
spacing = [spacing[1], spacing[0], spacing[1], spacing[0], spacing[0], spacing[1], 1];
break;
case 3:
spacing = [spacing[1], spacing[0], spacing[1], spacing[0], spacing[0], spacing[1], spacing[2]];
break;
case 6:
spacing = [spacing[0], spacing[1], spacing[2], spacing[3], spacing[4], spacing[5], 1];
break;
case 7:
break;
default:
throw 'Invalid spacing syntax';
}
}
if (!this._compareSpacing(this._spacing, spacing)) {
this._spacing = spacing;
// update spacing variables
if (this._spacingVars) {
for (var i = 0; i < this._spacingVars.length; i++) {
if (this._spacingVars[i]) {
this._solver.suggestValue(this._spacingVars[i], this._spacing![i]);
}
}
this._solver.updateVariables();
}
}
return this;
}
_compareSpacing(old, newz) {
if (old === newz) {
return true;
}
if (!old || !newz) {
return false;
}
for (var i = 0; i < 7; i++) {
if (old[i] !== newz[i]) {
return false;
}
}
return true;
}
/**
* Adds a constraint definition.
*
* A constraint definition has the following format:
*
* ```javascript
* constraint: {
* view1: {String},
* attr1: {AutoLayout.Attribute},
* relation: {AutoLayout.Relation},
* view2: {String},
* attr2: {AutoLayout.Attribute},
* multiplier: {Number},
* constant: {Number},
* priority: {Number}(0..1000)
* }
* ```
* @param {Object} constraint Constraint definition.
* @return {View} this
*/
addConstraint(constraint) {
this._addConstraint(constraint);
this._solver.updateVariables();
return this;
}
/**
* Adds one or more constraint definitions.
*
* A constraint definition has the following format:
*
* ```javascript
* constraint: {
* view1: {String},
* attr1: {AutoLayout.Attribute},
* relation: {AutoLayout.Relation},
* view2: {String},
* attr2: {AutoLayout.Attribute},
* multiplier: {Number},
* constant: {Number},
* priority: {Number}(0..1000)
* }
* ```
* @param {Array} constraints One or more constraint definitions.
* @return {View} this
*/
addConstraints(constraints) {
for (var j = 0; j < constraints.length; j++) {
this._addConstraint(constraints[j]);
}
this._solver.updateVariables();
return this;
}
_addConstraint(constraint) {
//this.constraints.push(constraint);
let relation;
const multiplier = constraint.multiplier !== undefined ? constraint.multiplier : 1;
let constant = constraint.constant !== undefined ? constraint.constant : 0;
if (constant === 'default') {
constant = this._getSpacing(constraint);
}
const attr1 = this._getSubView(constraint.view1)._getAttr(constraint.attr1);
let attr2;
if (constraint.attr2 === Attribute.CONST) {
attr2 = this._getConst(undefined, constraint.constant);
} else {
attr2 = this._getSubView(constraint.view2)._getAttr(constraint.attr2);
if (multiplier !== 1 && constant) {
attr2 = attr2.multiply(multiplier).plus(constant);
} else if (constant) {
attr2 = attr2.plus(constant);
} else if (multiplier !== 1) {
attr2 = attr2.multiply(multiplier);
}
}
const strength =
constraint.priority !== undefined && constraint.priority < 1000
? kiwi.Strength.create(0, constraint.priority, 1000)
: defaultPriorityStrength;
switch (constraint.relation) {
case Relation.EQU:
relation = new kiwi.Constraint(attr1, kiwi.Operator.Eq, attr2, strength);
break;
case Relation.GEQ:
relation = new kiwi.Constraint(attr1, kiwi.Operator.Ge, attr2, strength);
break;
case Relation.LEQ:
relation = new kiwi.Constraint(attr1, kiwi.Operator.Le, attr2, strength);
break;
default:
throw 'Invalid relation specified: ' + constraint.relation;
}
this._solver.addConstraint(relation);
}
_getSpacing(constraint) {
let index = 4;
if (!constraint.view1 && constraint.attr1 === 'left') {
index = 3;
} else if (!constraint.view1 && constraint.attr1 === 'top') {
index = 0;
} else if (!constraint.view2 && constraint.attr2 === 'right') {
index = 1;
} else if (!constraint.view2 && constraint.attr2 === 'bottom') {
index = 2;
} else {
switch (constraint.attr1) {
case 'left':
case 'right':
case 'centerX':
case 'leading':
case 'trailing':
index = 4;
break;
case 'zIndex':
index = 6;
break;
default:
index = 5;
}
}
this._spacingVars = this._spacingVars || new Array(7);
this._spacingExpr = this._spacingExpr || new Array(7);
if (!this._spacingVars[index]) {
this._spacingVars[index] = new kiwi.Variable();
this._solver.addEditVariable(this._spacingVars[index], kiwi.Strength.create(999, 1000, 1000));
this._spacingExpr[index] = this._spacingVars[index].multiply(-1);
this._solver.suggestValue(this._spacingVars[index], this._spacing![index]);
}
return this._spacingExpr[index];
}
_getSubView(viewName) {
if (!viewName) {
return this._parentSubView;
} else if (viewName.name) {
this._subViews[viewName.name] =
this._subViews[viewName.name] ||
new SubView({
name: viewName.name,
solver: this._solver,
});
this._subViews[viewName.name]._type = this._subViews[viewName.name]._type || viewName.type;
return this._subViews[viewName.name];
} else {
this._subViews[viewName] =
this._subViews[viewName] ||
new SubView({
name: viewName,
solver: this._solver,
});
return this._subViews[viewName];
}
}
_getConst(name, value) {
const vr = new kiwi.Variable();
this._solver.addConstraint(new kiwi.Constraint(vr, kiwi.Operator.Eq, value));
return vr;
}
/**
* Dictionary of `SubView` objects that have been created when adding constraints.
* @readonly
* @type {Object.SubView}
*/
get subViews() {
return this._subViews;
}
/**
* Checks whether the constraints incompletely specify the location
* of the subViews.
* @private
*/
//get hasAmbiguousLayout() {
// Todo
//}
}
export default View; | the_stack |
import { Store } from 'storage/store';
import { MultiMap } from 'util/multimap';
import { Hash } from '../model/Hashing';
import { BFSHistoryWalk } from './BFSHistoryWalk';
import { FullHistoryWalk } from './FullHistoryWalk';
import { OpHeader } from './OpHeader';
// A CasualHistoryFragment is built from a (sub)set of operations
// for a given MutableObject target, that are stored in the "contents"
// (Hash -> OpCausalHistory) map.
// Since during sync the ops themselves are not available, a supplemental
// OpCausalHistory object is used. It only contains the hash of the op,
// the hash of the OpCausalHistory objects of its predecessors, and some
// extra information.
// All history manipulation is done over OpCausalHistory objects, the actual
// op hashes can be obtained once the causality has been sorted out.
// The fragment keeps track of the set of terminal ops (ops without any
// following ops, in the sense that they are the last ops to have been
// applied according to te causal ordering defined by the "prevOps" field).
// It also keeps track of the ops that are referenced by the ops in the
// fragment but are not in it (in the "missingPrevOpHistories" field).
// Therefore the fragment may be seen as a set of ops that takes the target
// MutableObject from a state that contains all the ops in "missingPrevOpHistories" to a
// state that contains all the ops in "terminalOpHistories".
// lemma: if an op is new to the fragment, then it either
//
// a) is in the missingOps set.
//
// or
//
// b) is not a direct dependency of any ops in the fragment
// and therefore it should go into terminalOps.
// proof: assume neither a) or b) hold, then you have a
// new op that is not in missingOps, but is a
// direct dependency of an op present in the fragment.
// But then, since it is a direct dependency and it is not in
// missingOps, it must be present in the fragment, contrary
// to our assumption.
class HistoryFragment {
mutableObj: Hash;
terminalOpHeaders : Set<Hash>;
missingPrevOpHeaders : Set<Hash>;
contents : Map<Hash, OpHeader>;
roots : Set<Hash>;
opHeadersForOp: MultiMap<Hash, Hash>;
nextOpHeaders : MultiMap<Hash, Hash>;
constructor(target: Hash) {
this.mutableObj = target;
this.terminalOpHeaders = new Set();
this.missingPrevOpHeaders = new Set();
this.contents = new Map();
this.roots = new Set();
this.opHeadersForOp = new MultiMap();
this.nextOpHeaders = new MultiMap();
}
add(opHeader: OpHeader) {
if (this.isNew(opHeader.headerHash)) {
this.contents.set(opHeader.headerHash, opHeader);
this.opHeadersForOp.add(opHeader.opHash, opHeader.headerHash)
if (opHeader.prevOpHeaders.size === 0) {
this.roots.add(opHeader.headerHash);
}
// Adjust missingOps and terminalOps (see lemma above)
if (this.missingPrevOpHeaders.has(opHeader.headerHash)) {
this.missingPrevOpHeaders.delete(opHeader.headerHash);
} else {
this.terminalOpHeaders.add(opHeader.headerHash);
}
for (const prevOpHeader of opHeader.prevOpHeaders) {
// Adjust missingOps and terminalOps with info about this new prev op
if (this.isNew(prevOpHeader)) {
// It may or may not be in missingOps but, since prevOp
// is new, in any case add:
this.missingPrevOpHeaders.add(prevOpHeader);
} else {
// It may or may not be in terminalOps but, since prevOp
// is not new, in any case remove:
this.terminalOpHeaders.delete(prevOpHeader);
}
// Add reverse mapping to nextOps
this.nextOpHeaders.add(prevOpHeader, opHeader.headerHash)
}
}
}
remove(opHeaderHash: Hash) {
const opHeader = this.contents.get(opHeaderHash);
if (opHeader !== undefined) {
this.contents.delete(opHeader.headerHash);
this.opHeadersForOp.delete(opHeader.opHash, opHeader.headerHash);
this.terminalOpHeaders.delete(opHeader.headerHash);
if (opHeader.prevOpHeaders.size === 0) {
this.roots.delete(opHeader.headerHash);
}
if (this.nextOpHeaders.get(opHeaderHash).size > 0) {
this.missingPrevOpHeaders.add(opHeaderHash);
}
for (const prevOpHistoryHash of opHeader.prevOpHeaders) {
this.nextOpHeaders.delete(prevOpHistoryHash, opHeader.headerHash);
if (this.nextOpHeaders.get(prevOpHistoryHash).size === 0) {
if (this.contents.has(prevOpHistoryHash)) {
this.terminalOpHeaders.add(prevOpHistoryHash)
} else {
this.missingPrevOpHeaders.delete(prevOpHistoryHash);
}
}
}
}
}
verifyUniqueOps(): boolean {
for (const opHashes of this.opHeadersForOp.values()) {
if (opHashes.size > 1) {
return false;
}
}
return true;
}
clone(): HistoryFragment {
const clone = new HistoryFragment(this.mutableObj);
for (const opHistory of this.contents.values()) {
clone.add(opHistory);
}
return clone;
}
filterByTerminalOpHeaders(terminalOpHeaders: Set<Hash>): HistoryFragment {
const filteredOpHeaders = this.closureFrom(terminalOpHeaders, 'backward');
const filtered = new HistoryFragment(this.mutableObj);
for (const hash of filteredOpHeaders.values()) {
filtered.add(this.contents.get(hash) as OpHeader);
}
return filtered;
}
removeNonTerminalOps() {
const terminal = new Set<Hash>(this.terminalOpHeaders);
for (const hash of Array.from(this.contents.keys())) {
if (!terminal.has(hash)) {
this.remove(hash);
}
}
}
addAllPredecessors(origin: Hash | Set<Hash>, fragment: HistoryFragment) {
for (const opHeader of fragment.iterateFrom(origin, 'backward', 'bfs')) {
this.add(opHeader);
}
}
getStartingOpHeaders(): Set<Hash> {
const startingOpHeaders = new Set<Hash>();
for (const root of this.roots) {
startingOpHeaders.add(root);
}
for (const missing of this.missingPrevOpHeaders) {
for (const starting of this.nextOpHeaders.get(missing)) {
startingOpHeaders.add(starting);
}
}
return startingOpHeaders;
}
getTerminalOps(): Set<Hash> {
return this.getOpsForHeaders(this.terminalOpHeaders);
}
getStartingOps(): Set<Hash> {
return this.getOpsForHeaders(this.getStartingOpHeaders());
}
getOpHeaderForOp(opHash: Hash): OpHeader | undefined {
let opHistories = this.opHeadersForOp.get(opHash);
if (opHistories === undefined) {
return undefined;
} else {
if (opHistories.size > 1) {
throw new Error('Op histories matching op ' + opHash + ' were requested from fragment, but there is more than one (' + opHistories.size + ')');
} else {
return this.contents.get(opHistories.values().next().value);
}
}
}
getAllOpHeadersForOp(opHash: Hash): Array<OpHeader> {
const opHistories = (Array.from(this.opHeadersForOp.get(opHash))
.map((hash: Hash) => this.contents.get(hash)));
return opHistories as Array<OpHeader>;
}
// The following 3 functions operate on the known part of the fragment (what's
// in this.contents, not the hashes in missingOpHistories).
// Returns an iterator that visits all opHistories reachable from the initial set.
// - If method is 'bfs', each op history is visited once, in BFS order.
// - If method is 'causal', each op history is visited as many tomes as there is
// a causality relation leading to it (in the provided direction).
iterateFrom(initial: Set<Hash>|Hash, direction:'forward'|'backward'='forward', method: 'bfs'|'full'='bfs', filter?: (opHistory: Hash) => boolean): BFSHistoryWalk {
if (!(initial instanceof Set)) {
initial = new Set([initial]);
}
if (method === 'bfs') {
return new BFSHistoryWalk(direction, initial, this, filter);
} else {
return new FullHistoryWalk(direction, initial, this, filter);
}
}
// Returns the set of terminal opHistories reachable from initial.
terminalOpsFor(originOpHeaders: Set<Hash>|Hash, direction:'forward'|'backward'='forward'): Set<OpHeader> {
if (!(originOpHeaders instanceof Set)) {
originOpHeaders = new Set([originOpHeaders]);
}
const terminal = new Set<OpHeader>();
for (const opHeader of this.iterateFrom(originOpHeaders, direction, 'bfs')) {
let isTerminal: boolean;
if (direction === 'forward') {
isTerminal = this.nextOpHeaders.get(opHeader.headerHash).size === 0;
} else if (direction === 'backward') {
isTerminal = true;
for (const prevOpHistory of opHeader.prevOpHeaders) {
if (!this.missingPrevOpHeaders.has(prevOpHistory)) {
isTerminal = false;
break;
}
}
} else {
throw new Error("Direction should be 'forward' or 'backward'.")
}
if (isTerminal) {
terminal.add(opHeader);
}
}
return terminal;
}
// Returns true if ALL the hashes in destination are reachable from origin.
isReachable(originOpHeaders: Set<Hash>, destinationOpHeaders: Set<Hash>, direction: 'forward'|'backward'): boolean {
const targets = new Set<Hash>(destinationOpHeaders.values());
for (const opHistory of this.iterateFrom(originOpHeaders, direction, 'bfs')) {
targets.delete(opHistory.headerHash);
if (targets.size === 0) {
break;
}
}
return targets.size === 0;
}
closureFrom(originOpHeaders: Set<Hash>, direction: 'forward'|'backward', filter?: (opHeader: Hash) => boolean): Set<Hash> {
const result = new Set<Hash>();
for (const opHeader of this.iterateFrom(originOpHeaders, direction, 'bfs', filter)) {
result.add(opHeader.headerHash);
}
return result;
}
causalClosureFrom(startingOpHeaders: Set<Hash>, providedOpHeaders: Set<Hash>, maxOps?: number, ignoreOpHeader?: (h: Hash) => boolean, filterOpHeader?: (h: Hash) => boolean): Hash[] {
// We iterate over all the depenency "arcs", each time recording that one dependency has been
// fullfilled by removing it from a set in missingOpHistories. If the set ever empties, this
// op can be iterated over (all its prevOps have already been visited).
const closure = new Set<Hash>();
const missingPrevOpHeaders = new Map<Hash, Set<Hash>>();
const result = new Array<Hash>();
// Create the initial entries in missingPrevOpHistories, not considering anyPrevOps in
// providedOpHistories.
/*
for (const startingHash of startingOpHistories) {
if (filterOpHistory === undefined || filterOpHistory(startingHash)) {
const startingOpHistory = this.contents.get(startingHash) as OpCausalHistory;
CausalHistoryFragment.loadMissingPrevOpHistories(missingPrevOpHistories, startingOpHistory, providedOpHistories);
}
}
*/
for (const opHeader of this.iterateFrom(startingOpHeaders, 'forward', 'full')) {
if (maxOps !== undefined && maxOps === result.length) {
break;
}
const hash = opHeader.headerHash;
if ((filterOpHeader === undefined || filterOpHeader(hash))) {
HistoryFragment.loadMissingPrevOpHeaders(missingPrevOpHeaders, opHeader, providedOpHeaders);
if (missingPrevOpHeaders.get(hash)?.size === 0) {
for (const nextHash of this.nextOpHeaders.get(hash)) {
const nextOpHeader = this.contents.get(nextHash) as OpHeader;
if (filterOpHeader === undefined || filterOpHeader(nextHash)) {
HistoryFragment.loadMissingPrevOpHeaders(missingPrevOpHeaders, nextOpHeader, providedOpHeaders);
missingPrevOpHeaders.get(nextHash)?.delete(hash);
}
}
if (!closure.has(hash)) {
closure.add(hash);
if (ignoreOpHeader === undefined || !ignoreOpHeader(hash)) {
result.push(hash);
}
}
}
}
}
return result;
}
causalClosure(providedOpHeaders: Set<Hash>, maxOps?: number, ignoreOpHeader?: (h: Hash) => boolean, filterOpHeader?: (h: Hash) => boolean) {
return this.causalClosureFrom(this.getStartingOpHeaders(), providedOpHeaders, maxOps, ignoreOpHeader, filterOpHeader);
}
async loadFromTerminalOpHeaders(store: Store, terminalOpHeaders: Set<Hash>, maxOpHeaders?: number, forbiddenOpHeaders?: Set<Hash>) {
let next = new Array<Hash>();
for (const opHeaderHash of terminalOpHeaders) {
if (forbiddenOpHeaders === undefined || !forbiddenOpHeaders.has(opHeaderHash)) {
next.push(opHeaderHash);
}
}
do {
for (const opHeaderHash of next) {
const opHistory = await store.loadOpHeaderByHeaderHash(opHeaderHash) as OpHeader;
this.add(opHistory);
if (maxOpHeaders === this.contents.size) {
break;
}
}
next = [];
for (const opHeaderHash of this.missingPrevOpHeaders) {
if (forbiddenOpHeaders === undefined || !forbiddenOpHeaders.has(opHeaderHash)) {
next.push(opHeaderHash);
}
}
} while (next.length > 0 && !(this.contents.size === maxOpHeaders))
}
private static loadMissingPrevOpHeaders(missingPrevOpHeaders: Map<Hash, Set<Hash>>, opHeader: OpHeader, providedOpHeaders: Set<Hash>) {
let missing = missingPrevOpHeaders.get(opHeader.headerHash);
if (missing === undefined) {
missing = new Set<Hash>();
for (const prevOp of opHeader.prevOpHeaders) {
if (!providedOpHeaders.has(prevOp)) {
missing.add(prevOp);
}
}
missingPrevOpHeaders.set(opHeader.headerHash, missing);
}
}
private isNew(headerHash: Hash) {
return !this.contents.has(headerHash);
}
private getOpsForHeaders(headers: Set<Hash>): Set<Hash> {
return new Set(Array.from(headers).map((history: Hash) => this.contents.get(history)?.opHash)) as Set<Hash>;
}
}
export { HistoryFragment }; | the_stack |
import { Http, Response } from '@angular/http';
import { esIndex } from './consts';
import {Injectable, Inject} from "@angular/core";
import * as firebase from 'firebase';
import {} from 'firebase';
import { Observable } from "rxjs/Observable";
import { FormGroup } from '@angular/forms';
import { Subject } from 'rxjs/Subject';
import { Subscription } from 'rxjs/Rx';
/**
* Service that realize logic with connecting to firebase realtime database and authentication.
* Components user doesn't directly calls connector method. He calls them from [DAL]{@link https://www.npmjs.com/package/@nodeart/dal}
*
* Querying to `Firebase Realtime Database` are executed with [Firebase Flashlight]{@link https://github.com/firebase/flashlight}.
* If you want to create you own connector you must adopt it to `ElasticSearch flashlight` output.
*/
@Injectable()
export class FirebaseConnector {
/**
* User visited router
*/
private sfVisitedRoutes;
/**
* User performed clicks
*/
private sfUserClicks;
private basketHistory$: Subject<any> = new Subject();
private basketHistorySubscription$: Subscription;
private orderSubject: Subject<any> = new Subject();
private database = firebase.database();
private auth = firebase.auth();
constructor(private http: Http){
}
/**
* Connect [Session-flow]{@link https://www.npmjs.com/package/@nodeart/session-flow} to databese.
*
* @param {SessionFlow} sessionFlow SessionFlow service
* @param {string} deviceId User device id generated by SessionFlow
* @param {string} sessionId User session id generated by SessionFlow
*
*/
connectSessionFlowToDB(sessionFlow, deviceId, sessionId) {
this.sfVisitedRoutes = this.database
.ref('/session-flows/' + deviceId + '/' + sessionId + '/visitedRoutes');
this.sfUserClicks = this.database
.ref('/session-flows/' + deviceId + '/' + sessionId + '/userClicks');
this.listenSfObject(sessionFlow);
}
/**
* Subscribes to user visited routes and clicks
*
* @param {SessionFlow} sf SessionFlow service
*/
private listenSfObject(sf) {
sf.visitedRoute.subscribe((value) => {
this.sfVisitedRoutes.push(value.getStringObject());
});
sf.click.asObservable().subscribe((value) => {
this.sfUserClicks.push(value.getStringObject());
});
}
/**
* Returns firebase object. Avoid manipulating with connector directly. Use dal methods to communicate with connector
*
* @returns Firebase object
*/
getFirebase(){
return firebase;
};
/**
* Returns firebase realtime database object. Avoid manipulating with connector directly. Use dal methods to communicate with connector
*
* @returns Firebase realtime database object
*/
getFirebaseDB(){
return this.database;
}
/**
* Returns firebase auth object. Avoid manipulating with connector directly. Use dal methods to communicate with connector
*
* @returns Firebase auth object
*/
getAuth(){
return this.auth;
}
/**
* Register user with email and password
*
* @param {string} email User email
* @param {string} password User password
*
* @returns [firebase.Promise]{@link https://firebase.google.com/docs/reference/js/firebase.Promise} containing non-null [firebase.User]{@link https://firebase.google.com/docs/reference/js/firebase.User}
*/
register(email, password){
return this.auth.createUserWithEmailAndPassword(email, password);
}
/**
* Register user with email and password. Save additional information in database
*
* @param registerForm Object that have email, password and any additional information about user.
* Additional information stores in firebase as user backet
*/
registerUser(registerForm) : Observable<any>{
let email = registerForm.email;
let password = registerForm.password;
delete registerForm.password;
let userId = this.guid();
// add current time
registerForm["registerTime"] = Date.now();
return Observable.create(observer => {
this.register(email, password).then(authData => {
let uid = authData.uid;
registerForm.uid = uid;
this.database.ref('user/' + userId).set(registerForm).then(data => {
this.loginEmail(email, password).subscribe(
data => {
observer.next(data);
observer.complete();
},
error => {
observer.error(error);
});
});
}).catch( error => {
observer.error(error);
});
});
}
/**
* Generate guid for user Id
*
* @returns guid
*/
private guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
/**
* Login with email and password
*
* @param {string} email User email
* @param {string} password User password
*
* @returns {Observable} Observable containing non-null [firebase.User]{@link https://firebase.google.com/docs/reference/js/firebase.User}
*/
loginEmail(email, password){
return Observable.create( observer => {
this.auth.signInWithEmailAndPassword(email, password)
.then(data => {
observer.next(data);
observer.complete();
})
.catch(error => {
observer.error(error);
observer.complete();
});
});
}
/**
* Get user data
*
* @param {string} uid user Id
*
* @returns [firebase.database.Reference]{@link https://firebase.google.com/docs/reference/js/firebase.database.Reference}
*/
getUserData(uid){
let queryObj = {
query: {
match: {
"uid" : uid
}
}
};
return this.requestData(esIndex, 'user', queryObj);
}
/**
* Logout user from firebase
*/
logout(){
this.auth.signOut();
}
/**
* Check old session flow using device id
*
* @param {string} deviceId User device Id
*/
checkOldSessionFlow(deviceId){
if(localStorage.getItem("oldSessionFlow")){
let oldSessionFlow = JSON.parse(localStorage.getItem("oldSessionFlow"));
let sessionId = oldSessionFlow.sessionId;
delete oldSessionFlow.sessionId;
this.database.ref('/session-flows/' + deviceId + '/' + sessionId).set(oldSessionFlow);
}
}
/**
* Returns basket content of specific user
*
* @param {string} userId user Id
*
* @returns {Observable} Observable of basket
*/
getBasketContent(userId){
return Observable.create( observer => {
this.database.ref().child('/basket/' + userId).on('value', data => {
observer.next(data);
});
});
}
/**
* Will be realized in next versions
*/
getComparison(id){
return this.database.ref().child('comparison/' + id).once('value');
}
/**
* Initialize basket history for user. If you want to track basket history run this method when user sign in
*
* @param {string} userId userId or deviceId
*
*/
initializeBasketHistory(userId) {
if(this.basketHistorySubscription$){
this.basketHistorySubscription$.unsubscribe();
}
this.basketHistorySubscription$ = this.basketHistory$.subscribe( data => {
this.database.ref('/basket-history/' + userId).push(data);
});
}
/**
* Returns basket history subject
*
* @returns {Subject} basketHistory Subject of basketHistory
*/
getBasketHistorySubject(): Subject<any> {
return this.basketHistory$;
}
/**
* Returns Rx Observable of basket history of user by userId or deviceId
*
* @param {string} userId userId or deviceId
*
* @returns {Observable} Rx Observable of basket history
*/
getBasketHistoryById(userId){
return Observable.fromPromise(
this.database.ref().child('/basket-history/' + userId).once('value') as Promise<any>
);
}
/**
* Set new basket by user id or device id
* @param id userId or deviceId
* @param newBasket
*
* @returns {Observable} Observable of basket
*/
setNewBasket(id, newBasket){
return Observable.create( observer => {
this.database.ref().child('basket/' + id).set(newBasket).then( data => {
observer.next(data);
observer.complete();
});
});
}
/**
* Will be realized in next versions
*/
addProductToComparison(id, product){
return this.database.ref().child('comparison/' + id).push(product);
}
/**
* Will be realized in next versions
*/
removeProductFromComparison(id, idInComparison){
return this.database.ref().child('comparison/' + id + '/' + idInComparison).remove();
}
/**
* Gets data hits from firebase using [flashlight]{@link https://github.com/firebase/flashlight} lib for ElasticSearch
*
* @param {string} index ElasticSearch index
* @param {string} type ElasticSearch type
* @param {Object} body query object for ElasticSearch
*
* @returns {Observable} Observable of requested data hits
*/
requestData(index, type, body) {
const key = this.database
.ref('search/request')
.push({ index, type, body })
.key;
return Observable.fromPromise(
this.database.ref(`search/response/${key}/hits/hits`).once('child_added') as Promise<any>
);
}
/**
* Gets full data from firebase using [flashlight]{@link https://github.com/firebase/flashlight} lib for ElasticSearch
*
* @param {string} index ElasticSearch index
* @param {string} type ElasticSearch type
* @param {Object} body query object for ElasticSearch
*
* @returns {Observable} Observable of requested data
*/
requestFullData(index, type, body){
const key = this.database
.ref('search/request')
.push({ index, type, body })
.key;
return Observable.fromPromise(
this.database.ref(`search/response/${key}/hits`).once('child_added') as Promise<any>
);
}
/**
* Gets total item of data from firebase using [flashlight]{@link https://github.com/firebase/flashlight} lib for ElasticSearch
*
* @param {string} index ElasticSearch index
* @param {string} type ElasticSearch type
* @param {Object} body query object for ElasticSearch
*
* @returns {Observable} Observable of total item
*/
requestItemsTotal(index, type, body){
const key = this.database
.ref('search/request')
.push({ index, type, body })
.key;
console.log(key);
return Observable.create( observer => {
const ref = this.database.ref(`search/response/${key}/hits/total`);
let promise = new Promise( (resolve, reject) => {
ref.on('value', ( data ) => {
if(data.val() !== null){
resolve(data);
}
});
});
promise.then( data => {
ref.off('value');
observer.next(data);
observer.complete();
});
});
}
/**
* Add product to database
*
* @param {Object} product product Object
*/
addProduct(product){
this.database.ref('product/').push(product);
}
/**
* Returns visited routes
*
* @returns array of visited routes objects
*/
getVisitedRoutes(){
return this.sfVisitedRoutes;
}
/**
* Returns user clicks
*
* @returns array of user clicks objects
*/
getUserClicks(){
return this.sfUserClicks;
}
/**
* Add general category to database
*
* @param {FormGroup} generalCategoryForm form of general category
*/
addGeneralCategory(generalCategoryForm: FormGroup){
this.database.ref('general-category').push(generalCategoryForm.value);
}
/**
* Add category to database
*
* @param {FormGroup} categoryForm form of category
*/
addCategory(categoryForm : FormGroup){
this.database.ref('category/').push(categoryForm.value);
}
/**
* Add new attribute to database
*
* @param {FormGroup} attributeForm form of attribute
* @param {string} categoryId id of category
*/
addAttribute(attributeForm : FormGroup, categoryId){
this.database.ref('attributes/').push(attributeForm.value).then(ref => {
this.database.ref().child('category/' + categoryId +'/attrs').once('value').then(data => {
if(data.val()){
console.log(data);
if(data.val()[0] == '1234' && data.val()[1] == '1234'){
let attrs = ['1234'];
attrs.push(ref['key']);
console.log(attrs);
this.database.ref().child('category/' + categoryId + '/attrs').set(attrs);
} else {
let attrs = [].concat(...data.val());
console.log(attrs);
attrs.push(ref['key']);
console.log(attrs);
this.database.ref().child('category/' + categoryId + '/attrs').set(attrs);
}
}
});
});
}
/**
* Add new tag to database
*
* @param {FormGroup} tagForm form of tag
* @param {string} categoryId id of category
*/
addTag(tagForm: FormGroup, categoryId){
this.database.ref('tags/').push(tagForm.value).then(ref => {
this.database.ref().child('category/' + categoryId +'/tags').once('value').then(data => {
if(data.val()){
console.log(data);
if(data.val()[0] == '1234' && data.val()[1] == '1234'){
let tags = ['1234'];
tags.push(ref['key']);
console.log(tags);
this.database.ref().child('category/' + categoryId + '/tags').set(tags);
} else {
let tags = [].concat(data.val());
tags.push(ref['key']);
console.log(tags);
this.database.ref().child('category/' + categoryId + '/tags').set(tags);
}
}
});
});
}
/**
* Save new order to database
*
* @param {Object} paymentData
*
* @returns {Observable} Observable of orders
*/
saveOrder(paymentData){
return Observable.create( observer => {
this.database.ref('orders').push(paymentData).then( data => {
observer.next(data);
observer.complete();
});
});
}
/**
* Add payment requets. Server listens firebase backet with payments request and process coming requests
*
* @param {Object} data PaymentData
* @param {string} paymentMethod name of payment method
*
* @returns [firebase.database.ThenableReference]{@link https://firebase.google.com/docs/reference/js/firebase.database.ThenableReference}
*/
addPaymentRequest(data, paymentMethod) {
return this.database.ref('payment-request').push({
data: data,
payMethod: paymentMethod
});
}
/**
* Returns payment response by id
*
* @param {string} paymentKey id of payment response. Payment request and payment response have same ids in their backets
*
* @returns {Observable} Observable of payment response
*/
listenPaymentResponse(paymentKey) {
return Observable.create( observer => {
this.database.ref('payment-response/' + paymentKey).on('value', data => {
if(data.val()){
observer.next(data);
}
});
});
}
/**
* Send letter with password resetting to specific email
*
* @param {string} email User email
*
* @returns [firebase.Promise]{@link https://firebase.google.com/docs/reference/js/firebase.Promise} containing void
*/
resetPassword(email) {
return this.auth.sendPasswordResetEmail(email);
}
/**
* Get order by Id
* @param id id of order
* @returns {Observable} Observable of order
*/
getOrderById(id) {
return Observable.create( observer => {
this.database.ref('orders/' + id).on('value', data => {
if(data.val()){
observer.next(data.val());
}
});
});
}
/**
* Emits order object when new order added
*
* @returns {Observable} Observable of new order
*/
listenOrders() : Observable<any>{
return Observable.create( observer => {
this.database.ref('orders').on('child_added', newOrder => {
if(newOrder.val()){
observer.next(newOrder.val());
}
});
})
}
getOrderSubject() {
return this.orderSubject;
}
getSeoText(url: string, indexBlock: number) : Observable<any>{
return Observable.create( observer => {
this.database.ref('seo-text').orderByChild('url').equalTo(url).on('value', data => {
if(data.val() && data.val() !== null){
Object.keys(data.val()).map( key => {
observer.next(data.val()[key]['blocks'][indexBlock]);
});
} else {
observer.next(null);
}
});
});
}
} | the_stack |
// Myna is a parsing library: https://github.com/cdiggins/myna-parser
import { Myna as m } from "./node_modules/myna-parser/myna";
// A type-inference library: https://github.com/cdiggins/type-inference
import { TypeInference as ti } from "./node_modules/type-inference/type_inference";
// This is a full rewrite of the Cat language (which was originally in C#) written in TypeScript
export module CatLanguage
{
// Defines a Myna grammar for parsing Cat programs and types
export var catGrammar = new function()
{
var _this = this;
this.identifier = m.identifier.ast;
this.integer = m.integer.ast;
this.true = m.keyword("true").ast;
this.false = m.keyword("false").ast;
this.typeExprRec = m.delay(() => { return _this.typeExpr});
this.typeArray = m.guardedSeq('[', m.ws, this.typeExprRec.ws.zeroOrMore, ']').ast;
this.funcInput = this.typeExprRec.ws.zeroOrMore.ast;
this.funcOutput = this.typeExprRec.ws.zeroOrMore.ast;
this.typeFunc = m.guardedSeq('(', m.ws, this.funcInput, '->', m.ws, this.funcOutput, ')').ast;
this.typeVar = m.guardedSeq("'", m.identifier).ast;
this.typeConstant = m.identifier.ast;
this.typeExpr = m.choice(this.typeArray, this.typeFunc, this.typeVar, this.typeConstant).ast;
this.recTerm = m.delay(() => { return _this.term; });
this.quotation = m.guardedSeq('[', m.ws, this.recTerm.ws.zeroOrMore, ']').ast;
this.term = m.choice(this.quotation, this.integer, this.true, this.false, this.identifier);
this.terms = m.ws.then(this.term.ws.zeroOrMore);
this.definedName = m.identifier.ast;
this.typeSig = m.guardedSeq(":", m.ws, this.typeExpr).ast;
this.extern = m.guardedSeq(m.keyword('extern').ws, this.definedName, m.ws, this.typeSig).ast;
this.definition = m.guardedSeq('{', this.term.zeroOrMore, '}').ast;
this.define = m.guardedSeq(m.keyword('define').ws, this.definedName, m.ws, this.typeSig.opt, this.definition).ast;
this.program = m.choice(this.define, this.extern, this.term).zeroOrMore.ast;
}
// Register the Cat grammar
m.registerGrammar('cat', catGrammar, catGrammar.program);
// Outputs the AST tree generated from the Cat grammar
export function astSchemaString() : string {
return m.astSchemaToString('cat');
}
// Outputs the Cat grammar as a string
export function grammarString() : string {
return m.grammarToString('cat');
}
//====================================================================
// Helper Functions
// Converts a cons list into a flat list of types like Cat prefers
function consListToString(t:ti.Type) : string {
if (t instanceof ti.TypeArray)
return _typeToString(t.types[0]) + " " + consListToString(t.types[1]);
else
return _typeToString(t);
}
// Converts a string into a type expression
function _typeToString(t:ti.Type) : string {
if (ti.isFunctionType(t)) {
return "("
+ consListToString(ti.functionInput(t)) + " -> "
+ consListToString(ti.functionOutput(t)) + ")";
}
else if (t instanceof ti.TypeVariable) {
return "'" + t.toString();
}
else {
return t.toString();
}
}
export function typeToString(t:ti.Type) : string {
return _typeToString(ti.normalizeVarNames(t));
}
// Converts a string into a type expression
export function stringToType(input:string) : ti.Type {
var ast = m.parse(m.grammars['cat'].typeExpr, input);
return astToType(ast);
}
// Converts a series of cat terms into an AST
export function stringToCatAst(input:string) : m.AstNode {
return m.parse(m.grammars['cat'].terms, input);
}
// Converts the AST children to a cons list
export function astToConsList(astNodes:m.AstNode[]) : ti.Type {
if (astNodes.length == 0)
throw new Error("Expected at least one AST node");
var tmp = astToType(astNodes[0]);
if (astNodes.length == 1)
{
if (!(tmp instanceof ti.TypeVariable))
throw new Error("The last type of a function input or output must be a type variable");
return tmp;
}
else {
return ti.typeArray([tmp,astToConsList(astNodes.slice(1))]);
}
}
// Converts an AST generated from a parse int o type expression
export function astToType(ast:m.AstNode) : ti.Type {
if (!ast)
throw new Error("Missing AST node");
switch (ast.name)
{
case "typeVar":
return ti.typeVariable(ast.allText.substr(1));
case "typeConstant":
return ti.typeConstant(ast.allText);
case "typeFunc":
return ti.functionType(
astToType(ast.children[0]),
astToType(ast.children[1]));
case "funcInput":
case "funcOutput":
return astToConsList(ast.children);
case "typeArray":
return ti.typeArray(ast.children.map(astToType));
case "typeExpr":
return astToType(ast.children[0]);
default:
throw new Error("Unrecognized type expression: " + ast.name);
}
}
// Converts an AST into a Cat instruction
export function astToInstruction(ast:m.AstNode, env:CatEnvironment) : CatInstruction {
if (!ast)
throw new Error("Missing AST node");
switch (ast.name)
{
case "identifier":
return env.getInstruction(ast.allText);
case "integer":
return new CatConstant(parseInt(ast.allText));
case "true":
return new CatConstant(true);
case "false":
return new CatConstant(false);
case "quotation":
return new CatAbstraction(ast.children.map((c) => astToInstruction(c, env)))
default:
throw new Error("Unrecognized term: " + ast.name);
}
}
// Converts a string into a Cat instruction
export function stringToInstruction(name:string, code:string, env:CatEnvironment) : CatInstruction {
var ast = m.parse(m.grammars['cat'].terms, code);
return new CatDefinition(name, ast.children.map((c) => astToInstruction(c, env)));
}
// Returns the type of data
export function dataType(data:CatValue) : ti.Type {
if (typeof(data) == 'number')
return new ti.TypeConstant('Num');
if (typeof(data) == 'boolean')
return new ti.TypeConstant('Bool');
if (typeof(data) == 'string')
return new ti.TypeConstant('Str');
if (data instanceof CatInstruction)
return data.type;
throw new Error("Could not figure out the type of the data: " + data);
}
// Returns true if the type can be a valid input/output of a Cat function type.
export function isValidFunctionPart(t:ti.Type) : boolean {
if (t instanceof ti.TypeArray) {
if (t.types.length != 2)
return false;
return isValidFunctionPart(t.types[1]);
}
else {
return t instanceof ti.TypeVariable;
}
}
// Returns true if the function is truly a valid Cat function type
export function isCatFunctionType(t:ti.Type) : boolean {
if (!ti.isFunctionType(t))
return false;
var input = ti.functionInput(t);
if (!isValidFunctionPart(input))
return false;
var output = ti.functionOutput(t);
if (!isValidFunctionPart(output))
return false;
return true;
}
// Given the type of the current stack, and a function type, returns the type of the resulting stack.
export function evalType(stack : ti.TypeArray, func : ti.TypeArray) : ti.TypeArray {
throw new Error("Not implemented yet");
}
// Applies a function to a stack transforming its internal state
export function applyFunc(stack : CatStack, func : Function) {
func.apply(stack);
}
// Gets the type of a sequence of instructions
export function instructionSequenceType(q:CatInstruction[]) : ti.TypeArray {
return ti.composeFunctionChain(q.map(i => i.type));
}
// Given the type of a stack, validates that the stack is in fact compatible with it or throws an error
export function validateType(stack : CatStack, type : ti.TypeArray) {
throw new Error("Not implemented");
}
// Converts a JavaScript function to a Cat function
export function jsFunctionToCat(f:Function) : CatFunction {
return (stack) => stack._function(f);
}
//======================================================================
// Classes and interfaces
// Used for looking up instructions by name
export interface ICatInstructionLookup {
[name:string] : CatInstruction;
}
// The type of Cat functions in the implementation.
// The implementation uses a shared mutable structure called a "CatStack".
export type CatFunction = (CatStack) => void;
// A Cat instruction (aka word in Forth)
export class CatInstruction {
constructor(
public name : string,
public func : CatFunction,
public type : ti.TypeArray)
{
if (!isCatFunctionType(type))
throw new Error("Expected a valid Cat function type to describe an instruction");
}
toString() : string {
return this.name;
}
toDebugString() : string {
return this.name + "\t: " + typeToString(this.type);
}
}
// A list of instructions
export class CatDefinition extends CatInstruction {
constructor(
public name:string,
public instructions:CatInstruction[])
{
super(name,
(stack) => instructions.forEach(i => i.func(stack)),
instructionSequenceType(instructions)
);
}
definitionString() : string {
return this.instructions.map(i => i.toString()).join(" ");
}
toDebugString() : string {
return this.name + "\t: " + typeToString(this.type) + " = { " + this.definitionString() + "}";
}
};
// A list of instructions
export class CatAbstraction extends CatInstruction {
constructor(
public instructions:CatInstruction[])
{
super("_quotation_",
(stack) => instructions.forEach(i => i.func(stack)),
ti.quotation(instructionSequenceType(instructions))
);
}
toString() : string {
return '[' + this.instructions.map(i => i.toString()).join(" ") + ']';
}
toDebugString() : string {
return this.name + "\t: " + typeToString(this.type) + "\t = { " + this.toString() + "}";
}
};
// An instruction that pushes data on the stack
export class CatConstant extends CatInstruction {
constructor(
public data:CatValue)
{
super(data.toString(),
(stack) => stack.push(data),
ti.rowPolymorphicFunction([], [dataType(data)]));
}
toString() : string {
return this.data.toString();
}
toDebugString() : string {
return this.name + "\t: " + typeToString(this.type) + "\t = { " + this.toString() + "}";
}
};
// The type of things on the Cat stack
export type CatValue = number | boolean | string | CatInstruction;
// Wraps the shared stack used by an executing Cat program
export class CatStack
{
stack:CatValue[] = [];
// Pushes a value onto the stack.
push(x:CatValue) {
this.stack.push(x);
}
// Returns the top value on the stack.
top() : CatValue {
return this.stack[this.stack.length-1];
}
// Removes the top value from the stack
pop() : CatValue {
return this.stack.pop();
}
// Removes the top valued from the stack, and returns it as the specified type.
popType<T extends CatValue>() : T {
return this.pop() as T;
}
// Removes the top value from the stack, assuring it is a function
popFunc() : CatFunction {
var i = this.popType<CatInstruction>();
if (!i) throw new Error("Expected Cat instruction on the top of the stack");
return i.func;
}
// Swaps the top two values of the stack
swap() {
var x = this.pop();
var y = this.pop();
this.push(x);
this.push(y);
}
// Duplicates the top value on the stack
dup() {
this.push(this.top());
}
// Pops a function from the stack and applies it to the stack.
apply() {
this.popFunc()(this);
}
// Pops a boolean and two values from the stack, pushing either the top value back on the stack if the boolean is true,
// or the other value otherwise.
cond() {
var b = this.pop();
var onTrue = this.pop();
var onFalse = this.pop();
this.push(b ? onTrue : onFalse);
}
// Executes a conditional function and then a body function repeatedly while the result of the conditional
// function is true.
while() {
var cond = this.popFunc();
var body = this.popFunc();
cond(this);
while (this.pop()) {
body(this);
cond(this);
}
}
// Creates a function that returns a value
quote() {
this.push(new CatConstant(this.pop()));
}
// Creates a new quotation by combining two existing quotations
compose() {
var a = this.popType<CatInstruction>();
var b = this.popType<CatInstruction>();
this.push(new CatAbstraction([b, a]));
}
// Calls a plain JavaScript function using arguments from the stack
// and pushes the result back onto the stack.
_function(f:Function) {
var args = [];
for (var i=0; i < f.length; ++i)
args.push(this.pop());
this.push(f.apply(null, args));
}
}
// A cat environment holds the dictionary of instructions and their types.
export class CatEnvironment
{
// The list of defined instruction.
instructions : ICatInstructionLookup = {};
// These are operations directly available on the "stack" object.
// They are retrieved by the name.
primOps = {
apply : "(('S -> 'R) 'S -> 'R)",
quote : "('a 'S -> ('R -> 'a 'R) 'S)",
compose : "(('B -> 'C) ('A -> 'B) 'S -> ('A -> 'C) 'S)",
dup : "('a 'S -> 'a 'a 'S)",
pop : "('a 'S -> 'S)",
swap : "('a 'b 'S -> 'b 'a 'S)",
cond : "(Bool 'a 'a 'S -> 'a 'S)",
while : "(('S -> Bool 'R) ('R -> 'S) 'S -> 'S)",
};
// These are additional primitives defined as lambdas
primFuncs = {
eq : [(x,y) => x == y, "('a 'a 'S -> Bool 'S)"],
neq : [(x,y) => x != y, "('a 'a 'S -> Bool 'S)"],
add : [(x,y) => x + y, "(Num Num 'S -> Num 'S)"],
neg : [(x) => -x, "(Num 'S -> Num 'S)"],
sub : [(x,y) => x - y, "(Num Num 'S -> Num 'S)"],
mul : [(x,y) => x * y, "(Num Num 'S -> Num 'S)"],
div : [(x,y) => x / y, "(Num Num 'S -> Num 'S)"],
mod : [(x,y) => x % y, "(Num Num 'S -> Num 'S)"],
not : [(x) => !x, "(Bool 'S -> Bool 'S)"],
gt : [(x,y) => x > y, "(Num Num 'S -> Bool 'S)"],
gteq : [(x,y) => x >= y, "(Num Num 'S -> Bool 'S)"],
lt : [(x,y) => x < y, "(Num Num 'S -> Bool 'S)"],
lteq : [(x,y) => x <= y, "(Num Num 'S -> Bool 'S)"],
and : [(x,y) => x && y, "(Bool Bool 'S -> Bool 'S)"],
or : [(x,y) => x || y, "(Bool Bool 'S -> Bool 'S)"],
xor : [(x,y) => x ^ y, "(Bool Bool 'S -> Bool 'S)"],
succ : [(x) => x + 1, "(Num 'S -> Num 'S)"],
pred : [(x) => x - 1, "(Num 'S -> Num 'S)"],
}
// Standard operations, their definitions and expected types.
// The type is not required: it is used for validation purposes
// http://www.kevinalbrecht.com/code/joy-mirror/j03atm.html
stdOps = {
"dip" : ["swap quote compose apply", "(('S -> 'R) 'a 'S -> 'a 'R)"],
"rcompose" : ["swap compose", "(('A -> 'B) ('B -> 'C) 'S -> ('A -> 'C) 'S)"],
"papply" : ["quote rcompose", "('a ('a 'S -> 'R) 'T -> ('S -> 'R) 'T)"],
"dipd" : ["swap [dip] dip", "(('S -> 'R) 'a 'b 'S -> 'a 'b 'R)"],
"popd" : ["[pop] dip", "('a 'b 'S -> 'a 'S)"],
"popop" : ["pop pop", "('a 'b 'S -> 'S)"],
"dupd" : ["[dup] dip", "('a 'b 'S -> 'a 'b 'b 'S)"],
"swapd" : ["[swap] dip", "('a 'b 'c 'S -> 'a 'c 'b 'S)"],
"rollup" : ["swap swapd", "('a 'b 'c 'S -> 'b 'c 'a 'S)"],
"rolldown" : ["swapd swap", "('a 'b 'c 'S -> 'c 'a 'b 'S)"],
"if" : ["cond apply", "(Bool ('A -> 'B) ('A -> 'B) 'A -> 'B)"],
"id" : ["", "('A -> 'A)"]
}
// Helper function to get the function associated with an instruction
getInstruction(s:string) : CatInstruction {
if (!(s in this.instructions))
throw new Error("Could not find instruction: " + s);
return this.instructions[s];
}
// Helper function to get the type associated with an instruction
getType(s:string) : ti.TypeArray {
if (!(s in this.instructions))
throw new Error("Could not find instruction: " + s);
return this.instructions[s].type;
}
// Gets the list of all defined Cat instructions
getInstructions() : CatInstruction[] {
var r = new Array<CatInstruction>();
for (var k in this.instructions)
r.push(this.instructions[k]);
return r;
}
// Returns the type of a quotation given the nodes in the quotation
getQuotationType(astNodes : m.AstNode[]) : ti.TypeArray {
var types = astNodes.map(ast => astToType(ast) as ti.TypeArray);
return ti.composeFunctionChain(types);
}
getTypeFromAst(ast : m.AstNode) : ti.Type {
if (!ast) throw new Error("Not a valid AST");
switch (ast.name)
{
case "identifier":
return this.getType(ast.allText);
case "integer":
return new ti.TypeConstant("Num");
case "true":
case "false":
return new ti.TypeConstant("Bool");
case "quotation":
return this.getQuotationType(ast.children);
default:
throw new Error("AST node has no known type: " + ast.name);
}
}
// Creates a new instruction and returns it
addInstruction(name:string, func:CatFunction, type:string) : CatInstruction {
return this.instructions[name] = new CatInstruction(name, func, stringToType(type) as ti.TypeArray);
}
// Creates a new instruction from a definition
addDefinition(name:string, code:string, type:string = null) : CatInstruction {
var i = stringToInstruction(name, code, this);
var inferredType = i.type;
if (type)
{
var expectedType = stringToType(type);
if (!ti.areTypesSame(inferredType, expectedType)) {
var a = ti.normalizeVarNames(inferredType).toString();
var b = ti.normalizeVarNames(expectedType).toString();
throw new Error("Inferred type: " + a + " does not match expected type: " + b);
}
}
return this.instructions[name] = i;
}
// Constructor
constructor()
{
// Register the primitive operations (stack built-in functions)
for (let k in this.primOps)
this.addInstruction(k, (stack) => stack[k](), this.primOps[k]);
// Register core functions expressed as JavaScript functions
for (let k in this.primFuncs)
this.addInstruction(k, jsFunctionToCat(this.primFuncs[k][0]), this.primFuncs[k][1]);
// Register core functions expressed as JavaScript functions
for (let k in this.stdOps)
this.addDefinition(k, this.stdOps[k][0], this.stdOps[k][1]);
}
}
// The evaluator holds a Cat environment containing the dictionary of defined Cat words
// It also caches an evaluator function. It contains helper evaluation functions.
// The evaluator also maintains the current type of the Cat stack, and predicts it based
// on the terms it is about to evaluate.
export class CatEvaluator
{
env : CatEnvironment = new CatEnvironment();
stk : CatStack = new CatStack();
type : ti.Type = ti.typeArray([]);
trace : boolean = true;
print() {
console.log("stack = " + this.stk.stack + " : " + typeToString(this.type));
}
eval(s : string) {
this.evalTerm(stringToCatAst(s));
}
evalTerms(ast : m.AstNode) {
ast.children.forEach(c => this.evalTerm(c));
}
evalInstruction(instruction : CatInstruction) {
if (this.trace)
console.log("evaluating " + instruction.toDebugString());
// Apply the function type to the stack type
this.type = ti.applyFunction(instruction.type, this.type);
// Apply the function to the stack
instruction.func(this.stk);
if (this.trace)
this.print();
}
evalTerm(ast : m.AstNode) {
if (!ast) throw new Error("Not a valid AST");
switch (ast.name)
{
case "terms":
return this.evalTerms(ast);
default:
return this.evalInstruction(astToInstruction(ast, this.env));
}
}
}
} | the_stack |
import { ChildProcess, spawn } from 'child_process';
import { randomInt } from 'crypto';
import appRoot from 'app-root-path';
import axios from 'axios';
import debug from 'debug';
import { Multiaddr, multiaddr } from 'multiaddr';
import PeerId from 'peer-id';
import { hexToBuf } from '../lib/utils';
import { DefaultPubSubTopic } from '../lib/waku';
import { WakuMessage } from '../lib/waku_message';
import * as proto from '../proto/waku/v2/message';
import { existsAsync, mkdirAsync, openAsync } from './async_fs';
import waitForLine from './log_file';
const dbg = debug('waku:nim-waku');
const NIM_WAKU_DEFAULT_P2P_PORT = 60000;
const NIM_WAKU_DEFAULT_RPC_PORT = 8545;
const NIM_WAKU_DIR = appRoot + '/nim-waku';
const NIM_WAKU_BIN = NIM_WAKU_DIR + '/build/wakunode2';
const LOG_DIR = './log';
export interface Args {
staticnode?: string;
nat?: 'none';
listenAddress?: string;
relay?: boolean;
rpc?: boolean;
rpcAdmin?: boolean;
nodekey?: string;
portsShift?: number;
logLevel?: LogLevel;
persistMessages?: boolean;
lightpush?: boolean;
topics?: string;
rpcPrivate?: boolean;
}
export enum LogLevel {
Error = 'error',
Info = 'info',
Warn = 'warn',
Debug = 'debug',
Trace = 'trace',
Notice = 'notice',
Fatal = 'fatal',
}
export interface KeyPair {
privateKey: string;
publicKey: string;
}
export interface WakuRelayMessage {
payload: string;
contentTopic?: string;
timestamp?: number; // Float in seconds
}
export class NimWaku {
private process?: ChildProcess;
private pid?: number;
private portsShift: number;
private peerId?: PeerId;
private multiaddrWithId?: Multiaddr;
private logPath: string;
constructor(logName: string) {
this.portsShift = randomInt(0, 5000);
this.logPath = `${LOG_DIR}/nim-waku_${logName}.log`;
}
async start(args?: Args): Promise<void> {
try {
await existsAsync(LOG_DIR);
} catch (e) {
try {
await mkdirAsync(LOG_DIR);
} catch (e) {
// Looks like 2 tests tried to create the director at the same time,
// it can be ignored
}
}
const logFile = await openAsync(this.logPath, 'w');
const mergedArgs = defaultArgs();
// Object.assign overrides the properties with the source (if there are conflicts)
Object.assign(
mergedArgs,
{ portsShift: this.portsShift, logLevel: LogLevel.Trace },
args
);
const argsArray = argsToArray(mergedArgs);
this.process = spawn(NIM_WAKU_BIN, argsArray, {
cwd: NIM_WAKU_DIR,
stdio: [
'ignore', // stdin
logFile, // stdout
logFile, // stderr
],
});
this.pid = this.process.pid;
dbg(
`nim-waku ${
this.process.pid
} started at ${new Date().toLocaleTimeString()}`
);
this.process.on('exit', (signal) => {
dbg(
`nim-waku ${
this.process ? this.process.pid : this.pid
} process exited with ${signal} at ${new Date().toLocaleTimeString()}`
);
});
this.process.on('error', (err) => {
console.log(
`nim-waku ${
this.process ? this.process.pid : this.pid
} process encountered an error: ${err} at ${new Date().toLocaleTimeString()}`
);
});
dbg("Waiting to see 'Node setup complete' in nim-waku logs");
await this.waitForLog('Node setup complete', 9000);
dbg('nim-waku node has been started');
}
public stop(): void {
dbg(
`nim-waku ${
this.process ? this.process.pid : this.pid
} getting SIGINT at ${new Date().toLocaleTimeString()}`
);
this.process ? this.process.kill('SIGINT') : null;
this.process = undefined;
}
async waitForLog(msg: string, timeout: number): Promise<void> {
return waitForLine(this.logPath, msg, timeout);
}
/** Calls nim-waku2 JSON-RPC API `get_waku_v2_admin_v1_peers` to check
* for known peers
* @throws if nim-waku2 isn't started.
*/
async peers(): Promise<string[]> {
this.checkProcess();
return this.rpcCall<string[]>('get_waku_v2_admin_v1_peers', []);
}
async info(): Promise<RpcInfoResponse> {
this.checkProcess();
return this.rpcCall<RpcInfoResponse>('get_waku_v2_debug_v1_info', []);
}
async sendMessage(
message: WakuMessage,
pubSubTopic?: string
): Promise<boolean> {
this.checkProcess();
if (!message.payload) {
throw 'Attempting to send empty message';
}
let timestamp;
if (message.timestamp) {
timestamp = message.timestamp.valueOf() / 1000;
if (Number.isInteger(timestamp)) {
// Add a millisecond to ensure it's not an integer
// Until https://github.com/status-im/nim-waku/issues/691 is done
timestamp += 0.001;
}
}
const rpcMessage = {
payload: bufToHex(message.payload),
contentTopic: message.contentTopic,
timestamp,
};
return this.rpcCall<boolean>('post_waku_v2_relay_v1_message', [
pubSubTopic ? pubSubTopic : DefaultPubSubTopic,
rpcMessage,
]);
}
async messages(): Promise<WakuMessage[]> {
this.checkProcess();
const isDefined = (msg: WakuMessage | undefined): msg is WakuMessage => {
return !!msg;
};
const protoMsgs = await this.rpcCall<proto.WakuMessage[]>(
'get_waku_v2_relay_v1_messages',
[DefaultPubSubTopic]
);
const msgs = await Promise.all(
protoMsgs.map(async (protoMsg) => await WakuMessage.decodeProto(protoMsg))
);
return msgs.filter(isDefined);
}
async getAsymmetricKeyPair(): Promise<KeyPair> {
this.checkProcess();
const { seckey, pubkey } = await this.rpcCall<{
seckey: string;
pubkey: string;
}>('get_waku_v2_private_v1_asymmetric_keypair', []);
return { privateKey: seckey, publicKey: pubkey };
}
async postAsymmetricMessage(
message: WakuRelayMessage,
publicKey: Uint8Array,
pubSubTopic?: string
): Promise<boolean> {
this.checkProcess();
if (!message.payload) {
throw 'Attempting to send empty message';
}
return this.rpcCall<boolean>('post_waku_v2_private_v1_asymmetric_message', [
pubSubTopic ? pubSubTopic : DefaultPubSubTopic,
message,
'0x' + bufToHex(publicKey),
]);
}
async getAsymmetricMessages(
privateKey: Uint8Array,
pubSubTopic?: string
): Promise<WakuRelayMessage[]> {
this.checkProcess();
return await this.rpcCall<WakuRelayMessage[]>(
'get_waku_v2_private_v1_asymmetric_messages',
[
pubSubTopic ? pubSubTopic : DefaultPubSubTopic,
'0x' + bufToHex(privateKey),
]
);
}
async getSymmetricKey(): Promise<Buffer> {
this.checkProcess();
return this.rpcCall<string>(
'get_waku_v2_private_v1_symmetric_key',
[]
).then(hexToBuf);
}
async postSymmetricMessage(
message: WakuRelayMessage,
symKey: Uint8Array,
pubSubTopic?: string
): Promise<boolean> {
this.checkProcess();
if (!message.payload) {
throw 'Attempting to send empty message';
}
return this.rpcCall<boolean>('post_waku_v2_private_v1_symmetric_message', [
pubSubTopic ? pubSubTopic : DefaultPubSubTopic,
message,
'0x' + bufToHex(symKey),
]);
}
async getSymmetricMessages(
symKey: Uint8Array,
pubSubTopic?: string
): Promise<WakuRelayMessage[]> {
this.checkProcess();
return await this.rpcCall<WakuRelayMessage[]>(
'get_waku_v2_private_v1_symmetric_messages',
[pubSubTopic ? pubSubTopic : DefaultPubSubTopic, '0x' + bufToHex(symKey)]
);
}
async getPeerId(): Promise<PeerId> {
return await this.setPeerId().then((res) => res.peerId);
}
async getMultiaddrWithId(): Promise<Multiaddr> {
return await this.setPeerId().then((res) => res.multiaddrWithId);
}
private async setPeerId(): Promise<{
peerId: PeerId;
multiaddrWithId: Multiaddr;
}> {
if (this.peerId && this.multiaddrWithId) {
return { peerId: this.peerId, multiaddrWithId: this.multiaddrWithId };
}
const res = await this.info();
this.multiaddrWithId = multiaddr(res.listenStr);
const peerIdStr = this.multiaddrWithId.getPeerId();
if (!peerIdStr) throw 'Nim-waku multiaddr does not contain peerId';
this.peerId = PeerId.createFromB58String(peerIdStr);
return { peerId: this.peerId, multiaddrWithId: this.multiaddrWithId };
}
get multiaddr(): Multiaddr {
const port = NIM_WAKU_DEFAULT_P2P_PORT + this.portsShift;
return multiaddr(`/ip4/127.0.0.1/tcp/${port}/`);
}
get rpcUrl(): string {
const port = NIM_WAKU_DEFAULT_RPC_PORT + this.portsShift;
return `http://localhost:${port}/`;
}
private async rpcCall<T>(
method: string,
params: Array<string | number | unknown>
): Promise<T> {
const res = await axios.post(
this.rpcUrl,
{
jsonrpc: '2.0',
id: 1,
method,
params,
},
{
headers: { 'Content-Type': 'application/json' },
}
);
return res.data.result;
}
private checkProcess(): void {
if (!this.process) {
throw "Nim Waku isn't started";
}
}
}
export function argsToArray(args: Args): Array<string> {
const array = [];
for (const [key, value] of Object.entries(args)) {
// Change the key from camelCase to kebab-case
const kebabKey = key.replace(/([A-Z])/, (_, capital) => {
return '-' + capital.toLowerCase();
});
const arg = `--${kebabKey}=${value}`;
array.push(arg);
}
return array;
}
export function defaultArgs(): Args {
return {
nat: 'none',
listenAddress: '127.0.0.1',
relay: true,
rpc: true,
rpcAdmin: true,
};
}
export function strToHex(str: string): string {
let hex: string;
try {
hex = unescape(encodeURIComponent(str))
.split('')
.map(function (v) {
return v.charCodeAt(0).toString(16);
})
.join('');
} catch (e) {
hex = str;
console.log('invalid text input: ' + str);
}
return hex;
}
export function bufToHex(buffer: Uint8Array): string {
return Array.prototype.map
.call(buffer, (x) => ('00' + x.toString(16)).slice(-2))
.join('');
}
interface RpcInfoResponse {
// multiaddr including id.
listenStr: string;
} | the_stack |
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {ForceSvgComponent} from './forcesvg.component';
import {
FnService, IconService,
LionService,
LogService, SvgUtilService,
UrlFnService,
WebSocketService
} from 'org_onosproject_onos/web/gui2-fw-lib/public_api';
import {DraggableDirective} from './draggable/draggable.directive';
import {ActivatedRoute, Params} from '@angular/router';
import {of} from 'rxjs';
import {DeviceNodeSvgComponent} from './visuals/devicenodesvg/devicenodesvg.component';
import {SubRegionNodeSvgComponent} from './visuals/subregionnodesvg/subregionnodesvg.component';
import {HostNodeSvgComponent} from './visuals/hostnodesvg/hostnodesvg.component';
import {LinkSvgComponent} from './visuals/linksvg/linksvg.component';
import {Device, Host, Link, LinkType, LinkHighlight, Region, Node} from './models';
import {ChangeDetectorRef, SimpleChange} from '@angular/core';
import {TopologyService} from '../../topology.service';
import {BadgeSvgComponent} from './visuals/badgesvg/badgesvg.component';
export const test_module_topo2CurrentRegion = `{
"event": "topo2CurrentRegion",
"payload": {
"id": "(root)",
"subregions": [],
"links": [
{
"id": "00:AA:00:00:00:03/None~of:0000000000000205/6",
"epA": "00:AA:00:00:00:03/None",
"epB": "of:0000000000000205",
"type": "UiEdgeLink",
"portB": "6",
"rollup": [
{
"id": "00:AA:00:00:00:03/None~of:0000000000000205/6",
"epA": "00:AA:00:00:00:03/None",
"epB": "of:0000000000000205",
"type": "UiEdgeLink",
"portB": "6"
}
]
},
{
"id": "of:0000000000000205/3~of:0000000000000227/5",
"epA": "of:0000000000000205/3",
"epB": "of:0000000000000227/5",
"type": "UiDeviceLink",
"portA": "3",
"portB": "5",
"rollup": [
{
"id": "of:0000000000000205/3~of:0000000000000227/5",
"epA": "of:0000000000000205/3",
"epB": "of:0000000000000227/5",
"type": "UiDeviceLink",
"portA": "3",
"portB": "5"
}
]
},
{
"id": "of:0000000000000206/2~of:0000000000000226/8",
"epA": "of:0000000000000206/2",
"epB": "of:0000000000000226/8",
"type": "UiDeviceLink",
"portA": "2",
"portB": "8",
"rollup": [
{
"id": "of:0000000000000206/2~of:0000000000000226/8",
"epA": "of:0000000000000206/2",
"epB": "of:0000000000000226/8",
"type": "UiDeviceLink",
"portA": "2",
"portB": "8"
}
]
},
{
"id": "00:BB:00:00:00:05/None~of:0000000000000203/7",
"epA": "00:BB:00:00:00:05/None",
"epB": "of:0000000000000203",
"type": "UiEdgeLink",
"portB": "7",
"rollup": [
{
"id": "00:BB:00:00:00:05/None~of:0000000000000203/7",
"epA": "00:BB:00:00:00:05/None",
"epB": "of:0000000000000203",
"type": "UiEdgeLink",
"portB": "7"
}
]
},
{
"id": "00:DD:00:00:00:01/None~of:0000000000000207/3",
"epA": "00:DD:00:00:00:01/None",
"epB": "of:0000000000000207",
"type": "UiEdgeLink",
"portB": "3",
"rollup": [
{
"id": "00:DD:00:00:00:01/None~of:0000000000000207/3",
"epA": "00:DD:00:00:00:01/None",
"epB": "of:0000000000000207",
"type": "UiEdgeLink",
"portB": "3"
}
]
},
{
"id": "of:0000000000000203/1~of:0000000000000226/1",
"epA": "of:0000000000000203/1",
"epB": "of:0000000000000226/1",
"type": "UiDeviceLink",
"portA": "1",
"portB": "1",
"rollup": [
{
"id": "of:0000000000000203/1~of:0000000000000226/1",
"epA": "of:0000000000000203/1",
"epB": "of:0000000000000226/1",
"type": "UiDeviceLink",
"portA": "1",
"portB": "1"
}
]
},
{
"id": "of:0000000000000207/2~of:0000000000000247/1",
"epA": "of:0000000000000207/2",
"epB": "of:0000000000000247/1",
"type": "UiDeviceLink",
"portA": "2",
"portB": "1",
"rollup": [
{
"id": "of:0000000000000207/2~of:0000000000000247/1",
"epA": "of:0000000000000207/2",
"epB": "of:0000000000000247/1",
"type": "UiDeviceLink",
"portA": "2",
"portB": "1"
}
]
},
{
"id": "00:99:66:00:00:01/None~of:0000000000000205/10",
"epA": "00:99:66:00:00:01/None",
"epB": "of:0000000000000205",
"type": "UiEdgeLink",
"portB": "10",
"rollup": [
{
"id": "00:99:66:00:00:01/None~of:0000000000000205/10",
"epA": "00:99:66:00:00:01/None",
"epB": "of:0000000000000205",
"type": "UiEdgeLink",
"portB": "10"
}
]
},
{
"id": "of:0000000000000208/1~of:0000000000000246/2",
"epA": "of:0000000000000208/1",
"epB": "of:0000000000000246/2",
"type": "UiDeviceLink",
"portA": "1",
"portB": "2",
"rollup": [
{
"id": "of:0000000000000208/1~of:0000000000000246/2",
"epA": "of:0000000000000208/1",
"epB": "of:0000000000000246/2",
"type": "UiDeviceLink",
"portA": "1",
"portB": "2"
}
]
},
{
"id": "of:0000000000000206/1~of:0000000000000226/7",
"epA": "of:0000000000000206/1",
"epB": "of:0000000000000226/7",
"type": "UiDeviceLink",
"portA": "1",
"portB": "7",
"rollup": [
{
"id": "of:0000000000000206/1~of:0000000000000226/7",
"epA": "of:0000000000000206/1",
"epB": "of:0000000000000226/7",
"type": "UiDeviceLink",
"portA": "1",
"portB": "7"
}
]
},
{
"id": "of:0000000000000226/9~of:0000000000000246/3",
"epA": "of:0000000000000226/9",
"epB": "of:0000000000000246/3",
"type": "UiDeviceLink",
"portA": "9",
"portB": "3",
"rollup": [
{
"id": "of:0000000000000226/9~of:0000000000000246/3",
"epA": "of:0000000000000226/9",
"epB": "of:0000000000000246/3",
"type": "UiDeviceLink",
"portA": "9",
"portB": "3"
}
]
},
{
"id": "00:AA:00:00:00:04/None~of:0000000000000205/7",
"epA": "00:AA:00:00:00:04/None",
"epB": "of:0000000000000205",
"type": "UiEdgeLink",
"portB": "7",
"rollup": [
{
"id": "00:AA:00:00:00:04/None~of:0000000000000205/7",
"epA": "00:AA:00:00:00:04/None",
"epB": "of:0000000000000205",
"type": "UiEdgeLink",
"portB": "7"
}
]
},
{
"id": "00:88:00:00:00:03/110~of:0000000000000205/11",
"epA": "00:88:00:00:00:03/110",
"epB": "of:0000000000000205",
"type": "UiEdgeLink",
"portB": "11",
"rollup": [
{
"id": "00:88:00:00:00:03/110~of:0000000000000205/11",
"epA": "00:88:00:00:00:03/110",
"epB": "of:0000000000000205",
"type": "UiEdgeLink",
"portB": "11"
}
]
},
{
"id": "of:0000000000000204/1~of:0000000000000226/3",
"epA": "of:0000000000000204/1",
"epB": "of:0000000000000226/3",
"type": "UiDeviceLink",
"portA": "1",
"portB": "3",
"rollup": [
{
"id": "of:0000000000000204/1~of:0000000000000226/3",
"epA": "of:0000000000000204/1",
"epB": "of:0000000000000226/3",
"type": "UiDeviceLink",
"portA": "1",
"portB": "3"
}
]
},
{
"id": "of:0000000000000203/2~of:0000000000000226/2",
"epA": "of:0000000000000203/2",
"epB": "of:0000000000000226/2",
"type": "UiDeviceLink",
"portA": "2",
"portB": "2",
"rollup": [
{
"id": "of:0000000000000203/2~of:0000000000000226/2",
"epA": "of:0000000000000203/2",
"epB": "of:0000000000000226/2",
"type": "UiDeviceLink",
"portA": "2",
"portB": "2"
}
]
},
{
"id": "00:88:00:00:00:01/None~of:0000000000000205/12",
"epA": "00:88:00:00:00:01/None",
"epB": "of:0000000000000205",
"type": "UiEdgeLink",
"portB": "12",
"rollup": [
{
"id": "00:88:00:00:00:01/None~of:0000000000000205/12",
"epA": "00:88:00:00:00:01/None",
"epB": "of:0000000000000205",
"type": "UiEdgeLink",
"portB": "12"
}
]
},
{
"id": "00:88:00:00:00:04/160~of:0000000000000206/6",
"epA": "00:88:00:00:00:04/160",
"epB": "of:0000000000000206",
"type": "UiEdgeLink",
"portB": "6",
"rollup": [
{
"id": "00:88:00:00:00:04/160~of:0000000000000206/6",
"epA": "00:88:00:00:00:04/160",
"epB": "of:0000000000000206",
"type": "UiEdgeLink",
"portB": "6"
}
]
},
{
"id": "00:DD:00:00:00:02/None~of:0000000000000208/3",
"epA": "00:DD:00:00:00:02/None",
"epB": "of:0000000000000208",
"type": "UiEdgeLink",
"portB": "3",
"rollup": [
{
"id": "00:DD:00:00:00:02/None~of:0000000000000208/3",
"epA": "00:DD:00:00:00:02/None",
"epB": "of:0000000000000208",
"type": "UiEdgeLink",
"portB": "3"
}
]
},
{
"id": "of:0000000000000203/3~of:0000000000000227/1",
"epA": "of:0000000000000203/3",
"epB": "of:0000000000000227/1",
"type": "UiDeviceLink",
"portA": "3",
"portB": "1",
"rollup": [
{
"id": "of:0000000000000203/3~of:0000000000000227/1",
"epA": "of:0000000000000203/3",
"epB": "of:0000000000000227/1",
"type": "UiDeviceLink",
"portA": "3",
"portB": "1"
}
]
},
{
"id": "of:0000000000000208/2~of:0000000000000247/2",
"epA": "of:0000000000000208/2",
"epB": "of:0000000000000247/2",
"type": "UiDeviceLink",
"portA": "2",
"portB": "2",
"rollup": [
{
"id": "of:0000000000000208/2~of:0000000000000247/2",
"epA": "of:0000000000000208/2",
"epB": "of:0000000000000247/2",
"type": "UiDeviceLink",
"portA": "2",
"portB": "2"
}
]
},
{
"id": "of:0000000000000205/1~of:0000000000000226/5",
"epA": "of:0000000000000205/1",
"epB": "of:0000000000000226/5",
"type": "UiDeviceLink",
"portA": "1",
"portB": "5",
"rollup": [
{
"id": "of:0000000000000205/1~of:0000000000000226/5",
"epA": "of:0000000000000205/1",
"epB": "of:0000000000000226/5",
"type": "UiDeviceLink",
"portA": "1",
"portB": "5"
}
]
},
{
"id": "of:0000000000000204/2~of:0000000000000226/4",
"epA": "of:0000000000000204/2",
"epB": "of:0000000000000226/4",
"type": "UiDeviceLink",
"portA": "2",
"portB": "4",
"rollup": [
{
"id": "of:0000000000000204/2~of:0000000000000226/4",
"epA": "of:0000000000000204/2",
"epB": "of:0000000000000226/4",
"type": "UiDeviceLink",
"portA": "2",
"portB": "4"
}
]
},
{
"id": "00:AA:00:00:00:01/None~of:0000000000000204/6",
"epA": "00:AA:00:00:00:01/None",
"epB": "of:0000000000000204",
"type": "UiEdgeLink",
"portB": "6",
"rollup": [
{
"id": "00:AA:00:00:00:01/None~of:0000000000000204/6",
"epA": "00:AA:00:00:00:01/None",
"epB": "of:0000000000000204",
"type": "UiEdgeLink",
"portB": "6"
}
]
},
{
"id": "00:BB:00:00:00:03/None~of:0000000000000205/8",
"epA": "00:BB:00:00:00:03/None",
"epB": "of:0000000000000205",
"type": "UiEdgeLink",
"portB": "8",
"rollup": [
{
"id": "00:BB:00:00:00:03/None~of:0000000000000205/8",
"epA": "00:BB:00:00:00:03/None",
"epB": "of:0000000000000205",
"type": "UiEdgeLink",
"portB": "8"
}
]
},
{
"id": "of:0000000000000206/4~of:0000000000000227/8",
"epA": "of:0000000000000206/4",
"epB": "of:0000000000000227/8",
"type": "UiDeviceLink",
"portA": "4",
"portB": "8",
"rollup": [
{
"id": "of:0000000000000206/4~of:0000000000000227/8",
"epA": "of:0000000000000206/4",
"epB": "of:0000000000000227/8",
"type": "UiDeviceLink",
"portA": "4",
"portB": "8"
}
]
},
{
"id": "00:AA:00:00:00:05/None~of:0000000000000203/6",
"epA": "00:AA:00:00:00:05/None",
"epB": "of:0000000000000203",
"type": "UiEdgeLink",
"portB": "6",
"rollup": [
{
"id": "00:AA:00:00:00:05/None~of:0000000000000203/6",
"epA": "00:AA:00:00:00:05/None",
"epB": "of:0000000000000203",
"type": "UiEdgeLink",
"portB": "6"
}
]
},
{
"id": "of:0000000000000205/5~of:0000000000000206/5",
"epA": "of:0000000000000205/5",
"epB": "of:0000000000000206/5",
"type": "UiDeviceLink",
"portA": "5",
"portB": "5",
"rollup": [
{
"id": "of:0000000000000205/5~of:0000000000000206/5",
"epA": "of:0000000000000205/5",
"epB": "of:0000000000000206/5",
"type": "UiDeviceLink",
"portA": "5",
"portB": "5"
}
]
},
{
"id": "00:BB:00:00:00:02/None~of:0000000000000204/9",
"epA": "00:BB:00:00:00:02/None",
"epB": "of:0000000000000204",
"type": "UiEdgeLink",
"portB": "9",
"rollup": [
{
"id": "00:BB:00:00:00:02/None~of:0000000000000204/9",
"epA": "00:BB:00:00:00:02/None",
"epB": "of:0000000000000204",
"type": "UiEdgeLink",
"portB": "9"
}
]
},
{
"id": "of:0000000000000204/3~of:0000000000000227/3",
"epA": "of:0000000000000204/3",
"epB": "of:0000000000000227/3",
"type": "UiDeviceLink",
"portA": "3",
"portB": "3",
"rollup": [
{
"id": "of:0000000000000204/3~of:0000000000000227/3",
"epA": "of:0000000000000204/3",
"epB": "of:0000000000000227/3",
"type": "UiDeviceLink",
"portA": "3",
"portB": "3"
}
]
},
{
"id": "00:EE:00:00:00:01/None~of:0000000000000207/4",
"epA": "00:EE:00:00:00:01/None",
"epB": "of:0000000000000207",
"type": "UiEdgeLink",
"portB": "4",
"rollup": [
{
"id": "00:EE:00:00:00:01/None~of:0000000000000207/4",
"epA": "00:EE:00:00:00:01/None",
"epB": "of:0000000000000207",
"type": "UiEdgeLink",
"portB": "4"
}
]
},
{
"id": "of:0000000000000203/4~of:0000000000000227/2",
"epA": "of:0000000000000203/4",
"epB": "of:0000000000000227/2",
"type": "UiDeviceLink",
"portA": "4",
"portB": "2",
"rollup": [
{
"id": "of:0000000000000203/4~of:0000000000000227/2",
"epA": "of:0000000000000203/4",
"epB": "of:0000000000000227/2",
"type": "UiDeviceLink",
"portA": "4",
"portB": "2"
}
]
},
{
"id": "of:0000000000000205/2~of:0000000000000226/6",
"epA": "of:0000000000000205/2",
"epB": "of:0000000000000226/6",
"type": "UiDeviceLink",
"portA": "2",
"portB": "6",
"rollup": [
{
"id": "of:0000000000000205/2~of:0000000000000226/6",
"epA": "of:0000000000000205/2",
"epB": "of:0000000000000226/6",
"type": "UiDeviceLink",
"portA": "2",
"portB": "6"
}
]
},
{
"id": "00:99:00:00:00:01/None~of:0000000000000205/10",
"epA": "00:99:00:00:00:01/None",
"epB": "of:0000000000000205",
"type": "UiEdgeLink",
"portB": "10",
"rollup": [
{
"id": "00:99:00:00:00:01/None~of:0000000000000205/10",
"epA": "00:99:00:00:00:01/None",
"epB": "of:0000000000000205",
"type": "UiEdgeLink",
"portB": "10"
}
]
},
{
"id": "of:0000000000000205/4~of:0000000000000227/6",
"epA": "of:0000000000000205/4",
"epB": "of:0000000000000227/6",
"type": "UiDeviceLink",
"portA": "4",
"portB": "6",
"rollup": [
{
"id": "of:0000000000000205/4~of:0000000000000227/6",
"epA": "of:0000000000000205/4",
"epB": "of:0000000000000227/6",
"type": "UiDeviceLink",
"portA": "4",
"portB": "6"
}
]
},
{
"id": "of:0000000000000206/3~of:0000000000000227/7",
"epA": "of:0000000000000206/3",
"epB": "of:0000000000000227/7",
"type": "UiDeviceLink",
"portA": "3",
"portB": "7",
"rollup": [
{
"id": "of:0000000000000206/3~of:0000000000000227/7",
"epA": "of:0000000000000206/3",
"epB": "of:0000000000000227/7",
"type": "UiDeviceLink",
"portA": "3",
"portB": "7"
}
]
},
{
"id": "00:BB:00:00:00:04/None~of:0000000000000205/9",
"epA": "00:BB:00:00:00:04/None",
"epB": "of:0000000000000205",
"type": "UiEdgeLink",
"portB": "9",
"rollup": [
{
"id": "00:BB:00:00:00:04/None~of:0000000000000205/9",
"epA": "00:BB:00:00:00:04/None",
"epB": "of:0000000000000205",
"type": "UiEdgeLink",
"portB": "9"
}
]
},
{
"id": "00:AA:00:00:00:02/None~of:0000000000000204/7",
"epA": "00:AA:00:00:00:02/None",
"epB": "of:0000000000000204",
"type": "UiEdgeLink",
"portB": "7",
"rollup": [
{
"id": "00:AA:00:00:00:02/None~of:0000000000000204/7",
"epA": "00:AA:00:00:00:02/None",
"epB": "of:0000000000000204",
"type": "UiEdgeLink",
"portB": "7"
}
]
},
{
"id": "00:BB:00:00:00:01/None~of:0000000000000204/8",
"epA": "00:BB:00:00:00:01/None",
"epB": "of:0000000000000204",
"type": "UiEdgeLink",
"portB": "8",
"rollup": [
{
"id": "00:BB:00:00:00:01/None~of:0000000000000204/8",
"epA": "00:BB:00:00:00:01/None",
"epB": "of:0000000000000204",
"type": "UiEdgeLink",
"portB": "8"
}
]
},
{
"id": "of:0000000000000207/1~of:0000000000000246/1",
"epA": "of:0000000000000207/1",
"epB": "of:0000000000000246/1",
"type": "UiDeviceLink",
"portA": "1",
"portB": "1",
"rollup": [
{
"id": "of:0000000000000207/1~of:0000000000000246/1",
"epA": "of:0000000000000207/1",
"epB": "of:0000000000000246/1",
"type": "UiDeviceLink",
"portA": "1",
"portB": "1"
}
]
},
{
"id": "00:88:00:00:00:02/None~of:0000000000000206/7",
"epA": "00:88:00:00:00:02/None",
"epB": "of:0000000000000206",
"type": "UiEdgeLink",
"portB": "7",
"rollup": [
{
"id": "00:88:00:00:00:02/None~of:0000000000000206/7",
"epA": "00:88:00:00:00:02/None",
"epB": "of:0000000000000206",
"type": "UiEdgeLink",
"portB": "7"
}
]
},
{
"id": "00:EE:00:00:00:02/None~of:0000000000000208/4",
"epA": "00:EE:00:00:00:02/None",
"epB": "of:0000000000000208",
"type": "UiEdgeLink",
"portB": "4",
"rollup": [
{
"id": "00:EE:00:00:00:02/None~of:0000000000000208/4",
"epA": "00:EE:00:00:00:02/None",
"epB": "of:0000000000000208",
"type": "UiEdgeLink",
"portB": "4"
}
]
},
{
"id": "of:0000000000000204/4~of:0000000000000227/4",
"epA": "of:0000000000000204/4",
"epB": "of:0000000000000227/4",
"type": "UiDeviceLink",
"portA": "4",
"portB": "4",
"rollup": [
{
"id": "of:0000000000000204/4~of:0000000000000227/4",
"epA": "of:0000000000000204/4",
"epB": "of:0000000000000227/4",
"type": "UiDeviceLink",
"portA": "4",
"portB": "4"
}
]
},
{
"id": "of:0000000000000203/5~of:0000000000000204/5",
"epA": "of:0000000000000203/5",
"epB": "of:0000000000000204/5",
"type": "UiDeviceLink",
"portA": "5",
"portB": "5",
"rollup": [
{
"id": "of:0000000000000203/5~of:0000000000000204/5",
"epA": "of:0000000000000203/5",
"epB": "of:0000000000000204/5",
"type": "UiDeviceLink",
"portA": "5",
"portB": "5"
}
]
},
{
"id": "of:0000000000000227/9~of:0000000000000247/3",
"epA": "of:0000000000000227/9",
"epB": "of:0000000000000247/3",
"type": "UiDeviceLink",
"portA": "9",
"portB": "3",
"rollup": [
{
"id": "of:0000000000000227/9~of:0000000000000247/3",
"epA": "of:0000000000000227/9",
"epB": "of:0000000000000247/3",
"type": "UiDeviceLink",
"portA": "9",
"portB": "3"
}
]
}
],
"devices": [
[],
[],
[
{
"id": "of:0000000000000246",
"nodeType": "device",
"type": "switch",
"online": true,
"master": "10.192.19.68",
"layer": "def",
"props": {
"managementAddress": "10.192.19.69",
"protocol": "OF_13",
"driver": "ofdpa-ovs",
"latitude": "40.15",
"name": "s246",
"locType": "geo",
"channelId": "10.192.19.69:59980",
"longitude": "-121.679"
},
"location": {
"locType": "geo",
"latOrY": 40.15,
"longOrX": -121.679
}
},
{
"id": "of:0000000000000206",
"nodeType": "device",
"type": "switch",
"online": true,
"master": "10.192.19.68",
"layer": "def",
"props": {
"managementAddress": "10.192.19.69",
"protocol": "OF_13",
"driver": "ofdpa-ovs",
"latitude": "36.766",
"name": "s206",
"locType": "geo",
"channelId": "10.192.19.69:59975",
"longitude": "-92.029"
},
"location": {
"locType": "geo",
"latOrY": 36.766,
"longOrX": -92.029
}
},
{
"id": "of:0000000000000227",
"nodeType": "device",
"type": "switch",
"online": true,
"master": "10.192.19.68",
"layer": "def",
"props": {
"managementAddress": "10.192.19.69",
"protocol": "OF_13",
"driver": "ofdpa-ovs",
"latitude": "44.205",
"name": "s227",
"locType": "geo",
"channelId": "10.192.19.69:59979",
"longitude": "-96.359"
},
"location": {
"locType": "geo",
"latOrY": 44.205,
"longOrX": -96.359
}
},
{
"id": "of:0000000000000208",
"nodeType": "device",
"type": "switch",
"online": true,
"master": "10.192.19.68",
"layer": "def",
"props": {
"managementAddress": "10.192.19.69",
"protocol": "OF_13",
"driver": "ofdpa-ovs",
"latitude": "36.766",
"name": "s208",
"locType": "geo",
"channelId": "10.192.19.69:59977",
"longitude": "-116.029"
},
"location": {
"locType": "geo",
"latOrY": 36.766,
"longOrX": -116.029
}
},
{
"id": "of:0000000000000205",
"nodeType": "device",
"type": "switch",
"online": true,
"master": "10.192.19.68",
"layer": "def",
"props": {
"managementAddress": "10.192.19.69",
"protocol": "OF_13",
"driver": "ofdpa-ovs",
"latitude": "36.766",
"name": "s205",
"locType": "geo",
"channelId": "10.192.19.69:59974",
"longitude": "-96.89"
},
"location": {
"locType": "geo",
"latOrY": 36.766,
"longOrX": -96.89
}
},
{
"id": "of:0000000000000247",
"nodeType": "device",
"type": "switch",
"online": true,
"master": "10.192.19.68",
"layer": "def",
"props": {
"managementAddress": "10.192.19.69",
"protocol": "OF_13",
"driver": "ofdpa-ovs",
"latitude": "40.205",
"name": "s247",
"locType": "geo",
"channelId": "10.192.19.69:59981",
"longitude": "-117.359"
},
"location": {
"locType": "geo",
"latOrY": 40.205,
"longOrX": -117.359
}
},
{
"id": "of:0000000000000226",
"nodeType": "device",
"type": "switch",
"online": true,
"master": "10.192.19.68",
"layer": "def",
"props": {
"managementAddress": "10.192.19.69",
"protocol": "OF_13",
"driver": "ofdpa-ovs",
"latitude": "44.15",
"name": "s226",
"locType": "geo",
"channelId": "10.192.19.69:59978",
"longitude": "-107.679"
},
"location": {
"locType": "geo",
"latOrY": 44.15,
"longOrX": -107.679
}
},
{
"id": "of:0000000000000203",
"nodeType": "device",
"type": "switch",
"online": true,
"master": "10.192.19.68",
"layer": "def",
"props": {
"managementAddress": "10.192.19.69",
"protocol": "OF_13",
"driver": "ofdpa-ovs",
"latitude": "36.766",
"name": "s203",
"locType": "geo",
"channelId": "10.192.19.69:59972",
"longitude": "-111.359"
},
"location": {
"locType": "geo",
"latOrY": 36.766,
"longOrX": -111.359
}
},
{
"id": "of:0000000000000204",
"nodeType": "device",
"type": "switch",
"online": true,
"master": "10.192.19.68",
"layer": "def",
"props": {
"managementAddress": "10.192.19.69",
"protocol": "OF_13",
"driver": "ofdpa-ovs",
"latitude": "36.766",
"name": "s204",
"locType": "geo",
"channelId": "10.192.19.69:59973",
"longitude": "-106.359"
},
"location": {
"locType": "geo",
"latOrY": 36.766,
"longOrX": -106.359
}
},
{
"id": "of:0000000000000207",
"nodeType": "device",
"type": "switch",
"online": true,
"master": "10.192.19.68",
"layer": "def",
"props": {
"managementAddress": "10.192.19.69",
"protocol": "OF_13",
"driver": "ofdpa-ovs",
"latitude": "36.766",
"name": "s207",
"locType": "geo",
"channelId": "10.192.19.69:59976",
"longitude": "-122.359"
},
"location": {
"locType": "geo",
"latOrY": 36.766,
"longOrX": -122.359
}
}
]
],
"hosts": [
[],
[],
[
{
"id": "00:88:00:00:00:03/110",
"nodeType": "host",
"layer": "def",
"ips": [
"fe80::288:ff:fe00:3",
"2000::102",
"10.0.1.2"
],
"props": {},
"configured": false
},
{
"id": "00:DD:00:00:00:01/None",
"nodeType": "host",
"layer": "def",
"ips": [],
"props": {},
"configured": false
},
{
"id": "00:88:00:00:00:04/160",
"nodeType": "host",
"layer": "def",
"ips": [
"fe80::288:ff:fe00:4",
"10.0.6.2",
"2000::602"
],
"props": {},
"configured": false
},
{
"id": "00:BB:00:00:00:02/None",
"nodeType": "host",
"layer": "def",
"ips": [
"fe80::2bb:ff:fe00:2"
],
"props": {},
"configured": false
},
{
"id": "00:AA:00:00:00:05/None",
"nodeType": "host",
"layer": "def",
"ips": [],
"props": {},
"configured": false
},
{
"id": "00:88:00:00:00:01/None",
"nodeType": "host",
"layer": "def",
"ips": [
"fe80::288:ff:fe00:1",
"2000::101",
"10.0.1.1"
],
"props": {},
"configured": false
},
{
"id": "00:AA:00:00:00:01/None",
"nodeType": "host",
"layer": "def",
"ips": [],
"props": {},
"configured": false
},
{
"id": "00:AA:00:00:00:03/None",
"nodeType": "host",
"layer": "def",
"ips": [],
"props": {},
"configured": false
},
{
"id": "00:BB:00:00:00:04/None",
"nodeType": "host",
"layer": "def",
"ips": [
"fe80::2bb:ff:fe00:4"
],
"props": {},
"configured": false
},
{
"id": "00:EE:00:00:00:02/None",
"nodeType": "host",
"layer": "def",
"ips": [
"fe80::2ee:ff:fe00:2"
],
"props": {},
"configured": false
},
{
"id": "00:99:00:00:00:01/None",
"nodeType": "host",
"layer": "def",
"ips": [
"10.0.3.253",
"fe80::299:ff:fe00:1"
],
"props": {},
"configured": false
},
{
"id": "00:99:66:00:00:01/None",
"nodeType": "host",
"layer": "def",
"ips": [
"fe80::299:66ff:fe00:1",
"2000::3fd"
],
"props": {},
"configured": false
},
{
"id": "00:EE:00:00:00:01/None",
"nodeType": "host",
"layer": "def",
"ips": [
"fe80::2ee:ff:fe00:1"
],
"props": {},
"configured": false
},
{
"id": "00:BB:00:00:00:01/None",
"nodeType": "host",
"layer": "def",
"ips": [
"fe80::2bb:ff:fe00:1"
],
"props": {},
"configured": false
},
{
"id": "00:BB:00:00:00:03/None",
"nodeType": "host",
"layer": "def",
"ips": [
"fe80::2bb:ff:fe00:3"
],
"props": {},
"configured": false
},
{
"id": "00:AA:00:00:00:04/None",
"nodeType": "host",
"layer": "def",
"ips": [],
"props": {},
"configured": false
},
{
"id": "00:BB:00:00:00:05/None",
"nodeType": "host",
"layer": "def",
"ips": [
"fe80::2bb:ff:fe00:5"
],
"props": {},
"configured": false
},
{
"id": "00:88:00:00:00:02/None",
"nodeType": "host",
"layer": "def",
"ips": [
"fe80::288:ff:fe00:2",
"2000::601",
"10.0.6.1"
],
"props": {},
"configured": false
},
{
"id": "00:AA:00:00:00:02/None",
"nodeType": "host",
"layer": "def",
"ips": [],
"props": {},
"configured": false
},
{
"id": "00:DD:00:00:00:02/None",
"nodeType": "host",
"layer": "def",
"ips": [],
"props": {},
"configured": false
}
]
],
"layerOrder": [
"opt",
"pkt",
"def"
]
}
}`;
const test_OdtnConfig_topo2CurrentRegion = `{
"event": "topo2CurrentRegion",
"payload": {
"id": "(root)",
"subregions": [],
"links": [
{
"id": "netconf:127.0.0.1:11002/201~netconf:127.0.0.1:11003/201",
"epA": "netconf:127.0.0.1:11002/201",
"epB": "netconf:127.0.0.1:11003/201",
"type": "UiDeviceLink",
"portA": "201",
"portB": "201",
"rollup": [
{
"id": "netconf:127.0.0.1:11002/201~netconf:127.0.0.1:11003/201",
"epA": "netconf:127.0.0.1:11002/201",
"epB": "netconf:127.0.0.1:11003/201",
"type": "UiDeviceLink",
"portA": "201",
"portB": "201"
}
]
},
{
"id": "netconf:127.0.0.1:11002/202~netconf:127.0.0.1:11003/202",
"epA": "netconf:127.0.0.1:11002/202",
"epB": "netconf:127.0.0.1:11003/202",
"type": "UiDeviceLink",
"portA": "202",
"portB": "202",
"rollup": [
{
"id": "netconf:127.0.0.1:11002/202~netconf:127.0.0.1:11003/202",
"epA": "netconf:127.0.0.1:11002/202",
"epB": "netconf:127.0.0.1:11003/202",
"type": "UiDeviceLink",
"portA": "202",
"portB": "202"
}
]
},
{
"id": "netconf:127.0.0.1:11002/203~netconf:127.0.0.1:11003/203",
"epA": "netconf:127.0.0.1:11002/203",
"epB": "netconf:127.0.0.1:11003/203",
"type": "UiDeviceLink",
"portA": "203",
"portB": "203",
"rollup": [
{
"id": "netconf:127.0.0.1:11002/203~netconf:127.0.0.1:11003/203",
"epA": "netconf:127.0.0.1:11002/203",
"epB": "netconf:127.0.0.1:11003/203",
"type": "UiDeviceLink",
"portA": "203",
"portB": "203"
}
]
},
{
"id": "netconf:127.0.0.1:11002/204~netconf:127.0.0.1:11003/204",
"epA": "netconf:127.0.0.1:11002/204",
"epB": "netconf:127.0.0.1:11003/204",
"type": "UiDeviceLink",
"portA": "204",
"portB": "204",
"rollup": [
{
"id": "netconf:127.0.0.1:11002/204~netconf:127.0.0.1:11003/204",
"epA": "netconf:127.0.0.1:11002/204",
"epB": "netconf:127.0.0.1:11003/204",
"type": "UiDeviceLink",
"portA": "204",
"portB": "204"
}
]
},
{
"id": "netconf:127.0.0.1:11002/205~netconf:127.0.0.1:11003/205",
"epA": "netconf:127.0.0.1:11002/205",
"epB": "netconf:127.0.0.1:11003/205",
"type": "UiDeviceLink",
"portA": "205",
"portB": "205",
"rollup": [
{
"id": "netconf:127.0.0.1:11002/205~netconf:127.0.0.1:11003/205",
"epA": "netconf:127.0.0.1:11002/205",
"epB": "netconf:127.0.0.1:11003/205",
"type": "UiDeviceLink",
"portA": "205",
"portB": "205"
}
]
},
{
"id": "netconf:127.0.0.1:11002/206~netconf:127.0.0.1:11003/206",
"epA": "netconf:127.0.0.1:11002/206",
"epB": "netconf:127.0.0.1:11003/206",
"type": "UiDeviceLink",
"portA": "206",
"portB": "206",
"rollup": [
{
"id": "netconf:127.0.0.1:11002/206~netconf:127.0.0.1:11003/206",
"epA": "netconf:127.0.0.1:11002/206",
"epB": "netconf:127.0.0.1:11003/206",
"type": "UiDeviceLink",
"portA": "206",
"portB": "206"
}
]
}
],
"devices": [
[],
[],
[
{
"id": "netconf:127.0.0.1:11002",
"nodeType": "device",
"type": "terminal_device",
"online": true,
"master": "127.0.0.1",
"layer": "def",
"props": {
"ipaddress": "127.0.0.1",
"protocol": "NETCONF",
"driver": "cassini-ocnos",
"port": "11002",
"name": "cassini2",
"locType": "none"
}
},
{
"id": "netconf:127.0.0.1:11003",
"nodeType": "device",
"type": "terminal_device",
"online": true,
"master": "127.0.0.1",
"layer": "def",
"props": {
"ipaddress": "127.0.0.1",
"protocol": "NETCONF",
"driver": "cassini-ocnos",
"port": "11003",
"name": "cassini1",
"locType": "none"
}
}
]
],
"hosts": [
[],
[],
[]
],
"layerOrder": [
"opt",
"pkt",
"def"
]
}
}`;
const topo2Highlights_base_data = `{
"event": "topo2CurrentRegion",
"payload": {
"id": "(root)",
"subregions": [],
"links": [
{
"id": "00:00:00:00:00:22/120~device:leaf4/[3/0](3)",
"epA": "00:00:00:00:00:22/120",
"epB": "device:leaf4",
"type": "UiEdgeLink",
"portB": "[3/0](3)",
"rollup": [
{
"id": "00:00:00:00:00:22/120~device:leaf4/[3/0](3)",
"epA": "00:00:00:00:00:22/120",
"epB": "device:leaf4",
"type": "UiEdgeLink",
"portB": "[3/0](3)"
}
]
},
{
"id": "00:00:00:00:00:1E/None~device:leaf4/[2/0](2)",
"epA": "00:00:00:00:00:1E/None",
"epB": "device:leaf4",
"type": "UiEdgeLink",
"portB": "[2/0](2)",
"rollup": [
{
"id": "00:00:00:00:00:1E/None~device:leaf4/[2/0](2)",
"epA": "00:00:00:00:00:1E/None",
"epB": "device:leaf4",
"type": "UiEdgeLink",
"portB": "[2/0](2)"
}
]
},
{
"id": "device:leaf4/[1/0](1)~device:spine1/[3/0](3)",
"epA": "device:leaf4/[1/0](1)",
"epB": "device:spine1/[3/0](3)",
"type": "UiDeviceLink",
"portA": "[1/0](1)",
"portB": "[3/0](3)",
"rollup": [
{
"id": "device:leaf4/[1/0](1)~device:spine1/[3/0](3)",
"epA": "device:leaf4/[1/0](1)",
"epB": "device:spine1/[3/0](3)",
"type": "UiDeviceLink",
"portA": "[1/0](1)",
"portB": "[3/0](3)"
}
]
},
{
"id": "00:00:00:00:00:21/120~device:leaf3/[leaf3-eth3](3)",
"epA": "00:00:00:00:00:21/120",
"epB": "device:leaf3",
"type": "UiEdgeLink",
"portB": "[leaf3-eth3](3)",
"rollup": [
{
"id": "00:00:00:00:00:21/120~device:leaf3/[leaf3-eth3](3)",
"epA": "00:00:00:00:00:21/120",
"epB": "device:leaf3",
"type": "UiEdgeLink",
"portB": "[leaf3-eth3](3)"
}
]
},
{
"id": "00:00:00:00:00:1D/None~device:leaf3/[leaf3-eth2](2)",
"epA": "00:00:00:00:00:1D/None",
"epB": "device:leaf3",
"type": "UiEdgeLink",
"portB": "[leaf3-eth2](2)",
"rollup": [
{
"id": "00:00:00:00:00:1D/None~device:leaf3/[leaf3-eth2](2)",
"epA": "00:00:00:00:00:1D/None",
"epB": "device:leaf3",
"type": "UiEdgeLink",
"portB": "[leaf3-eth2](2)"
}
]
},
{
"id": "device:leaf3/[leaf3-eth1](1)~device:spine1/[spine1-eth3](3)",
"epA": "device:leaf3/[leaf3-eth1](1)",
"epB": "device:spine1/[spine1-eth3](3)",
"type": "UiDeviceLink",
"portA": "[leaf3-eth1](1)",
"portB": "[spine1-eth3](3)",
"rollup": [
{
"id": "device:leaf3/[leaf3-eth1](1)~device:spine1/[spine1-eth3](3)",
"epA": "device:leaf3/[leaf3-eth1](1)",
"epB": "device:spine1/[spine1-eth3](3)",
"type": "UiDeviceLink",
"portA": "[leaf3-eth1](1)",
"portB": "[spine1-eth3](3)"
}
]
},
{
"id": "00:00:00:00:00:1F/120~device:leaf1/7",
"epA": "00:00:00:00:00:1F/120",
"epB": "device:leaf1",
"type": "UiEdgeLink",
"portB": "7",
"rollup": [
{
"id": "00:00:00:00:00:1F/120~device:leaf1/7",
"epA": "00:00:00:00:00:1F/120",
"epB": "device:leaf1",
"type": "UiEdgeLink",
"portB": "7"
}
]
},
{
"id": "device:leaf1/1~device:spine1/1",
"epA": "device:leaf1/1",
"epB": "device:spine1/1",
"type": "UiDeviceLink",
"portA": "1",
"portB": "1",
"rollup": [
{
"id": "device:leaf1/1~device:spine1/1",
"epA": "device:leaf1/1",
"epB": "device:spine1/1",
"type": "UiDeviceLink",
"portA": "1",
"portB": "1"
}
]
},
{
"id": "device:leaf2/2~device:spine2/2",
"epA": "device:leaf2/2",
"epB": "device:spine2/2",
"type": "UiDeviceLink",
"portA": "2",
"portB": "2",
"rollup": [
{
"id": "device:leaf2/2~device:spine2/2",
"epA": "device:leaf2/2",
"epB": "device:spine2/2",
"type": "UiDeviceLink",
"portA": "2",
"portB": "2"
}
]
},
{
"id": "00:00:00:00:00:1A/None~device:leaf1/3",
"epA": "00:00:00:00:00:1A/None",
"epB": "device:leaf1",
"type": "UiEdgeLink",
"portB": "3",
"rollup": [
{
"id": "00:00:00:00:00:1A/None~device:leaf1/3",
"epA": "00:00:00:00:00:1A/None",
"epB": "device:leaf1",
"type": "UiEdgeLink",
"portB": "3"
}
]
},
{
"id": "00:00:00:00:00:30/None~device:leaf2/3",
"epA": "00:00:00:00:00:30/None",
"epB": "device:leaf2",
"type": "UiEdgeLink",
"portB": "3",
"rollup": [
{
"id": "00:00:00:00:00:30/None~device:leaf2/3",
"epA": "00:00:00:00:00:30/None",
"epB": "device:leaf2",
"type": "UiEdgeLink",
"portB": "3"
}
]
},
{
"id": "device:leaf1/2~device:spine2/1",
"epA": "device:leaf1/2",
"epB": "device:spine2/1",
"type": "UiDeviceLink",
"portA": "2",
"portB": "1",
"rollup": [
{
"id": "device:leaf1/2~device:spine2/1",
"epA": "device:leaf1/2",
"epB": "device:spine2/1",
"type": "UiDeviceLink",
"portA": "2",
"portB": "1"
}
]
},
{
"id": "device:leaf2/1~device:spine1/2",
"epA": "device:leaf2/1",
"epB": "device:spine1/2",
"type": "UiDeviceLink",
"portA": "1",
"portB": "2",
"rollup": [
{
"id": "device:leaf2/1~device:spine1/2",
"epA": "device:leaf2/1",
"epB": "device:spine1/2",
"type": "UiDeviceLink",
"portA": "1",
"portB": "2"
}
]
},
{
"id": "00:00:00:00:00:20/None~device:leaf1/6",
"epA": "00:00:00:00:00:20/None",
"epB": "device:leaf1",
"type": "UiEdgeLink",
"portB": "6",
"rollup": [
{
"id": "00:00:00:00:00:20/None~device:leaf1/6",
"epA": "00:00:00:00:00:20/None",
"epB": "device:leaf1",
"type": "UiEdgeLink",
"portB": "6"
}
]
},
{
"id": "00:00:00:00:00:1C/None~device:leaf1/5",
"epA": "00:00:00:00:00:1C/None",
"epB": "device:leaf1",
"type": "UiEdgeLink",
"portB": "5",
"rollup": [
{
"id": "00:00:00:00:00:1C/None~device:leaf1/5",
"epA": "00:00:00:00:00:1C/None",
"epB": "device:leaf1",
"type": "UiEdgeLink",
"portB": "5"
}
]
},
{
"id": "00:00:00:00:00:1B/None~device:leaf1/4",
"epA": "00:00:00:00:00:1B/None",
"epB": "device:leaf1",
"type": "UiEdgeLink",
"portB": "4",
"rollup": [
{
"id": "00:00:00:00:00:1B/None~device:leaf1/4",
"epA": "00:00:00:00:00:1B/None",
"epB": "device:leaf1",
"type": "UiEdgeLink",
"portB": "4"
}
]
}
],
"devices": [
[],
[],
[
{
"id": "device:leaf4",
"nodeType": "device",
"type": "switch",
"online": true,
"master": "172.24.0.3",
"layer": "def",
"props": {
"managementAddress": "grpc://pippo:50003?device_id=1",
"protocol": "P4Runtime, gNMI, gNOI",
"gridX": "400.0",
"gridY": "400.0",
"driver": "stratum-tofino",
"name": "device:leaf4",
"p4DeviceId": "1",
"locType": "grid"
},
"location": {
"locType": "grid",
"latOrY": 400.0,
"longOrX": 400.0
}
},
{
"id": "device:leaf3",
"nodeType": "device",
"type": "switch",
"online": true,
"master": "172.24.0.3",
"layer": "def",
"props": {
"managementAddress": "grpc://mininet:50003?device_id=1",
"protocol": "P4Runtime, gNMI, gNOI",
"gridX": "400.0",
"gridY": "400.0",
"driver": "stratum-bmv2",
"name": "device:leaf3",
"p4DeviceId": "1",
"locType": "grid"
},
"location": {
"locType": "grid",
"latOrY": 400.0,
"longOrX": 400.0
}
},
{
"id": "device:spine1",
"nodeType": "device",
"type": "switch",
"online": true,
"master": "172.24.0.3",
"layer": "def",
"props": {
"managementAddress": "grpc://mininet:50003?device_id=1",
"protocol": "P4Runtime, gNMI, gNOI",
"gridX": "400.0",
"gridY": "400.0",
"driver": "stratum-bmv2",
"name": "device:spine1",
"p4DeviceId": "1",
"locType": "grid"
},
"location": {
"locType": "grid",
"latOrY": 400.0,
"longOrX": 400.0
}
},
{
"id": "device:spine2",
"nodeType": "device",
"type": "switch",
"online": true,
"master": "172.24.0.3",
"layer": "def",
"props": {
"managementAddress": "grpc://mininet:50004?device_id=1",
"protocol": "P4Runtime, gNMI, gNOI",
"gridX": "600.0",
"gridY": "400.0",
"driver": "stratum-bmv2",
"name": "device:spine2",
"p4DeviceId": "1",
"locType": "grid"
},
"location": {
"locType": "grid",
"latOrY": 400.0,
"longOrX": 600.0
}
},
{
"id": "device:leaf2",
"nodeType": "device",
"type": "switch",
"online": true,
"master": "172.24.0.3",
"layer": "def",
"props": {
"managementAddress": "grpc://mininet:50002?device_id=1",
"protocol": "P4Runtime, gNMI, gNOI",
"gridX": "800.0",
"gridY": "600.0",
"driver": "stratum-bmv2",
"name": "device:leaf2",
"p4DeviceId": "1",
"locType": "grid"
},
"location": {
"locType": "grid",
"latOrY": 600.0,
"longOrX": 800.0
}
},
{
"id": "device:leaf1",
"nodeType": "device",
"type": "switch",
"online": true,
"master": "172.24.0.3",
"layer": "def",
"props": {
"managementAddress": "grpc://mininet:50001?device_id=1",
"protocol": "P4Runtime, gNMI, gNOI",
"gridX": "200.0",
"gridY": "600.0",
"driver": "stratum-bmv2",
"name": "device:leaf1",
"p4DeviceId": "1",
"locType": "grid"
},
"location": {
"locType": "grid",
"latOrY": 600.0,
"longOrX": 200.0
}
}
]
],
"hosts": [
[],
[],
[
{
"id": "00:00:00:00:00:22/120",
"nodeType": "host",
"layer": "def",
"ips": [
"2001:2:3::1"
],
"props": {
"gridX": "750.0",
"gridY": "700.0",
"latitude": null,
"name": "h3",
"locType": "grid",
"longitude": null
},
"location": {
"locType": "grid",
"latOrY": 700.0,
"longOrX": 750.0
},
"configured": false
},
{
"id": "00:00:00:00:00:21/120",
"nodeType": "host",
"layer": "def",
"ips": [
"2001:2:3::1"
],
"props": {
"gridX": "750.0",
"gridY": "700.0",
"latitude": null,
"name": "h3",
"locType": "grid",
"longitude": null
},
"location": {
"locType": "grid",
"latOrY": 700.0,
"longOrX": 750.0
},
"configured": false
},
{
"id": "00:00:00:00:00:1F/120",
"nodeType": "host",
"layer": "def",
"ips": [
"2001:2:3::1"
],
"props": {
"gridX": "750.0",
"gridY": "700.0",
"latitude": null,
"name": "h3",
"locType": "grid",
"longitude": null
},
"location": {
"locType": "grid",
"latOrY": 700.0,
"longOrX": 750.0
},
"configured": false
},
{
"id": "00:00:00:00:00:1E/None",
"nodeType": "host",
"layer": "def",
"ips": [
"2001:2:3::1"
],
"props": {
"gridX": "750.0",
"gridY": "700.0",
"latitude": null,
"name": "h3",
"locType": "grid",
"longitude": null
},
"location": {
"locType": "grid",
"latOrY": 700.0,
"longOrX": 750.0
},
"configured": false
},
{
"id": "00:00:00:00:00:1D/None",
"nodeType": "host",
"layer": "def",
"ips": [
"2001:2:3::1"
],
"props": {
"gridX": "750.0",
"gridY": "700.0",
"latitude": null,
"name": "h3",
"locType": "grid",
"longitude": null
},
"location": {
"locType": "grid",
"latOrY": 700.0,
"longOrX": 750.0
},
"configured": false
},
{
"id": "00:00:00:00:00:30/None",
"nodeType": "host",
"layer": "def",
"ips": [
"2001:2:3::1"
],
"props": {
"gridX": "750.0",
"gridY": "700.0",
"latitude": null,
"name": "h3",
"locType": "grid",
"longitude": null
},
"location": {
"locType": "grid",
"latOrY": 700.0,
"longOrX": 750.0
},
"configured": false
},
{
"id": "00:00:00:00:00:1A/None",
"nodeType": "host",
"layer": "def",
"ips": [
"2001:1:1::a"
],
"props": {
"gridX": "100.0",
"gridY": "700.0",
"latitude": null,
"name": "h1a",
"locType": "grid",
"longitude": null
},
"location": {
"locType": "grid",
"latOrY": 700.0,
"longOrX": 100.0
},
"configured": false
},
{
"id": "00:00:00:00:00:1B/None",
"nodeType": "host",
"layer": "def",
"ips": [
"2001:1:1::b"
],
"props": {
"gridX": "100.0",
"gridY": "800.0",
"latitude": null,
"name": "h1b",
"locType": "grid",
"longitude": null
},
"location": {
"locType": "grid",
"latOrY": 800.0,
"longOrX": 100.0
},
"configured": false
},
{
"id": "00:00:00:00:00:1C/None",
"nodeType": "host",
"layer": "def",
"ips": [
"2001:1:1::c"
],
"props": {
"gridX": "250.0",
"gridY": "800.0",
"latitude": null,
"name": "h1c",
"locType": "grid",
"longitude": null
},
"location": {
"locType": "grid",
"latOrY": 800.0,
"longOrX": 250.0
},
"configured": false
},
{
"id": "00:00:00:00:00:20/None",
"nodeType": "host",
"layer": "def",
"ips": [
"2001:1:2::1"
],
"props": {
"gridX": "400.0",
"gridY": "700.0",
"latitude": null,
"name": "h2",
"locType": "grid",
"longitude": null
},
"location": {
"locType": "grid",
"latOrY": 700.0,
"longOrX": 400.0
},
"configured": false
}
]
],
"layerOrder": [
"opt",
"pkt",
"def"
]
}
}`;
const topo2Highlights_sample = `
{
"event": "topo2Highlights",
"payload": {
"devices": [],
"hosts": [],
"links": [
{
"id": "00:00:00:00:00:22/120~device:leaf4/[3/0](3)",
"label": "964.91 Kbps",
"css": "secondary port-traffic-green"
},
{
"id": "00:00:00:00:00:1E/None~device:leaf4/[2/0](2)",
"label": "964.91 Kbps",
"css": "secondary port-traffic-green"
},
{
"id": "device:leaf4/[1/0](1)~device:spine1/[3/0](3)",
"label": "964.91 Kbps",
"css": "secondary port-traffic-green"
},
{
"id": "00:00:00:00:00:21/120~device:leaf3/[leaf3-eth3](3)",
"label": "964.91 Kbps",
"css": "secondary port-traffic-green"
},
{
"id": "00:00:00:00:00:1D/None~device:leaf3/[leaf3-eth2](2)",
"label": "964.91 Kbps",
"css": "secondary port-traffic-green"
},
{
"id": "device:leaf3/[leaf3-eth1](1)~device:spine1/[spine1-eth3](3)",
"label": "964.91 Kbps",
"css": "secondary port-traffic-green"
},
{
"id": "00:00:00:00:00:1F/120~device:leaf1/7",
"label": "964.91 Kbps",
"css": "secondary port-traffic-green"
},
{
"id": "device:leaf2/2~device:spine2/2",
"label": "964.91 Kbps",
"css": "secondary port-traffic-green"
},
{
"id": "device:leaf1/1~device:spine1/1",
"label": "3.92 Mbps",
"css": "secondary port-traffic-yellow"
},
{
"id": "00:00:00:00:00:30/None~device:leaf2/3",
"label": "4.46 Mbps",
"css": "secondary port-traffic-yellow"
},
{
"id": "device:leaf2/1~device:spine1/2",
"label": "3.53 Mbps",
"css": "secondary port-traffic-yellow"
},
{
"id": "device:leaf1/2~device:spine2/1",
"label": "1.06 Mbps",
"css": "secondary port-traffic-yellow"
},
{
"id": "00:00:00:00:00:20/None~device:leaf1/6",
"label": "4.98 Mbps",
"css": "secondary port-traffic-yellow"
}
]
}
}`;
const topo2Highlights_sample2 = `
{
"event": "topo2Highlights",
"payload": {
"devices": [],
"hosts": [],
"links": []
}
}`;
class MockActivatedRoute extends ActivatedRoute {
constructor(params: Params) {
super();
this.queryParams = of(params);
}
}
class MockIconService {
loadIconDef() { }
}
class MockSvgUtilService {
cat7() {
const tcid = 'd3utilTestCard';
function getColor(id, muted, theme) {
// NOTE: since we are lazily assigning domain ids, we need to
// get the color from all 4 scales, to keep the domains
// in sync.
const ln = '#5b99d2';
const lm = '#9ebedf';
const dn = '#5b99d2';
const dm = '#9ebedf';
if (theme === 'dark') {
return muted ? dm : dn;
} else {
return muted ? lm : ln;
}
}
return {
// testCard: testCard,
getColor: getColor,
};
}
}
class MockUrlFnService { }
class MockWebSocketService {
createWebSocket() { }
isConnected() { return false; }
unbindHandlers() { }
bindHandlers() { }
}
class MockTopologyService {
public instancesIndex: Map<string, number>;
constructor() {
this.instancesIndex = new Map();
}
}
describe('ForceSvgComponent', () => {
let fs: FnService;
let ar: MockActivatedRoute;
let windowMock: Window;
let logServiceSpy: jasmine.SpyObj<LogService>;
let component: ForceSvgComponent;
let fixture: ComponentFixture<ForceSvgComponent>;
const openflowSampleData = JSON.parse(test_module_topo2CurrentRegion);
const openflowRegionData: Region = <Region><unknown>(openflowSampleData.payload);
const odtnSampleData = JSON.parse(test_OdtnConfig_topo2CurrentRegion);
const odtnRegionData: Region = <Region><unknown>(odtnSampleData.payload);
const topo2BaseData = JSON.parse(topo2Highlights_base_data);
const topo2BaseRegionData: Region = <Region><unknown>(topo2BaseData.payload);
const highlightSampleData = JSON.parse(topo2Highlights_sample);
const linkHightlights: LinkHighlight[] = <LinkHighlight[]><unknown>(highlightSampleData.payload.links);
const emptyRegion: Region = <Region>{devices: [ [], [], [] ], hosts: [ [], [], [] ], links: []};
beforeEach(() => {
const logSpy = jasmine.createSpyObj('LogService', ['info', 'debug', 'warn', 'error']);
ar = new MockActivatedRoute({ 'debug': 'txrx' });
windowMock = <any>{
location: <any>{
hostname: 'foo',
host: 'foo',
port: '80',
protocol: 'http',
search: { debug: 'true' },
href: 'ws://foo:123/onos/ui/websock/path',
absUrl: 'ws://foo:123/onos/ui/websock/path'
}
};
const bundleObj = {
'core.view.Topo': {
test: 'test1'
}
};
const mockLion = (key) => {
return bundleObj[key] || '%' + key + '%';
};
fs = new FnService(ar, logSpy, windowMock);
TestBed.configureTestingModule({
declarations: [
ForceSvgComponent,
DeviceNodeSvgComponent,
HostNodeSvgComponent,
SubRegionNodeSvgComponent,
LinkSvgComponent,
DraggableDirective,
BadgeSvgComponent
],
providers: [
{ provide: LogService, useValue: logSpy },
{ provide: ActivatedRoute, useValue: ar },
{ provide: FnService, useValue: fs },
{ provide: ChangeDetectorRef, useClass: ChangeDetectorRef },
{ provide: UrlFnService, useClass: MockUrlFnService },
{ provide: WebSocketService, useClass: MockWebSocketService },
{ provide: LionService, useFactory: (() => {
return {
bundle: ((bundleId) => mockLion),
ubercache: new Array(),
loadCbs: new Map<string, () => void>([])
};
})
},
{ provide: IconService, useClass: MockIconService },
{ provide: SvgUtilService, useClass: MockSvgUtilService },
{ provide: TopologyService, useClass: MockTopologyService },
{ provide: 'Window', useValue: windowMock },
]
})
.compileComponents();
logServiceSpy = TestBed.get(LogService);
fixture = TestBed.createComponent(ForceSvgComponent);
component = fixture.debugElement.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('load sample files', () => {
expect(openflowSampleData).toBeTruthy();
expect(openflowSampleData.payload).toBeTruthy();
expect(openflowSampleData.payload.id).toBe('(root)');
expect(odtnSampleData).toBeTruthy();
expect(odtnSampleData.payload).toBeTruthy();
expect(odtnSampleData.payload.id).toBe('(root)');
});
it('should read sample data payload as Region', () => {
expect(openflowRegionData).toBeTruthy();
// console.log(regionData);
expect(openflowRegionData.id).toBe('(root)');
expect(openflowRegionData.devices).toBeTruthy();
expect(openflowRegionData.devices.length).toBe(3);
expect(openflowRegionData.devices[2].length).toBe(10);
expect(openflowRegionData.hosts.length).toBe(3);
expect(openflowRegionData.hosts[2].length).toBe(20);
expect(openflowRegionData.links.length).toBe(44);
});
it('should read device246 correctly', () => {
const device246: Device = openflowRegionData.devices[2][0];
expect(device246.id).toBe('of:0000000000000246');
expect(device246.nodeType).toBe('device');
expect(device246.type).toBe('switch');
expect(device246.online).toBe(true);
expect(device246.master).toBe('10.192.19.68');
expect(device246.layer).toBe('def');
expect(device246.props.managementAddress).toBe('10.192.19.69');
expect(device246.props.protocol).toBe('OF_13');
expect(device246.props.driver).toBe('ofdpa-ovs');
expect(device246.props.latitude).toBe('40.15');
expect(device246.props.name).toBe('s246');
expect(device246.props.locType).toBe('geo');
expect(device246.props.channelId).toBe('10.192.19.69:59980');
expect(device246.props.longitude).toBe('-121.679');
expect(device246.location.locType).toBe('geo');
expect(device246.location.latOrY).toBe(40.15);
expect(device246.location.longOrX).toBe(-121.679);
});
it('should read host 3 correctly', () => {
const host3: Host = openflowRegionData.hosts[2][0];
expect(host3.id).toBe('00:88:00:00:00:03/110');
expect(host3.nodeType).toBe('host');
expect(host3.layer).toBe('def');
expect(host3.configured).toBe(false);
expect(host3.ips.length).toBe(3);
expect(host3.ips[0]).toBe('fe80::288:ff:fe00:3');
expect(host3.ips[1]).toBe('2000::102');
expect(host3.ips[2]).toBe('10.0.1.2');
});
it('should read link 3-205 correctly', () => {
const link3_205: Link = openflowRegionData.links[0];
expect(link3_205.id).toBe('00:AA:00:00:00:03/None~of:0000000000000205/6');
expect(link3_205.epA).toBe('00:AA:00:00:00:03/None');
expect(link3_205.epB).toBe('of:0000000000000205');
expect(String(LinkType[link3_205.type])).toBe('2');
expect(link3_205.portA).toBe(undefined);
expect(link3_205.portB).toBe('6');
expect(link3_205.rollup).toBeTruthy();
expect(link3_205.rollup.length).toBe(1);
expect(link3_205.rollup[0].id).toBe('00:AA:00:00:00:03/None~of:0000000000000205/6');
expect(link3_205.rollup[0].epA).toBe('00:AA:00:00:00:03/None');
expect(link3_205.rollup[0].epB).toBe('of:0000000000000205');
expect(String(LinkType[link3_205.rollup[0].type])).toBe('2');
expect(link3_205.rollup[0].portA).toBe(undefined);
expect(link3_205.rollup[0].portB).toBe('6');
});
it('should handle regionData change - empty Region', () => {
component.ngOnChanges(
{'regionData' : new SimpleChange(<Region>{}, emptyRegion, true)});
expect(component.graph.nodes.length).toBe(0);
});
it('should know how to format names', () => {
expect(ForceSvgComponent.extractNodeName('00:AA:00:00:00:03/None', undefined))
.toEqual('00:AA:00:00:00:03/None');
expect(ForceSvgComponent.extractNodeName('00:AA:00:00:00:03/161', '161'))
.toEqual('00:AA:00:00:00:03');
// Like epB of first example in sampleData file - endPtStr contains port number
expect(ForceSvgComponent.extractNodeName('of:0000000000000206/6', '6'))
.toEqual('of:0000000000000206');
// Like epB of second example in sampleData file - endPtStr does not contain port number
expect(ForceSvgComponent.extractNodeName('of:0000000000000206', '6'))
.toEqual('of:0000000000000206');
// bmv2 case - no port in the endpoint
expect(ForceSvgComponent.extractNodeName('device:leaf1', '[leaf1-eth1](1)'))
.toEqual('device:leaf1');
// bmv2 case - port in the endpoint
expect(ForceSvgComponent.extractNodeName('device:leaf1/[leaf1-eth1](1)', '[leaf1-eth1](1)'))
.toEqual('device:leaf1');
// tofino case - no port in the endpoint
expect(ForceSvgComponent.extractNodeName('device:leaf1', '[1/0](1)'))
.toEqual('device:leaf1');
// tofino case - port in the endpoint
expect(ForceSvgComponent.extractNodeName('device:leaf1/[1/0](1)', '[1/0](1)'))
.toEqual('device:leaf1');
});
it('should handle openflow regionData change - sample Region', () => {
component.regionData = openflowRegionData;
component.ngOnChanges(
{'regionData' : new SimpleChange(<Region>{}, openflowRegionData, true)});
expect(component.graph.nodes.length).toBe(30);
expect(component.graph.links.length).toBe(44);
});
it('should handle odtn regionData change - sample odtn Region', () => {
component.regionData = odtnRegionData;
component.ngOnChanges(
{'regionData' : new SimpleChange(<Region>{}, odtnRegionData, true)});
expect(component.graph.nodes.length).toBe(2);
expect(component.graph.links.length).toBe(6);
});
it('should handle highlights and match them to existing links', () => {
component.regionData = topo2BaseRegionData;
component.ngOnChanges(
{'regionData' : new SimpleChange(<Region>{}, topo2BaseRegionData, true)});
expect(component.graph.links.length).toBe(16);
expect(component.graph.nodes.length).toBe(16)
expect(linkHightlights.length).toBe(13);
// sanitize deviceNameFromEp
component.graph.links.forEach((l: Link) => {
if (<LinkType><unknown>LinkType[l.type] === LinkType.UiEdgeLink) {
// edge link has only one epoint valid (the other is not deviceId)
const foundNode = component.graph.nodes.find((n: Node) => n.id === Link.deviceNameFromEp(l.epB));
expect(foundNode).toBeDefined();
} else {
var foundNode = component.graph.nodes.find((n: Node) => n.id === Link.deviceNameFromEp(l.epA));
expect(foundNode).toBeDefined();
foundNode = component.graph.nodes.find((n: Node) => n.id === Link.deviceNameFromEp(l.epB));
expect(foundNode).toBeDefined();
}
});
// should be able to find all of the highlighted links in the original data set
linkHightlights.forEach((lh: LinkHighlight) => {
const foundLink = component.graph.links.find((l: Link) => l.id === Link.linkIdFromShowHighlights(lh.id));
expect(foundLink).toBeDefined();
});
});
}); | the_stack |
import { Map } from 'immutable'
import { connect } from 'react-redux'
import { getTranslate } from 'react-localize-redux'
import { withRouter } from 'react-router-dom'
import { withStyles } from '@material-ui/core/styles'
import Button from '@material-ui/core/Button'
import Checkbox from '@material-ui/core/Checkbox'
import Divider from '@material-ui/core/Divider'
import FormControl from '@material-ui/core/FormControl'
import FormControlLabel from '@material-ui/core/FormControlLabel'
import FormHelperText from '@material-ui/core/FormHelperText'
import Grid from '@material-ui/core/Grid'
import Input from '@material-ui/core/Input'
import InputBase from '@material-ui/core/InputBase'
import InputLabel from '@material-ui/core/InputLabel'
import MenuItem from '@material-ui/core/MenuItem'
import Paper from '@material-ui/core/Paper'
import Radio from '@material-ui/core/Radio'
import RadioGroup from '@material-ui/core/RadioGroup'
import React, { Component } from 'react'
import Select from '@material-ui/core/Select'
import Typography from '@material-ui/core/Typography'
import classNames from 'classnames'
import { Order } from 'core/domain/cart'
import { ShippingAddress } from 'core/domain/shippings'
import * as addToCartActions from 'store/actions/addToCartActions'
import * as shippingsActions from 'store/actions/shippingsActions'
import { IAddressFormComponentProps } from './IAddressFormComponentProps'
import { IAddressFormComponentState } from './IAddressFormComponentState'
import FormButton from '../formButton'
const styles = (theme: any) => ({
root: {
padding: 0,
'label + &': {
marginTop: theme.spacing(7)
}
},
formroot: {
margin: theme.spacing.unit,
width: '100%'
},
paperbuttons: {
marginBottom: theme.spacing(3),
backgroundColor: '#f7f7f7',
borderTopLeftRadius: 0,
borderTopRightRadius: 0,
boxShadow:
'0px 2px 2px 0px rgba(0,0,0,0.14), 0px 3px 1px -2px rgba(0,0,0,0.12)',
padding: theme.spacing(2),
[theme.breakpoints.up(600 + theme.spacing(3) * 2)]: {
padding: `${24}px ${48}px`
},
position: 'relative',
width: '116%',
bottom: -72,
left: -48
},
inputSizeSmall: {
fontSize: 14,
padding: theme.spacing(1),
width: `calc(100% - ${theme.spacing(2)}px)`,
borderColor: '#e1e1e1'
},
formLabel: {
fontSize: 12,
fontFamily: '"Montserrat", sans-serif',
color: '#b4b4b4',
left: -12,
fontWeight: 'bold'
},
group: {
flexDirection: 'row'
},
title: {
fontSize: 16,
fontFamily: '"Montserrat", sans-serif',
lineHeight: '150%',
color: '#2e2e2e',
textTransform: 'capitalize'
},
griditem: {
padding: '0px 12px 0px 0px!important'
},
paymentFieldsRoot: {
'label + &': {
marginTop: theme.spacing.unit * 3,
},
},
paymentFieldsInput: {
borderRadius: 4,
position: 'relative',
backgroundColor: theme.palette.common.white,
border: '1px solid #e1e1e1',
fontSize: 16,
padding: '10px 12px',
transition: theme.transitions.create(['border-color', 'box-shadow']),
// Use the system font instead of the default Roboto font.
fontFamily: [
'-apple-system',
'BlinkMacSystemFont',
'"Segoe UI"',
'Roboto',
'"Helvetica Neue"',
'Arial',
'sans-serif',
'"Apple Color Emoji"',
'"Segoe UI Emoji"',
'"Segoe UI Symbol"',
].join(','),
'&:focus': {
borderRadius: 4,
borderColor: '#77db77'
},
},
paymentFieldsLabel: {
fontSize: 16,
color: '#b4b4b4',
fontWeight: 'bold',
fontFamily: '"Montserrat", sans-serif',
},
countrytitle : {
color: '#b4b4b4',
fontSize: 12
},
countryname : {
color: '#2e2e2e',
marginLeft: '0.5rem',
fontSize: 12
},
billinginfo: {
color: '#2e2e2e',
fontSize: 12
},
button: {
textTransform: 'capitalize',
borderRadius: 30,
padding: `${15}px ${60}px`,
boxShadow: 'none'
},
backbutton: {
backgroundColor: '#ffffff',
color: '#f62f5e'
},
radiowrapper: {
flexDirection: 'row',
width: '100%'
},
formHelperText: {
color: '#f62f5e'
}
})
/**
* Create component class
*/
export class AddressFormComponent extends Component<
IAddressFormComponentProps,
IAddressFormComponentState
> {
static propTypes = {
/**
* List of users
*/
}
/**
* Component constructor
* @param {object} props is an object properties of component
*/
constructor(props: IAddressFormComponentProps) {
super(props)
console.log('shipping', this.props.shippingAddress)
// Defaul state
this.state = {
region: 1,
open: false,
activeStep: 0,
address: this.props.shippingAddress ? this.props.shippingAddress.address1 : '',
city: this.props.shippingAddress ? this.props.shippingAddress.city : '',
state: this.props.shippingAddress ? this.props.shippingAddress.country : '',
zip: this.props.shippingAddress ? this.props.shippingAddress.postalCode : '',
firstNameInputError: '',
lastNameInputError: '',
addressInputError: '',
cityInputError: '',
stateInputError: '',
zipInputError: '',
regionSelectError: '',
shippingTypeError: '',
shippingType: ''
}
// Binding functions to `this`
this.handleNext = this.handleNext.bind(this)
}
shippingList = () => {
const allShippingRegions = this.props.shippingRegions
const shippingRegionsList: any[] = []
if (allShippingRegions) {
allShippingRegions.forEach(
(shippingRegion: Map<string, any>, key: string) => {
const shippingRegionId = shippingRegion.get('shippingRegionId')
let shippingRegionValue = shippingRegion.get('shippingRegion')
shippingRegionsList.push(
<MenuItem key={key} value={shippingRegionId}>
{shippingRegionValue}
</MenuItem>
)
}
)
}
return shippingRegionsList
}
handleChangeradio = (event: any, shippingType: any) => {
this.setState({ shippingType })
}
/**
* Create a list of shipping rates
* @return {DOM} shipping rates
*/
shippingRatesLoad = () => {
const { shippingRates } = this.props
let ratesList: any = []
if (shippingRates) {
shippingRates.forEach((shippingRates: Map<string, any>, key: string) => {
let shippingType = shippingRates.get('shippingType')
let shippingCost = shippingRates.get('shippingCost')
ratesList.push(
<FormControlLabel name={shippingCost} value={shippingType} control={<Radio />} label={shippingType} />
)
})
}
return ratesList
}
handleChange(event: any) {
// this.setState(event.target.value)
}
/**
* Handle data on input change
* @param {event} evt is an event of inputs of element on change
*/
handleInputChange = (event: any) => {
const target = event.target
const value = target.type === 'checkbox' ? target.checked : target.value
const name = target.name
if (name === 'region') {
this.setState({
shippingRegionId: target.key
})
this.props.getShippingRates!(value)
}
this.setState({
[name]: value
})
switch (name) {
case 'firstName':
this.setState({
firstNameInputError: ''
})
break
case 'lastName':
this.setState({
lastNameInputError: ''
})
break
case 'address':
this.setState({
addressInputError: ''
})
break
case 'city':
this.setState({
cityInputError: ''
})
break
case 'state':
this.setState({
stateInputError: ''
})
break
case 'zip':
this.setState({
zipInputError: ''
})
break
default:
}
}
/**
* Handle close request of select
*/
handleClose = () => {
this.setState({ open: false })
}
/**
* Handle open request of select
*/
handleOpen = () => {
this.setState({ open: true })
}
/**
* Handle backbutton step on change
*/
handleBack = () => {
this.setState({
activeStep: 0
})
}
/**
* Handle backbutton step on change
*/
handleNext = () => {
const { translate, uid, shippingAddress} = this.props
const getCartProducts = this.props.getCart
const {
firstName,
lastName,
city,
state,
zip,
region,
shippingType
} = this.state
var regionValue
{
region === 2
? (regionValue = 'US / Canada')
: region === 3
? (regionValue = 'Europe')
: region === 4 ? (regionValue = 'Rest of World') : (regionValue = 'Please Select')
}
var shippingCost, shippingId, cartId
if (getCartProducts) {
getCartProducts.forEach((row: any, key: string) => {
cartId = key
})
} else {
cartId = ''
}
this.props.shippingRates.forEach((shippingRates: Map<string, any>, key: string) => {
if (shippingRates.get('shippingType') === shippingType) {
shippingCost = shippingRates.get('shippingCost')
shippingId = shippingRates.get('shippingId')
}
})
let error = false
if (this.state.firstName === undefined || (this.state.firstName.trim() === '' || this.state.firstName.trim().length === 0)) {
this.setState({
firstNameInputError: translate!('login.emailRequiredError')
})
error = true
}
if (this.state.lastName === undefined || (this.state.lastName.trim() === '' || this.state.lastName.trim().length === 0)) {
this.setState({
lastNameInputError: translate!('login.emailRequiredError')
})
error = true
}
if (this.state.region === 1 || this.state.region === undefined) {
this.setState({
regionSelectError: translate!('login.emailRequiredError')
})
error = true
}
if (this.state.shippingType === undefined || (this.state.shippingType.trim() === '' || this.state.shippingType.trim().length === 0)) {
this.setState({
shippingTypeError: translate!('login.emailRequiredError')
})
error = true
}
if (!shippingAddress) {
if (this.state.address === undefined || (this.state.address.trim() === '' || this.state.address.trim().length === 0)) {
this.setState({
addressInputError: translate!('login.emailRequiredError')
})
error = true
}
if (this.state.city === undefined || ((this.state.city.trim() === '' ) || this.state.city.trim().length === 0)) {
this.setState({
cityInputError: translate!('login.emailRequiredError')
})
error = true
}
if (this.state.state === undefined || (this.state.state.trim() === '' || this.state.state.trim().length === 0)) {
this.setState({
stateInputError: translate!('login.emailRequiredError')
})
error = true
}
if (this.state.zip === undefined || (this.state.zip.trim() === '' || this.state.zip.trim().length === 0)) {
this.setState({
zipInputError: translate!('login.emailRequiredError')
})
error = true
}
}
if (!error) {
this.props.update!({
firstName: firstName,
lastName: lastName,
address: this.state.address,
city: city,
state: state,
postalCode: zip,
region: region,
regionValue: regionValue,
shippingType: shippingType,
shippingCost: shippingCost,
shippingId: shippingId,
customerId: uid
})
this.props.addOrder!({
cartId: cartId,
shippingId: shippingId,
customerId: uid,
taxId: 1
})
}
}
/**
* Handle Reset step on change
*/
handleReset = () => {
this.setState({
activeStep: 0
})
}
/**
* Reneder component DOM
* @return {react element} return the DOM which rendered by component
*/
render() {
const { classes, shippingAddress } = this.props
return (
<React.Fragment>
<form>
<Grid container spacing={2}>
<Grid item xs={12} sm={6} className={classes.griditem}>
<FormControl className={classes.formroot}>
<InputLabel
shrink
htmlFor='first name'
className={classes.paymentFieldsLabel}
>
First Name
</InputLabel>
<InputBase
id='firstName'
required
name='firstName'
value={this.state.firstName}
onChange={this.handleInputChange}
fullWidth
error
classes={{
root: classes.paymentFieldsRoot,
input: classes.paymentFieldsInput
}}
/>
<FormHelperText id='component-helper-text' className={classes.formHelperText}>
{this.state.firstNameInputError}
</FormHelperText>
</FormControl>
</Grid>
<Grid item xs={12} sm={6} className={classes.griditem}>
<FormControl className={classes.formroot}>
<InputLabel
shrink
htmlFor='last-name'
className={classes.paymentFieldsLabel}
>
Last name
</InputLabel>
<InputBase
id='last-name'
required
name='lastName'
value={this.state.lastName}
onChange={this.handleInputChange}
fullWidth
classes={{
root: classes.paymentFieldsRoot,
input: classes.paymentFieldsInput
}}
/>
<FormHelperText id='component-helper-text' className={classes.formHelperText}>
{this.state.lastNameInputError}
</FormHelperText>
</FormControl>
</Grid>
<Grid item xs={12} sm={6} className={classes.griditem}>
<FormControl className={classes.formroot}>
<InputLabel
shrink
htmlFor='address'
className={classes.paymentFieldsLabel}
>
Address
</InputLabel>
<InputBase
id='address'
required
name='address'
value={this.state.address ? this.state.address : shippingAddress ? shippingAddress.address1 : ''}
onChange={this.handleInputChange}
fullWidth
classes={{
root: classes.paymentFieldsRoot,
input: classes.paymentFieldsInput
}}
/>
<FormHelperText id='component-helper-text' className={classes.formHelperText}>
{this.state.addressInputError}
</FormHelperText>
</FormControl>
</Grid>
<Grid item xs={12} sm={6} className={classes.griditem}>
<FormControl className={classes.formroot}>
<InputLabel
shrink
htmlFor='city'
className={classes.paymentFieldsLabel}
>
City
</InputLabel>
<InputBase
id='city'
required
name='city'
value={this.state.city ? this.state.city : shippingAddress ? shippingAddress.city : ''}
onChange={this.handleInputChange}
fullWidth
classes={{
root: classes.paymentFieldsRoot,
input: classes.paymentFieldsInput
}}
/>
<FormHelperText id='component-helper-text' className={classes.formHelperText}>
{this.state.cityInputError}
</FormHelperText>
</FormControl>
</Grid>
<Grid item xs={12} sm={6} className={classes.griditem}>
<FormControl className={classes.formroot}>
<InputLabel
shrink
htmlFor='state'
className={classes.paymentFieldsLabel}
>
State
</InputLabel>
<InputBase
id='state'
required
name='state'
value={this.state.state ? this.state.state : shippingAddress ? shippingAddress.country : ''}
onChange={this.handleInputChange}
fullWidth
classes={{
root: classes.paymentFieldsRoot,
input: classes.paymentFieldsInput
}}
/>
<FormHelperText id='component-helper-text' className={classes.formHelperText}>
{this.state.stateInputError}
</FormHelperText>
</FormControl>
</Grid>
<Grid item xs={12} sm={6} className={classes.griditem}>
<FormControl className={classes.formroot}>
<InputLabel
shrink
htmlFor='zip'
className={classes.paymentFieldsLabel}
>
Zip code
</InputLabel>
<InputBase
id='zip'
required
name='zip'
value={this.state.zip ? this.state.zip : shippingAddress ? shippingAddress.postalCode : ''}
onChange={this.handleInputChange}
fullWidth
classes={{
root: classes.paymentFieldsRoot,
input: classes.paymentFieldsInput
}}
/>
<FormHelperText id='component-helper-text' className={classes.formHelperText}>
{this.state.zipInputError}
</FormHelperText>
</FormControl>
</Grid>
<Grid item xs={12} sm={6} className={classes.griditem}>
<FormControl className={classes.formroot}>
<InputLabel
htmlFor='region'
className={classes.paymentFieldsLabel}
>
Region
</InputLabel>
<Select
id='region'
required
name='region'
value={this.state.region}
input={<Input name='region' id='rigion' />}
onClose={this.handleClose}
onOpen={this.handleOpen}
onChange={this.handleInputChange}
classes={{
root: classes.paymentFieldsRoot,
select: classes.paymentFieldsInput
}}
>
{this.shippingList()}
</Select>
<FormHelperText id='component-helper-text' className={classes.formHelperText}>
{this.state.regionSelectError}
</FormHelperText>
</FormControl>
</Grid>
<Grid item xs={12} container direction='row'>
<Typography
className={classNames(
classes.countrytitle,
classes.paymentFieldsLabel
)}
>
Country:
</Typography>
<Typography
className={classNames(
classes.countryname,
classes.paymentFieldsLabel
)}
>
Great Britain *
</Typography>
</Grid>
<Grid item xs={12}>
<FormControlLabel
control={
<Checkbox
checked={this.state.saveAddress}
color='secondary'
name='saveAddress'
onChange={this.handleInputChange}
value={'saveAddress'}
/>
}
label='My billing information is the same as my delivery information'
classes={{
label: classNames(
classes.billinginfo,
classes.paymentFieldsLabel
)
}}
/>
</Grid>
<Grid item xs={12}>
<Divider variant='middle' />
</Grid>
<Grid item xs={12}>
<Typography variant='h6' gutterBottom className={classes.title}>
Delivery options
</Typography>
</Grid>
<Grid item xs={12} container direction='row'>
<FormHelperText id='component-helper-text' className={classes.formHelperText}>
{this.state.shippingTypeError}
</FormHelperText>
<RadioGroup value={this.state.value} onChange={this.handleChangeradio} classes={{
root: classes.radiowrapper
}}>
{this.shippingRatesLoad()}
</RadioGroup>
</Grid>
{/* {shippingRates ? <div>
<FormControl component={'fieldset' as 'div'} className={classes.formControl}>
<RadioGroup
className={classes.group}
aria-label='delivery-options'
name='delivery-options'
value={'standard-shipping'}
>
<FormControlLabel value='standard-shipping' control={<Radio />} label='Standard shipping: (free, 2-3 business days)' />
</Grid>
<Grid item xs={12} sm={6}>
<FormControlLabel value='express-shipping' control={<Radio />} label='Express shipping: ($28, 1-2 business days)' />
</Grid>
</RadioGroup>
</FormControl></div> : ''} */}
</Grid>
<Paper className={classes.paperbuttons}>
<React.Fragment>
<Grid container spacing={8}>
<Grid
item
container
xs={12}
sm={6}
direction='row'
justify='flex-start'
alignItems='center'
>
<Button
onClick={this.handleBack}
className={classNames(classes.backbutton, classes.button)}
variant='contained'
>
Back
</Button>
</Grid>
<Grid
item
xs={12}
sm={6}
container
direction='row'
justify='flex-end'
alignItems='center'
>
<FormButton
size='small'
className={classes.button}
color='secondary'
onClick={this.handleNext}
>
Next Step
</FormButton>
</Grid>
</Grid>
</React.Fragment>
</Paper>
</form>
</React.Fragment>
)
}
}
/**
* Map dispatch to props
* @param {func} dispatch is the function to dispatch action to reducers
* @param {object} ownProps is the props belong to component
* @return {object} props of component
*/
const mapDispatchToProps = (
dispatch: Function,
ownProps: IAddressFormComponentProps
) => {
return {
update: (shippingAddress: ShippingAddress) => {
dispatch(shippingsActions.dbAddShippingAddressfromcheckout(shippingAddress))
},
getShippingRates: (regionId: string) => {
dispatch(shippingsActions.dbGetShippingRates(regionId))
},
addOrder: (order: Order) => dispatch(addToCartActions.dbAddOrder(order))
}
}
/**
* Map state to props
* @param {object} state is the obeject from redux store
* @param {object} ownProps is the props belong to component
* @return {object} props of component
*/
const mapStateToProps = (
state: Map<string, any>,
ownProps: IAddressFormComponentProps
) => {
const uid = state.getIn(['authorize', 'uid'], 0)
const shippingRegions = state.getIn(['shippings', 'shippingRegions'])
const getshippingId = state.getIn(['shippings', 'shippingAddress','shippingId'])
const shippingAddress = state.getIn(['shippings', 'shippingAddress'])
const getCart = state.getIn(['addToCart', 'cartProducts'])
return {
uid,
shippingRegions,
getshippingId,
getCart,
shippingAddress,
translate: getTranslate(state.get('locale')),
}
}
export default withRouter<any>(
connect(
mapStateToProps,
mapDispatchToProps
)(withStyles(styles as any, { withTheme: true })(
AddressFormComponent as any
) as any)
) as typeof AddressFormComponent | the_stack |
// clang-format off
import {webUIListenerCallback} from 'chrome://resources/js/cr.m.js';
import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {CookiePrimarySetting, PrivacyReviewHistorySyncFragmentElement, PrivacyReviewStep, PrivacyReviewWelcomeFragmentElement, SafeBrowsingSetting, SettingsCheckboxElement, SettingsPrivacyReviewPageElement, SettingsRadioGroupElement} from 'chrome://settings/lazy_load.js';
import {Router, routes, StatusAction, SyncBrowserProxyImpl, SyncPrefs, syncPrefsIndividualDataTypes} from 'chrome://settings/settings.js';
import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js';
import {eventToPromise, flushTasks, isChildVisible} from 'chrome://webui-test/test_util.js';
import {TestSyncBrowserProxy} from './test_sync_browser_proxy.js';
// clang-format on
/* Maximum number of steps in the privacy review, excluding the welcome and
* completion steps.
*/
const PRIVACY_REVIEW_STEPS = 4;
suite('PrivacyReviewPage', function() {
let page: SettingsPrivacyReviewPageElement;
let syncBrowserProxy: TestSyncBrowserProxy;
let shouldShowCookiesCard: boolean;
let shouldShowSafeBrowsingCard: boolean;
setup(function() {
syncBrowserProxy = new TestSyncBrowserProxy();
syncBrowserProxy.testSyncStatus = null;
SyncBrowserProxyImpl.setInstance(syncBrowserProxy);
document.body.innerHTML = '';
page = document.createElement('settings-privacy-review-page');
page.disableAnimationsForTesting();
page.prefs = {
privacy_review: {
show_welcome_card: {
type: chrome.settingsPrivate.PrefType.BOOLEAN,
value: true,
},
},
privacy_guide: {
viewed: {
type: chrome.settingsPrivate.PrefType.BOOLEAN,
value: false,
},
},
generated: {
cookie_primary_setting: {
type: chrome.settingsPrivate.PrefType.NUMBER,
value: CookiePrimarySetting.BLOCK_THIRD_PARTY,
},
safe_browsing: {
type: chrome.settingsPrivate.PrefType.NUMBER,
value: SafeBrowsingSetting.STANDARD,
},
},
};
document.body.appendChild(page);
shouldShowCookiesCard = true;
shouldShowSafeBrowsingCard = true;
// Simulates the route of the user entering the privacy review from the S&P
// settings. This is necessary as tests seem to by default define the
// previous route as Settings "/". On a back navigation, "/" matches the
// criteria for a valid Settings parent no matter how deep the subpage is in
// the Settings tree. This would always navigate to Settings "/" instead of
// to the parent of the current subpage.
Router.getInstance().navigateTo(routes.PRIVACY);
return flushTasks();
});
teardown(function() {
page.remove();
// Reset route to default. The route is updated as we navigate through the
// cards, but the browser instance is shared among the tests, so otherwise
// the next test will be initialized to the same card as the previous test.
Router.getInstance().navigateTo(routes.BASIC);
});
/**
* Returns a new promise that resolves after a window 'popstate' event.
*/
function whenPopState(causeEvent: () => void): Promise<void> {
const promise = eventToPromise('popstate', window);
causeEvent();
return promise;
}
/**
* Equivalent of the user manually navigating to the corresponding step via
* typing the URL and step parameter in the Omnibox.
*/
function navigateToStep(step: PrivacyReviewStep) {
Router.getInstance().navigateTo(
routes.PRIVACY_REVIEW,
/* opt_dynamicParameters */ new URLSearchParams('step=' + step));
flush();
}
function assertQueryParameter(step: PrivacyReviewStep) {
assertEquals(step, Router.getInstance().getQueryParameters().get('step'));
}
/**
* Fire a sync status changed event and flush the UI.
*/
function setSyncEnabled(syncOn: boolean) {
syncBrowserProxy.testSyncStatus = {
signedIn: syncOn,
hasError: false,
statusAction: StatusAction.NO_ACTION,
};
webUIListenerCallback(
'sync-status-changed', syncBrowserProxy.testSyncStatus);
flush();
}
function shouldShowHistorySyncCard(): boolean {
return !syncBrowserProxy.testSyncStatus ||
!!syncBrowserProxy.testSyncStatus.signedIn;
}
/**
* Set the cookies setting for the privacy review.
*/
function setCookieSetting(setting: CookiePrimarySetting) {
page.set('prefs.generated.cookie_primary_setting', {
type: chrome.settingsPrivate.PrefType.NUMBER,
value: setting,
});
shouldShowCookiesCard =
setting === CookiePrimarySetting.BLOCK_THIRD_PARTY ||
setting === CookiePrimarySetting.BLOCK_THIRD_PARTY_INCOGNITO;
flush();
}
/**
* Set the safe browsing setting for the privacy review.
*/
function setSafeBrowsingSetting(setting: SafeBrowsingSetting) {
page.set('prefs.generated.safe_browsing', {
type: chrome.settingsPrivate.PrefType.NUMBER,
value: setting,
});
shouldShowSafeBrowsingCard = setting === SafeBrowsingSetting.ENHANCED ||
setting === SafeBrowsingSetting.STANDARD;
flush();
}
/**
* Fire a sign in status change event and flush the UI.
*/
function setSignInState(signedIn: boolean) {
const event = {
signedIn: signedIn,
};
webUIListenerCallback('update-sync-state', event);
flush();
}
type AssertCardComponentsVisibleParams = {
isSettingFooterVisibleExpected?: boolean,
isBackButtonVisibleExpected?: boolean,
isWelcomeFragmentVisibleExpected?: boolean,
isCompletionFragmentVisibleExpected?: boolean,
isMsbbFragmentVisibleExpected?: boolean,
isClearOnExitFragmentVisibleExpected?: boolean,
isHistorySyncFragmentVisibleExpected?: boolean,
isSafeBrowsingFragmentVisibleExpected?: boolean,
isCookiesFragmentVisibleExpected?: boolean,
};
function assertCardComponentsVisible({
isSettingFooterVisibleExpected,
isBackButtonVisibleExpected,
isWelcomeFragmentVisibleExpected,
isCompletionFragmentVisibleExpected,
isMsbbFragmentVisibleExpected,
isClearOnExitFragmentVisibleExpected,
isHistorySyncFragmentVisibleExpected,
isSafeBrowsingFragmentVisibleExpected,
isCookiesFragmentVisibleExpected,
}: AssertCardComponentsVisibleParams) {
assertEquals(
!!isSettingFooterVisibleExpected,
isChildVisible(page, '#settingFooter'));
if (isSettingFooterVisibleExpected) {
const backButtonVisibility =
getComputedStyle(
page.shadowRoot!.querySelector<HTMLElement>('#backButton')!)
.visibility;
assertEquals(
isBackButtonVisibleExpected ? 'visible' : 'hidden',
backButtonVisibility);
}
assertEquals(
!!isWelcomeFragmentVisibleExpected,
isChildVisible(page, '#' + PrivacyReviewStep.WELCOME));
assertEquals(
!!isCompletionFragmentVisibleExpected,
isChildVisible(page, '#' + PrivacyReviewStep.COMPLETION));
assertEquals(
!!isMsbbFragmentVisibleExpected,
isChildVisible(page, '#' + PrivacyReviewStep.MSBB));
assertEquals(
!!isClearOnExitFragmentVisibleExpected,
isChildVisible(page, '#' + PrivacyReviewStep.CLEAR_ON_EXIT));
assertEquals(
!!isHistorySyncFragmentVisibleExpected,
isChildVisible(page, '#' + PrivacyReviewStep.HISTORY_SYNC));
assertEquals(
!!isSafeBrowsingFragmentVisibleExpected,
isChildVisible(page, '#' + PrivacyReviewStep.SAFE_BROWSING));
assertEquals(
!!isCookiesFragmentVisibleExpected,
isChildVisible(page, '#' + PrivacyReviewStep.COOKIES));
}
/**
* @return The expected total number of active cards for the step indicator.
*/
function getExpectedNumberOfActiveCards() {
let numSteps = PRIVACY_REVIEW_STEPS;
if (!shouldShowHistorySyncCard()) {
numSteps -= 1;
}
if (!shouldShowCookiesCard) {
numSteps -= 1;
}
if (!shouldShowSafeBrowsingCard) {
numSteps -= 1;
}
return numSteps;
}
function assertStepIndicatorModel(activeIndex: number) {
const model = page.computeStepIndicatorModel();
assertEquals(activeIndex, model.active);
assertEquals(getExpectedNumberOfActiveCards(), model.total);
}
function assertWelcomeCardVisible() {
assertQueryParameter(PrivacyReviewStep.WELCOME);
assertCardComponentsVisible({
isWelcomeFragmentVisibleExpected: true,
});
}
function assertCompletionCardVisible() {
assertQueryParameter(PrivacyReviewStep.COMPLETION);
assertCardComponentsVisible({
isCompletionFragmentVisibleExpected: true,
});
}
function assertMsbbCardVisible() {
assertQueryParameter(PrivacyReviewStep.MSBB);
assertCardComponentsVisible({
isSettingFooterVisibleExpected: true,
isMsbbFragmentVisibleExpected: true,
});
assertStepIndicatorModel(0);
}
function assertHistorySyncCardVisible() {
assertQueryParameter(PrivacyReviewStep.HISTORY_SYNC);
assertCardComponentsVisible({
isSettingFooterVisibleExpected: true,
isBackButtonVisibleExpected: true,
isHistorySyncFragmentVisibleExpected: true,
});
assertStepIndicatorModel(1);
}
function assertSafeBrowsingCardVisible() {
assertQueryParameter(PrivacyReviewStep.SAFE_BROWSING);
assertCardComponentsVisible({
isSettingFooterVisibleExpected: true,
isBackButtonVisibleExpected: true,
isSafeBrowsingFragmentVisibleExpected: true,
});
assertStepIndicatorModel(shouldShowHistorySyncCard() ? 2 : 1);
}
function assertCookiesCardVisible() {
assertQueryParameter(PrivacyReviewStep.COOKIES);
assertCardComponentsVisible({
isSettingFooterVisibleExpected: true,
isBackButtonVisibleExpected: true,
isCookiesFragmentVisibleExpected: true,
});
let activeIndex = 3;
if (!shouldShowHistorySyncCard()) {
activeIndex -= 1;
}
if (!shouldShowSafeBrowsingCard) {
activeIndex -= 1;
}
assertStepIndicatorModel(activeIndex);
}
test('startPrivacyReview', function() {
// Make sure the pref to show the welcome card is on.
page.setPrefValue('privacy_review.show_welcome_card', true);
// Navigating to the privacy review without a step parameter navigates to
// the welcome card.
Router.getInstance().navigateTo(routes.PRIVACY_REVIEW);
flush();
assertWelcomeCardVisible();
assertTrue(page.getPref('privacy_guide.viewed').value);
const welcomeFragment =
page.shadowRoot!.querySelector<PrivacyReviewWelcomeFragmentElement>(
'#' + PrivacyReviewStep.WELCOME)!;
const dontShowAgainCheckbox =
welcomeFragment.shadowRoot!.querySelector<SettingsCheckboxElement>(
'#dontShowAgainCheckbox')!;
assertFalse(dontShowAgainCheckbox.checked);
dontShowAgainCheckbox.$.checkbox.click();
welcomeFragment.$.startButton.click();
flush();
assertMsbbCardVisible();
// Navigating this time should skip the welcome card.
assertFalse(page.getPref('privacy_review.show_welcome_card').value);
Router.getInstance().navigateTo(routes.PRIVACY_REVIEW);
assertMsbbCardVisible();
});
test('welcomeForwardNavigation', function() {
page.setPrefValue('privacy_review.show_welcome_card', true);
// Navigating to the privacy review without a step parameter navigates to
// the welcome card.
Router.getInstance().navigateTo(routes.PRIVACY_REVIEW);
flush();
assertWelcomeCardVisible();
const welcomeFragment =
page.shadowRoot!.querySelector<PrivacyReviewWelcomeFragmentElement>(
'#' + PrivacyReviewStep.WELCOME)!;
welcomeFragment.$.startButton.click();
flush();
assertMsbbCardVisible();
setSyncEnabled(true);
assertMsbbCardVisible();
});
test('msbbForwardNavigationSyncOn', function() {
navigateToStep(PrivacyReviewStep.MSBB);
setSyncEnabled(true);
assertMsbbCardVisible();
page.shadowRoot!.querySelector<HTMLElement>('#nextButton')!.click();
assertHistorySyncCardVisible();
});
test('msbbForwardNavigationSyncOff', function() {
navigateToStep(PrivacyReviewStep.MSBB);
setSyncEnabled(false);
assertMsbbCardVisible();
page.shadowRoot!.querySelector<HTMLElement>('#nextButton')!.click();
assertSafeBrowsingCardVisible();
});
test('historySyncBackNavigation', function() {
navigateToStep(PrivacyReviewStep.HISTORY_SYNC);
setSyncEnabled(true);
assertHistorySyncCardVisible();
page.shadowRoot!.querySelector<HTMLElement>('#backButton')!.click();
assertMsbbCardVisible();
});
test('historySyncNavigatesAwayOnSyncOff', function() {
navigateToStep(PrivacyReviewStep.HISTORY_SYNC);
setSyncEnabled(true);
assertHistorySyncCardVisible();
// User disables sync while history sync card is shown.
setSyncEnabled(false);
assertSafeBrowsingCardVisible();
});
test('historySyncNotReachableWhenSyncOff', function() {
navigateToStep(PrivacyReviewStep.HISTORY_SYNC);
setSyncEnabled(false);
assertSafeBrowsingCardVisible();
});
test(
'historySyncCardForwardNavigationShouldShowSafeBrowsingCard', function() {
navigateToStep(PrivacyReviewStep.HISTORY_SYNC);
setSyncEnabled(true);
setSafeBrowsingSetting(SafeBrowsingSetting.ENHANCED);
setCookieSetting(CookiePrimarySetting.BLOCK_THIRD_PARTY);
assertHistorySyncCardVisible();
page.shadowRoot!.querySelector<HTMLElement>('#nextButton')!.click();
assertSafeBrowsingCardVisible();
});
test(
'historySyncCardForwardNavigationShouldHideSafeBrowsingCard', function() {
navigateToStep(PrivacyReviewStep.HISTORY_SYNC);
setSyncEnabled(true);
setSafeBrowsingSetting(SafeBrowsingSetting.DISABLED);
setCookieSetting(CookiePrimarySetting.BLOCK_THIRD_PARTY);
assertHistorySyncCardVisible();
page.shadowRoot!.querySelector<HTMLElement>('#nextButton')!.click();
assertCookiesCardVisible();
});
test('safeBrowsingCardBackNavigationSyncOn', function() {
navigateToStep(PrivacyReviewStep.SAFE_BROWSING);
setSyncEnabled(true);
assertSafeBrowsingCardVisible();
page.shadowRoot!.querySelector<HTMLElement>('#backButton')!.click();
assertHistorySyncCardVisible();
});
test('safeBrowsingCardBackNavigationSyncOff', function() {
navigateToStep(PrivacyReviewStep.SAFE_BROWSING);
setSyncEnabled(false);
assertSafeBrowsingCardVisible();
page.shadowRoot!.querySelector<HTMLElement>('#backButton')!.click();
assertMsbbCardVisible();
});
test('safeBrowsingCardGetsUpdated', function() {
navigateToStep(PrivacyReviewStep.SAFE_BROWSING);
setSafeBrowsingSetting(SafeBrowsingSetting.ENHANCED);
setCookieSetting(CookiePrimarySetting.BLOCK_THIRD_PARTY);
assertSafeBrowsingCardVisible();
const radioButtonGroup =
page.shadowRoot!.querySelector('#' + PrivacyReviewStep.SAFE_BROWSING)!
.shadowRoot!.querySelector<SettingsRadioGroupElement>(
'#safeBrowsingRadioGroup')!;
assertEquals(
Number(radioButtonGroup.selected), SafeBrowsingSetting.ENHANCED);
// Changing the safe browsing setting should automatically change the
// selected radio button.
setSafeBrowsingSetting(SafeBrowsingSetting.STANDARD);
assertEquals(
Number(radioButtonGroup.selected), SafeBrowsingSetting.STANDARD);
// Changing the safe browsing setting to a disabled state while shown should
// navigate away from the safe browsing card.
setSafeBrowsingSetting(SafeBrowsingSetting.DISABLED);
assertCookiesCardVisible();
});
test('safeBrowsingCardForwardNavigationShouldShowCookiesCard', function() {
navigateToStep(PrivacyReviewStep.SAFE_BROWSING);
setCookieSetting(CookiePrimarySetting.BLOCK_THIRD_PARTY);
assertSafeBrowsingCardVisible();
page.shadowRoot!.querySelector<HTMLElement>('#nextButton')!.click();
flush();
assertCookiesCardVisible();
});
test('safeBrowsingCardForwardNavigationShouldHideCookiesCard', function() {
navigateToStep(PrivacyReviewStep.SAFE_BROWSING);
setCookieSetting(CookiePrimarySetting.ALLOW_ALL);
assertSafeBrowsingCardVisible();
page.shadowRoot!.querySelector<HTMLElement>('#nextButton')!.click();
flush();
assertCompletionCardVisible();
});
test('cookiesCardBackNavigationShouldShowSafeBrowsingCard', function() {
navigateToStep(PrivacyReviewStep.COOKIES);
setSyncEnabled(true);
setSafeBrowsingSetting(SafeBrowsingSetting.STANDARD);
assertCookiesCardVisible();
page.shadowRoot!.querySelector<HTMLElement>('#backButton')!.click();
flush();
assertSafeBrowsingCardVisible();
});
test('cookiesCardBackNavigationShouldHideSafeBrowsingCard', function() {
navigateToStep(PrivacyReviewStep.COOKIES);
setSyncEnabled(true);
setSafeBrowsingSetting(SafeBrowsingSetting.DISABLED);
assertCookiesCardVisible();
page.shadowRoot!.querySelector<HTMLElement>('#backButton')!.click();
flush();
assertHistorySyncCardVisible();
});
test('cookiesCardForwardNavigation', function() {
navigateToStep(PrivacyReviewStep.COOKIES);
assertCookiesCardVisible();
page.shadowRoot!.querySelector<HTMLElement>('#nextButton')!.click();
flush();
assertCompletionCardVisible();
});
test('cookiesCardGetsUpdated', function() {
navigateToStep(PrivacyReviewStep.COOKIES);
setCookieSetting(CookiePrimarySetting.BLOCK_THIRD_PARTY);
assertCookiesCardVisible();
const radioButtonGroup =
page.shadowRoot!.querySelector('#' + PrivacyReviewStep.COOKIES)!
.shadowRoot!.querySelector<SettingsRadioGroupElement>(
'#cookiesRadioGroup')!;
assertEquals(
Number(radioButtonGroup.selected),
CookiePrimarySetting.BLOCK_THIRD_PARTY);
// Changing the cookie setting should automatically change the selected
// radio button.
setCookieSetting(CookiePrimarySetting.BLOCK_THIRD_PARTY_INCOGNITO);
assertEquals(
Number(radioButtonGroup.selected),
CookiePrimarySetting.BLOCK_THIRD_PARTY_INCOGNITO);
// Changing the cookie setting to a non-third-party state while shown should
// navigate away from the cookies card.
setCookieSetting(CookiePrimarySetting.ALLOW_ALL);
assertCompletionCardVisible();
});
test('completionCardBackNavigation', function() {
navigateToStep(PrivacyReviewStep.COMPLETION);
setCookieSetting(CookiePrimarySetting.BLOCK_THIRD_PARTY);
assertCompletionCardVisible();
const completionFragment =
page.shadowRoot!.querySelector('#' + PrivacyReviewStep.COMPLETION)!;
completionFragment.shadowRoot!.querySelector<HTMLElement>(
'#backButton')!.click();
flush();
assertCookiesCardVisible();
});
test('completionCardBackToSettingsNavigation', function() {
navigateToStep(PrivacyReviewStep.COMPLETION);
assertCompletionCardVisible();
return whenPopState(function() {
const completionFragment = page.shadowRoot!.querySelector(
'#' + PrivacyReviewStep.COMPLETION)!;
completionFragment.shadowRoot!
.querySelector<HTMLElement>('#leaveButton')!.click();
})
.then(function() {
assertEquals(routes.PRIVACY, Router.getInstance().getCurrentRoute());
});
});
test('completionCardGetsUpdated', function() {
navigateToStep(PrivacyReviewStep.COMPLETION);
setSignInState(true);
assertCompletionCardVisible();
const completionFragment =
page.shadowRoot!.querySelector('#' + PrivacyReviewStep.COMPLETION)!;
assertTrue(isChildVisible(completionFragment, '#privacySandboxRow'));
assertTrue(isChildVisible(completionFragment, '#waaRow'));
// Sign the user out and expect the waa row to no longer be visible.
setSignInState(false);
assertTrue(isChildVisible(completionFragment, '#privacySandboxRow'));
assertFalse(isChildVisible(completionFragment, '#waaRow'));
});
});
suite('HistorySyncFragment', function() {
let page: PrivacyReviewHistorySyncFragmentElement;
let syncBrowserProxy: TestSyncBrowserProxy;
setup(function() {
syncBrowserProxy = new TestSyncBrowserProxy();
SyncBrowserProxyImpl.setInstance(syncBrowserProxy);
document.body.innerHTML = '';
page = document.createElement('privacy-review-history-sync-fragment');
document.body.appendChild(page);
return flushTasks();
});
teardown(function() {
page.remove();
});
function setSyncStatus({
syncAllDataTypes,
typedUrlsSynced,
passwordsSynced,
}: {
syncAllDataTypes: boolean,
typedUrlsSynced: boolean,
passwordsSynced: boolean,
}) {
if (syncAllDataTypes) {
assertTrue(typedUrlsSynced);
assertTrue(passwordsSynced);
}
const event: SyncPrefs = {} as unknown as SyncPrefs;
for (const datatype of syncPrefsIndividualDataTypes) {
(event as unknown as {[key: string]: boolean})[datatype] = true;
}
// Overwrite datatypes needed in tests.
event.syncAllDataTypes = syncAllDataTypes;
event.typedUrlsSynced = typedUrlsSynced;
event.passwordsSynced = passwordsSynced;
webUIListenerCallback('sync-prefs-changed', event);
flush();
}
async function assertBrowserProxyCall({
syncAllDatatypesExpected,
typedUrlsSyncedExpected,
}: {
syncAllDatatypesExpected: boolean,
typedUrlsSyncedExpected: boolean,
}) {
const syncPrefs = await syncBrowserProxy.whenCalled('setSyncDatatypes');
assertEquals(syncAllDatatypesExpected, syncPrefs.syncAllDataTypes);
assertEquals(typedUrlsSyncedExpected, syncPrefs.typedUrlsSynced);
syncBrowserProxy.resetResolver('setSyncDatatypes');
}
test('syncAllOnDisableReenableHistorySync', async function() {
setSyncStatus({
syncAllDataTypes: true,
typedUrlsSynced: true,
passwordsSynced: true,
});
page.$.historyToggle.click();
await assertBrowserProxyCall({
syncAllDatatypesExpected: false,
typedUrlsSyncedExpected: false,
});
// Re-enabling history sync re-enables sync all if sync all was on before
// and if all sync datatypes are still enabled.
page.$.historyToggle.click();
return assertBrowserProxyCall({
syncAllDatatypesExpected: true,
typedUrlsSyncedExpected: true,
});
});
test('syncAllOnDisableReenableHistorySyncOtherDatatypeOff', async function() {
setSyncStatus({
syncAllDataTypes: true,
typedUrlsSynced: true,
passwordsSynced: true,
});
page.$.historyToggle.click();
await assertBrowserProxyCall({
syncAllDatatypesExpected: false,
typedUrlsSyncedExpected: false,
});
// The user disables another datatype in a different tab.
setSyncStatus({
syncAllDataTypes: false,
typedUrlsSynced: false,
passwordsSynced: false,
});
// Re-enabling history sync in the privacy review doesn't re-enable sync
// all.
page.$.historyToggle.click();
return assertBrowserProxyCall({
syncAllDatatypesExpected: false,
typedUrlsSyncedExpected: true,
});
});
test('syncAllOnDisableReenableHistorySyncWithNavigation', async function() {
setSyncStatus({
syncAllDataTypes: true,
typedUrlsSynced: true,
passwordsSynced: true,
});
page.$.historyToggle.click();
await assertBrowserProxyCall({
syncAllDatatypesExpected: false,
typedUrlsSyncedExpected: false,
});
// The user navigates to another card, then back to the history sync card.
Router.getInstance().navigateTo(
routes.PRIVACY_REVIEW,
/* opt_dynamicParameters */ new URLSearchParams('step=msbb'));
Router.getInstance().navigateTo(
routes.PRIVACY_REVIEW,
/* opt_dynamicParameters */ new URLSearchParams('step=historySync'));
// Re-enabling history sync in the privacy review doesn't re-enable sync
// all.
page.$.historyToggle.click();
return assertBrowserProxyCall({
syncAllDatatypesExpected: false,
typedUrlsSyncedExpected: true,
});
});
test('syncAllOffDisableReenableHistorySync', async function() {
setSyncStatus({
syncAllDataTypes: false,
typedUrlsSynced: true,
passwordsSynced: true,
});
page.$.historyToggle.click();
await assertBrowserProxyCall({
syncAllDatatypesExpected: false,
typedUrlsSyncedExpected: false,
});
// Re-enabling history sync doesn't re-enable sync all if sync all wasn't on
// originally.
page.$.historyToggle.click();
return assertBrowserProxyCall({
syncAllDatatypesExpected: false,
typedUrlsSyncedExpected: true,
});
});
test('syncAllOffEnableHistorySync', function() {
setSyncStatus({
syncAllDataTypes: false,
typedUrlsSynced: false,
passwordsSynced: true,
});
page.$.historyToggle.click();
return assertBrowserProxyCall({
syncAllDatatypesExpected: false,
typedUrlsSyncedExpected: true,
});
});
}); | the_stack |
import {getInstance, MarginsType, NativeInitialSettings, NativeLayerImpl, PluginProxyImpl, PrintPreviewAppElement, ScalingType, SerializedSettings, Setting, SettingsMixinInterface} from 'chrome://print/print_preview.js';
import {assert} from 'chrome://resources/js/assert.m.js';
import {assertEquals} from 'chrome://webui-test/chai_assert.js';
// <if expr="chromeos_ash or chromeos_lacros">
import {setNativeLayerCrosInstance} from './native_layer_cros_stub.js';
// </if>
import {NativeLayerStub} from './native_layer_stub.js';
import {getCddTemplateWithAdvancedSettings, getDefaultInitialSettings} from './print_preview_test_utils.js';
import {TestPluginProxy} from './test_plugin_proxy.js';
const restore_state_test = {
suiteName: 'RestoreStateTest',
TestNames: {
RestoreTrueValues: 'restore true values',
RestoreFalseValues: 'restore false values',
SaveValues: 'save values',
},
};
Object.assign(window, {restore_state_test: restore_state_test});
suite(restore_state_test.suiteName, function() {
let page: PrintPreviewAppElement;
let nativeLayer: NativeLayerStub;
const initialSettings: NativeInitialSettings = getDefaultInitialSettings();
setup(function() {
nativeLayer = new NativeLayerStub();
NativeLayerImpl.setInstance(nativeLayer);
// <if expr="chromeos_ash or chromeos_lacros">
setNativeLayerCrosInstance();
// </if>
document.body.innerHTML = '';
});
/**
* @param stickySettings Settings to verify.
*/
function verifyStickySettingsApplied(stickySettings: SerializedSettings) {
assertEquals(
stickySettings.dpi!.horizontal_dpi,
page.settings.dpi.value.horizontal_dpi);
assertEquals(
stickySettings.dpi!.vertical_dpi, page.settings.dpi.value.vertical_dpi);
assertEquals(
stickySettings.mediaSize!.name, page.settings.mediaSize.value.name);
assertEquals(
stickySettings.mediaSize!.height_microns,
page.settings.mediaSize.value.height_microns);
assertEquals(
stickySettings.mediaSize!.width_microns,
page.settings.mediaSize.value.width_microns);
assertEquals(
(stickySettings.vendorOptions! as {[key: string]: any})!['paperType'],
page.settings.vendorItems.value.paperType);
assertEquals(
(stickySettings.vendorOptions! as {[key: string]: any})['printArea'],
page.settings.vendorItems.value.printArea);
[['margins', 'marginsType'],
['color', 'isColorEnabled'],
['headerFooter', 'isHeaderFooterEnabled'],
['layout', 'isLandscapeEnabled'],
['collate', 'isCollateEnabled'],
['cssBackground', 'isCssBackgroundEnabled'],
['scaling', 'scaling'],
['scalingType', 'scalingType'],
['scalingTypePdf', 'scalingTypePdf'],
].forEach(keys => {
assertEquals(
(stickySettings as {[key: string]: any})[keys[1]!],
(page.settings! as {[key: string]: Setting})[keys[0]!]!.value);
});
}
/**
* Performs initialization and verifies settings.
*/
async function testInitializeWithStickySettings(
stickySettings: SerializedSettings) {
initialSettings.serializedAppStateStr = JSON.stringify(stickySettings);
nativeLayer.setInitialSettings(initialSettings);
nativeLayer.setLocalDestinations(
[{deviceName: initialSettings.printerName, printerName: 'FooName'}]);
nativeLayer.setLocalDestinationCapabilities(
getCddTemplateWithAdvancedSettings(2, initialSettings.printerName));
const pluginProxy = new TestPluginProxy();
PluginProxyImpl.setInstance(pluginProxy);
page = document.createElement('print-preview-app');
document.body.appendChild(page);
await Promise.all([
nativeLayer.whenCalled('getInitialSettings'),
nativeLayer.whenCalled('getPrinterCapabilities')
]);
verifyStickySettingsApplied(stickySettings);
}
/**
* Tests state restoration with all boolean settings set to true, scaling =
* 90, dpi = 100, custom square paper, and custom margins.
*/
test(
assert(restore_state_test.TestNames.RestoreTrueValues), async function() {
const stickySettings: SerializedSettings = {
version: 2,
recentDestinations: [],
dpi: {horizontal_dpi: 100, vertical_dpi: 100},
mediaSize: {
name: 'CUSTOM',
width_microns: 215900,
height_microns: 215900,
custom_display_name: 'CUSTOM_SQUARE'
},
customMargins: {
marginTop: 74,
marginRight: 74,
marginBottom: 74,
marginLeft: 74
},
vendorOptions: {
paperType: 1,
printArea: 6,
},
marginsType: 3, /* custom */
scaling: '90',
scalingType: ScalingType.CUSTOM,
scalingTypePdf: ScalingType.FIT_TO_PAGE,
isHeaderFooterEnabled: true,
isCssBackgroundEnabled: true,
isCollateEnabled: true,
isDuplexEnabled: true,
isDuplexShortEdge: true,
isLandscapeEnabled: true,
isColorEnabled: true,
// <if expr="chromeos_ash or chromeos_lacros">
isPinEnabled: true,
pinValue: '0000',
// </if>
};
await testInitializeWithStickySettings(stickySettings);
});
/**
* Tests state restoration with all boolean settings set to false, scaling =
* 120, dpi = 200, letter paper and default margins.
*/
test(
assert(restore_state_test.TestNames.RestoreFalseValues),
async function() {
const stickySettings: SerializedSettings = {
version: 2,
recentDestinations: [],
dpi: {horizontal_dpi: 200, vertical_dpi: 200},
mediaSize: {
name: 'NA_LETTER',
width_microns: 215900,
height_microns: 279400,
is_default: true,
custom_display_name: 'Letter'
},
vendorOptions: {
paperType: 0,
printArea: 4,
},
marginsType: 0, /* default */
scaling: '120',
scalingType: ScalingType.DEFAULT,
scalingTypePdf: ScalingType.DEFAULT,
isHeaderFooterEnabled: false,
isCssBackgroundEnabled: false,
isCollateEnabled: false,
isDuplexEnabled: false,
isDuplexShortEdge: false,
isLandscapeEnabled: false,
isColorEnabled: false,
// <if expr="chromeos_ash or chromeos_lacros">
isPinEnabled: false,
pinValue: '',
// </if>
};
await testInitializeWithStickySettings(stickySettings);
});
/**
* Tests that setting the settings values results in the correct serialized
* values being sent to the native layer.
*/
test(assert(restore_state_test.TestNames.SaveValues), async function() {
type TestCase = {
section: string,
settingName: string,
key: string,
value: any,
};
/**
* Array of section names, setting names, keys for serialized state, and
* values for testing.
*/
const testData: TestCase[] = [
{
section: 'print-preview-copies-settings',
settingName: 'collate',
key: 'isCollateEnabled',
value: true,
},
{
section: 'print-preview-layout-settings',
settingName: 'layout',
key: 'isLandscapeEnabled',
value: true,
},
{
section: 'print-preview-color-settings',
settingName: 'color',
key: 'isColorEnabled',
value: false,
},
{
section: 'print-preview-media-size-settings',
settingName: 'mediaSize',
key: 'mediaSize',
value: {
name: 'CUSTOM',
width_microns: 215900,
height_microns: 215900,
custom_display_name: 'CUSTOM_SQUARE',
},
},
{
section: 'print-preview-margins-settings',
settingName: 'margins',
key: 'marginsType',
value: MarginsType.MINIMUM,
},
{
section: 'print-preview-dpi-settings',
settingName: 'dpi',
key: 'dpi',
value: {horizontal_dpi: 100, vertical_dpi: 100},
},
{
section: 'print-preview-scaling-settings',
settingName: 'scalingType',
key: 'scalingType',
value: ScalingType.CUSTOM,
},
{
section: 'print-preview-scaling-settings',
settingName: 'scalingTypePdf',
key: 'scalingTypePdf',
value: ScalingType.CUSTOM,
},
{
section: 'print-preview-scaling-settings',
settingName: 'scaling',
key: 'scaling',
value: '85',
},
{
section: 'print-preview-duplex-settings',
settingName: 'duplex',
key: 'isDuplexEnabled',
value: false,
},
{
section: 'print-preview-duplex-settings',
settingName: 'duplexShortEdge',
key: 'isDuplexShortEdge',
value: true,
},
{
section: 'print-preview-other-options-settings',
settingName: 'headerFooter',
key: 'isHeaderFooterEnabled',
value: false,
},
{
section: 'print-preview-other-options-settings',
settingName: 'cssBackground',
key: 'isCssBackgroundEnabled',
value: true,
},
{
section: 'print-preview-advanced-options-settings',
settingName: 'vendorItems',
key: 'vendorOptions',
value: {
paperType: 1,
printArea: 6,
},
},
// <if expr="chromeos_ash or chromeos_lacros">
{
section: 'print-preview-pin-settings',
settingName: 'pin',
key: 'isPinEnabled',
value: true,
},
{
section: 'print-preview-pin-settings',
settingName: 'pinValue',
key: 'pinValue',
value: '0000',
},
// </if>
];
// Setup
nativeLayer.setInitialSettings(initialSettings);
nativeLayer.setLocalDestinations(
[{deviceName: initialSettings.printerName, printerName: 'FooName'}]);
const pluginProxy = new TestPluginProxy();
PluginProxyImpl.setInstance(pluginProxy);
page = document.createElement('print-preview-app');
document.body.appendChild(page);
await Promise.all([
nativeLayer.whenCalled('getInitialSettings'),
nativeLayer.whenCalled('getPrinterCapabilities')
]);
// Set all the settings sections.
testData.forEach((testValue: TestCase, index: number) => {
if (index === testData.length - 1) {
nativeLayer.resetResolver('saveAppState');
}
// Since advanced options settings doesn't set this setting in
// production, just use the model instead of creating the dialog.
const element = testValue.settingName === 'vendorItems' ?
getInstance() :
page.shadowRoot!.querySelector('print-preview-sidebar')!.shadowRoot!
.querySelector<SettingsMixinInterface&HTMLElement>(
testValue.section)!;
element.setSetting(testValue.settingName, testValue.value);
});
// Wait on only the last call to saveAppState, which should
// contain all the update settings values.
const serializedSettingsStr = await nativeLayer.whenCalled('saveAppState');
const serializedSettings =
JSON.parse(serializedSettingsStr) as {[key: string]: any};
// Validate serialized state.
testData.forEach(testValue => {
assertEquals(
JSON.stringify(testValue.value),
JSON.stringify(serializedSettings[testValue.key]));
});
});
}); | the_stack |
import { Dispatch } from 'redux';
import isEqual from 'lodash/isEqual';
import * as actionCreators from '../src/redux/actionCreators';
import { EnqueuedAction, NetworkState } from '../src/types';
import createReducer, {
initialState,
networkSelector,
} from '../src/redux/createReducer';
import getSimilarActionInQueue from '../src/utils/getSimilarActionInQueue';
const networkReducer = createReducer();
const getState = (isConnected = false, ...actionQueue: EnqueuedAction[]) => ({
isConnected,
actionQueue,
isQueuePaused: false,
});
/** Actions used from now on to test different scenarios */
const prevActionToRetry1 = {
type: 'FETCH_DATA_REQUEST',
payload: {
id: '1',
},
meta: {
retry: true,
},
};
const prevActionToRetry2 = {
type: 'FETCH_OTHER_REQUEST',
payload: {
isFetching: true,
},
meta: {
retry: true,
},
};
const prevActionToRetry1WithDifferentPayload = {
type: 'FETCH_DATA_REQUEST',
payload: {
id: '2',
},
meta: {
retry: true,
},
};
describe('unknown action type', () => {
it('returns prevState on initialization', () => {
expect(networkReducer(undefined, { type: 'ACTION_I_DONT_CARE' })).toEqual(
initialState,
);
});
it('returns prevState if the action is not handled', () => {
expect(
networkReducer(initialState, { type: 'ANOTHER_ACTION_I_DONT_CARE' }),
).toEqual(initialState);
});
});
describe('CONNECTION_CHANGE action type', () => {
it('changes isConnected state properly', () => {
const mockAction = actionCreators.connectionChange(false);
expect(networkReducer(initialState, mockAction)).toEqual({
isConnected: false,
actionQueue: [],
isQueuePaused: false,
});
});
});
describe('OFFLINE_ACTION action type', () => {
describe('meta.retry !== true', () => {
it('should NOT add the action to the queue', () => {
const prevAction = {
type: 'FETCH_DATA_REQUEST',
payload: {
id: '1',
},
};
const anotherPrevAction = {
type: 'FETCH_DATA_REQUEST',
payload: {
id: '1',
},
meta: {
retry: false,
},
};
const action = actionCreators.fetchOfflineMode(prevAction);
const anotherAction = actionCreators.fetchOfflineMode(anotherPrevAction);
expect(networkReducer(initialState, action)).toEqual(initialState);
expect(networkReducer(initialState, anotherAction)).toEqual(initialState);
});
});
describe('meta.retry === true', () => {
describe('actions with DIFFERENT type', () => {
it('actions are pushed into the queue in order of arrival', () => {
const preAction = actionCreators.connectionChange(false);
const action1 = actionCreators.fetchOfflineMode(prevActionToRetry1);
const prevState = networkReducer(initialState, preAction);
let nextState = networkReducer(prevState, action1);
expect(nextState).toEqual({
isConnected: false,
actionQueue: [prevActionToRetry1],
isQueuePaused: false,
});
const action2 = actionCreators.fetchOfflineMode(prevActionToRetry2);
nextState = networkReducer(nextState, action2);
expect(nextState).toEqual(
getState(false, prevActionToRetry1, prevActionToRetry2),
);
});
});
describe('thunks that are the same with custom comparison function', () => {
function comparisonFn(action: any, actionQueue: EnqueuedAction[]) {
if (typeof action === 'object') {
return actionQueue.find(queued => isEqual(queued, action));
}
if (typeof action === 'function') {
return actionQueue.find(
queued =>
action.meta.name === queued.meta!.name &&
action.meta.args.id === queued.meta!.args.id,
);
}
return undefined;
}
const thunkFactory = (id: number, name: string, age: number) => {
function thunk(dispatch: Dispatch) {
dispatch({ type: 'UPDATE_DATA_REQUEST', payload: { id, name, age } });
}
thunk.meta = {
args: { id, name, age },
retry: true,
};
return thunk;
};
it(`should add thunks if function is same but thunks are modifying different items`, () => {
const prevState = getState(false, thunkFactory(1, 'Bilbo', 55));
const thunk = thunkFactory(2, 'Link', 54);
const wrappedThunk = actionCreators.fetchOfflineMode(thunk);
expect(getSimilarActionInQueue(thunk, prevState.actionQueue)).toEqual(
prevState.actionQueue[0],
);
const nextState = createReducer(comparisonFn)(prevState, wrappedThunk);
expect(nextState.actionQueue).toHaveLength(2);
});
it(`should replace a thunk if thunk already exists to modify same item`, () => {
const prevState = getState(false, thunkFactory(1, 'Bilbo', 55));
const thunk = thunkFactory(1, 'Bilbo', 65);
const wrappedThunk = actionCreators.fetchOfflineMode(thunk);
expect(getSimilarActionInQueue(thunk, prevState.actionQueue)).toEqual(
prevState.actionQueue[0],
);
const nextState = createReducer(comparisonFn)(prevState, wrappedThunk);
expect(nextState.actionQueue).toHaveLength(1);
});
});
describe('actions with the same type', () => {
it(`should remove the action and add it back at the end of the queue
if the action has the same payload`, () => {
const prevState = getState(
false,
prevActionToRetry1,
prevActionToRetry2,
);
const action = actionCreators.fetchOfflineMode(prevActionToRetry1);
const nextState = networkReducer(prevState, action);
expect(nextState).toEqual(
getState(false, prevActionToRetry2, prevActionToRetry1),
);
});
it(`should push the action if the payload is different`, () => {
const prevState = getState(
false,
prevActionToRetry2,
prevActionToRetry1,
);
const action = actionCreators.fetchOfflineMode(
prevActionToRetry1WithDifferentPayload,
);
expect(networkReducer(prevState, action)).toEqual(
getState(
false,
prevActionToRetry2,
prevActionToRetry1,
prevActionToRetry1WithDifferentPayload,
),
);
});
});
});
});
describe('REMOVE_ACTION_FROM_QUEUE action type', () => {
it('removes the action from the queue properly', () => {
const prevState = getState(
false,
prevActionToRetry2,
prevActionToRetry1,
prevActionToRetry1WithDifferentPayload,
);
// Different object references but same shape, checking that deep equal works correctly
const action = actionCreators.removeActionFromQueue({
...prevActionToRetry2,
});
expect(networkReducer(prevState, action)).toEqual(
getState(
false,
prevActionToRetry1,
prevActionToRetry1WithDifferentPayload,
),
);
});
});
describe('QUEUE_SEMAPHORE_CHANGE action type', () => {
it('Pauses the queue if semaphore is red', () => {
expect(
networkReducer(undefined, actionCreators.changeQueueSemaphore('RED')),
).toEqual({
...initialState,
isQueuePaused: true,
});
});
it('Resumes the queue if semaphore is green', () => {
expect(
networkReducer(undefined, actionCreators.changeQueueSemaphore('GREEN')),
).toEqual({
...initialState,
isQueuePaused: false,
});
});
});
describe('thunks', () => {
function fetchThunk(dispatch: Dispatch) {
dispatch({ type: 'FETCH_DATA_REQUEST' });
}
describe('FETCH_OFFLINE_MODE action type', () => {
describe('action with meta.retry !== true', () => {
it('should NOT add the action to the queue', () => {
const action = actionCreators.fetchOfflineMode(fetchThunk);
expect(networkReducer(initialState, action)).toEqual(initialState);
});
});
describe('action with meta.retry === true', () => {
it('should add the action to the queue if the thunk is different', () => {
const prevState = getState(false);
// Property 'meta' does not exist on type '(dispatch: Dispatch<AnyAction>) => void'
(fetchThunk as any).meta = {
retry: true,
};
const action = actionCreators.fetchOfflineMode(fetchThunk);
expect(networkReducer(prevState, action)).toEqual(
getState(false, fetchThunk),
);
});
it(`should remove the thunk and add it back at the end of the queue
if it presents the same shape`, () => {
const thunkFactory = (param: any) => {
function thunk1(dispatch: Dispatch) {
dispatch({ type: 'FETCH_DATA_REQUEST', payload: param });
}
return thunk1;
};
const thunk = thunkFactory('foo');
const prevState = getState(false, thunk);
const similarThunk = thunkFactory('bar');
(similarThunk as any).meta = {
retry: true,
};
const action = actionCreators.fetchOfflineMode(similarThunk);
const nextState = networkReducer(prevState, action);
expect(nextState).toEqual(getState(false, similarThunk));
});
});
});
describe('REMOVE_ACTION_FROM_QUEUE action type', () => {
it('removes the thunk from the queue properly', () => {
const prevState = getState(false, fetchThunk);
const action = actionCreators.removeActionFromQueue(fetchThunk);
expect(networkReducer(prevState, action)).toEqual(getState(false));
});
});
});
describe('dismiss feature', () => {
const actionEnqueued1 = {
type: 'FETCH_PAGE_REQUEST',
payload: {
id: '2',
},
meta: {
retry: true,
dismiss: ['NAVIGATE_BACK', 'NAVIGATE_TO_LOGIN'],
},
};
const actionEnqueued2 = {
type: 'FETCH_USER_REQUEST',
payload: {
id: '4',
},
meta: {
retry: true,
dismiss: ['NAVIGATE_TO_LOGIN'],
},
};
const actionEnqueued3 = {
type: 'FETCH_USER_REQUEST',
payload: {
id: '4',
},
meta: {
retry: true,
},
};
it('NAVIGATE_BACK dispatched, dismissing 1 action', () => {
const prevState = getState(
false,
actionEnqueued1,
actionEnqueued2,
actionEnqueued3,
);
const action = actionCreators.dismissActionsFromQueue('NAVIGATE_BACK');
expect(networkReducer(prevState, action)).toEqual(
getState(false, actionEnqueued2, actionEnqueued3),
);
});
it('NAVIGATE_TO_LOGIN dispatched, dismissing 2 actions', () => {
const prevState = getState(
false,
actionEnqueued1,
actionEnqueued2,
actionEnqueued3,
);
const action = actionCreators.dismissActionsFromQueue('NAVIGATE_TO_LOGIN');
expect(networkReducer(prevState, action)).toEqual(
getState(false, actionEnqueued3),
);
});
it("Any other action dispatched, no changes (although the middleware won't allow that)", () => {
const prevState = getState(
false,
actionEnqueued1,
actionEnqueued2,
actionEnqueued3,
);
const action = actionCreators.dismissActionsFromQueue('NAVIGATE_AWAY');
expect(networkReducer(prevState, action)).toEqual(
getState(false, actionEnqueued1, actionEnqueued2, actionEnqueued3),
);
});
});
describe('networkSelector', () => {
it('returns the correct shape', () => {
const state: { network: NetworkState } = {
network: {
isConnected: true,
actionQueue: [{ type: 'foo', payload: {} }],
isQueuePaused: false,
},
};
expect(networkSelector(state)).toEqual({
isConnected: true,
actionQueue: [{ type: 'foo', payload: {} }],
isQueuePaused: false,
});
});
}); | the_stack |
import * as fs from "fs";
import jBinary = require("jbinary");
// #region as
(() => {
const title = '"as"';
const binary1 = new jBinary([0x05, 0x03, 0x7f, 0x1e]);
const binary2 = binary1.as({ "jBinary.all": "uint8" });
const data2 = binary2.readAll();
if (data2 === 5) {
console.log(`[OK.] ${title} => Aliasing data went fine.`);
} else {
console.log(`[ERR] ${title} => Expected 5 but got ${data2}.`);
}
})();
(() => {
const title = '"as" (with modifyOriginal)';
const binary1 = new jBinary([0x05, 0x03, 0x7f, 0x1e]);
const binary2 = binary1.as({ "jBinary.all": "uint8" }, true);
const data1 = binary1.readAll();
const data2 = binary2.readAll();
if (data1 === data2) {
console.log(`[OK.] ${title} => Aliasing data went fine.`);
} else {
console.log(`[ERR] ${title} => Expected ${data1} to be equal to ${data2}.`);
}
})();
// #endregion as
// #region load
(() => {
const title = '"load" (with Callback and ReadableStream)';
const inputStream = fs.createReadStream("./test.bin");
jBinary.load(inputStream, undefined, (err, jb) => {
if (err) {
console.log(`[ERR] ${title} => Error reading file: ${err.message}`);
} else {
console.log(`[OK.] ${title} => Loaded ${jb.view.buffer.length} bytes of data.`);
}
});
})();
(() => {
const title = '"load" (with Promise and file path)';
jBinary
.load("./test.bin")
.then(jb => {
console.log(`[OK.] ${title} => Loaded ${jb.view.buffer.length} bytes of data.`);
})
.catch(reason => {
if (reason instanceof Error) {
console.log(`[ERR] ${title} => Error reading file: ${reason.message}`);
}
});
})();
// #endregion load
// #region loadData
(() => {
const title = '"loadData" (with Callback and file path)';
jBinary.loadData("./test.bin", (err, data) => {
if (err) {
console.log(`[ERR] ${title} => Error reading file: ${err.message}`);
} else if (data) {
console.log(`[OK.] ${title} => Loaded ${data.length} bytes of data.`);
} else {
console.log(`[???] ${title} => No error and no data.`);
}
});
})();
(() => {
const title = '"loadData" (with Promise and ReadableStream)';
const inputStream = fs.createReadStream("./test.bin");
jBinary
.loadData(inputStream)
.then(data => {
console.log(`[OK.] ${title} => Loaded ${data.length} bytes of data.`);
})
.catch(reason => {
if (reason instanceof Error) {
console.log(`[ERR] ${title} => Error reading file: ${reason.message}`);
}
});
})();
// #endregion loadData
// #region read
(() => {
const title = '"read"';
const binary = new jBinary([0x05, 0x03, 0x7f, 0x1e]);
const data = binary.read("uint8");
if (data === 5) {
console.log(`[OK.] ${title} => Reading data went fine.`);
} else {
console.log(`[ERR] ${title} => Expected 5 but got ${data}.`);
}
})();
(() => {
const title = '"read" (with custom position)';
const binary = new jBinary([0x05, 0x03, 0x7f, 0x1e]);
const data = binary.read("uint8", 1);
if (data === 3) {
console.log(`[OK.] ${title} => Reading data went fine.`);
} else {
console.log(`[ERR] ${title} => Expected 3 but got ${data}.`);
}
})();
// #endregion read
// #region readAll
(() => {
const title = '"readAll" (with typeset)';
const binary = new jBinary([0x05, 0x03, 0x7f, 0x1e], { "jBinary.all": "uint8" });
const data = binary.readAll();
if (data === 5) {
console.log(`[OK.] ${title} => Reading data went fine.`);
} else {
console.log(`[ERR] ${title} => Expected 5 but got ${data}.`);
}
})();
// #endregion readAll
// #region saveAs
(() => {
const title = '"saveAs" (with Callback, file path and text as data)';
const filePath = "./test-saveas-callback.txt";
const binary = new jBinary("ABCDEFG");
binary.saveAs(filePath, "text/plain", err => {
if (err instanceof Error) {
console.log(`[ERR] ${title} => Error writing file: ${err.message}`);
} else {
console.log(`[OK.] ${title} => Data saved.`);
}
fs.unlinkSync(filePath);
});
})();
(() => {
const title = '"saveAs" (with Promise, WritableStream and Array<number> as data)';
const filePath = "./test-saveas-promise.bin";
const outputStream = fs.createWriteStream(filePath);
const binary = new jBinary([0x05, 0x03, 0x7f, 0x1e]);
binary
.saveAs(outputStream)
.then(() => {
console.log(`[OK.] ${title} => Data saved.`);
})
.catch(reason => {
if (reason instanceof Error) {
console.log(`[ERR] ${title} => Error writing file: ${reason.message}`);
}
})
.finally(() => {
outputStream.close();
fs.unlinkSync(filePath);
});
})();
// #endregion saveAs
// #region seek
(() => {
const title = '"seek"';
const binary = new jBinary([0x05, 0x03, 0x7f, 0x1e]);
binary.seek(3);
const data = binary.read("uint8");
if (data === 30) {
console.log(`[OK.] ${title} => Seeking and reading data went fine.`);
} else {
console.log(`[ERR] ${title} => Expected 30 after seek but got ${data}.`);
}
})();
(() => {
const title = '"seek" (with Callback)';
const binary = new jBinary([0x05, 0x03, 0x7f, 0x1e]);
const data = binary.seek(3, () => {
return binary.read("uint8");
});
if (data === 30) {
console.log(`[OK.] ${title} => Seeking and reading data went fine.`);
} else {
console.log(`[ERR] ${title} => Expected 30 after seek but got ${data}.`);
}
})();
// #endregion seek
// #region skip
(() => {
const title = '"skip"';
const binary = new jBinary([0x05, 0x03, 0x7f, 0x1e]);
binary.skip(2);
const data = binary.read("uint8");
if (data === 127) {
console.log(`[OK.] ${title} => Skipping and reading data went fine.`);
} else {
console.log(`[ERR] ${title} => Expected 127 after skip but got ${data}.`);
}
})();
(() => {
const title = '"skip" (with Callback)';
const binary = new jBinary([0x05, 0x03, 0x7f, 0x1e]);
const data = binary.skip(2, () => {
return binary.read("uint8");
});
if (data === 127) {
console.log(`[OK.] ${title} => Skipping and reading data went fine.`);
} else {
console.log(`[ERR] ${title} => Expected 127 after skip but got ${data}.`);
}
})();
// #endregion skip
// #region slice
(() => {
const title = '"slice"';
const binary1 = new jBinary([0x05, 0x03, 0x7f, 0x1e]);
const binary2 = binary1.slice(1, 2);
const data = binary2.read("uint8");
if (data === 3) {
console.log(`[OK.] ${title} => Slicing and reading data went fine.`);
} else {
console.log(`[ERR] ${title} => Expected 3 after slice but got ${data}.`);
}
})();
// #endregion slice
// #region tell
(() => {
const title = '"tell"';
const binary = new jBinary([0x05, 0x03, 0x7f, 0x1e]);
binary.skip(1);
const pos = binary.tell();
if (pos === 1) {
console.log(`[OK.] ${title} => Telling position in binary went fine.`);
} else {
console.log(`[ERR] ${title} => Expected position in binary to be 1 after skip but was ${pos}.`);
}
})();
// #endregion tell
// #region toURI
(() => {
const title = '"toURI"';
const binary = new jBinary([0x05, 0x03, 0x7f, 0x1e]);
if (binary.toURI() === "data:application/octet-stream;base64,BQN/Hg==") {
console.log(`[OK.] ${title} => URI generation went fine.`);
} else {
console.log(`[ERR] ${title} => Unexpected result.`);
}
})();
(() => {
const title = '"toURI" (with MIME type)';
const binary = new jBinary("ABCDEFG");
if (binary.toURI("text/plain") === "data:text/plain;base64,QUJDREVGRw==") {
console.log(`[OK.] ${title} => URI generation went fine.`);
} else {
console.log(`[ERR] ${title} => Unexpected result.`);
}
})();
// #endregion toURI
// #region Template
(() => {
const title = '"Template"';
const binary = new jBinary([0x00, 0x03, 0x04, 0x05, 0x06, 0x07], {
DynamicArray: jBinary.Template({
setParams(itemType) {
this.baseType = {
length: "uint16",
values: ["array", itemType, "length"],
};
},
read() {
return this.baseRead().values;
},
write(values) {
this.baseWrite({
length: values.length,
values,
});
},
}),
byteArray: ["DynamicArray", "uint8"],
});
const byteArray = binary.read("byteArray") as number[];
if (byteArray.length === 3 && byteArray[0] === 4 && byteArray[1] === 5 && byteArray[2] === 6) {
console.log(`[OK.] ${title} => Reading data using template type went fine.`);
} else {
console.log(`[ERR] ${title} => Unexpected result.`);
}
})();
// #endregion Template
// #region Type
(() => {
const title = '"Type"';
const binary = new jBinary([0x00, 0x03, 0x04, 0x05, 0x06, 0x07], {
DynamicArray: jBinary.Type({
params: ["itemType"],
resolve(getType) {
this.itemType = getType(this.itemType);
},
read() {
const length = this.binary.read("uint16") as number;
return this.binary.read(["array", this.itemType, length]);
},
write(values: number[]) {
this.binary.write("uint16", values.length);
this.binary.write(["array", this.itemType], values);
},
}),
byteArray: ["DynamicArray", "uint8"],
});
const byteArray = binary.read("byteArray") as number[];
if (byteArray.length === 3 && byteArray[0] === 4 && byteArray[1] === 5 && byteArray[2] === 6) {
console.log(`[OK.] ${title} => Reading data using custom type went fine.`);
} else {
console.log(`[ERR] ${title} => Unexpected result.`);
}
})();
// #endregion Type
// #region write
(() => {
const title = '"write"';
const binary = new jBinary([0x05, 0x03, 0x7f, 0x1e]);
binary.write("uint8", 21);
binary.seek(0);
const data = binary.read("uint8");
if (data === 21) {
console.log(`[OK.] ${title} => Writing to binary went fine.`);
} else {
console.log(`[ERR] ${title} => Unexpected result when reading updated data.`);
}
})();
(() => {
const title = '"write" (with offset)';
const binary = new jBinary([0x05, 0x03, 0x7f, 0x1e]);
binary.write("uint8", 21, 3);
binary.seek(3);
const data = binary.read("uint8");
if (data === 21) {
console.log(`[OK.] ${title} => Writing to binary went fine.`);
} else {
console.log(`[ERR] ${title} => Unexpected result when reading updated data.`);
}
})();
// //#endregion write
// #region writeAll
(() => {
const title = '"writeAll"';
const binary = new jBinary([0x05, 0x03, 0x7f, 0x1e], { "jBinary.all": "uint8" });
binary.writeAll(128);
binary.seek(0);
const data = binary.read("uint8");
if (data === 128) {
console.log(`[OK.] ${title} => Writing to binary went fine.`);
} else {
console.log(`[ERR] ${title} => Unexpected result when reading updated data.`);
}
})();
//#endregion writeAll | the_stack |
import React from "react";
import { cleanup, render, screen } from "@testing-library/react";
import "@testing-library/jest-dom";
import { Table } from "./Table";
import { ClassNames } from "@emotion/core";
import { matchers } from "jest-emotion";
import { colors } from "../colors";
// Add the custom matchers provided by 'jest-emotion'
expect.extend(matchers);
test("when passed headers in `columns`, should render them, even with no data", () => {
const { container, getByText } = render(
<Table
keyOn={(user) => user.name}
data={[
{
name: "Mason",
dateAdded: "07/14/2018",
},
{
name: "Sadie",
dateAdded: "07/14/2018",
},
]}
columns={[
{
id: "name",
headerTitle: "Name",
render: ({ name }) => name,
},
{
id: "dateAdded",
headerTitle: "Date Added",
render: ({ dateAdded }) => dateAdded,
},
]}
/>,
);
const thead = container.querySelector<HTMLTableSectionElement>("thead");
if (!thead) throw new Error("could not find thead");
expect(thead).toBeInTheDocument();
expect(getByText("Date Added")).toBeInTheDocument();
expect(getByText("Name")).toBeInTheDocument();
});
test("should render content", () => {
const { getAllByText, getByText } = render(
<Table
keyOn={(user) => user.name}
data={[
{
name: "Mason",
dateAdded: "07/14/2018",
},
{
name: "Sadie",
dateAdded: "07/14/2018",
},
]}
columns={[
{
id: 2,
headerTitle: "Name",
render: ({ name }) => name,
},
{
id: 3,
headerTitle: "Date Added",
render: ({ dateAdded }) => dateAdded,
},
]}
/>,
);
// All the user names should be rendered
expect(getByText("Mason")).toBeInTheDocument();
expect(getByText("Sadie")).toBeInTheDocument();
// All dates should be rendered
expect(getAllByText("07/14/2018")).toHaveLength(2);
});
test("when passed col for columns, should render them", () => {
const { container } = render(
<Table
keyOn={(user) => user.name}
data={[
{
name: "Mason",
dateAdded: "07/14/2018",
},
{
name: "Sadie",
dateAdded: "07/14/2018",
},
]}
columns={[
{
id: "name",
headerTitle: "Name",
render: ({ name }) => name,
colProps: { className: "w-0" },
},
{
id: "dateAdded",
headerTitle: "Date Added",
render: ({ dateAdded }) => dateAdded,
colProps: { width: "25%" },
},
]}
/>,
);
const colgroup = container.querySelector<HTMLTableColElement>("colgroup");
if (!colgroup) throw new Error("could not find colgroup");
expect(colgroup).toMatchInlineSnapshot(`
<colgroup>
<col
class="w-0"
/>
<col
width="25%"
/>
</colgroup>
`);
});
it("when passed `column` values for `th`, they are rendered", () => {
render(
<ClassNames>
{({ css }) => (
<Table
keyOn="name"
data={[
{ name: "Mason", firstWord: "Apollo" },
{ name: "Sadie", firstWord: "GraphQL" },
]}
columns={[
{
id: "name",
headerTitle: "Name",
render: ({ name }) => name,
thAs: <th className={css({ color: colors.red.light })} />,
},
{
id: "firstWord",
headerTitle: "First Word Spoken",
render: ({ firstWord }) => firstWord,
thAs: <th className={css({ color: colors.blue.light })} />,
},
]}
/>
)}
</ClassNames>,
);
expect(document.querySelector("thead > tr > th")).toHaveStyleRule(
"color",
colors.red.light,
);
expect(
document.querySelector("thead > tr > th:nth-of-type(2)"),
).toHaveStyleRule("color", colors.blue.light);
});
it("when passed `column` values for `td`, they are rendered", () => {
render(
<ClassNames>
{({ css }) => (
<Table
keyOn="name"
data={[
{ name: "Mason", firstWord: "Apollo" },
{ name: "Sadie", firstWord: "GraphQL" },
]}
columns={[
{
id: "name",
headerTitle: "Name",
render: ({ name }) => name,
as: <td className={css({ color: colors.red.light })} />,
},
{
id: "firstWord",
headerTitle: "First Word Spoken",
render: ({ firstWord }) => firstWord,
as: <td className={css({ color: colors.blue.light })} />,
},
]}
trAs={<tr className="injected-class" />}
/>
)}
</ClassNames>,
);
expect(document.querySelector("tbody > tr > td")).toHaveStyleRule(
"color",
colors.red.light,
);
expect(
document.querySelector("tbody > tr > td:nth-of-type(2)"),
).toHaveStyleRule("color", colors.blue.light);
});
it("when passed `trAs` single value, `className`s are merged to head and body `tr`s", () => {
// We first test that the `tr` elements don't have the style, then that they
// do. This ensures that we're actually changing something to be what we want.
const headTr = () =>
document.querySelector<HTMLTableRowElement>("thead > tr");
const bodyTrs = (): HTMLTableRowElement[] =>
Array.from(document.querySelectorAll<HTMLTableRowElement>("tbody > tr"));
render(
<Table
keyOn="name"
data={[{ name: "Mason" }, { name: "Sadie" }]}
columns={[
{
id: "name",
headerTitle: "Name",
render: ({ name }) => name,
},
]}
trAs={<tr className="injected-class" />}
/>,
);
expect(headTr()).toBeInTheDocument();
expect(headTr()).toHaveClass("injected-class");
expect(headTr()).not.toHaveStyleRule("color", "red");
expect(bodyTrs()).toHaveLength(2);
bodyTrs().forEach((tr) => {
expect(tr).not.toHaveStyleRule("color", "red");
expect(tr).toHaveClass("injected-class");
});
// We must call `cleanup` between renders if we want to test style properties
// because emotion uses side-effects to add styles to the DOM.
cleanup();
render(
<ClassNames>
{({ css, cx }) => (
<Table
keyOn="name"
data={[{ name: "Mason" }, { name: "Sadie" }]}
columns={[
{
id: "name",
headerTitle: "Name",
render: ({ name }) => name,
},
]}
trAs={<tr className={cx(css({ color: "red" }), "injected-class")} />}
/>
)}
</ClassNames>,
);
expect(headTr()).toBeInTheDocument();
expect(headTr()).toHaveStyleRule("color", "red");
expect(headTr()).toHaveClass("injected-class");
expect(bodyTrs()).toHaveLength(2);
bodyTrs().forEach((tr) => {
expect(tr).toHaveStyleRule("color", "red");
expect(tr).toHaveClass("injected-class");
});
});
it("when passed `trAs` with a `head` with additional classes, `className`s are merged to head and not body `tr`s", () => {
// We first test that the `tr` elements don't have the style, then that they
// do. This ensures that we're actually changing something to be what we want.
const headTr = () =>
document.querySelector<HTMLTableRowElement>("thead > tr");
const bodyTrs = (): HTMLTableRowElement[] =>
Array.from(document.querySelectorAll<HTMLTableRowElement>("tbody > tr"));
render(
<Table
keyOn="name"
data={[{ name: "Mason" }, { name: "Sadie" }]}
columns={[
{
id: "name",
headerTitle: "Name",
render: ({ name }) => name,
},
]}
trAs={{ head: <tr className="injected-class" /> }}
/>,
);
expect(headTr()).toBeInTheDocument();
expect(headTr()).toHaveClass("injected-class");
expect(headTr()).not.toHaveStyleRule("color", "red");
expect(bodyTrs()).toHaveLength(2);
bodyTrs().forEach((tr) => {
expect(tr).not.toHaveStyleRule("color", "red");
expect(tr).not.toHaveClass("injected-class");
});
// We must call `cleanup` between renders if we want to test style properties
// because emotion uses side-effects to add styles to the DOM.
cleanup();
render(
<ClassNames>
{({ css, cx }) => (
<Table
keyOn="name"
data={[{ name: "Mason" }, { name: "Sadie" }]}
columns={[
{
id: "name",
headerTitle: "Name",
render: ({ name }) => name,
},
]}
trAs={{
head: (
<tr className={cx(css({ color: "red" }), "injected-class")} />
),
}}
/>
)}
</ClassNames>,
);
expect(headTr()).toBeInTheDocument();
expect(headTr()).toHaveStyleRule("color", "red");
expect(headTr()).toHaveClass("injected-class");
expect(bodyTrs()).toHaveLength(2);
bodyTrs().forEach((tr) => {
expect(tr).not.toHaveStyleRule("color", "red");
expect(tr).not.toHaveClass("injected-class");
});
});
it("when passed `trAs` with a `body` with additional classes, `className`s are merged to body and not head `tr`s", () => {
// We first test that the `tr` elements don't have the style, then that they
// do. This ensures that we're actually changing something to be what we want.
const headTr = () =>
document.querySelector<HTMLTableRowElement>("thead > tr");
const bodyTrs = (): HTMLTableRowElement[] =>
Array.from(document.querySelectorAll<HTMLTableRowElement>("tbody > tr"));
render(
<Table
keyOn="name"
data={[{ name: "Mason" }, { name: "Sadie" }]}
columns={[
{
id: "name",
headerTitle: "Name",
render: ({ name }) => name,
},
]}
trAs={{ body: <tr className="injected-class" /> }}
/>,
);
expect(headTr()).toBeInTheDocument();
expect(headTr()).not.toHaveClass("injected-class");
expect(headTr()).not.toHaveStyleRule("color", "red");
expect(bodyTrs()).toHaveLength(2);
bodyTrs().forEach((tr) => {
expect(tr).toHaveClass("injected-class");
expect(tr).not.toHaveStyleRule("color", "red");
});
// We must call `cleanup` between renders if we want to test style properties
// because emotion uses side-effects to add styles to the DOM.
cleanup();
render(
<ClassNames>
{({ css, cx }) => (
<Table
keyOn="name"
data={[{ name: "Mason" }, { name: "Sadie" }]}
columns={[
{
id: "name",
headerTitle: "Name",
render: ({ name }) => name,
},
]}
trAs={{
body: (
<tr className={cx(css({ color: "red" }), "injected-class")} />
),
}}
/>
)}
</ClassNames>,
);
expect(headTr()).toBeInTheDocument();
expect(headTr()).not.toHaveStyleRule("color", "red");
expect(headTr()).not.toHaveClass("injected-class");
expect(bodyTrs()).toHaveLength(2);
bodyTrs().forEach((tr) => {
expect(tr).toHaveClass("injected-class");
expect(tr).toHaveStyleRule("color", "red");
});
});
it("when passed `trAs` with a `body` and `head` with different additional classes, `className`s are merged", () => {
// We first test that the `tr` elements don't have the style, then that they
// do. This ensures that we're actually changing something to be what we want.
const headTr = () =>
document.querySelector<HTMLTableRowElement>("thead > tr");
const bodyTrs = (): HTMLTableRowElement[] =>
Array.from(document.querySelectorAll<HTMLTableRowElement>("tbody > tr"));
render(
<Table
keyOn="name"
data={[{ name: "Mason" }, { name: "Sadie" }]}
columns={[
{
id: "name",
headerTitle: "Name",
render: ({ name }) => name,
},
]}
trAs={{
body: <tr className="body-injected-class" />,
head: <tr className="head-injected-class" />,
}}
/>,
);
expect(headTr()).toBeInTheDocument();
expect(headTr()).toHaveClass("head-injected-class");
expect(headTr()).not.toHaveClass("body-injected-class");
expect(headTr()).not.toHaveStyleRule("color", "red");
expect(bodyTrs()).toHaveLength(2);
bodyTrs().forEach((tr) => {
expect(tr).toHaveClass("body-injected-class");
expect(tr).not.toHaveClass("head-injected-class");
expect(tr).not.toHaveStyleRule("color", "red");
});
// We must call `cleanup` between renders if we want to test style properties
// because emotion uses side-effects to add styles to the DOM.
cleanup();
render(
<ClassNames>
{({ css, cx }) => (
<Table
keyOn="name"
data={[{ name: "Mason" }, { name: "Sadie" }]}
columns={[
{
id: "name",
headerTitle: "Name",
render: ({ name }) => name,
},
]}
trAs={{
body: (
<tr
className={cx(css({ color: "red" }), "body-injected-class")}
/>
),
head: (
<tr
className={cx(css({ color: "blue" }), "head-injected-class")}
/>
),
}}
/>
)}
</ClassNames>,
);
expect(headTr()).toBeInTheDocument();
expect(headTr()).toHaveStyleRule("color", "blue");
expect(headTr()).not.toHaveClass("body-injected-class");
expect(headTr()).toHaveClass("head-injected-class");
expect(bodyTrs()).toHaveLength(2);
bodyTrs().forEach((tr) => {
expect(tr).toHaveClass("body-injected-class");
expect(tr).not.toHaveClass("head-injected-class");
expect(tr).toHaveStyleRule("color", "red");
});
});
test("when passed an `as` prop, `className`s are merged", () => {
render(
<Table
as={<table className="test-class" data-testid="table" />}
data={[{ name: "Mason" }]}
keyOn="name"
columns={[
{
id: "name",
headerTitle: "Name",
render: ({ name }) => name,
},
]}
/>,
);
expect(screen.getByTestId("table")).toHaveClass("test-class");
expect(screen.getByTestId("table").classList.length).toBeGreaterThanOrEqual(
2,
);
}); | the_stack |
import { EnumShape, ShapeGuards, ShapeVisitor, TypeShape, UnionShape, Value } from '@punchcard/shape';
import { ArrayShape, MapShape, SetShape } from '@punchcard/shape/lib/collection';
import { AnyShape, BinaryShape, bool, BoolShape, NothingShape, number, NumberShape, string, StringShape, timestamp, TimestampShape } from '@punchcard/shape/lib/primitive';
import { Shape } from '@punchcard/shape/lib/shape';
import { AttributeValue } from './attribute';
import { Mapper } from './mapper';
import { Writer } from './writer';
// tslint:disable: ban-types
// we have a thing named Object inside Query, so stash this here.
const Objekt = Object;
export namespace DSL {
export type Tag = typeof Tag;
export const Tag = Symbol.for('@punchcard/shape-dynamodb.Query.Tag');
export type Of<T extends Shape> =
T extends BinaryShape ? DSL.Binary :
T extends BoolShape ? DSL.Bool :
T extends AnyShape ? DSL.Any<T> :
T extends NumberShape ? DSL.Number :
/*
{ type: 'string' }
*/
T extends StringShape ? DSL.String :
T extends TimestampShape ? DSL.Timestamp :
T extends UnionShape<infer U> ?
U extends 1 ? {
[i in Extract<keyof U, number>]: Of<U[i]>
}[1] :
NothingShape extends Extract<U[Extract<keyof U, number>], NothingShape> ?
U['length'] extends 1 ? DSL.Object<NothingShape> :
U['length'] extends 2 ?
Exclude<{
[i in Extract<keyof U, number>]: Of<U[i]>;
}[Extract<keyof U, number>], DSL.Object<NothingShape>> :
DSL.Union<T> :
DSL.Union<T> :
T extends EnumShape ? Enum<T> :
T extends TypeShape<any> ? DSL.Struct<T> :
T extends MapShape<infer V> ? DSL.Map<V> :
T extends SetShape<infer I> ? DSL.Set<I> :
T extends ArrayShape<infer I> ? DSL.List<I> :
T extends { [Tag]: infer Q } ? Q :
DSL.Object<T>
;
export type Root<T extends TypeShape<any>> = Struct<T>['fields'];
export function of<T extends TypeShape<any>>(shape: T): Root<T> {
const result: any = {};
for (const [name, member] of Objekt.entries(shape.Members)) {
result[name] = (member as Shape).visit(DslVisitor, new RootProperty(member as Shape, name));
}
return result;
}
export function _of<T extends Shape>(shape: T, expr: ExpressionNode<any>): Of<T> {
return shape.visit(DslVisitor as any, expr) as Of<T>;
}
export const DslVisitor: ShapeVisitor<Node, ExpressionNode<any>> = {
enumShape: (shape, expr) => {
return new Enum(shape, expr);
},
literalShape: (shape, expression) => {
return shape.Type.visit(DslVisitor as any, expression);
},
unionShape: (shape, expression) => {
const items = shape.Items.filter(i => !ShapeGuards.isNothingShape(i));
if (items.length === 1) {
return _of(items[0], expression);
}
return new Union(shape, expression);
},
functionShape: (() => {
throw new Error(`functionShape is not valid on a DynamoDB DSL`);
}) as any,
neverShape: (() => {
throw new Error(`neverShape is not valid on a DynamoDB DSL`);
}) as any,
nothingShape: (shape: NothingShape, expression: ExpressionNode<any>): Object<NothingShape> => {
return new Object(shape, expression);
},
anyShape: (shape: AnyShape, expression: ExpressionNode<any>): Any<any> => {
return new Any(shape, expression);
},
binaryShape: (shape: BinaryShape, expression: ExpressionNode<any>): Binary => {
return new Binary(shape, expression);
},
arrayShape: (shape: ArrayShape<any>, expression: ExpressionNode<any>): List<any> => {
return new Proxy(new List(shape, expression), {
get: (target, prop) => {
if (typeof prop === 'string') {
if (!isNaN(prop as any)) {
return target.get(parseInt(prop, 10));
}
} else if (typeof prop === 'number' && prop % 1 === 0) {
return target.get(prop);
}
return (target as any)[prop];
}
});
},
boolShape: (shape: BoolShape, expression: ExpressionNode<any>): Bool => {
return new Bool(expression, shape);
},
recordShape: (shape: TypeShape<any>, expression: ExpressionNode<any>): Struct<any> => {
return new Struct(shape, expression);
},
mapShape: (shape: MapShape<any>, expression: ExpressionNode<any>): Map<any> => {
return new Proxy(new Map(shape, expression), {
get: (target, prop) => {
if (typeof prop === 'string') {
if (typeof (target as any)[prop] === 'function') {
return (target as any)[prop];
}
return target.get(prop);
}
return (target as any)[prop];
}
});
},
numberShape: (shape: NumberShape, expression: ExpressionNode<any>): Number => {
return new DSL.Number(expression, shape);
},
setShape: (shape: SetShape<any>, expression: ExpressionNode<any>): Set<any> => {
return new Set(shape.Items, expression);
},
stringShape: (shape: StringShape, expression: ExpressionNode<any>): Node => {
// tslint:disable: no-construct
return new String(expression, shape);
},
timestampShape: (shape: TimestampShape, expression: ExpressionNode<any>): Node => {
return new Timestamp(expression, shape);
}
};
}
export namespace DSL {
export const isNode = (a: any): a is Node => a[NodeType] !== undefined;
export type Expression<T extends Shape> = ExpressionNode<T> | Value.Of<T>;
export const NodeType = Symbol.for('@punchcard/shape-dynamodb.DSL.NodeType');
export const SubNodeType = Symbol.for('@punchcard/shape-dynamodb.DSL.SubNodeType');
export const DataType = Symbol.for('@punchcard/shape-dynamodb.DSL.DataType');
export const InstanceExpression = Symbol.for('@punchcard/shape-dynamodb.DSL.InstanceExpression');
export const Synthesize = Symbol.for('@punchcard/shape-dynamodb.DSL.Synthesize');
export abstract class Node<T extends string = string> {
public readonly [NodeType]: T;
constructor(nodeType: T) {
this[NodeType] = nodeType;
}
public abstract [Synthesize](writer: Writer): void;
}
export function isStatementNode(a: any): a is StatementNode {
return a[NodeType] === 'statement';
}
export abstract class StatementNode extends Node<'statement'> {
public abstract [SubNodeType]: string;
constructor() {
super('statement');
}
}
export abstract class ExpressionNode<S extends Shape> extends Node<'expression'> {
public readonly [DataType]: S;
public abstract readonly [SubNodeType]: string;
constructor(shape: S) {
super('expression');
this[DataType] = shape;
}
}
export class Id extends ExpressionNode<StringShape> {
public readonly [SubNodeType] = 'identifier';
constructor(public readonly value: string) {
super(string);
}
public [Synthesize](writer: Writer): void {
writer.writeName(this.value);
}
}
export function isLiteral(a: any): a is Literal<any> {
return a[SubNodeType] === 'literal';
}
export class Literal<T extends Shape> extends ExpressionNode<T> {
public readonly [SubNodeType] = 'literal';
constructor(type: T, public readonly value: Value.Of<AttributeValue.ShapeOf<T>>) {
super(type);
}
public [Synthesize](writer: Writer): void {
writer.writeValue(this.value as AWS.DynamoDB.AttributeValue);
}
}
export class RootProperty<T extends Shape> extends ExpressionNode<T> {
public [SubNodeType] = 'root-property';
constructor(type: T, public readonly name: string) {
super(type);
}
public [Synthesize](writer: Writer): void {
writer.writeName(this.name);
}
}
function resolveExpression<T extends Shape>(type: T, expression: Expression<T> | Computation<T>): ExpressionNode<T> {
return isComputation(expression) ?
new ComputationExpression(type, expression) :
isNode(expression) ?
expression :
new Literal(type, Mapper.of(type).write(expression as any) as any)
;
}
export class FunctionCall<T extends Shape> extends ExpressionNode<T> {
public [SubNodeType] = 'function-call';
constructor(
public readonly name: string,
public readonly returnType: T,
public readonly parameters: ExpressionNode<any>[]
) {
super(returnType);
}
public [Synthesize](writer: Writer): void {
writer.writeToken(this.name);
writer.writeToken('(');
if (this.parameters.length > 0) {
this.parameters.forEach(p => {
p[Synthesize](writer);
writer.writeToken(',');
});
writer.pop();
}
writer.writeToken(')');
}
}
export class Object<T extends Shape> extends ExpressionNode<T> {
public readonly [SubNodeType] = 'object';
public readonly [InstanceExpression]: ExpressionNode<T>;
constructor(type: T, instanceExpression: ExpressionNode<T>) {
super(type);
this[InstanceExpression] = instanceExpression;
}
public [Synthesize](writer: Writer): void {
this[InstanceExpression][Synthesize](writer);
}
public equals(other: Expression<T>): Bool {
return new Bool(new Object.Equals(this, resolveExpression(this[DataType], other)));
}
public get size(): Number {
return new Number(new FunctionCall('size', number, [this]));
}
public set(value: Expression<T> | Computation<T>): Action {
return new Action(ActionType.SET, new Object.Assign(this, resolveExpression(this[DataType], value)));
}
public exists(): Bool {
return new Bool(new FunctionCall('attribute_exists', bool, [this]));
}
public notExists(): Bool {
return new Bool(new FunctionCall('attribute_not_exists', bool, [this]));
}
}
export namespace Object {
export function beginsWith(lhs: Expression<StringShape>, rhs: Expression<StringShape>) {
return new Bool(new String.BeginsWith(resolveExpression(string, lhs), resolveExpression(string, rhs)));
}
export class Assign<T extends Shape> extends StatementNode {
public [SubNodeType] = 'assign';
constructor(private readonly instance: Object<T>, private readonly value: Node) {
super();
}
public [Synthesize](writer: Writer): void {
this.instance[Synthesize](writer);
writer.writeToken('=');
this.value[Synthesize](writer);
}
}
export abstract class Comparison<T extends Shape, U extends Shape> extends ExpressionNode<BoolShape> {
protected abstract operator: string;
constructor(public readonly left: ExpressionNode<T>, public readonly right: ExpressionNode<U>) {
super(bool);
}
public [Synthesize](writer: Writer): void {
this.left[Synthesize](writer);
writer.writeToken(this.operator);
this.right[Synthesize](writer);
}
}
export class Equals<T extends Shape> extends Object.Comparison<T, T> {
protected readonly operator: '=' = '=';
public readonly [SubNodeType] = 'equals';
}
}
export function size(path: Object<any>) {
return new Size(path);
}
export class Size extends FunctionCall<NumberShape> {
constructor(path: Object<any>) {
super('size', number, [path]);
}
}
export class Bool extends Object<BoolShape> {
constructor(expression: ExpressionNode<BoolShape>, boolShape?: BoolShape) {
super(boolShape || bool, expression);
}
public and(...conditions: Expression<BoolShape>[]): Bool {
return new Bool(new Bool.And([this, ...(conditions.map(c => resolveExpression(bool, c)))]));
}
public or(...conditions: Expression<BoolShape>[]): Bool {
return new Bool(new Bool.Or([this, ...(conditions.map(c => resolveExpression(bool, c)))]));
}
public not(): Bool {
return new Bool(new Bool.Not(this), this[DataType]);
}
}
export namespace Bool {
export abstract class Operands extends ExpressionNode<BoolShape> {
public abstract readonly operator: string;
constructor(public readonly operands: ExpressionNode<BoolShape>[]) {
super(bool);
}
public [Synthesize](writer: Writer): void {
writer.writeToken('(');
for (const op of this.operands) {
op[Synthesize](writer);
writer.writeToken(` ${this.operator} `);
}
writer.pop();
writer.writeToken(')');
}
}
export class And extends Operands {
public readonly operator = 'AND';
public [SubNodeType]: 'and' = 'and';
}
export class Or extends Operands {
public readonly operator = 'OR';
public [SubNodeType]: 'or' = 'or';
}
export class Not extends ExpressionNode<BoolShape> {
public [SubNodeType]: 'not' = 'not';
constructor(public readonly operand: ExpressionNode<BoolShape>) {
super(bool);
}
public [Synthesize](writer: Writer): void {
writer.writeToken('NOT');
writer.writeToken('(');
this.operand[Synthesize](writer);
writer.writeToken(')');
}
}
}
export function or(...operands: ExpressionNode<BoolShape>[]): Bool {
return new Bool(new Bool.Or(operands));
}
export function and(...operands: ExpressionNode<BoolShape>[]): Bool {
return new Bool(new Bool.And(operands));
}
export function not(operand: ExpressionNode<BoolShape>): Bool {
return new Bool(new Bool.Not(operand));
}
export class Ord<T extends Shape> extends Object<T> {
public greaterThan(other: Expression<NumberShape>): Bool {
return new Bool(new Ord.Gt(this, resolveExpression(number, other)));
}
public greaterThanOrEqual(other: Expression<NumberShape>): Bool {
return new Bool(new Ord.Gte(this, resolveExpression(number, other)));
}
public lessThan(other: Expression<NumberShape>): Bool {
return new Bool(new Ord.Lt(this, resolveExpression(number, other)));
}
public lessThanOrEqual(other: Expression<NumberShape>): Bool {
return new Bool(new Ord.Lte(this, resolveExpression(number, other)));
}
public between(lowerBound: Expression<T>, upperBound: Expression<T>): Bool {
return new Bool(new Ord.Between(this, resolveExpression(this[DataType], lowerBound), resolveExpression(this[DataType], upperBound)));
}
}
export namespace Ord {
export class Gt<T extends Shape> extends Object.Comparison<T, NumberShape> {
protected readonly operator: '>' = '>';
public readonly [SubNodeType] = 'greaterThan';
}
export class Gte<T extends Shape> extends Object.Comparison<T, NumberShape> {
protected readonly operator: '>=' = '>=';
public readonly [SubNodeType] = 'greaterThanOrEqual';
}
export class Lt<T extends Shape> extends Object.Comparison<T, NumberShape> {
protected readonly operator: '<' = '<';
public readonly [SubNodeType] = 'lessThan';
}
export class Lte<T extends Shape> extends Object.Comparison<T, NumberShape> {
protected readonly operator: '<=' = '<=';
public readonly [SubNodeType] = 'lessThanOrEqual';
}
export class Between<T extends Shape> extends ExpressionNode<BoolShape> {
public readonly [SubNodeType] = 'between';
constructor(
public readonly lhs: ExpressionNode<T>,
public readonly lowerBound: ExpressionNode<T>,
public readonly upperBound: ExpressionNode<T>
) {
super(bool);
}
public [Synthesize](writer: Writer): void {
this.lhs[Synthesize](writer);
writer.writeToken(' BETWEEN ');
this.lowerBound[Synthesize](writer);
writer.writeToken(' AND ');
this.upperBound[Synthesize](writer);
}
}
}
export function isComputation(a: any): a is Computation<any> {
return isStatementNode(a) && a[SubNodeType] === 'computation';
}
/**
* Computations are not Expressions, although they do represent a value.
*
* This is because they are not usable within Query or Filter expressions.
*
* E.g. this is impossible:
* ```
* table.putIf(.., item => item.plus(1).equals(2))
* ```
*/
export abstract class Computation<T extends Shape> extends StatementNode {
public readonly [SubNodeType] = 'computation';
public abstract readonly operator: string;
constructor(public readonly lhs: ExpressionNode<T>, public readonly rhs: ExpressionNode<T>) {
super();
}
public [Synthesize](writer: Writer): void {
this.lhs[Synthesize](writer);
writer.writeToken(this.operator);
this.rhs[Synthesize](writer);
}
}
export class ComputationExpression<T extends Shape> extends ExpressionNode<T> {
public [SubNodeType] = 'computation-expression';
constructor(shape: T, public readonly computation: Computation<T>) {
super(shape);
}
public [Synthesize](writer: Writer): void {
this.computation[Synthesize](writer);
}
}
export enum ActionType {
SET = 'SET'
}
export class Action {
constructor(public readonly actionType: ActionType, public readonly statement: StatementNode) {}
}
/**
* Represents a number in a DynamoDB Filter, Query or Update expression.
*/
export class Number extends Ord<NumberShape> {
constructor(expression: ExpressionNode<NumberShape>, shape?: NumberShape) {
super(shape || number, expression);
}
public decrement(value?: Expression<NumberShape>) {
return this.set(this.minus(value === undefined ? 1 : value));
}
public increment(value?: Expression<NumberShape>) {
return this.set(this.plus(value === undefined ? 1 : value));
}
public minus(value: Expression<NumberShape>): Number.Minus {
return new Number.Minus(this, resolveExpression(this[DataType], value));
}
public plus(value: Expression<NumberShape>): Number.Plus {
return new Number.Plus(this, resolveExpression(this[DataType], value));
}
}
export namespace Number {
export class Plus extends Computation<NumberShape> {
public operator: '+' = '+';
}
export class Minus extends Computation<NumberShape> {
public operator: '-' = '-';
}
}
export class Binary extends Object<BinaryShape> {}
export class StringLike<T extends StringShape | EnumShape> extends Ord<T> {
public beginsWith(value: Expression<StringShape>): Bool {
return String.beginsWith(this, value);
}
public get length() {
return this.size;
}
}
export class String extends StringLike<StringShape> {
constructor(expression: ExpressionNode<StringShape>, shape?: StringShape) {
super(shape || string, expression);
}
}
export namespace String {
export class BeginsWith extends FunctionCall<BoolShape> {
public readonly [SubNodeType] = 'string-begins-with';
constructor(lhs: ExpressionNode<StringShape | EnumShape>, rhs: ExpressionNode<StringShape | EnumShape>) {
super('begins_with', bool, [lhs, rhs]);
}
}
export function beginsWith(lhs: Expression<StringShape | EnumShape>, rhs: Expression<StringShape | EnumShape>) {
return new Bool(new String.BeginsWith(resolveExpression(string, lhs), resolveExpression(string, rhs)));
}
}
export class Timestamp extends Object<TimestampShape> {
constructor(expression: ExpressionNode<TimestampShape>, shape?: TimestampShape) {
super(shape || timestamp, expression);
}
}
export class Enum<E extends EnumShape> extends StringLike<E> {}
export class List<T extends Shape> extends Object<ArrayShape<T>> {
constructor(type: ArrayShape<T>, expression: ExpressionNode<ArrayShape<T>>) {
super(type, expression);
}
[index: number]: Of<T>;
public get length() {
return this.size;
}
public get(index: Expression<NumberShape>): Of<T> {
return this[DataType].Items.visit(DSL.DslVisitor as any, new List.Item(this, resolveExpression(number, index)));
}
public push(item: Expression<T>): Action {
return new Action(ActionType.SET, new Object.Assign(this.get(1) as any, resolveExpression(this[DataType].Items, item)));
}
public concat(list: Expression<ArrayShape<T>>): Action {
return new Action(ActionType.SET, new Object.Assign(this, new List.Append(this, resolveExpression(this[DataType], list) as List<T>)));
}
}
export namespace List {
export class Item<T extends Shape> extends ExpressionNode<T> {
public readonly [SubNodeType] = 'list-item';
constructor(public readonly list: List<T>, public readonly index: ExpressionNode<NumberShape>) {
super(list[DataType].Items as T);
}
public [Synthesize](writer: Writer): void {
this.list[Synthesize](writer);
writer.writeToken('[');
if (isLiteral(this.index)) {
// indexing a list should not write the literal as an attribute value
writer.writeToken((this.index as any).value.N);
} else {
this.index[Synthesize](writer);
}
writer.writeToken(']');
}
}
export class Append<T extends Shape> extends FunctionCall<ArrayShape<T>> {
public [SubNodeType]: 'list-append' = 'list-append';
constructor(public readonly list: List<T>, public readonly values: List<T>) {
super('list_append', list[DataType], [list, values]);
}
}
}
export class Set<T extends Shape> extends Object<SetShape<T>> {
public contains(value: Expression<T>): Bool {
return new Bool(new Set.Contains(this, resolveExpression(this[DataType].Items, value)));
}
}
export namespace Set {
export class Contains<T extends Shape> extends FunctionCall<BoolShape> {
constructor(set: Set<T>, value: ExpressionNode<T>) {
super('contains', bool, [set, value]);
}
}
}
export class Map<T extends Shape> extends Object<MapShape<T>> {
public get(key: Expression<StringShape>): Of<T> {
return this[DataType].Items.visit(DSL.DslVisitor as any, typeof key === 'string' ? new Map.GetValue(this, new Id(key)) as any : new Map.GetValue(this, resolveExpression(string, key)));
}
public put(key: Expression<StringShape>, value: Expression<T>): Action {
return new Action(ActionType.SET, new Object.Assign(this.get(key) as any, resolveExpression(this[DataType].Items, value)));
}
}
export namespace Map {
export class GetValue<T extends Shape> extends ExpressionNode<T> {
public readonly [SubNodeType] = 'map-value';
constructor(public readonly map: Map<T>, public readonly key: ExpressionNode<StringShape>) {
super(map[DataType].Items as T);
}
public [Synthesize](writer: Writer): void {
this.map[Synthesize](writer);
writer.writeToken('.');
this.key[Synthesize](writer);
}
}
}
export class Struct<T extends TypeShape<any>> extends Object<T> {
public readonly fields: {
[fieldName in keyof T['Members']]: Of<T['Members'][fieldName]>;
};
constructor(type: T, expression: ExpressionNode<T>) {
super(type, expression);
this.fields = {} as any;
for (const [name, prop] of Objekt.entries(type.Members)) {
(this.fields as any)[name] = (prop as Shape).visit(DslVisitor, new Struct.Field(this, prop as Shape, name));
}
}
}
export namespace Struct {
export class Field<T extends Shape> extends ExpressionNode<T> {
public readonly [SubNodeType] = 'struct-field';
constructor(public readonly struct: Struct<any>, type: T, public readonly name: string) {
super(type);
}
public [Synthesize](writer: Writer): void {
this.struct[Synthesize](writer);
writer.writeToken('.');
writer.writeName(this.name);
}
}
}
export class Any<T extends AnyShape> extends Object<T> {
public as<S extends Shape>(shape: S): DSL.Of<S> {
return shape.visit(DslVisitor as any, this);
}
public equals(args: never): never {
throw new Error('equals is not supported on a dynamic type, you must first cast with `as(shape)`');
}
public set(args: never): never {
throw new Error('equals is not supported on a dynamic type, you must first cast with `as(shape)`');
}
}
export class Union<T extends UnionShape<Shape[]>> extends Object<T> {
public as<S extends T['Items'][Extract<keyof T['Items'], number>]>(shape: S): DSL.Of<S> {
return shape.visit(DslVisitor as any, this);
}
}
} | the_stack |
import { html } from 'lit';
export default {
title: 'Stories/Table',
parameters: {
options: { showPanel: true },
// a11y: { disable: true },
},
};
// const tableOptions = {
// default: '',
// compact: 'compact',
// vertical: 'vertical',
// };
// const alignmentOptions = {
// 'left (default)': 'left',
// center: 'center',
// right: 'right',
// };
// export function API() {
// const tableStyle = select('Table Style', tableOptions, '', propertiesGroup);
// const alignmentStyle = select('Alignment', alignmentOptions, '', propertiesGroup);
// const rowBorder = boolean('Row Border', true, propertiesGroup);
// const colBorder = boolean('Col Border', false, propertiesGroup);
// const outsideBorder = boolean('Outside Border', true, propertiesGroup);
// const zebraStyle = boolean('Zebra Row Highlights', false, propertiesGroup);
// return html`
// <div cds-layout="vertical gap:md">
// <table
// cds-table="${tableStyle} ${zebraStyle ? 'zebra' : ''} ${rowBorder ? 'border:row' : ''} ${outsideBorder
// ? 'border:outside'
// : ''} ${colBorder ? 'border:column' : ''}"
// cds-text=${alignmentStyle}
// >
// <caption>
// Nearest stars to Earth
// </caption>
// <thead>
// <tr>
// <th>Star</th>
// <th>Distance (Light Years)</th>
// <th>Solar Masses</th>
// </tr>
// </thead>
// <tbody>
// <tr>
// <td>Sun (Sol)</td>
// <td>0.0000158 ly</td>
// <td>1 M☉</td>
// </tr>
// <tr>
// <td>Proxima Centauri</td>
// <td>4.24 ly</td>
// <td>0.122 M☉</td>
// </tr>
// <tr>
// <td>Alpha Centauri B</td>
// <td>4.36 ly</td>
// <td>0.907 M☉</td>
// </tr>
// <tr>
// <td>Alpha Centauri A</td>
// <td>4.36 ly</td>
// <td>1.10 M☉</td>
// </tr>
// <tr>
// <td>Barnard's Star</td>
// <td>5.95 ly</td>
// <td>1.44 M☉</td>
// </tr>
// <tr>
// <td>Luhman 16B</td>
// <td>6.50 ly</td>
// <td>0.027 M☉</td>
// </tr>
// <tr>
// <td>Luhman 16A</td>
// <td>6.50 ly</td>
// <td>0.032 M☉</td>
// </tr>
// </tbody>
// </table>
// </div>
// `;
// }
/** @website */
export function basic() {
return html`
<table cds-table="border:row border:outside">
<caption>
List of nearby spiral galaxies
</caption>
<thead>
<tr>
<th>Name</th>
<th>Constellation</th>
<th>Number of stars</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>Milky Way</td>
<td>none</td>
<td>200 billion</td>
<td>Barred Spiral</td>
</tr>
<tr>
<td>Andromeda</td>
<td>Andromeda</td>
<td>1 trillion</td>
<td>Barred Spiral</td>
</tr>
<tr>
<td>Pinwheel</td>
<td>Ursa Major</td>
<td>1 trillion</td>
<td>Spiral</td>
</tr>
<tr>
<td>Messier 63</td>
<td>Canes Venatici</td>
<td>400 billion</td>
<td>Spiral</td>
</tr>
<tr>
<td>Triangulum</td>
<td>Triangulum</td>
<td>40 billion</td>
<td>Spiral</td>
</tr>
<tr>
<td>Whirlpool</td>
<td>Canes Venatici</td>
<td>40 billion</td>
<td>Spiral</td>
</tr>
</tbody>
</table>
`;
}
/** @website */
export function centerTable() {
return html`
<table cds-table="border:row border:outside" cds-text="center">
<caption>
List of nearby spiral galaxies
</caption>
<thead>
<tr>
<th>Name</th>
<th>Constellation</th>
<th>Number of stars</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>Milky Way</td>
<td>none</td>
<td>200 billion</td>
<td>Barred Spiral</td>
</tr>
<tr>
<td>Andromeda</td>
<td>Andromeda</td>
<td>1 trillion</td>
<td>Barred Spiral</td>
</tr>
<tr>
<td>Pinwheel</td>
<td>Ursa Major</td>
<td>1 trillion</td>
<td>Spiral</td>
</tr>
<tr>
<td>Messier 63</td>
<td>Canes Venatici</td>
<td>400 billion</td>
<td>Spiral</td>
</tr>
<tr>
<td>Triangulum</td>
<td>Triangulum</td>
<td>40 billion</td>
<td>Spiral</td>
</tr>
<tr>
<td>Whirlpool</td>
<td>Canes Venatici</td>
<td>40 billion</td>
<td>Spiral</td>
</tr>
</tbody>
</table>
`;
}
/** @website */
export function rightTable() {
return html`
<table cds-table="border:row border:outside" cds-text="right">
<caption>
Popular items in Messier catalog of stellar objects
</caption>
<thead>
<tr>
<th>Messier Number</th>
<th>Name</th>
<th>Type</th>
<th>Constellation</th>
<th>Apparent magnitude</th>
</tr>
</thead>
<tbody>
<tr>
<td>M1</td>
<td>Crab Nebula</td>
<td>Supernova remnant</td>
<td>Taurus</td>
<td cds-text="monospace">8.4</td>
</tr>
<tr>
<td>M27</td>
<td>Dumbbell Nebula</td>
<td>Planetary nebula</td>
<td>vulpecula</td>
<td cds-text="monospace">7.5</td>
</tr>
<tr>
<td>M42</td>
<td>Orion Nebula</td>
<td>HII region nebula</td>
<td>Orion</td>
<td cds-text="monospace">4.0</td>
</tr>
<tr>
<td>M81</td>
<td>Bode's Galaxy</td>
<td>Spiral galaxy</td>
<td>Ursa Major</td>
<td cds-text="monospace">6.9</td>
</tr>
<tr>
<td>M104</td>
<td>Sombrero Galaxy</td>
<td>Spiral galaxy</td>
<td>Virgo</td>
<td cds-text="monospace">9.0</td>
</tr>
</tbody>
</table>
`;
}
/** @website */
export function modifierTable() {
return html`
<table cds-table="border:row border:outside">
<caption>
Solar system planets (and demonstrations of how to modify the alignment and typography)
</caption>
<thead cds-text="title">
<tr>
<th>Name</th>
<th>Diameter (Earth masses)</th>
<th>Orbital period (years)</th>
<th>Known moons</th>
<th>Rings</th>
</tr>
</thead>
<tbody>
<tr>
<td cds-text="left">Mercury</td>
<td cds-text="right monospace">0.06 M</td>
<td>0.24 yr</td>
<td>0</td>
<td>No</td>
</tr>
<tr>
<td cds-text="left">Venus</td>
<td cds-text="right monospace">0.81 M</td>
<td>0.62 yr</td>
<td>0</td>
<td>No</td>
</tr>
<tr cds-text="section">
<td cds-text="left">Earth</td>
<td cds-text="right monospace">1.00 M</td>
<td>1.0 yr</td>
<td>1</td>
<td>No</td>
</tr>
<tr>
<td cds-text="left">Mars</td>
<td cds-text="right monospace">0.11 M</td>
<td>1.88 yr</td>
<td>2</td>
<td>No</td>
</tr>
<tr>
<td cds-text="left">Jupiter</td>
<td cds-text="right monospace">317.8 M</td>
<td>11.86 yr</td>
<td>79</td>
<td>Yes</td>
</tr>
<tr>
<td cds-text="left">Saturn</td>
<td cds-text="right monospace">95.16 M</td>
<td>29.45 yr</td>
<td>82</td>
<td>Yes</td>
</tr>
<tr>
<td cds-text="left">Uranus</td>
<td cds-text="right monospace">14.54 M</td>
<td>84.02 yr</td>
<td>27</td>
<td>Yes</td>
</tr>
<tr>
<td cds-text="left">Neptune</td>
<td cds-text="right monospace">15.15 M</td>
<td>164.79 yr</td>
<td>14</td>
<td>Yes</td>
</tr>
</tbody>
</table>
`;
}
/** @website */
export function noborderTable() {
return html`
<table cds-table>
<caption>
List of numbered comets
</caption>
<thead>
<tr>
<th>Comet designation</th>
<th>Orbital Period (years)</th>
<th>Absolute magnitude</th>
</tr>
</thead>
<tbody>
<tr>
<td>1P Halley</td>
<td>75.32</td>
<td>5.5</td>
</tr>
<tr>
<td>2P Encke</td>
<td>3.30</td>
<td>15.5</td>
</tr>
<tr>
<td>3D Biela</td>
<td>6.65</td>
<td>7.1</td>
</tr>
<tr>
<td>4P Faye</td>
<td>7.52</td>
<td>10.9</td>
</tr>
<tr>
<td>5D Borsen</td>
<td>5.46</td>
<td>8.3</td>
</tr>
</tbody>
</table>
`;
}
/** @website */
export function compactTable() {
return html`
<table cds-table="border:row border:outside compact">
<caption>
Largest moons in the solar system
</caption>
<thead>
<tr>
<th>Moon Name</th>
<th>Planet</th>
<th>Year of discovery</th>
<th>Diameter (kilometers)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ganymede</td>
<td>Jupiter</td>
<td>1610</td>
<td>5,268 km</td>
</tr>
<tr>
<td>Tital</td>
<td>Saturn</td>
<td>1655</td>
<td>5,151 km</td>
</tr>
<tr>
<td>Callisto</td>
<td>Jupiter</td>
<td>1610</td>
<td>4,816 km</td>
</tr>
<tr>
<td>Io</td>
<td>Jupiter</td>
<td>1610</td>
<td>3,636 km</td>
</tr>
<tr>
<td>The Moon</td>
<td>Earth</td>
<td>Prehistory</td>
<td>3,474 km</td>
</tr>
<tr>
<td>Europa</td>
<td>Jupiter</td>
<td>1610</td>
<td>3,121 km</td>
</tr>
<tr>
<td>Triton</td>
<td>Neptune</td>
<td>1846</td>
<td>2,706 km</td>
</tr>
<tr>
<td>Titania</td>
<td>Uranus</td>
<td>1787</td>
<td>1,577 km</td>
</tr>
<tr>
<td>Rhea</td>
<td>Saturn</td>
<td>1672</td>
<td>1,529 km</td>
</tr>
<tr>
<td>Oberon</td>
<td>Uranus</td>
<td>1787</td>
<td>1,522 km</td>
</tr>
</tbody>
</table>
`;
}
/** @website */
export function verticalTable() {
return html`
<table cds-table="border:row border:outside vertical">
<caption>
Dwarf planets in the solar system
</caption>
<thead>
<tr>
<th>Name</th>
<th>Region</th>
<th>Orbital period (years)</th>
<th>Diameter (kilometers)</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Ceres</th>
<td>Astroid belt</td>
<td>4.6 yr</td>
<td>939 km</td>
</tr>
<tr>
<th scope="row">Orcus</th>
<td>Kuiper belt</td>
<td>247.3 yr</td>
<td>910 km</td>
</tr>
<tr>
<th scope="row">Pluto</th>
<td>Kuiper belt</td>
<td>247.9 yr</td>
<td>2377 km</td>
</tr>
<tr>
<th scope="row">Haumea</th>
<td>Kuiper belt</td>
<td>284.1 yr</td>
<td>1560 km</td>
</tr>
<tr>
<th scope="row">Quaoar</th>
<td>Kuiper belt</td>
<td>288.8 yr</td>
<td>1110 km</td>
</tr>
</tbody>
</table>
`;
}
/** @website */
export function borderTable() {
return html`
<table cds-table="border:all">
<caption>
Active space telescopes
</caption>
<thead>
<tr>
<th>Name</th>
<th>Space Agency</th>
<th>Launch Date</th>
<th>Telescope type</th>
</tr>
</thead>
<tbody>
<tr>
<td>Fermi Gamma-ray Space Telescope</td>
<td>NASA</td>
<td>June 11, 2008</td>
<td>Gamma</td>
</tr>
<tr>
<td>Swift Gamma Ray Burst Explorer</td>
<td>NASA</td>
<td>November 20, 2004</td>
<td>Gamma, X-ray, Ultraviolet</td>
</tr>
<tr>
<td>Astrosat</td>
<td>ISRO</td>
<td>September 28, 2015</td>
<td>X-ray</td>
</tr>
<tr>
<td>Nisaki</td>
<td>JAXA</td>
<td>September 14, 2013</td>
<td>X-ray, Ultraviolet</td>
</tr>
<tr>
<td>Hubble Space Telescope</td>
<td>NASA</td>
<td>April 24, 1990</td>
<td>Visible light</td>
</tr>
<tr>
<td>IBEX</td>
<td>NASA</td>
<td>October 19, 2008</td>
<td>Particle detection</td>
</tr>
</tbody>
</table>
`;
}
/** @website */
export function quirksMode() {
return html`
<div cds-layout="vertical gap:md">
<p cds-text="message" cds-layout="m-border:md">
Sample tables of different construction to verify display, testing purposes only
</p>
<table cds-table="border:all">
<caption>
Table without thead, tbody, tfoot
</caption>
<tr>
<th>Wizard</th>
<th>Allegiance</th>
<th>Triwizard Champion?</th>
<th>Can Cast Fireball</th>
</tr>
<tr>
<td>Harry</td>
<td>Gryffindor</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td>Gandalf</td>
<td>Hobbits</td>
<td>Maybe?</td>
<td>I don't think so...</td>
</tr>
<tr>
<td>Obi-Wan Kenobi</td>
<td>Republic/Rebellion</td>
<td>No</td>
<td>No</td>
</tr>
<tr>
<td>Merlin</td>
<td>King Arthur</td>
<td>Probably invented the tournament</td>
<td>Solid maybe</td>
</tr>
</table>
<table cds-table="border:all">
<caption>
Table with two theads
</caption>
<thead>
<tr>
<th>Wizard</th>
<th>Allegiance</th>
<th>Triwizard Champion?</th>
<th>Can Cast Fireball</th>
</tr>
</thead>
<tbody>
<tr>
<td>Harry</td>
<td>Gryffindor</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td>Gandalf</td>
<td>Hobbits</td>
<td>Maybe?</td>
<td>I don't think so...</td>
</tr>
</tbody>
<thead>
<tr>
<th>Wizard</th>
<th>Allegiance</th>
<th>Triwizard Champion?</th>
<th>Can Cast Fireball</th>
</tr>
</thead>
<tbody>
<tr>
<td>Obi-Wan Kenobi</td>
<td>Republic/Rebellion</td>
<td>No</td>
<td>No</td>
</tr>
<tr>
<td>Merlin</td>
<td>King Arthur</td>
<td>Probably invented the tournament</td>
<td>Solid maybe</td>
</tr>
</tbody>
</table>
<table cds-table="border:all">
<caption>
Table with only thead
</caption>
<thead>
<tr>
<th>Wizard</th>
<th>Allegiance</th>
<th>Triwizard Champion?</th>
<th>Can Cast Fireball</th>
</tr>
</thead>
<tr>
<td>Harry</td>
<td>Gryffindor</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td>Gandalf</td>
<td>Hobbits</td>
<td>Maybe?</td>
<td>I don't think so...</td>
</tr>
<tr>
<td>Obi-Wan Kenobi</td>
<td>Republic/Rebellion</td>
<td>No</td>
<td>No</td>
</tr>
<tr>
<td>Merlin</td>
<td>King Arthur</td>
<td>Probably invented the tournament</td>
<td>Solid maybe</td>
</tr>
</table>
<table cds-table="border:all">
<caption>
Table with only tbody
</caption>
<tr>
<th>Wizard</th>
<th>Allegiance</th>
<th>Triwizard Champion?</th>
<th>Can Cast Fireball</th>
</tr>
<tbody>
<tr>
<td>Harry</td>
<td>Gryffindor</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td>Gandalf</td>
<td>Hobbits</td>
<td>Maybe?</td>
<td>I don't think so...</td>
</tr>
<tr>
<td>Obi-Wan Kenobi</td>
<td>Republic/Rebellion</td>
<td>No</td>
<td>No</td>
</tr>
<tr>
<td>Merlin</td>
<td>King Arthur</td>
<td>Probably invented the tournament</td>
<td>Solid maybe</td>
</tr>
</tbody>
</table>
<p cds-text="center">No caption</p>
<table cds-table="border:all">
<tr>
<th>Wizard</th>
<th>Allegiance</th>
<th>Triwizard Champion?</th>
<th>Can Cast Fireball</th>
</tr>
<tr>
<td>Harry</td>
<td>Gryffindor</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td>Gandalf</td>
<td>Hobbits</td>
<td>Maybe?</td>
<td>I don't think so...</td>
</tr>
<tr>
<td>Obi-Wan Kenobi</td>
<td>Republic/Rebellion</td>
<td>No</td>
<td>No</td>
</tr>
<tr>
<td>Merlin</td>
<td>King Arthur</td>
<td>Probably invented the tournament</td>
<td>Solid maybe</td>
</tr>
</table>
<p cds-text="center">No caption or header row</p>
<table cds-table="border:all">
<tr>
<td>Harry</td>
<td>Gryffindor</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td>Gandalf</td>
<td>Hobbits</td>
<td>Maybe?</td>
<td>I don't think so...</td>
</tr>
<tr>
<td>Obi-Wan Kenobi</td>
<td>Republic/Rebellion</td>
<td>No</td>
<td>No</td>
</tr>
<tr>
<td>Merlin</td>
<td>King Arthur</td>
<td>Probably invented the tournament</td>
<td>Solid maybe</td>
</tr>
</table>
<table cds-table="border:all">
<caption>
Table with only tfoot
</caption>
<tr>
<th>Wizard</th>
<th>Allegiance</th>
<th>Triwizard Champion?</th>
<th>Can Cast Fireball</th>
</tr>
<tr>
<td>Harry</td>
<td>Gryffindor</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td>Gandalf</td>
<td>Hobbits</td>
<td>Maybe?</td>
<td>I don't think so...</td>
</tr>
<tr>
<td>Obi-Wan Kenobi</td>
<td>Republic/Rebellion</td>
<td>No</td>
<td>No</td>
</tr>
<tr>
<td>Merlin</td>
<td>King Arthur</td>
<td>Probably invented the tournament</td>
<td>Solid maybe</td>
</tr>
<tfoot>
<td>Wizard</td>
<td>Allegiance</td>
<td>Triwizard Champion?</td>
<td>Can Cast Fireball</td>
</tfoot>
</table>
<table cds-table="border:all">
<caption>
Table with col and row spans, have to provide modifier classes to set correct border and radius
</caption>
<tr>
<th colspan="2">Wizard / Allegiance</th>
<th colspan="2">Triwizard Champion? / Can Cast Fireball</th>
</tr>
<tr>
<td>Harry</td>
<td>Gryffindor</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td>Gandalf</td>
<td>Hobbits</td>
<td>Maybe?</td>
<td>I don't think so...</td>
</tr>
<tr>
<td>Obi-Wan Kenobi</td>
<td>Republic/Rebellion</td>
<td>No</td>
<td
rowspan="2"
style="border-bottom-right-radius: var(--border-radius); border-bottom: var(--border); border-right: var(--border);"
>
No<br />No<br />No<br />No
</td>
</tr>
<tr>
<td>Merlin</td>
<td>King Arthur</td>
<td style="border-radius: 0; border-right: var(--cell-border)">Probably invented the tournament</td>
</tr>
</table>
</div>
`;
} | the_stack |
export class EDTAA3 {
protected _useDualChannel: boolean = false;
// 目前Distance Texture是8bit的,所以maxDist最大是8(4bit表示16,内外平分)
public RenderSDF(texture: cc.RenderTexture, maxDist: number = 8): { texture: cc.RenderTexture, alpha: Uint8ClampedArray } {
this._useDualChannel = (maxDist > 8);
let imgData = texture.readPixels();
let width = texture.width;
let height = texture.height;
let alpha = this.GenerateSDF(imgData, width, height, maxDist);
// let alphaChannel = this.RenderSDFToData(imgData, width, height, radius, cutoff);
let resultTexture = new cc.RenderTexture;
if (this._useDualChannel) {
// 手动插值需要用point采样
resultTexture.setFilters(cc.Texture2D.Filter.NEAREST, cc.Texture2D.Filter.NEAREST);
}
resultTexture.initWithData(alpha, cc.Texture2D.PixelFormat.RGBA8888, width, height);
resultTexture.packable = false;
// resultTexture.initWithData(imgData, cc.Texture2D.PixelFormat.I8, width, height);
return {
texture: resultTexture,
alpha: alpha
};
};
/**
* 生成img图片对应的SDF
* 假设img是单通道图片,并且满足edtaa3对原图的要求:基于理想边缘box-filter采样,AA宽度不大于1 texel(详见论文)
* @param imgorigin
* @param height
* @param width
*/
// NOTE: 这里mrows和ncols的含义可能正好相反,mrows对应w,ncols对应h
public GenerateSDF(imgorigin: Uint8Array, mrows: number, ncols: number, maxDist: number = 8): Uint8ClampedArray {
// imgorigin是RGBA类型
// alpha通道[0,256)转换成float64类型[0,1)
let coef = 1./255;
let img = new Float64Array(mrows * ncols);
for (let i = 0, n = mrows * ncols; i < n; ++i) {
img[i] = imgorigin[i * 4 + 3] * coef;
}
let outside = this.edtaa_main(img, mrows, ncols);
for (let i = 0, n = mrows * ncols; i < n; ++i) {
img[i] = 1.0 - img[i];
}
let inside = this.edtaa_main(img, mrows, ncols);
// todo: 这里只用1通道可以吗?
// distmap = outside - inside;
let sdf = new Uint8ClampedArray(mrows * ncols * 4);
let dist: number;
let base: number;
if (this._useDualChannel) {
// use dual channel
for (let i = 0, n = mrows * ncols; i < n; ++i) {
// inside > 0, outside < 0
dist = inside[i] - outside[i];
// clamp dist value to [0, 65535]
// store hi 8 bits in A channel
// store lo 8 bits in R channel
dist = Math.round(32768 + dist * 256);
if (dist < 0) dist = 0;
if (dist > 65535) dist = 65535;
base = i * 4;
sdf[base+3] = Math.floor(dist / 256); // 特地把高位分量放到alpha通道,避免正常渲染啥都看不到
sdf[base] = dist % 256;
}
} else {
for (let i = 0, n = mrows * ncols; i < n; ++i) {
dist = inside[i] - outside[i];
base = i * 4;
sdf[base+3] = 128 + dist * 16; // 优先填充alpha通道
// sdf[base] = sdf[base+1] = sdf[base+2] = sdf[base+3] = 128 + dist * 16; // 8bit拆分成2个4bit,分别表示整数部分和小数部分。此时1个像素距离色值差16
}
}
return sdf;
}
// flow of mexFunction in edtaa3.c
protected edtaa_main(img: Float64Array, mrows: number, ncols: number): Float64Array {
// plhs[0] = mxCreateDoubleMatrix(mrows, ncols, mxREAL);
// Dout = mxGetPr(plhs[0]);
let Dout = new Float64Array(mrows * ncols);
// /* Call the C subroutine. */
// xdist = (short*)mxMalloc(mrows*ncols*sizeof(short)); // local data
// ydist = (short*)mxMalloc(mrows*ncols*sizeof(short));
// gx = (double*)mxCalloc(mrows*ncols, sizeof(double));
// gy = (double*)mxCalloc(mrows*ncols, sizeof(double));
let xdist = new Int16Array(mrows * ncols);
let ydist = new Int16Array(mrows * ncols);
let gx = new Float64Array(mrows * ncols);
let gy = new Float64Array(mrows * ncols);
// computegradient(img, mrows, ncols, gx, gy);
this.computegradient(img, mrows, ncols, gx, gy);
// edtaa3(img, gx, gy, mrows, ncols, xdist, ydist, Dout);
this.edtaa3(img, gx, gy, mrows, ncols, xdist, ydist, Dout);
// // Pixels with grayscale>0.5 will have a negative distance.
// // This is correct, but we don't want values <0 returned here.
for (let i=0, n=mrows*ncols; i<n; ++i) {
if(Dout[i] < 0) Dout[i]=0.0;
}
// 返回值有2个,double类型Dout和int32类型Iout
// Iout保存的是下标索引值,暂时用不上
// if(nlhs > 1) {
// /* Create a new int array, set output data pointer to it. */
// plhs[1] = mxCreateNumericMatrix(mrows, ncols, mxINT32_CLASS, mxREAL);
// Iout = mxGetData(plhs[1]);
// // Compute output data for optional 'index to closest object pixel'
// for(i=0; i<mrows*ncols; i++) {
// Iout[i] = i+1 - xdist[i] - ydist[i]*mrows;
// }
// }
// mxFree(xdist); // Local data allocated with mxMalloc()
// mxFree(ydist); // (Would be automatically deallocated, but be tidy)
// mxFree(gx);
// mxFree(gy);
return Dout;
}
/*
* Compute the local gradient at edge pixels using convolution filters.
* The gradient is computed only at edge pixels. At other places in the
* image, it is never used, and it's mostly zero anyway.
*/
// void computegradient(double *img, int w, int h, double *gx, double *gy)
protected computegradient(img: Float64Array, w: number, h: number, gx: Float64Array, gy: Float64Array) {
let i: number, j: number, k: number, p: number, q: number;
let glength: number;
let SQRT2: number = 1.4142136;
for(i = 1; i < h-1; i++) { // Avoid edges where the kernels would spill over
for(j = 1; j < w-1; j++) {
k = i*w + j;
if((img[k]>0.0) && (img[k]<1.0)) { // Compute gradient for edge pixels only
gx[k] = -img[k-w-1] - SQRT2*img[k-1] - img[k+w-1] + img[k-w+1] + SQRT2*img[k+1] + img[k+w+1];
gy[k] = -img[k-w-1] - SQRT2*img[k-w] - img[k-w+1] + img[k+w-1] + SQRT2*img[k+w] + img[k+w+1];
glength = gx[k]*gx[k] + gy[k]*gy[k];
if(glength > 0.0) { // Avoid division by zero
glength = Math.sqrt(glength);
gx[k]=gx[k]/glength;
gy[k]=gy[k]/glength;
}
}
}
}
}
protected edgedf(gx: number, gy: number, a: number)
{
let df: number, glength: number, temp: number, a1: number; // double
if ((gx == 0) || (gy == 0)) { // Either A) gu or gv are zero, or B) both
df = 0.5-a; // Linear approximation is A) correct or B) a fair guess
} else {
glength = Math.sqrt(gx*gx + gy*gy);
if(glength>0) {
gx = gx/glength;
gy = gy/glength;
}
/* Everything is symmetric wrt sign and transposition,
* so move to first octant (gx>=0, gy>=0, gx>=gy) to
* avoid handling all possible edge directions.
*/
gx = Math.abs(gx);
gy = Math.abs(gy);
if(gx<gy) {
temp = gx;
gx = gy;
gy = temp;
}
a1 = 0.5*gy/gx;
if (a < a1) { // 0 <= a < a1
df = 0.5*(gx + gy) - Math.sqrt(2.0*gx*gy*a);
} else if (a < (1.0-a1)) { // a1 <= a <= 1-a1
df = (0.5-a)*gx;
} else { // 1-a1 < a <= 1
df = -0.5*(gx + gy) + Math.sqrt(2.0*gx*gy*(1.0-a));
}
}
return df;
}
protected distaa3(img: Float64Array, gximg: Float64Array, gyimg: Float64Array,
w: number, c: number, xc: number, yc: number, xi: number, yi: number)
{
let di: number, df: number, dx: number, dy: number, gx: number, gy: number, a: number; // double
let closest: number; // int
closest = c-xc-yc*w; // Index to the edge pixel pointed to from c
a = img[closest]; // Grayscale value at the edge pixel
gx = gximg[closest]; // X gradient component at the edge pixel
gy = gyimg[closest]; // Y gradient component at the edge pixel
if(a > 1.0) a = 1.0;
if(a < 0.0) a = 0.0; // Clip grayscale values outside the range [0,1]
if(a == 0.0) return 1000000.0; // Not an object pixel, return "very far" ("don't know yet")
dx = xi;
dy = yi;
di = Math.sqrt(dx*dx + dy*dy); // Length of integer vector, like a traditional EDT
if(di==0) { // Use local gradient only at edges
// Estimate based on local gradient only
df = this.edgedf(gx, gy, a);
} else {
// Estimate gradient based on direction to edge (accurate for large di)
df = this.edgedf(dx, dy, a);
}
return di + df; // Same metric as edtaa2, except at edges (where di=0)
}
protected edtaa3(img: Float64Array, gx: Float64Array, gy: Float64Array,
w: number, h: number, distx: Int16Array, disty: Int16Array, dist: Float64Array)
{
let x: number, y: number, i: number, c: number; // int
let offset_u: number, offset_ur: number, offset_r: number, offset_rd: number,
offset_d: number, offset_dl: number, offset_l: number, offset_lu: number; // int
let olddist: number, newdist: number; // double
let cdistx: number, cdisty: number, newdistx: number, newdisty: number; // int
let changed: number; // int
let epsilon = 1e-3;
/* Initialize index offsets for the current image width */
offset_u = -w;
offset_ur = -w+1;
offset_r = 1;
offset_rd = w+1;
offset_d = w;
offset_dl = w-1;
offset_l = -1;
offset_lu = -w-1;
/* Initialize the distance images */
for(i=0; i<w*h; i++) {
distx[i] = 0; // At first, all pixels point to
disty[i] = 0; // themselves as the closest known.
if(img[i] <= 0.0) {
dist[i]= 1000000.0; // Big value, means "not set yet"
} else if (img[i]<1.0) {
dist[i] = this.edgedf(gx[i], gy[i], img[i]); // Gradient-assisted estimate
} else {
dist[i]= 0.0; // Inside the object
}
}
/* Perform the transformation */
do {
changed = 0;
/* Scan rows, except first row */
for(y=1; y<h; y++) {
/* move index to leftmost pixel of current row */
i = y*w;
/* scan right, propagate distances from above & left */
/* Leftmost pixel is special, has no left neighbors */
olddist = dist[i];
if(olddist > 0) // If non-zero distance or not set yet
{
c = i + offset_u; // Index of candidate for testing
cdistx = distx[c];
cdisty = disty[c];
newdistx = cdistx;
newdisty = cdisty+1;
newdist = this.distaa3(img, gx, gy, w, c, cdistx, cdisty, newdistx, newdisty);
// newdist = this.distaa3(img, gx, gy, w, c, cdistx, cdisty, newdistx, newdisty);
if(newdist < olddist-epsilon)
{
distx[i]=newdistx;
disty[i]=newdisty;
dist[i]=newdist;
olddist=newdist;
changed = 1;
}
c = i+offset_ur;
cdistx = distx[c];
cdisty = disty[c];
newdistx = cdistx-1;
newdisty = cdisty+1;
newdist = this.distaa3(img, gx, gy, w, c, cdistx, cdisty, newdistx, newdisty);
if(newdist < olddist-epsilon)
{
distx[i]=newdistx;
disty[i]=newdisty;
dist[i]=newdist;
changed = 1;
}
}
i++;
/* Middle pixels have all neighbors */
for(x=1; x<w-1; x++, i++)
{
olddist = dist[i];
if(olddist <= 0) continue; // No need to update further
c = i+offset_l;
cdistx = distx[c];
cdisty = disty[c];
newdistx = cdistx+1;
newdisty = cdisty;
newdist = this.distaa3(img, gx, gy, w, c, cdistx, cdisty, newdistx, newdisty);
if(newdist < olddist-epsilon)
{
distx[i]=newdistx;
disty[i]=newdisty;
dist[i]=newdist;
olddist=newdist;
changed = 1;
}
c = i+offset_lu;
cdistx = distx[c];
cdisty = disty[c];
newdistx = cdistx+1;
newdisty = cdisty+1;
newdist = this.distaa3(img, gx, gy, w, c, cdistx, cdisty, newdistx, newdisty);
if(newdist < olddist-epsilon)
{
distx[i]=newdistx;
disty[i]=newdisty;
dist[i]=newdist;
olddist=newdist;
changed = 1;
}
c = i+offset_u;
cdistx = distx[c];
cdisty = disty[c];
newdistx = cdistx;
newdisty = cdisty+1;
newdist = this.distaa3(img, gx, gy, w, c, cdistx, cdisty, newdistx, newdisty);
if(newdist < olddist-epsilon)
{
distx[i]=newdistx;
disty[i]=newdisty;
dist[i]=newdist;
olddist=newdist;
changed = 1;
}
c = i+offset_ur;
cdistx = distx[c];
cdisty = disty[c];
newdistx = cdistx-1;
newdisty = cdisty+1;
newdist = this.distaa3(img, gx, gy, w, c, cdistx, cdisty, newdistx, newdisty);
if(newdist < olddist-epsilon)
{
distx[i]=newdistx;
disty[i]=newdisty;
dist[i]=newdist;
changed = 1;
}
}
/* Rightmost pixel of row is special, has no right neighbors */
olddist = dist[i];
if(olddist > 0) // If not already zero distance
{
c = i+offset_l;
cdistx = distx[c];
cdisty = disty[c];
newdistx = cdistx+1;
newdisty = cdisty;
newdist = this.distaa3(img, gx, gy, w, c, cdistx, cdisty, newdistx, newdisty);
if(newdist < olddist-epsilon)
{
distx[i]=newdistx;
disty[i]=newdisty;
dist[i]=newdist;
olddist=newdist;
changed = 1;
}
c = i+offset_lu;
cdistx = distx[c];
cdisty = disty[c];
newdistx = cdistx+1;
newdisty = cdisty+1;
newdist = this.distaa3(img, gx, gy, w, c, cdistx, cdisty, newdistx, newdisty);
if(newdist < olddist-epsilon)
{
distx[i]=newdistx;
disty[i]=newdisty;
dist[i]=newdist;
olddist=newdist;
changed = 1;
}
c = i+offset_u;
cdistx = distx[c];
cdisty = disty[c];
newdistx = cdistx;
newdisty = cdisty+1;
newdist = this.distaa3(img, gx, gy, w, c, cdistx, cdisty, newdistx, newdisty);
if(newdist < olddist-epsilon)
{
distx[i]=newdistx;
disty[i]=newdisty;
dist[i]=newdist;
changed = 1;
}
}
/* Move index to second rightmost pixel of current row. */
/* Rightmost pixel is skipped, it has no right neighbor. */
i = y*w + w-2;
/* scan left, propagate distance from right */
for(x=w-2; x>=0; x--, i--)
{
olddist = dist[i];
if(olddist <= 0) continue; // Already zero distance
c = i+offset_r;
cdistx = distx[c];
cdisty = disty[c];
newdistx = cdistx-1;
newdisty = cdisty;
newdist = this.distaa3(img, gx, gy, w, c, cdistx, cdisty, newdistx, newdisty);
if(newdist < olddist-epsilon)
{
distx[i]=newdistx;
disty[i]=newdisty;
dist[i]=newdist;
changed = 1;
}
}
}
/* Scan rows in reverse order, except last row */
for(y=h-2; y>=0; y--)
{
/* move index to rightmost pixel of current row */
i = y*w + w-1;
/* Scan left, propagate distances from below & right */
/* Rightmost pixel is special, has no right neighbors */
olddist = dist[i];
if(olddist > 0) // If not already zero distance
{
c = i+offset_d;
cdistx = distx[c];
cdisty = disty[c];
newdistx = cdistx;
newdisty = cdisty-1;
newdist = this.distaa3(img, gx, gy, w, c, cdistx, cdisty, newdistx, newdisty);
if(newdist < olddist-epsilon)
{
distx[i]=newdistx;
disty[i]=newdisty;
dist[i]=newdist;
olddist=newdist;
changed = 1;
}
c = i+offset_dl;
cdistx = distx[c];
cdisty = disty[c];
newdistx = cdistx+1;
newdisty = cdisty-1;
newdist = this.distaa3(img, gx, gy, w, c, cdistx, cdisty, newdistx, newdisty);
if(newdist < olddist-epsilon)
{
distx[i]=newdistx;
disty[i]=newdisty;
dist[i]=newdist;
changed = 1;
}
}
i--;
/* Middle pixels have all neighbors */
for(x=w-2; x>0; x--, i--)
{
olddist = dist[i];
if(olddist <= 0) continue; // Already zero distance
c = i+offset_r;
cdistx = distx[c];
cdisty = disty[c];
newdistx = cdistx-1;
newdisty = cdisty;
newdist = this.distaa3(img, gx, gy, w, c, cdistx, cdisty, newdistx, newdisty);
if(newdist < olddist-epsilon)
{
distx[i]=newdistx;
disty[i]=newdisty;
dist[i]=newdist;
olddist=newdist;
changed = 1;
}
c = i+offset_rd;
cdistx = distx[c];
cdisty = disty[c];
newdistx = cdistx-1;
newdisty = cdisty-1;
newdist = this.distaa3(img, gx, gy, w, c, cdistx, cdisty, newdistx, newdisty);
if(newdist < olddist-epsilon)
{
distx[i]=newdistx;
disty[i]=newdisty;
dist[i]=newdist;
olddist=newdist;
changed = 1;
}
c = i+offset_d;
cdistx = distx[c];
cdisty = disty[c];
newdistx = cdistx;
newdisty = cdisty-1;
newdist = this.distaa3(img, gx, gy, w, c, cdistx, cdisty, newdistx, newdisty);
if(newdist < olddist-epsilon)
{
distx[i]=newdistx;
disty[i]=newdisty;
dist[i]=newdist;
olddist=newdist;
changed = 1;
}
c = i+offset_dl;
cdistx = distx[c];
cdisty = disty[c];
newdistx = cdistx+1;
newdisty = cdisty-1;
newdist = this.distaa3(img, gx, gy, w, c, cdistx, cdisty, newdistx, newdisty);
if(newdist < olddist-epsilon)
{
distx[i]=newdistx;
disty[i]=newdisty;
dist[i]=newdist;
changed = 1;
}
}
/* Leftmost pixel is special, has no left neighbors */
olddist = dist[i];
if(olddist > 0) // If not already zero distance
{
c = i+offset_r;
cdistx = distx[c];
cdisty = disty[c];
newdistx = cdistx-1;
newdisty = cdisty;
newdist = this.distaa3(img, gx, gy, w, c, cdistx, cdisty, newdistx, newdisty);
if(newdist < olddist-epsilon)
{
distx[i]=newdistx;
disty[i]=newdisty;
dist[i]=newdist;
olddist=newdist;
changed = 1;
}
c = i+offset_rd;
cdistx = distx[c];
cdisty = disty[c];
newdistx = cdistx-1;
newdisty = cdisty-1;
newdist = this.distaa3(img, gx, gy, w, c, cdistx, cdisty, newdistx, newdisty);
if(newdist < olddist-epsilon)
{
distx[i]=newdistx;
disty[i]=newdisty;
dist[i]=newdist;
olddist=newdist;
changed = 1;
}
c = i+offset_d;
cdistx = distx[c];
cdisty = disty[c];
newdistx = cdistx;
newdisty = cdisty-1;
newdist = this.distaa3(img, gx, gy, w, c, cdistx, cdisty, newdistx, newdisty);
if(newdist < olddist-epsilon)
{
distx[i]=newdistx;
disty[i]=newdisty;
dist[i]=newdist;
changed = 1;
}
}
/* Move index to second leftmost pixel of current row. */
/* Leftmost pixel is skipped, it has no left neighbor. */
i = y*w + 1;
for(x=1; x<w; x++, i++)
{
/* scan right, propagate distance from left */
olddist = dist[i];
if(olddist <= 0) continue; // Already zero distance
c = i+offset_l;
cdistx = distx[c];
cdisty = disty[c];
newdistx = cdistx+1;
newdisty = cdisty;
newdist = this.distaa3(img, gx, gy, w, c, cdistx, cdisty, newdistx, newdisty);
if(newdist < olddist-epsilon)
{
distx[i]=newdistx;
disty[i]=newdisty;
dist[i]=newdist;
changed = 1;
}
}
}
}
while(changed); // Sweep until no more updates are made
/* The transformation is completed. */
}
} | the_stack |
import "reflect-metadata";
/* ------------------------------------------------------------------------------- */
/* --------------------------------- TYPES --------------------------------------- */
/* ------------------------------------------------------------------------------- */
type Class<T> = new (...args: any[]) => T
type LifetimeScope = "Singleton" | "Transient"
type ResolverConstructor = new (kernel: Kernel, cache: { [key: string]: any }) => Resolver
interface IndexNameType { index: number, name: string }
interface Resolver { resolve<T>(config: ComponentModel): T }
interface Kernel { resolve<T>(type: Class<T> | string): T }
interface AutoFactory<T> { get(): T }
interface ComponentModelModifier<T> {
singleton(): ComponentModelModifier<T>,
onCreated(callback: (instance: T, kernel: Kernel) => T): ComponentModelModifier<T>
}
interface ComponentModel {
kind: string,
name: string,
scope: LifetimeScope,
analyzed: boolean
onCreatedCallback?: (instance: any, kernel: Kernel) => any
}
/* ------------------------------------------------------------------------------- */
/* ----------------------------- CONSTANTS/CACHE --------------------------------- */
/* ------------------------------------------------------------------------------- */
/**
* Identifier of @inject.name() decorator
*/
const NAME_DECORATOR_KEY = "my-own-ioc-container:named-type"
const RESOLVERS: { [kind: string]: ResolverConstructor } = {}
/* ------------------------------------------------------------------------------- */
/* --------------------------------- HELPERS ------------------------------------- */
/* ------------------------------------------------------------------------------- */
/**
* Extract metadata of a class/target, and return empty array if no metadata found
* @param key Key of the metadata
* @param target Target class which has the metadata
*/
function getMetadata<T>(key: string, target: any) {
return (<T[]>Reflect.getMetadata(key, target) || [])
}
/**
* Extract constructor parameters, the result can be Type of TypeName specified by @inject.name() decorator
* @param target Target type
*/
function getConstructorParameters(target: Class<any>) {
//get TypeScript generated parameter types for target parameters
const parameterTypes = getMetadata<Class<any>>("design:paramtypes", target)
//get target parameter @name decorators
const decorators = getMetadata<IndexNameType>(NAME_DECORATOR_KEY, target).reverse()
//the @name decorator has highest priority so return the binding name if the parameter has @name decorator
return parameterTypes.map((x, i) => {
const decorator = decorators.filter(x => x.index == i)[0]
return decorator ? decorator.name : x
})
}
/**
* Traverse constructor parameters through the base class
* @param target Target class
*/
function traverseConstructorParameters(target: Class<any>): (string | Class<any>)[] {
//found parameterized constructor
if (target.length > 0) return getConstructorParameters(target)
//we are on the top of
if (!Boolean(target.prototype)) return []
else
return traverseConstructorParameters(Object.getPrototypeOf(target))
}
function getComponentName(component: string | Class<any>) {
return typeof component == "string" ? component : component.prototype.constructor.name
}
/* ------------------------------------------------------------------------------- */
/* --------------------------------- DECORATORS ---------------------------------- */
/* ------------------------------------------------------------------------------- */
namespace inject {
/**
* Inject constructor parameters of class with appropriate parameters type instance
*/
export function constructor() { return (target: any) => { } }
/**
* Inject decorated parameter with appropriate type registered by name in container
* @param name Registered name of the type on the container
*/
export function name(name: string) {
return (target: any, propertyName: string, index: number) => {
const list = getMetadata<IndexNameType>(NAME_DECORATOR_KEY, target).concat([{ index, name }])
Reflect.defineMetadata(NAME_DECORATOR_KEY, list, target)
}
}
}
function resolver(kind: string) {
return (target: ResolverConstructor) => {
RESOLVERS[kind] = target
}
}
/* ------------------------------------------------------------------------------- */
/* --------------------------------- CONTAINERS ---------------------------------- */
/* ------------------------------------------------------------------------------- */
abstract class ComponentModelBase<T> implements ComponentModel, ComponentModelModifier<T> {
abstract kind: string;
abstract name: string;
analyzed: boolean = false;
scope: LifetimeScope = "Transient"
onCreatedCallback?: (instance: any, kernel: Kernel) => any;
singleton(): ComponentModelModifier<T> {
this.scope = "Singleton"
return this
}
onCreated(callback: (instance: T, kernel: Kernel) => T): ComponentModelModifier<T> {
this.onCreatedCallback = callback
return this
}
}
abstract class ResolverBase implements Resolver {
protected abstract getInstance(typeInfo: ComponentModel): any
constructor(protected kernel: Kernel, protected cache: { [key: string]: any }) { }
resolve<T>(component: ComponentModel): T {
if (component.scope == "Singleton") {
let cache = this.cache[component.name]
if (!cache) this.cache[component.name] = cache = this.getInstance(component)
return cache
}
else {
if (component.onCreatedCallback)
return component.onCreatedCallback(this.getInstance(component), this.kernel)
else
return this.getInstance(component)
}
}
}
class DependencyGraphAnalyzer {
constructor(private models: ComponentModel[], private callback?:(path:string) => void) { }
private getModelByNameOrType(type: string | Class<any>): ComponentModel | undefined {
const filter = (x: ComponentModel) =>
typeof type == "function" && x instanceof TypeComponentModel ?
x.type == type : x.name == type
return this.models.filter(filter)[0]
}
private traverseAnalyze(path: (string | Class<any>)[], model?: ComponentModel): string | undefined {
/*
Traverse component model recursively to get issue in dependency graph
path: is traversal path for example:
class A {}
class B { constructor(a:A){} }
class C {}
class D { constructor(b:B, c:C){} }
if we traverse through D then the path will be:
1: [D, B, A]
2: [D, C]
model: the current model
*/
if (model && model.analyzed) return
const curName = getComponentName(path[path.length - 1])
const curPath = path.map(x => getComponentName(x)).join(" -> ")
if(this.callback) this.callback(curPath)
if (!model) return `Trying to resolve ${curPath} but ${curName} is not registered in container`
else {
if (this.hasCircularDependency(path, model)) return `Circular dependency detected on: ${curPath}`
if (model instanceof TypeComponentModel) {
for (let dependency of model.dependencies) {
const analysis = this.traverseAnalyze(path.concat(dependency), this.getModelByNameOrType(dependency))
model.analyzed = true
if (analysis) return analysis
}
}
}
}
private hasCircularDependency(path: (string | Class<any>)[], model: ComponentModel){
/*
Graph has circular dependency if the model is inside the path exclude the last path.
Example:
path: [Computer, LGMonitor], model: {type: LGMonitor} -> Not Circular
path: [Computer, Computer], model: {type: Computer} -> Circular
path: [Computer, LGMonitor, Computer], model: {type: Computer} -> Circular
path: [Computer], model: {type:Computer} -> Not Circular
*/
const matchName = (x: string | Class<any>) => (typeof x == "string" && x == model.name)
const matchType = (x: string | Class<any>) => (typeof x == "function" && model instanceof TypeComponentModel && x == model.type)
//exclude the last path
const testPath = path.slice(0, -1)
//check if the model is inside path
return (testPath.some(matchName) || testPath.some(matchType))
}
analyze(request: string | Class<any>) {
const model = this.getModelByNameOrType(request)
const analysis = this.traverseAnalyze([request], model)
if (analysis) throw new Error(analysis)
}
}
class Container implements Kernel {
private singletonCache: { [name: string]: any } = {}
private models: ComponentModel[] = []
private resolver: { [kind: string]: Resolver } = {}
private analyzer: DependencyGraphAnalyzer
constructor() {
//setup all registered RESOLVERS
//Resolver should be marked with @resolver decorator
Object.keys(RESOLVERS).forEach(x => {
this.resolver[x] = new RESOLVERS[x](this, this.singletonCache)
})
this.analyzer = new DependencyGraphAnalyzer(this.models)
}
private getModelByNameOrType(type: string | Class<any>): ComponentModel | undefined {
const filter = (x: ComponentModel) =>
typeof type == "function" && x instanceof TypeComponentModel ?
x.type == type : x.name == type
return this.models.filter(filter)[0]
}
/**
* Register named component, the component can be Type, Instance, Factory etc
* @param name Name of the component
*/
register<T>(name: string): ComponentRegistrar
/**
* Register Type, this feature require emitDecoratorMetadata enabled on tsconfig.json
* @param type: Type that will be registered to the container
*/
register<T>(type: Class<T>): ComponentModelModifier<T>
/**
* Register ComponentModel manually, this feature useful when you define your own Resolver logic
* @param model ComponentModel that will be registered to the container
*/
register<T>(model: ComponentModel): void
register<T>(nameOrComponent: string | Class<T> | ComponentModel): ComponentRegistrar | ComponentModelModifier<T> | void {
if (typeof nameOrComponent == "string")
return new ComponentRegistrar(this.models, nameOrComponent)
else if (typeof nameOrComponent == "object") {
this.models.push(nameOrComponent)
}
else {
const model = new TypeComponentModel<T>(nameOrComponent)
this.models.push(model)
return model
}
}
private resolveModel<T>(model: ComponentModel): T {
const resolver = this.resolver[model.kind]
if (!resolver) throw new Error(`No resolver registered for component model kind of ${model.kind}`)
return resolver.resolve(model)
}
/**
* Resolve a registered component
* @param type Type or Name of the component that will be resolved
*/
resolve<T>(type: Class<T> | string): T {
this.analyzer.analyze(type)
return this.resolveModel(this.getModelByNameOrType(type)!)
}
}
/* ------------------------------------------------------------------------------- */
/* -------------------------- TYPE INJECTION IMPLEMENTATION ---------------------- */
/* ------------------------------------------------------------------------------- */
class TypeComponentModel<T> extends ComponentModelBase<T> {
kind = "Type"
name: string
dependencies: (Class<T> | string)[]
constructor(public type: Class<T>, name?: string) {
super()
this.name = name || type.prototype.constructor.name
this.dependencies = traverseConstructorParameters(type)
}
}
@resolver("Type")
class TypeResolver extends ResolverBase {
protected getInstance<T>(config: TypeComponentModel<T>): T {
return new config.type(...config.dependencies.map(x => this.kernel.resolve(x)))
}
}
/* ------------------------------------------------------------------------------- */
/* ---------------------- INSTANCE INJECTION IMPLEMENTATION ---------------------- */
/* ------------------------------------------------------------------------------- */
class InstanceComponentModel<T> extends ComponentModelBase<T> {
kind = "Instance"
constructor(public value: T | ((kernel: Kernel) => T), public name: string) {
super()
}
}
@resolver("Instance")
class InstanceResolver extends ResolverBase {
protected getInstance<T>(info: InstanceComponentModel<T>): T {
if (typeof info.value == "function")
return (info.value as Function)(this.kernel)
else
return info.value
}
}
/* ------------------------------------------------------------------------------- */
/* ---------------------- AUTO FACTORY INJECTION IMPLEMENTATION ------------------ */
/* ------------------------------------------------------------------------------- */
class AutoFactoryComponentModel extends ComponentModelBase<any> {
kind = "AutoFactory"
constructor(public component: Class<any> | string, public name: string) {
super()
}
}
/**
* The AutoFactoryClass implementation that will be returned when register component using asAutoFactory
*/
class AutoFactoryImpl<T> implements AutoFactory<T>{
constructor(private kernel: Kernel, private component: string | Class<T>) { }
get(): T {
return this.kernel.resolve(this.component)
}
}
@resolver("AutoFactory")
class AutoFactoryResolver extends ResolverBase {
protected getInstance<T>(info: AutoFactoryComponentModel) {
return new AutoFactoryImpl(this.kernel, info.component)
}
}
/* ------------------------------------------------------------------------------- */
/* ------------------------- COMPONENT REGISTRAR ------------------------------- */
/* ------------------------------------------------------------------------------- */
class ComponentRegistrar {
constructor(private models: ComponentModel[], private name: string) { }
private register<T>(model: any): ComponentModelModifier<T> {
this.models.push(model)
return model
}
asType<T>(type: Class<T>): ComponentModelModifier<T> {
return this.register(new TypeComponentModel<T>(type, this.name))
}
asInstance<T>(instance: T | ((kernel: Kernel) => T)): ComponentModelModifier<T> {
return this.register(new InstanceComponentModel<T>(instance, this.name))
}
asAutoFactory<T>(component: string | Class<T>): ComponentModelModifier<AutoFactory<T>> {
return this.register(new AutoFactoryComponentModel(component, this.name))
}
}
export {
Class,
LifetimeScope,
Kernel,
ComponentModelModifier,
AutoFactory,
inject,
Container,
ComponentRegistrar,
ComponentModel,
DependencyGraphAnalyzer,
TypeComponentModel,
InstanceComponentModel,
AutoFactoryComponentModel
} | the_stack |
interface header {
name: string;
value: string
}
interface RequestHookResult {
request: Request;
isBreak: boolean
}
interface ResponseHookResult {
response: Response;
isBreak: boolean
}
interface requestHook {
(request: Request): RequestHookResult;
}
interface responseHook {
(response: Response): ResponseHookResult
}
class Xhttp {
private static instance: Xhttp;
private headers = new Headers();
private requestInit: RequestInit = {
method: "GET",
headers: this.getHeaders(),
mode: "cors",
cache: "default",
credentials: "include",
};
private static globalRequestHooks: Array<requestHook> = [];
private static globalResponseHooks: Array<responseHook> = [];
private requestHooks: Array<requestHook> = [];
private responseHooks: Array<responseHook> = [];
public constructor(init?: RequestInit) {
// console.log(`xhttp_constructor`);
if (init) {
this.requestInit = init;
}
}
/**
* 通过init静态方法创建Xhttp实例
* @param init
*/
public static new(init?: RequestInit): Xhttp {
return new Xhttp(init);
};
/**
* 调用request回调函数
* @param request
*/
private callRequestHook(request: Request): RequestHookResult {
let tmpRequest = request;
let result: RequestHookResult;
for (let i = 0; i < Xhttp.globalRequestHooks.length; i++) {
result = Xhttp.globalRequestHooks[i](tmpRequest);
tmpRequest = result.request;
if (result.isBreak) {
return result;
}
}
for (let i = 0; i < this.requestHooks.length; i++) {
result = this.requestHooks[i](tmpRequest);
tmpRequest = result.request;
if (result.isBreak) {
return result;
}
}
return { "request": tmpRequest, "isBreak": false };
}
/**
* 调用response回调函数
* @param response
*/
private callResponseHook(response: Response): ResponseHookResult {
let tmpResponse = response;
let result: ResponseHookResult;
for (let i = 0; i < Xhttp.globalResponseHooks.length; i++) {
result = Xhttp.globalResponseHooks[i](tmpResponse);
tmpResponse = result.response;
if (result.isBreak) {
return result;
}
}
for (let i = 0; i < this.responseHooks.length; i++) {
result = this.responseHooks[i](response);
tmpResponse = result.response;
if (result.isBreak) {
return result;
}
}
return { "response": tmpResponse, "isBreak": false };;
}
/**
* 单例模式
*/
// public static getInstance() {
// if (!Xhttp.instance) {
// Xhttp.instance = new Xhttp();
// }
// return Xhttp.instance;
// }
private static getInstance(): Xhttp {
return new Xhttp();
}
/**
* 获取请求Headers
*/
private getHeaders(): Headers {
return this.headers;
}
/**
* 同时设置多个header
* @param headers
*/
public setHeaders(headers: Array<header>): void {
headers.forEach((header) => {
this.headers.set(header.name, header.value);
});
}
/**
* 设置单个header
* @param name
* @param value
*/
public setHeader(name: string, value: string): void {
this.headers.set(name, value)
}
/**
* 获取请求RequestInit
*/
public getRequestInit(): RequestInit {
return this.requestInit
}
/**
* 设置请求RequestInit
* @param init
*/
public setRequestInit(init: RequestInit): void {
if (init.body) {
this.requestInit.body = init.body;
}
if (init.cache) {
this.requestInit.cache = init.cache;
}
if (init.credentials) {
this.requestInit.credentials = init.credentials;
}
if (init.headers) {
this.requestInit.headers = init.headers;
}
if (init.integrity) {
this.requestInit.integrity = init.integrity;
}
if (init.keepalive) {
this.requestInit.keepalive = init.keepalive;
}
if (init.method) {
this.requestInit.method = init.method;
}
if (init.mode) {
this.requestInit.mode = init.mode;
}
if (init.redirect) {
this.requestInit.redirect = init.redirect;
}
if (init.referrer) {
this.requestInit.referrer = init.referrer;
}
if (init.referrerPolicy) {
this.requestInit.referrerPolicy = init.referrerPolicy;
}
if (init.signal) {
this.requestInit.signal = init.signal;
}
if (init.window) {
this.requestInit.window = init.window;
}
}
public get(url: string, init?: RequestInit): Promise<Response> {
if (init) {
this.requestInit = init;
}
this.requestInit.method = "GET";
return this.ajax(url, this.getRequestInit());
}
public post(url: string, init?: RequestInit): Promise<Response> {
if (init) {
this.requestInit = init;
}
this.requestInit.method = "POST";
return this.ajax(url, this.getRequestInit());
}
public put(url: string, init?: RequestInit): Promise<Response> {
if (init) {
this.requestInit = init;
}
this.requestInit.method = "PUT";
return this.ajax(url, this.getRequestInit());
}
public patch(url: string, init?: RequestInit): Promise<Response> {
if (init) {
this.requestInit = init;
}
this.requestInit.method = "PATCH";
return this.ajax(url, this.getRequestInit());
}
public delete(url: string, init?: RequestInit): Promise<Response> {
if (init) {
this.requestInit = init;
}
this.requestInit.method = "DELETE";
return this.ajax(url, this.getRequestInit());
}
public head(url: string, init?: RequestInit): Promise<Response> {
if (init) {
this.requestInit = init;
}
this.requestInit.method = "HEAD";
return this.ajax(url, this.getRequestInit());
}
public options(url: string, init?: RequestInit): Promise<Response> {
if (init) {
this.requestInit = init;
}
this.requestInit.method = "OPTIONS";
return this.ajax(url, this.getRequestInit());
}
/**
* AJAX 请求方法
* @param url
* @param init
*/
public ajax(url: string, init: RequestInit): Promise<Response> {
let request = new Request(url, init);
// 调用request钩子函数,如果添加的钩子函数返回值是true,后续的钩子函数就不调用了,直接返回
let callRequestHookResult = this.callRequestHook(request);
if (callRequestHookResult.isBreak) {
return new Promise<Response>(() => {
return new Response();
});
}
return fetch(callRequestHookResult.request)
.then((response) => {
// let response = response.clone();
// 调用response钩子函数,如果添加的钩子函数返回值是true,后续的钩子函数就不调用了,直接返回
let callResponseHookResult = this.callResponseHook(response);
return callResponseHookResult.response;
});
}
/**
* 添加实例Request钩子函数
* @param hookFunction
*/
public addRequestHook(hookFunction: requestHook) {
this.requestHooks.push(hookFunction);
}
/**
* 添加全局Request钩子函数
* @param hookFunction
*/
public addGlobalRequestHook(hookFunction: requestHook) {
Xhttp.globalRequestHooks.push(hookFunction);
}
/**
* 添加实例Response钩子函数
* @param hookFunction
*/
public addResponseHook(hookFunction: responseHook) {
this.responseHooks.push(hookFunction);
}
/**
* 添加全局Response钩子函数
* @param hookFunction
*/
public addGlobalResponseHook(hookFunction: responseHook) {
Xhttp.globalResponseHooks.push(hookFunction);
}
}
function exportDefault() {
return new Xhttp();
}
export default exportDefault();
export {
Xhttp
}
//===============================================================================================
/**
let token = "";
function downloadFile(path: string, filename: string) {
let getHeaders = new Headers();
// getHeaders.append('Content-Type', 'image/jpeg');
getHeaders.append("token", token);
let getInit: RequestInit = {
method: "GET",
headers: getHeaders,
mode: "cors",
cache: "default",
credentials: "include",
};
let getRequest = new Request("/api/file/get?path=" + path, getInit);
fetch(getRequest).then((res) =>
res.blob().then((blob) => {
var a = document.createElement("a");
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
})
);
}
* 下载文件(只能是文件,不能是目录)
*/
/**
* 删除文件或目录
function deleteFile(index: Number, row: any) {
console.log("删除文件");
console.log(index);
console.log(row);
let formData = new FormData();
formData.append("path", row.path);
let getHeaders = new Headers();
getHeaders.append("token", token);
let getInit: RequestInit = {
method: "POST",
headers: getHeaders,
mode: "cors",
body: formData,
cache: "default",
credentials: "include",
};
let getRequest = new Request("/api/file/delete", getInit);
fetch(getRequest)
.then((res) => res.json())
.then((json) => {
console.log(json);
// data.files = json.files;
});
}
*/ | the_stack |
import { Cookies } from './cookies';
/* eslint-disable max-statements */
describe('Cookies mocked environment', () => {
let cookiesValue = '';
const cookieGetMock = jest.fn().mockImplementation(() => {
return cookiesValue;
});
const cookieSetMock = jest.fn().mockImplementation((nextCookiesValue) => {
cookiesValue = nextCookiesValue;
});
let dateSpy: jest.SpyInstance<Date, []>;
let cookies: Cookies;
beforeEach(() => {
Object.defineProperty(document, 'cookie', {
get: cookieGetMock,
set: cookieSetMock,
});
const RealDate = global.Date;
const dateMock = new Date(Date.UTC(2030, 11, 20, 23, 15, 30, 0)); // 2030-12-20 23:15:30
// @ts-ignore
dateSpy = jest.spyOn(global, 'Date').mockImplementation((value) => {
return value ? new RealDate(value) : dateMock;
});
cookies = new Cookies();
});
afterEach(() => {
cookiesValue = '';
dateSpy.mockRestore();
});
it('Get/set/erase basics', () => {
// Test set
cookies.set('banana', 'yellow');
expect(document.cookie).toBe('banana=yellow;path=/');
// Test get
cookies.set('banana', 'yellow');
expect(cookies.get('banana')).toBe('yellow');
// Test erase
cookies.erase('banana');
expect(document.cookie).toBe('banana=;expires=Thu, 19 Dec 2030 23:15:30 GMT;path=/');
});
it('Set a cookie using all possible options', () => {
// Set all options
const options = {
expires: 4,
domain: 'www.test.com',
path: '/some/path',
secure: true,
httpOnly: true,
sameSite: 'strict' as const,
};
cookies.set('banana', 'yellow', options);
// All options should have been applied
expect(document.cookie).toBe(
'banana=yellow;expires=Tue, 24 Dec 2030 23:15:30 GMT;domain=www.test.com;path=/some/path;secure;httponly;samesite=strict'
);
// Original options structure not modified
expect(options).toEqual({
expires: 4,
domain: 'www.test.com',
path: '/some/path',
secure: true,
httpOnly: true,
sameSite: 'strict',
});
});
it('Set all possible defaults', () => {
const defaults = {
expires: 7,
domain: 'www.test.com',
path: '/some/path',
secure: true,
httpOnly: true,
sameSite: 'strict' as const,
};
// Set new defaults
cookies = new Cookies(defaults);
// Set cookie, all default options should be applies
cookies.set('banana', 'yellow');
expect(document.cookie).toBe(
'banana=yellow;expires=Fri, 27 Dec 2030 23:15:30 GMT;domain=www.test.com;path=/some/path;secure;httponly;samesite=strict'
);
// The defaults should not have been modified
expect(defaults).toEqual({
expires: 7,
domain: 'www.test.com',
path: '/some/path',
secure: true,
httpOnly: true,
sameSite: 'strict',
});
});
it('Set empty cookie', () => {
cookies.set('banana', '');
expect(document.cookie).toBe('banana=;path=/');
});
it('Set cookie using using no global defaults at all', () => {
cookies = new Cookies({});
cookies.set('banana', 'yellow');
expect(document.cookie).toBe('banana=yellow;path=/');
});
it('Set expires option', () => {
// Set cookie with custom expiration time
cookies.set('banana', 'yellow', { expires: 30 });
expect(document.cookie).toBe('banana=yellow;expires=Sun, 19 Jan 2031 23:15:30 GMT;path=/');
// Set a default expiration time
cookies = new Cookies({ expires: 7 });
cookies.set('banana', 'yellow');
expect(document.cookie).toBe('banana=yellow;expires=Fri, 27 Dec 2030 23:15:30 GMT;path=/');
// Override the default expiration time using the function option
cookies.set('banana', 'yellow', { expires: 14 });
expect(document.cookie).toBe('banana=yellow;expires=Fri, 03 Jan 2031 23:15:30 GMT;path=/');
});
it('Verify erase options are applied', () => {
// Erase cookie with all available options
cookies.erase('banana', { domain: 'example.org', path: '/a/path' });
expect(document.cookie).toBe(
'banana=;expires=Thu, 19 Dec 2030 23:15:30 GMT;domain=example.org;path=/a/path'
);
// Erase cookie with only the path set
cookies.erase('banana', { path: '/a/path' });
expect(document.cookie).toBe('banana=;expires=Thu, 19 Dec 2030 23:15:30 GMT;path=/a/path');
// Erase cookie with only the domain set
cookies.erase('banana', { domain: 'example.org' });
expect(document.cookie).toBe(
'banana=;expires=Thu, 19 Dec 2030 23:15:30 GMT;domain=example.org;path=/'
);
});
it("Verify erase doesn't apply default configuration", () => {
// Set some defaults
cookies = new Cookies({
expires: 7,
domain: 'default.example.org',
path: '/default/path',
secure: true,
httpOnly: true,
});
// Erase cookie should apply the domain and path specified in the defaults above
cookies.erase('banana');
expect(document.cookie).toBe(
'banana=;expires=Thu, 19 Dec 2030 23:15:30 GMT;domain=default.example.org;path=/default/path'
);
// Erase cookie with specified domain and path overrules the defaults
cookies.erase('banana', { domain: 'other.example.org', path: '/other/path' });
expect(document.cookie).toBe(
'banana=;expires=Thu, 19 Dec 2030 23:15:30 GMT;domain=other.example.org;path=/other/path'
);
// All options besides domain and path should be ignored
cookies.erase('banana', {
domain: 'other.example.org',
path: '/other/path',
expires: 100,
secure: true,
httpOnly: true,
});
expect(document.cookie).toBe(
'banana=;expires=Thu, 19 Dec 2030 23:15:30 GMT;domain=other.example.org;path=/other/path'
);
});
it("Verify all allowed formats for the 'expires' option", () => {
// Verify usage of Date() format
cookies.set('banana', 'yellow', { expires: new Date(2030, 11, 20) });
expect(document.cookie.replace('GMT', 'UTC')).toBe(
`banana=yellow;expires=${new Date(2030, 11, 20).toUTCString().replace('GMT', 'UTC')};path=/`
);
// Verify usage of integer format (days till expiration)
cookies.set('banana', 'yellow', { expires: 5 });
expect(document.cookie).toBe('banana=yellow;expires=Wed, 25 Dec 2030 23:15:30 GMT;path=/');
// Verify usage of float format (set to one and a half day)
cookies.set('banana', 'yellow', { expires: 1.5 });
expect(document.cookie).toBe('banana=yellow;expires=Sun, 22 Dec 2030 11:15:30 GMT;path=/');
// Verify usage of string format (in a format recognized by Date.parse() )
cookies.set('banana', 'yellow', { expires: '01/08/2031' });
let expectedDate = new Date('01/08/2031').toUTCString();
expect(document.cookie).toBe(`banana=yellow;expires=${expectedDate};path=/`);
// Verify date may be set to unix epoch
cookies.set('banana', 'yellow', { expires: new Date(0) });
expectedDate = new Date(0).toUTCString();
expect(document.cookie).toBe(`banana=yellow;expires=${expectedDate};path=/`);
});
it("Verify unsupported formats for the 'expires' option are ignored", () => {
cookies.set('banana', 'yellow', { expires: 'anInvalidDateString' });
expect(document.cookie).toBe('banana=yellow;path=/');
// @ts-ignore
cookies.set('banana', 'yellow', { expires: ['an', 'array'] });
expect(document.cookie).toBe('banana=yellow;path=/');
cookies.set('banana', 'yellow', { expires: NaN });
expect(document.cookie).toBe('banana=yellow;path=/');
cookies.set('banana', 'yellow', { expires: null });
expect(document.cookie).toBe('banana=yellow;path=/');
});
it('Set domain option', () => {
// Set cookie with custom domain
cookies.set('banana', 'yellow', { domain: 'www.test.com' });
expect(document.cookie).toBe('banana=yellow;domain=www.test.com;path=/');
// Set a default domain
cookies = new Cookies({ domain: 'default.domain.com' });
cookies.set('banana', 'yellow');
expect(document.cookie).toBe('banana=yellow;domain=default.domain.com;path=/');
// Override the default domain using the function option
cookies.set('banana', 'yellow', { domain: 'override.domain.com' });
expect(document.cookie).toBe('banana=yellow;domain=override.domain.com;path=/');
});
it('Set path option', () => {
// Path defaults to '/'
cookies.set('banana', 'yellow');
expect(document.cookie).toBe('banana=yellow;path=/');
// Set cookie with custom path
cookies.set('banana', 'yellow', { path: '/some/path' });
expect(document.cookie).toBe('banana=yellow;path=/some/path');
// Set cookie with an empty path (the browser will use the current path)
cookies.set('banana', 'yellow', { path: '' });
expect(document.cookie).toBe('banana=yellow');
// Change the default path
cookies = new Cookies({ path: '/a/default/path' });
cookies.set('banana', 'yellow');
expect(document.cookie).toBe('banana=yellow;path=/a/default/path');
// Override the default path using the function option
cookies.set('banana', 'yellow', { path: '/override/path' });
expect(document.cookie).toBe('banana=yellow;path=/override/path');
// Default path may set set to ''
cookies = new Cookies({ path: '' });
cookies.set('banana', 'yellow');
expect(document.cookie).toBe('banana=yellow');
});
it('Set secure option', () => {
// Set cookie with the secure option
cookies.set('banana', 'yellow', { secure: true });
expect(document.cookie).toBe('banana=yellow;path=/;secure');
// Set cookie without the secure option
cookies.set('banana', 'yellow', { secure: false });
expect(document.cookie).toBe('banana=yellow;path=/');
// Change the default to true
cookies = new Cookies({ secure: true });
cookies.set('banana', 'yellow');
expect(document.cookie).toBe('banana=yellow;path=/;secure');
// Override the default to false using the function option
cookies.set('banana', 'yellow', { secure: false });
expect(document.cookie).toBe('banana=yellow;path=/');
// Change the default to false
cookies = new Cookies({ secure: false });
cookies.set('banana', 'yellow');
expect(document.cookie).toBe('banana=yellow;path=/');
// Override the default to true using the function option
cookies.set('banana', 'yellow', { secure: true });
expect(document.cookie).toBe('banana=yellow;path=/;secure');
});
it('Set httpOnly option', () => {
// Set cookie with the httpOnly option
cookies.set('banana', 'yellow', { httpOnly: true });
expect(document.cookie).toBe('banana=yellow;path=/;httponly');
// Set cookie without the httpOnly option
cookies.set('banana', 'yellow', { httpOnly: false });
expect(document.cookie).toBe('banana=yellow;path=/');
// Change the default to true
cookies = new Cookies({ httpOnly: true });
cookies.set('banana', 'yellow');
expect(document.cookie).toBe('banana=yellow;path=/;httponly');
// Override the default to false using the function option
cookies.set('banana', 'yellow', { httpOnly: false });
expect(document.cookie).toBe('banana=yellow;path=/');
// Change the default to false
cookies = new Cookies({ httpOnly: false });
cookies.set('banana', 'yellow');
expect(document.cookie).toBe('banana=yellow;path=/');
// Override the default to true using the function option
cookies.set('banana', 'yellow', { httpOnly: true });
expect(document.cookie).toBe('banana=yellow;path=/;httponly');
});
it('Set sameSite option', () => {
// Set cookie with the sameSite option (to Strict)
cookies.set('banana', 'yellow', { sameSite: 'strict' });
expect(document.cookie).toBe('banana=yellow;path=/;samesite=strict');
// Set cookie with the sameSite option (to Lax)
cookies.set('banana', 'yellow', { sameSite: 'lax' });
expect(document.cookie).toBe('banana=yellow;path=/;samesite=lax');
// Set cookie without the sameSite option
// @ts-ignore
cookies.set('banana', 'yellow', { sameSite: '' });
expect(document.cookie).toBe('banana=yellow;path=/');
// Change the default to 'lax'
cookies = new Cookies({ sameSite: 'lax' });
cookies.set('banana', 'yellow');
expect(document.cookie).toBe('banana=yellow;path=/;samesite=lax');
// Override the default using the function option to disable sameSite
// @ts-ignore
cookies.set('banana', 'yellow', { sameSite: '' });
expect(document.cookie).toBe('banana=yellow;path=/');
// Override the default using the function option (to 'strict')
cookies.set('banana', 'yellow', { sameSite: 'strict' });
expect(document.cookie).toBe('banana=yellow;path=/;samesite=strict');
});
it('Verify cookie name encoding', () => {
// Should apply URI encoding
cookies.set('báñâñâ', 'yellow');
expect(document.cookie).toBe('b%C3%A1%C3%B1%C3%A2%C3%B1%C3%A2=yellow;path=/');
// rfc6265 specifies a cookie name is of the `token` type as defined in rfc2616:
// token = 1*<any CHAR except CTLs or separators>
// separators = "(" | ")" | "<" | ">" | "@"
// | "," | ";" | ":" | "\" | <">
// | "/" | "[" | "]" | "?" | "="
// | "{" | "}" | SP | HT
//
// Note that a CHAR is defined as any US-ASCII character (octets 0 - 127)
const separators = {
'(': '%28',
')': '%29',
'<': '%3C',
'>': '%3E',
'@': '%40',
',': '%2C',
';': '%3B',
':': '%3A',
'\\': '%5C',
'"': '%22',
'/': '%2F',
'[': '%5B',
']': '%5D',
'?': '%3F',
'=': '%3D',
'{': '%7B',
'}': '%7D',
' ': '%20',
'\t': '%09',
};
// Check whether all separators are encoded
for (const separator in separators) {
cookies.set(`cookie${separator}`, 'value');
expect(document.cookie).toBe(`cookie${separators[separator]}=value;path=/`);
}
// Check whether CTLs are encoded
cookies.set('\x10', 'value');
expect(document.cookie).toBe('%10=value;path=/');
cookies.set('\x7F', 'value');
expect(document.cookie).toBe('%7F=value;path=/');
// The '%' sign should be encoded as it's used as prefix for percentage encoding
cookies.set('%', 'value');
expect(document.cookie).toBe('%25=value;path=/');
// Check whether all US-ASCII CHARS except for separators and CTLs are encoded
for (let i = 0; i < 256; i++) {
const ascii = String.fromCharCode(i);
// Skip CTLs, the % sign and separators
// eslint-disable-next-line eqeqeq, no-prototype-builtins
if (i < 32 || i >= 127 || ascii == '%' || separators.hasOwnProperty(ascii)) {
continue;
}
cookies.set(`cookie${ascii}`, 'value');
expect(document.cookie).toBe(`cookie${ascii}=value;path=/`);
}
});
it('Verify cookie name decoding', () => {
document.cookie = 'b%C3%A1%C3%B1%C3%A2%C3%B1%C3%A2=yellow';
expect(cookies.get('báñâñâ')).toBe('yellow');
expect(cookies.all()['báñâñâ']).toBe('yellow');
});
it('Return cookies with wrong encoded name without decoding', () => {
document.cookie = 'b%C3%A1%C3%B1%C3%A2%C3%B1%C3%A2=yellow; %ff=red';
expect(cookies.get('%ff')).toBe('red');
expect(cookies.all()).toEqual({ '%ff': 'red', báñâñâ: 'yellow' });
});
it('Return cookies with wrong encoded value without decoding', () => {
document.cookie = 'banana=yellow; apple=%ff';
expect(cookies.get('apple')).toBe('%ff');
expect(cookies.all()).toEqual({ apple: '%ff', banana: 'yellow' });
});
it('Verify cookie name parsing using whitespace', () => {
// Without whitespace
document.cookie = 'a=1;b=2;c=3';
expect(cookies.get('a')).toBe('1');
expect(cookies.get('b')).toBe('2');
expect(cookies.get('c')).toBe('3');
expect(cookies.all()).toEqual({ a: '1', b: '2', c: '3' });
// With leading whitespace
document.cookie = 'a=1; b=2;c=3';
expect(cookies.get('a')).toBe('1');
expect(cookies.get('b')).toBe('2');
expect(cookies.get('c')).toBe('3');
expect(cookies.all()).toEqual({ a: '1', b: '2', c: '3' });
});
it('Verify cookie value encoding', () => {
// Should apply URI encoding
cookies.set('banana', '¿yéllów?');
expect(document.cookie).toBe('banana=%C2%BFy%C3%A9ll%C3%B3w?;path=/');
// Should not modify the original value
const value = '¿yéllów?';
cookies.set('banana', value);
expect(document.cookie).toBe('banana=%C2%BFy%C3%A9ll%C3%B3w?;path=/');
expect(value).toBe('¿yéllów?');
// RFC 6265 (http://tools.ietf.org/html/rfc6265) is the 'real world' cookies specification.
// The specification allows the following subset of ASCII characters to be unescaped:
// hex : dec : ASCII
// 0x21 : 33 : !
cookies.set('a', '!');
expect(document.cookie).toBe('a=!;path=/');
// 0x23-2B: 35-43 : #$%&'()*+ (note that % should be encoded because it's the prefix for percent encoding)
cookies.set('b', "#$%&'()*+");
expect(document.cookie).toBe("b=#$%25&'()*+;path=/");
// 0x2D-3A: 45-58 : -./0123456789:
cookies.set('c', '-./0123456789:');
expect(document.cookie).toBe('c=-./0123456789:;path=/');
// 0x3C-5B: 60-91 : <=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[
cookies.set('d', '<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[');
expect(document.cookie).toBe('d=<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[;path=/');
// 0x5D-7E: 93-126: ]^_`abcdefghijklmnopqrstuvwxyz{|}~
cookies.set('e', ']^_`abcdefghijklmnopqrstuvwxyz{|}~');
expect(document.cookie).toBe('e=]^_`abcdefghijklmnopqrstuvwxyz{|}~;path=/');
// Now check the inverse of above: whether remaining character ranges are percent encoded (they should be)
cookies.set('f_CTL', '\x10');
expect(document.cookie).toBe('f_CTL=%10;path=/');
cookies.set('f_whitespace', ' ');
expect(document.cookie).toBe('f_whitespace=%20;path=/');
cookies.set('f_DQUOTE', '"');
expect(document.cookie).toBe('f_DQUOTE=%22;path=/');
cookies.set('f_comma', ',');
expect(document.cookie).toBe('f_comma=%2C;path=/');
cookies.set('f_semicolon', ';');
expect(document.cookie).toBe('f_semicolon=%3B;path=/');
cookies.set('f_backslash', '\\');
expect(document.cookie).toBe('f_backslash=%5C;path=/');
cookies.set('f_CTL2', '\x7F');
expect(document.cookie).toBe('f_CTL2=%7F;path=/');
});
describe('Verify compatibility with PHP server side', () => {
it("Using PHP setcookie() - doesn't encode the plus sign properly", () => {
// PHP output was generated using PHP 5.5
// http://php.net/manual/en/function.setcookie.php
// <?php setcookie('banana', '¿yéllów?'); ?>
document.cookie = 'banana=%C2%BFy%C3%A9ll%C3%B3w%3F';
expect(cookies.get('banana')).toBe('¿yéllów?');
// <?php setcookie('a', '!#$%&\'()*+-./0123456789:'); ?>
document.cookie = 'a=%21%23%24%25%26%27%28%29%2A%2B-.%2F0123456789%3A';
expect(cookies.get('a')).toBe("!#$%&'()*+-./0123456789:");
// <?php setcookie('b', '<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ['); ?>
document.cookie = 'b=%3C%3D%3E%3F%40ABCDEFGHIJKLMNOPQRSTUVWXYZ%5B';
expect(cookies.get('b')).toBe('<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[');
// <?php setcookie('c', ']^_`abcdefghijklmnopqrstuvwxyz{|}~'); ?>
document.cookie = 'c=%5D%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D%7E';
expect(cookies.get('c')).toBe(']^_`abcdefghijklmnopqrstuvwxyz{|}~');
// <?php setcookie('f', "\x10"); ?>
document.cookie = 'f=%10';
expect(cookies.get('f')).toBe('\x10');
// <?php setcookie('f', " "); ?>
document.cookie = 'f=+';
expect(cookies.get('f')).toBe('+'); // Note: should have been ' ' instead of '+'
// <?php setcookie('f', '"'); ?>
document.cookie = 'f=%22';
expect(cookies.get('f')).toBe('"');
// <?php setcookie('f', ","); ?>
document.cookie = 'f=%2C';
expect(cookies.get('f')).toBe(',');
// <?php setcookie('f', ";"); ?>
document.cookie = 'f=%3B';
expect(cookies.get('f')).toBe(';');
// <?php setcookie('f', "\\"); ?>
document.cookie = 'f=%5C';
expect(cookies.get('f')).toBe('\\');
// <?php setcookie('f', "\x7F"); ?>
document.cookie = 'f=%7F';
expect(cookies.get('f')).toBe('\x7F');
// PHP cookie array notation
// <?php setcookie('cookie[one]', "1"); ?>
// <?php setcookie('cookie[two]', "2"); ?>
document.cookie = 'cookie[one]=1; cookie[two]=2';
expect(cookies.get('cookie[one]')).toBe('1');
expect(cookies.get('cookie[two]')).toBe('2');
// PHP will overwrite existing cookies (which is the correct behavior)
// <?php setcookie('c', "1"); ?>
// <?php setcookie('c', "2"); ?>
document.cookie = 'c=2';
expect(cookies.get('c')).toBe('2');
});
it('Using PHP setrawcookie() and rawurlencode', () => {
// PHP output was generated using PHP 5.5
// http://php.net/manual/en/function.setcookie.php
// http://php.net/manual/en/function.rawurlencode.php
// <?php setrawcookie('banana', rawurlencode('¿yéllów?')); ?>
document.cookie = 'banana=%C2%BFy%C3%A9ll%C3%B3w%3F';
expect(cookies.get('banana')).toBe('¿yéllów?');
// <?php setrawcookie('a', rawurlencode('!#$%&\'()*+-./0123456789:')); ?>
document.cookie = 'a=%21%23%24%25%26%27%28%29%2A%2B-.%2F0123456789%3A';
expect(cookies.get('a')).toBe("!#$%&'()*+-./0123456789:");
// <?php setrawcookie('b', rawurlencode('<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[')); ?>
document.cookie = 'b=%3C%3D%3E%3F%40ABCDEFGHIJKLMNOPQRSTUVWXYZ%5B';
expect(cookies.get('b')).toBe('<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[');
// <?php setrawcookie('c', rawurlencode(']^_`abcdefghijklmnopqrstuvwxyz{|}~')); ?>
document.cookie = 'c=%5D%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D~';
expect(cookies.get('c')).toBe(']^_`abcdefghijklmnopqrstuvwxyz{|}~');
// <?php setrawcookie('f', rawurlencode("\x10")); ?>
document.cookie = 'f=%10';
expect(cookies.get('f')).toBe('\x10');
// <?php setrawcookie('f', rawurlencode(' ')); ?>
document.cookie = 'f=%20';
expect(cookies.get('f')).toBe(' ');
// <?php setrawcookie('f', rawurlencode('"')); ?>
document.cookie = 'f=%22';
expect(cookies.get('f')).toBe('"');
// <?php setrawcookie('f', rawurlencode(',')); ?>
document.cookie = 'f=%2C';
expect(cookies.get('f')).toBe(',');
// <?php setrawcookie('f', rawurlencode(';')); ?>
document.cookie = 'f=%3B';
expect(cookies.get('f')).toBe(';');
// <?php setrawcookie('f', rawurlencode("\\")); ?>
document.cookie = 'f=%5C';
expect(cookies.get('f')).toBe('\\');
// <?php setrawcookie('f', rawurlencode("\x7F")); ?>
document.cookie = 'f=%7F';
expect(cookies.get('f')).toBe('\x7F');
// PHP cookie array notation
// <?php setrawcookie('cookie[one]', rawurlencode("1")); ?>
// <?php setrawcookie('cookie[two]', rawurlencode("2")); ?>
document.cookie = 'cookie[one]=1; cookie[two]=2';
expect(cookies.get('cookie[one]')).toBe('1');
expect(cookies.get('cookie[two]')).toBe('2');
// PHP will overwrite existing cookies (which is the correct behavior)
// <?php setrawcookie('c', rawurlencode('1')); ?>
// <?php setrawcookie('c', rawurlencode('2')); ?>
document.cookie = 'c=2';
expect(cookies.get('c')).toBe('2');
});
});
});
/* eslint-enable max-statements */ | the_stack |
import {
objectiveId,
Objective,
OpenChannel,
CloseChannel,
SharedObjective,
SubmitChallenge,
DefundChannel,
unreachable,
} from '@statechannels/wallet-core';
import {Model, TransactionOrKnex} from 'objection';
import _ from 'lodash';
import {WaitingFor} from '../objectives/objective-manager';
function extractReferencedChannels(objective: Objective): string[] {
switch (objective.type) {
case 'OpenChannel':
case 'CloseChannel':
case 'VirtuallyFund':
case 'SubmitChallenge':
case 'DefundChannel':
return [objective.data.targetChannelId];
case 'FundGuarantor':
return [objective.data.guarantorId];
case 'FundLedger':
case 'CloseLedger':
return [objective.data.ledgerId];
default:
return [];
}
}
export type ObjectiveStatus = 'pending' | 'approved' | 'rejected' | 'failed' | 'succeeded';
/**
* A WalletObjective is a wire objective with a status, waitingFor state-string, timestamps and an objectiveId
*
* Limited to 'OpenChannel', 'CloseChannel', 'SubmitChallenge' and 'DefundChannel' which are the only objectives
* that are currently supported by the server wallet
*
*/
type ExtraProperties = {
objectiveId: string;
status: ObjectiveStatus;
waitingFor: WaitingFor;
createdAt: Date;
progressLastMadeAt: Date;
};
export type WalletObjective<O extends SupportedObjective = SupportedObjective> = O &
ExtraProperties;
export function isSharedObjective(
objective: WalletObjective<SupportedObjective>
): objective is WalletObjective<OpenChannel> | WalletObjective<CloseChannel> {
return objective.type === 'OpenChannel' || objective.type === 'CloseChannel';
}
type SupportedObjective = OpenChannel | CloseChannel | SubmitChallenge | DefundChannel;
export function isSupportedObjective(o: Objective): o is SupportedObjective {
return (
o.type === 'OpenChannel' ||
o.type === 'CloseChannel' ||
o.type === 'SubmitChallenge' ||
o.type === 'DefundChannel'
);
}
export const toWireObjective = (dbObj: WalletObjective<SupportedObjective>): SharedObjective => {
if (dbObj.type === 'SubmitChallenge' || dbObj.type === 'DefundChannel') {
throw new Error(
'SubmitChallenge and DefundChannel objectives are not supported as wire objectives'
);
}
/**
* This switch statement is unfortunate but is necessary to avoid a typescript error.
* It seems that the typescript error is the result of:
* - The parameter dbObj is a union type.
* - The return type is a union type.
* - The return value is constructed by creating an object with type, data, and participants fields.
* - Typescript considers a return object with "type" OpenChannel and "data" of CloseChannel objective to be a possible return type.
* - The above object does not belong to the union return type.
*/
switch (dbObj.type) {
case 'OpenChannel':
return {
type: dbObj.type,
data: dbObj.data,
participants: dbObj.participants,
};
case 'CloseChannel':
return {
type: dbObj.type,
data: dbObj.data,
participants: dbObj.participants,
};
default:
unreachable(dbObj);
}
};
export class ObjectiveChannelModel extends Model {
readonly objectiveId!: string;
readonly channelId!: string;
static tableName = 'objectives_channels';
static get idColumn(): string[] {
return ['objectiveId', 'channelId'];
}
}
export class ObjectiveModel extends Model {
readonly objectiveId!: ExtraProperties['objectiveId'];
readonly status!: ExtraProperties['status'];
readonly type!: SupportedObjective['type'];
readonly data!: SupportedObjective['data'];
readonly waitingFor!: ExtraProperties['waitingFor'];
// the default value of waitingFor is '', see Nothing.ToWaitFor type
createdAt!: Date;
progressLastMadeAt!: Date;
static tableName = 'objectives';
static get idColumn(): string[] {
return ['objectiveId'];
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
static get relationMappings() {
// Prevent a require loop
// https://vincit.github.io/objection.js/guide/relations.html#require-loops
// eslint-disable-next-line @typescript-eslint/no-var-requires
const {Channel} = require('./channel');
return {
objectivesChannels: {
relation: Model.ManyToManyRelation,
modelClass: Channel,
join: {
from: 'objectives.objectiveId',
through: {
from: 'objectives_channels.objectiveId',
to: 'objectives_channels.channelId',
},
to: 'channels.channelId',
},
},
};
}
static async insert<O extends SupportedObjective = SupportedObjective>(
objectiveToBeStored: O,
tx: TransactionOrKnex,
approvalStatus?: 'approved' | 'pending',
waitingFor?: WaitingFor // TODO this should be correlated to O
): Promise<WalletObjective<O>> {
const id: string = objectiveId(objectiveToBeStored);
return tx.transaction(async trx => {
const query = ObjectiveModel.query(trx)
.insert({
objectiveId: id,
status: approvalStatus ?? 'pending',
type: objectiveToBeStored.type,
data: objectiveToBeStored.data,
createdAt: new Date(),
progressLastMadeAt: new Date(),
waitingFor: waitingFor ?? 'approval',
})
// `Model.query(tx).insert(o)` returns `o` by default.
// The return value is therefore constrained by the type of `Model`.
// When data is fetched with e.g. `Model.query(tx).findById()`, however,
// the return type is dictated by the DB schema and driver, defined elsewhere.
// It is possible for these types to differ:
// and we are effectively *asserting* that they are the same.
// So it is important to check that the objects returned by *find* queries
// are of the same type as `Model`.
//
// This is particularly important for `timestamp` columns,
// which can be inserted as a `Date` or a `string` (without error),
// but will be parsed into a `Date` when fetched.
//
// Chaining `.returning('*').first()` is one way to ensure that the returned object
// has the same type as a fetched object. But it has a performance cost, and can still
// lead to a bad type assertion: for example, if o.createdAt were a `string`,
// by using `.returning('*').first()` that property would in fact be a `Date` when fetched.
// This could lead to nasty runtime errors not caught at compile-time, because
// the property would type asserted as a `string`.
//
// We use `.returning('*').first()` here because we are ignoring conflicts,
// and want to know what was "already there" in that case.
.returning('*')
.first();
// Knex does not like properties with undefined values so we strip them out
const override = _.pickBy({status: approvalStatus, waitingFor}, _.identity);
// This allows for for the insert method to override the existing status or waitingFor if desired
const model = _.isEmpty(override)
? await query.onConflict('objectiveId').ignore()
: await query.onConflict('objectiveId').merge(override);
// this avoids a UniqueViolationError being thrown
// and turns the query into an upsert. We are either:
// - re-approving the objective.
// - re-queueing the objective for approval
// Associate the objective with any channel that it references
// By inserting an ObjectiveChannel row for each channel
// Requires objective and channels to exist
await Promise.all(
extractReferencedChannels(objectiveToBeStored).map(
async value =>
ObjectiveChannelModel.query(trx)
.insert({objectiveId: id, channelId: value})
.onConflict(['objectiveId', 'channelId'])
.ignore() // this makes it an upsert
)
);
return model.toObjective<WalletObjective<O>>();
});
}
static async forId(
objectiveId: string,
tx: TransactionOrKnex
): Promise<WalletObjective<SupportedObjective>> {
const model = await ObjectiveModel.query(tx).findById(objectiveId);
return model.toObjective();
}
static async forIds(objectiveIds: string[], tx: TransactionOrKnex): Promise<WalletObjective[]> {
const model = await ObjectiveModel.query(tx).findByIds(objectiveIds);
return model.map(m => m.toObjective());
}
static async approve(
objectiveId: string,
tx: TransactionOrKnex
): Promise<WalletObjective<SupportedObjective>> {
return (
await ObjectiveModel.query(tx)
.findById(objectiveId)
.patch({status: 'approved'})
.returning('*')
.first()
).toObjective();
}
static async succeed(objectiveId: string, tx: TransactionOrKnex): Promise<ObjectiveModel> {
return ObjectiveModel.query(tx)
.findById(objectiveId)
.patch({status: 'succeeded'})
.returning('*')
.first();
}
static async failed(objectiveId: string, tx: TransactionOrKnex): Promise<ObjectiveModel> {
return ObjectiveModel.query(tx)
.findById(objectiveId)
.patch({status: 'failed'})
.returning('*')
.first();
}
static async updateProgressDate(
objectiveId: string,
tx: TransactionOrKnex
): Promise<WalletObjective<SupportedObjective>> {
return (
await ObjectiveModel.query(tx)
.findById(objectiveId)
.patch({progressLastMadeAt: new Date(Date.now())})
.returning('*')
.first()
).toObjective();
}
static async updateWaitingFor(
objectiveId: string,
waitingFor: WaitingFor,
tx: TransactionOrKnex
): Promise<WalletObjective<SupportedObjective>> {
return (
await ObjectiveModel.query(tx)
.findById(objectiveId)
.patch({progressLastMadeAt: new Date(), waitingFor})
.returning('*')
.first()
).toObjective();
}
static async approvedObjectiveIds(
targetChannelIds: string[],
tx: TransactionOrKnex
): Promise<string[]> {
// todo: make this more efficient
return (await this.forChannelIds(targetChannelIds, tx))
.filter(x => x.status === 'approved')
.map(x => x.objectiveId);
}
static async forChannelIds(
targetChannelIds: string[],
tx: TransactionOrKnex
): Promise<WalletObjective[]> {
const objectiveIds = (
await ObjectiveChannelModel.query(tx)
.column('objectiveId')
.select()
.whereIn('channelId', targetChannelIds)
).map(oc => oc.objectiveId);
return (await ObjectiveModel.query(tx).findByIds(objectiveIds)).map(m => m.toObjective());
}
toObjective<O extends SupportedObjective = SupportedObjective>(): WalletObjective<O> {
// Reconstruct the Objective, taking on trust that we inserted it properly
const o = {
type: this.type,
data: this.data,
participants: [] as SupportedObjective['participants'], // reinstate an empty participants array
} as O;
const walletObjective: WalletObjective<O> = {
...o,
objectiveId: this.objectiveId,
status: this.status,
createdAt: this.createdAt,
progressLastMadeAt: this.progressLastMadeAt,
waitingFor: this.waitingFor,
};
if (isSupportedObjective(o)) {
return walletObjective as WalletObjective<O>;
}
throw Error('unsupported');
}
} | the_stack |
import {
deployments,
ethers,
getNamedAccounts,
getUnnamedAccounts,
} from 'hardhat';
import {BigNumber} from 'ethers';
import {expect} from '../chai-setup';
import MerkleTree from '../../lib/merkleTree';
import {createClaimMerkleTree} from '../../data/giveaways/multi_giveaway_1/getClaims';
import helpers from '../../lib/merkleTreeHelper';
import {default as testData0} from '../../data/giveaways/multi_giveaway_1/claims_0_hardhat.json';
import {default as testData1} from '../../data/giveaways/multi_giveaway_1/claims_1_hardhat.json';
import {expectReceiptEventWithArgs, waitFor, withSnapshot} from '../utils';
const {createDataArrayMultiClaim} = helpers;
const ipfsHashString =
'0x78b9f42c22c3c8b260b781578da3151e8200c741c6b7437bafaff5a9df9b403e';
type Options = {
mint?: boolean;
sand?: boolean;
multi?: boolean;
mintSingleAsset?: number;
numberOfAssets?: number;
};
export const setupTestGiveaway = withSnapshot(
['Multi_Giveaway_1', 'Asset', 'Gems', 'Sand', 'Catalysts'],
async function (hre, options?: Options) {
const {network, getChainId} = hre;
const chainId = await getChainId();
const {mint, sand, multi, mintSingleAsset, numberOfAssets} = options || {};
const {
deployer,
assetBouncerAdmin,
landAdmin,
sandAdmin,
catalystMinter,
gemMinter,
} = await getNamedAccounts();
const otherAccounts = await getUnnamedAccounts();
const nftGiveawayAdmin = otherAccounts[0];
const others = otherAccounts.slice(1);
const sandContract = await ethers.getContract('Sand');
const assetContract = await ethers.getContract('Asset');
const speedGemContract = await ethers.getContract('Gem_SPEED');
const rareCatalystContract = await ethers.getContract('Catalyst_RARE');
await deployments.deploy('MockLand', {
from: deployer,
args: [sandContract.address, landAdmin],
deterministicDeployment: true, // Set a fixed address for MockLand, so that the address can be used in the test claim data
});
const sandContractAsAdmin = await sandContract.connect(
ethers.provider.getSigner(sandAdmin)
);
const SAND_AMOUNT = BigNumber.from(20000).mul('1000000000000000000');
await deployments.deploy('Test_Multi_Giveaway_1_with_ERC20', {
from: deployer,
contract: 'MultiGiveaway',
args: [nftGiveawayAdmin],
});
const giveawayContract = await ethers.getContract(
'Test_Multi_Giveaway_1_with_ERC20'
);
const giveawayContractAsAdmin = await giveawayContract.connect(
ethers.provider.getSigner(nftGiveawayAdmin)
);
// Supply SAND
if (sand) {
await sandContractAsAdmin.transfer(giveawayContract.address, SAND_AMOUNT);
}
// Supply Catalysts and Gems
await speedGemContract
.connect(ethers.provider.getSigner(gemMinter))
.mint(giveawayContract.address, 16);
await rareCatalystContract
.connect(ethers.provider.getSigner(catalystMinter))
.mint(giveawayContract.address, 8);
// Supply assets
const assetContractAsBouncerAdmin = await ethers.getContract(
'Asset',
assetBouncerAdmin
);
async function mintTestAssets(id: number, value: number) {
// Asset to be minted
const creator = others[0];
const packId = id;
const hash = ipfsHashString;
const supply = value;
const rarity = 1;
const owner = giveawayContract.address;
const data = '0x';
await assetContractAsBouncerAdmin.setBouncer(creator, true);
const assetContractAsCreator = await assetContract.connect(
ethers.provider.getSigner(creator)
);
const receipt = await waitFor(
assetContractAsCreator.mint(
creator,
packId,
hash,
supply,
rarity,
owner,
data
)
);
const transferEvent = await expectReceiptEventWithArgs(
receipt,
'TransferSingle'
);
const balanceAssetId = await assetContract['balanceOf(address,uint256)'](
giveawayContract.address,
transferEvent.args[3]
);
expect(balanceAssetId).to.equal(supply);
return transferEvent.args[3].toString(); // asset ID
}
const landContract = await ethers.getContract('MockLand');
// Supply lands to contract for testing
async function mintTestLands() {
const landContractAsAdmin = await landContract.connect(
ethers.provider.getSigner(landAdmin)
);
const owner = giveawayContract.address;
for (let i = 0; i < 18; i++) {
await landContractAsAdmin.mint(owner, i);
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function mintNewAssetIds(dataSet: any) {
return await Promise.all(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
dataSet.map(async (claim: any) => {
if (claim.erc1155) {
const newAsset = {
ids: [],
values: [],
contractAddress: '',
};
const newClaim = {
...claim,
erc1155: await Promise.all(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
claim.erc1155.map(async (asset: any, assetIndex: number) => {
newAsset.ids = await Promise.all(
asset.ids.map(
async (assetPackId: number, index: number) =>
await mintTestAssets(assetPackId, asset.values[index])
)
);
(newAsset.values = claim.erc1155[assetIndex].values),
(newAsset.contractAddress =
claim.erc1155[assetIndex].contractAddress);
return newAsset;
})
),
};
return newClaim;
} else return claim;
})
);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function assignReservedAddressToClaim(dataSet: any) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return dataSet.map(async (claim: any) => {
claim.to = others[0];
return claim;
});
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function assignTestContractAddressesToClaim(dataSet: any) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return dataSet.map(async (claim: any) => {
if (claim.erc1155) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
claim.erc1155.map(async (asset: any) => {
asset.contractAddress = assetContract.address;
return asset;
});
}
if (claim.erc721) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
claim.erc721.map(async (land: any) => {
land.contractAddress = landContract.address;
return land;
});
}
if (claim.erc20) {
if (claim.erc20.amounts.length === 1)
claim.erc20.contractAddresses = [sandContract.address];
if (claim.erc20.amounts.length === 3)
claim.erc20.contractAddresses = [
sandContract.address,
speedGemContract.address,
rareCatalystContract.address,
];
}
return claim;
});
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function setAssets(dataSet: any, amount: number) {
dataSet[0].erc1155[0].ids = [];
dataSet[0].erc1155[0].values = [];
for (let i = 0; i < amount; i++) {
// a big id to avoid collision with other setups
dataSet[0].erc1155[0].ids.push(i + 1000);
dataSet[0].erc1155[0].values.push(5);
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let dataWithIds0: any = JSON.parse(JSON.stringify(testData0));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let dataWithIds1: any = JSON.parse(JSON.stringify(testData1));
// To ensure the same address for others[0] for all tests
assignReservedAddressToClaim(dataWithIds0);
assignReservedAddressToClaim(dataWithIds1);
// To ensure the claim data works for all developers
assignTestContractAddressesToClaim(dataWithIds0);
assignTestContractAddressesToClaim(dataWithIds1);
if (numberOfAssets) {
setAssets(dataWithIds0, numberOfAssets);
}
if (mint) {
const claimsWithAssetIds0 = await mintNewAssetIds(dataWithIds0);
dataWithIds0 = claimsWithAssetIds0;
if (multi) {
const claimsWithAssetIds1 = await mintNewAssetIds(dataWithIds1);
dataWithIds1 = claimsWithAssetIds1;
}
await mintTestLands();
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function mintSingleAssetWithId(claim: any) {
const newAsset = {
ids: [],
values: [],
contractAddress: '',
};
return {
...claim,
erc1155: await Promise.all(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
claim.erc1155.map(async (asset: any, assetIndex: number) => {
newAsset.ids = await Promise.all(
asset.ids.map(
async (assetPackId: number, index: number) =>
await mintTestAssets(assetPackId, asset.values[index])
)
);
(newAsset.values = claim.erc1155[assetIndex].values),
(newAsset.contractAddress =
claim.erc1155[assetIndex].contractAddress);
return newAsset;
})
),
};
}
if (mintSingleAsset) {
await mintTestLands();
// Set up blank testData for thousands of users
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const emptyData: any = [];
for (let i = 0; i < 1; i++) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const claim: any = {
to: others[0],
erc1155: [
{
ids: [i],
values: [1],
contractAddress: assetContract.address,
},
],
erc721: [
{
ids: [1],
contractAddress: landContract.address,
},
],
erc20: {
amounts: [200],
contractAddresses: [sandContract.address],
},
};
emptyData.push(await mintSingleAssetWithId(claim));
}
for (let i = 1; i < mintSingleAsset; i++) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const claim: any = {
to: others[0],
erc1155: [
{
ids: [i],
values: [1],
contractAddress: assetContract.address,
},
],
erc721: [
{
ids: [1],
contractAddress: landContract.address,
},
],
erc20: {
amounts: [200],
contractAddresses: [sandContract.address],
},
};
emptyData.push(claim);
}
dataWithIds0 = emptyData;
}
// Set up tree with test assets for each applicable giveaway
const {
claims: claims0,
merkleRootHash: merkleRootHash0,
} = createClaimMerkleTree(network.live, chainId, dataWithIds0);
const allMerkleRoots = [];
const allClaims = [claims0];
const allTrees = [];
// Single giveaway
const hashArray = createDataArrayMultiClaim(claims0);
await giveawayContractAsAdmin.addNewGiveaway(
merkleRootHash0,
'0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF'
); // no expiry
allMerkleRoots.push(merkleRootHash0);
allTrees.push(new MerkleTree(hashArray));
// Multi giveaway
if (multi) {
const {
claims: claims1,
merkleRootHash: merkleRootHash1,
} = createClaimMerkleTree(network.live, chainId, dataWithIds1);
allClaims.push(claims1);
allMerkleRoots.push(merkleRootHash1);
const hashArray2 = createDataArrayMultiClaim(claims1);
allTrees.push(new MerkleTree(hashArray2));
await giveawayContractAsAdmin.addNewGiveaway(
merkleRootHash1,
'0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF'
); // no expiry
}
return {
giveawayContract,
sandContract,
assetContract,
landContract,
speedGemContract,
rareCatalystContract,
others,
allTrees,
allClaims,
nftGiveawayAdmin,
allMerkleRoots,
};
}
); | the_stack |
import * as path from 'path';
import * as fs from 'fs-extra';
import * as Promise from 'bluebird';
import * as _ from 'lodash';
import * as debug from 'debug';
import { memoryFile } from '../../../help';
import RasterFactory from './factories/raster';
import { dev } from '../../utils';
import { watchImagesPath } from '../../utils/constant';
/**
* Wrap with promises.
*/
Promise.promisifyAll(fs);
/**
* Plugin constants.
*/
const RELATIVE_TO_RULE = 'rule';
const BACKGROUND = 'background';
const BACKGROUND_IMAGE = 'background-image';
const ONE_SPACE = ' ';
const COMMENT_TOKEN_PREFIX = '@replace|';
const GROUP_DELIMITER = '.';
const GROUP_MASK = '*';
const TYPE_RASTER = 'raster';
const TYPE_VECTOR = 'vector';
/**
* Plugin defaults.
*/
export const defaults = {
basePath: './',
stylesheetPath: null,
spritePath: './',
relativeTo: 'file',
filterBy: [],
groupBy: [],
retina: false,
hooks: {
onSaveSpritesheet: null,
onUpdateRule: null
},
spritesmith: {
engine: 'pixelsmith',
algorithm: 'binary-tree',
padding: 0,
engineOpts: {},
exportOpts: {}
},
svgsprite: {
mode: {
css: {
dimensions: true,
bust: false,
render: {
css: true
}
}
},
shape: {
id: {
generator(name: any, file: any) {
// eslint-disable-next-line no-buffer-constructor
return new Buffer(file.path).toString('base64');
}
}
},
svg: {
precision: 5
}
},
verbose: false
};
/**
* Prepares the filter functions.
* @param {Object} opts
* @param {Result} result
* @return
*/
export function prepareFilterBy(opts: any) {
if (_.isFunction(opts.filterBy)) {
opts.filterBy = [opts.filterBy];
}
// Filter non existing images
opts.filterBy.unshift((image: any) => {
return (fs as any).statAsync(image.path).catch(() => {
const message = `Skip ${image.url} because doesn't exist.`;
opts.logger(message);
throw new Error(message);
});
});
}
/**
* Prepares the group functions.
* @param {Object} opts
* @return
*/
export function prepareGroupBy(opts: any) {
if (_.isFunction(opts.groupBy)) {
opts.groupBy = [opts.groupBy];
}
// Group by retina ratio
if (opts.retina) {
opts.groupBy.unshift((image: any) => {
if (image.retina) {
return Promise.resolve(`@${image.ratio}x`);
}
return Promise.reject(new Error('Not a retina image.'));
});
}
// Group by type - 'vector' or 'raster'
opts.groupBy.unshift((image: any) => {
if (/^\.svg/.test(path.extname(image.path))) {
return Promise.resolve(TYPE_VECTOR);
}
return Promise.resolve(TYPE_RASTER);
});
}
/**
* Walks the given CSS string and extracts all images
* that can be converted to sprite.
* @param {Node} root
* @param {Object} opts
* @param {Result} result
* @return {Promise}
*/
export function extractImages(root: any, opts: any): any {
let images: any = [];
opts.logger('Extracting the images...');
// Search for background & background image declartions
root.walkRules((rule: any) => {
const styleFilePath =
opts.relativeTo === RELATIVE_TO_RULE ? rule.source.input.file : root.source.input.file;
const ABSOLUTE_URL = /^\//;
// The host object of found image
const image = {
path: null,
url: null,
originalUrl: null,
retina: false,
ratio: 1,
groups: [],
token: '',
styleFilePath
};
// Manipulate only rules with image in them
if (hasImageInRule(rule.toString())) {
const imageUrl = getImageUrl(rule.toString());
(image as any).originalUrl = imageUrl[0];
(image as any).url = imageUrl[1];
if (isImageSupported(image.url)) {
// Search for retina images
if (opts.retina && isRetinaImage(image.url)) {
image.retina = true;
image.ratio = getRetinaRatio(image.url);
}
// Get the filesystem path to the image
if (ABSOLUTE_URL.test((image as any).url)) {
(image as any).path = path.resolve(opts.basePath + image.url);
} else {
(image as any).path = path.resolve(path.dirname(styleFilePath), (image as any).url);
}
images.push(image);
} else {
opts.logger(`Skip ${image.url} because isn't supported.`);
}
}
});
// Remove duplicates and empty values
images = _.uniqBy(images, 'path');
return Promise.resolve([opts, images]);
}
/**
* Apply filterBy functions over collection of exported images.
* @param {Object} opts
* @param {Array} images
* @return {Promise}
*/
export function applyFilterBy(opts: any, images: any) {
opts.logger('Applying the filters...');
return Promise.reduce(
opts.filterBy,
(images: any, filterFn: any) => {
return Promise.filter(
images,
(image: any) => {
return filterFn(image)
.then(() => true)
.catch(() => false);
},
{ concurrency: 1 }
);
},
images
).then((images: any) => [opts, images]);
}
/**
* Apply groupBy functions over collection of exported images.
* @param {Object} opts
* @param {Array} images
* @return {Promise}
*/
export function applyGroupBy(opts: any, images: any) {
opts.logger('Applying the groups...');
return Promise.reduce(
opts.groupBy,
(images: any, groupFn: any) => {
return Promise.map(images, (image: any) => {
return groupFn(image)
.then((group: any) => {
image.groups.push(group);
return image;
})
.catch(() => image);
});
},
images
).then((images: any) => [opts, images]);
}
/**
* Replaces the background declarations that needs to be updated
* with a sprite image.
* @param {Node} root
* @param {Object} opts
* @param {Array} images
* @return {Promise}
*/
export function setTokens(root: any, opts: any, images: any) {
return new Promise((resolve: any) => {
root.walkDecls(/^background(-image)?$/, (decl: any) => {
const rule = decl.parent;
const ruleStr = rule.toString();
let url;
let image;
let color;
let commentDecl;
if (!hasImageInRule(ruleStr)) {
return;
}
// Manipulate only rules with image in them
url = getImageUrl(ruleStr)[1];
image = _.find(images, { url });
if (!image) {
return;
}
// Remove all necessary background declarations
rule.walkDecls(/^background-(repeat|size|position)$/, (decl: any) => decl.remove());
// Extract color to background-color property
if (decl.prop === BACKGROUND) {
color = getColor(decl.value);
if (color) {
decl.cloneAfter({
prop: 'background-color',
value: color
}).raws.before = ONE_SPACE;
}
}
// Replace with comment token
if (_.includes([BACKGROUND, BACKGROUND_IMAGE], decl.prop)) {
commentDecl = decl.cloneAfter({
type: 'comment',
text: image.url
});
commentDecl.raws.left = `${ONE_SPACE}${COMMENT_TOKEN_PREFIX}`;
(image as any).token = commentDecl.toString();
decl.remove();
}
});
resolve([root, opts, images]);
});
}
/**
* Process the images through spritesmith module.
* @param {Object} opts
* @param {Array} images
* @return {Promise}
*/
export function runSpritesmith(opts: any, images: any) {
opts.logger('Generating the spritesheets...');
return new Promise((resolve: any, reject: any) => {
const promises: any = _.chain(images)
.groupBy((image) => {
const tmp: any = image.groups.map(maskGroup(true));
tmp.unshift('_');
return tmp.join(GROUP_DELIMITER);
})
.map((images: any, tmp: any) => {
if (dev()) {
let map: any = {};
if (memoryFile.existsSync(watchImagesPath)) {
const filemap = memoryFile.readFileSync(watchImagesPath, 'utf-8');
map = JSON.parse(filemap);
}
images.forEach((image: any) => {
if (map[image.path]) {
map[image.path].push(image.styleFilePath);
} else {
map[image.path] = [image.styleFilePath];
}
});
memoryFile.writeFileSync(watchImagesPath, JSON.stringify(map));
}
return RasterFactory(opts, images).then((spritesheet: any) => {
// Remove the '_', 'raster' or 'vector' prefixes
tmp = tmp.split(GROUP_DELIMITER).splice(2);
spritesheet.groups = tmp.map(maskGroup());
return spritesheet;
});
})
.value();
Promise.all(promises)
.then((spritesheets: any) => {
resolve([opts, images, spritesheets]);
})
.catch((err: any) => {
reject(err);
});
});
}
/**
* Saves the spritesheets to the disk.
* @param {Object} opts
* @param {Array} images
* @param {Array} spritesheets
* @return {Promise}
*/
export function saveSpritesheets(opts: any, images: any, spritesheets: any) {
opts.logger('Saving the spritesheets...');
return Promise.each(spritesheets, (spritesheet: any) => {
return (_.isFunction(opts.hooks.onSaveSpritesheet)
? Promise.resolve(opts.hooks.onSaveSpritesheet(opts, spritesheet))
: Promise.resolve(makeSpritesheetPath(opts, spritesheet))
).then((res: any) => {
if (!res) {
throw new Error('postcss-sprites: Spritesheet requires a relative path.');
}
if (_.isString(res)) {
spritesheet.path = res;
} else {
_.assign(spritesheet, res);
}
spritesheet.path = spritesheet.path.replace(/\\/g, '/');
return (fs as any).outputFileAsync(spritesheet.path, spritesheet.image);
});
}).then((spritesheets: any) => {
return [opts, images, spritesheets];
});
}
/**
* Map spritesheet props to every image.
* @param {Object} opts
* @param {Array} images
* @param {Array} spritesheets
* @return {Promise}
*/
export function mapSpritesheetProps(opts: any, images: any, spritesheets: any) {
_.forEach(spritesheets, ({ coordinates, path, properties }: any) => {
const spritePath = path;
const spriteWidth = properties.width;
const spriteHeight = properties.height;
_.forEach(coordinates, (coords, imagePath) => {
(_.chain(images).find(['path', imagePath]) as any)
.merge({
coords,
spritePath,
spriteWidth,
spriteHeight
})
.value();
});
});
return Promise.resolve([opts, images, spritesheets]);
}
/**
* Updates the CSS references.
* @param {Node} root
* @param {Object} opts
* @param {Array} images
* @param {Array} spritesheets
* @return {Promise}
*/
export function updateReferences(root: any, opts: any, images: any, spritesheets: any) {
opts.logger('Replacing the references...');
root.walkComments((comment: any) => {
let rule;
let image: any;
// Manipulate only comment tokens
if (isToken(comment.toString())) {
rule = comment.parent;
image = _.find(images, { url: comment.text });
// Update the rule with background declarations
if (image) {
// Generate CSS url to sprite
(image as any).spriteUrl = path.relative(
opts.stylesheetPath || path.dirname(root.source.input.file),
image.spritePath
);
image.spriteUrl = image.spriteUrl.split(path.sep).join('/');
// Update rule
if (_.isFunction(opts.hooks.onUpdateRule)) {
opts.hooks.onUpdateRule(rule, comment, image);
} else {
updateRule(rule, comment, image);
}
// Cleanup token
comment.remove();
}
}
});
return Promise.resolve([root, opts, images, spritesheets]);
}
/**
* Update an single CSS rule.
* @param {Node} rule
* @param {Node} token
* @param {Object} image
* @return
*/
export function updateRule(rule: any, token: any, image: any) {
const { ratio, coords, spriteUrl, spriteWidth, spriteHeight } = image;
const posX = -1 * Math.abs(coords.x / ratio);
const posY = -1 * Math.abs(coords.y / ratio);
const sizeX = spriteWidth / ratio;
const sizeY = spriteHeight / ratio;
token
.cloneAfter({
type: 'decl',
prop: 'background-image',
value: `url(${spriteUrl})`
})
.cloneAfter({
prop: 'background-position',
value: `${posX}px ${posY}px`
})
.cloneAfter({
prop: 'background-size',
value: `${sizeX}px ${sizeY}px`
});
}
/// //////////////////////
// ----- Helpers ----- //
/// //////////////////////
/**
* Checks for image url in the given CSS rules.
* @param {String} rule
* @return {Boolean}
*/
export function hasImageInRule(rule: any) {
return /background[^:]*.*url[^;]+/gi.test(rule);
}
/**
* Extracts the url of image from the given rule.
* @param {String} rule
* @return {Array}
*/
export function getImageUrl(rule: any) {
const matches = /url(?:\(['"]?)(.*?)(?:['"]?\))/gi.exec(rule);
let original = '';
let normalized = '';
if (matches) {
original = matches[1];
normalized = original
.replace(/['"]/gi, '') // replace all quotes
.replace(/\?.*$/gi, ''); // replace query params
}
return [original, normalized];
}
/**
* Checks whether the image is supported.
* @param {String} url
* @return {Boolean}
*/
export function isImageSupported(url: any) {
const http = /^http[s]?/gi;
const base64 = /^data\:image/gi;
const svg = /\.svg$/gi;
return !http.test(url) && !base64.test(url) && !svg.test(url);
}
/**
* Checks whether the image is retina.
* @param {String} url
* @return {Boolean}
*/
export function isRetinaImage(url: any) {
return /@(\d)x\.[a-z]{3,4}$/gi.test(url);
}
/**
* Extracts the retina ratio of image.
* @param {String} url
* @return {Number}
*/
export function getRetinaRatio(url: any) {
const matches = /@(\d)x\.[a-z]{3,4}$/gi.exec(url);
if (!matches) {
return 1;
}
return parseInt(matches[1], 10);
}
/**
* Extracts the color from background declaration.
* @param {String} declValue
* @return {String?}
*/
export function getColor(declValue: any) {
const regexes = ['(#([0-9a-f]{3}){1,2})', 'rgba?\\([^\\)]+\\)'];
let match = null;
_.forEach(regexes, (regex: any) => {
regex = new RegExp(regex, 'gi');
if (regex.test(declValue)) {
match = declValue.match(regex)[0];
}
});
return match;
}
/**
* Simple helper to avoid collisions with group names.
* @param {Boolean} toggle
* @return {Function}
*/
export function maskGroup(toggle = false) {
const input = new RegExp(`[${toggle ? GROUP_DELIMITER : GROUP_MASK}]`, 'gi');
const output = toggle ? GROUP_MASK : GROUP_DELIMITER;
return (value: any) => value.replace(input, output);
}
/**
* Generate the filepath to the sprite.
* @param {Object} opts
* @param {Object} spritesheet
* @return {String}
*/
export function makeSpritesheetPath(opts: any, { groups, extension }: any) {
return path.join(opts.spritePath, ['sprite', ...groups, extension].join('.'));
}
/**
* Check whether the comment is token that
* should be replaced with background declarations.
* @param {String} commentValue
* @return {Boolean}
*/
export function isToken(commentValue: any) {
return commentValue.indexOf(COMMENT_TOKEN_PREFIX) > -1;
}
/**
* Create a logger that can be disabled in runtime.
*
* @param {Boolean} enabled
* @return {Function}
*/
export function createLogger(enabled: any) {
if (enabled) {
debug.enable('postcss-sprites');
}
return debug('postcss-sprites');
} | the_stack |
import React from "react";
import App from "next/app";
import Head from "next/head";
import { Global, css } from "@emotion/core";
import { View } from "react-native";
import RView, { MediaRule } from "emotion-native-media-query";
import {
STRINGS,
BREAKPOINTS,
COLORS,
STANFORD_COLORS,
FONTS,
FOCUS_STATES,
LINKS,
srAndTabOnlyDropdown,
} from "helpers/constants";
import { SectionStyle } from "components/Section";
import { getBorderValue } from "components/pages/HomePage/getBorderValue";
import { TopSection } from "components/site-header/TopSection";
import { TopBarLinks } from "components/site-header/TopBarLinks";
import { FooterContent } from "components/FooterContent";
import DonationForm from "components/DonationForm";
import Link from "../components/Link";
const containerRStyle: any = {
[MediaRule.MinWidth]: {
0: {
margin: "0 auto",
width: "100%",
flexWrap: "wrap",
},
[BREAKPOINTS.TABLET]: {},
[BREAKPOINTS.DESKTOP]: {
maxWidth: BREAKPOINTS.DESKTOP,
},
1300: {
maxWidth: 1300,
},
},
};
const HeaderLogo: React.ElementType = () => {
return (
<View style={{ padding: 15 }}>
<RView
style={{
height: 60,
justifyContent: "center",
alignItems: "center",
}}
>
<h1
css={{
textAlign: "center",
margin: 0,
display: "flex",
justifyContent: "center",
height: "100%",
}}
>
<Link href="/" as="/">
<a
rel="home"
id="tsd-logo"
style={{
display: "flex",
alignItems: "center",
height: "100%",
}}
title="The Stanford Daily"
aria-label="Go to homepage"
css={css`
${FOCUS_STATES.BLACK_OUTLINE}
`}
>
<img
src="https://raw.githubusercontent.com/TheStanfordDaily/stanforddaily-graphic-assets/main/DailyLogo/DailyLogo.png"
alt="The words 'The Stanford Daily' in Canterbury font"
css={{
imageRendering: "-webkit-optimize-contrast",
height: "auto",
width: "auto",
maxHeight: "100%",
maxWidth: "100%",
}}
/>
</a>
</Link>
<Link href="/" as="/">
<a
id="tsd-logo-dataviz"
style={{
display: "none",
alignItems: "center",
height: "100%",
}}
aria-label="Go to homepage"
css={css`
${FOCUS_STATES.BLACK_OUTLINE}
`}
>
<img
src="/static/94305-logo.png"
alt="The Stanford Daily 94305 data team logo"
css={{
height: "auto",
width: "120%",
maxWidth: "100vw",
}}
/>
</a>
</Link>
</h1>
</RView>
</View>
);
};
// Content from top of site to bottom of top section; same on every page
const SiteHeader: React.ElementType = (props: any) => {
return (
<>
<RView
style={{
backgroundColor: "#eee",
}}
>
<RView
style={{
margin: "0 !important",
maxWidth: "none !important",
}}
rStyle={{
...containerRStyle,
}}
>
<a
css={css`
${srAndTabOnlyDropdown}
`}
href={LINKS.ACCESSIBILITY_STATEMENT}
>
Accessibility statement
</a>
<a
css={css`
${srAndTabOnlyDropdown}
`}
className="skip-to-content-link"
href="#main-content"
>
Skip to main content
</a>
<DonationForm large={true} />
</RView>
</RView>
<RView
WebTag="header"
style={{
backgroundColor: STANFORD_COLORS.WHITE,
}}
rStyle={{
[MediaRule.MinWidth]: {
[BREAKPOINTS.TABLET]: {
...getBorderValue("Bottom"),
},
},
}}
{...props}
>
<RView
style={{
order: 1,
}}
rStyle={{
[MediaRule.MinWidth]: {
[BREAKPOINTS.TABLET]: {
order: 2,
},
},
}}
>
<HeaderLogo />
</RView>
<RView
id="tsd-navbar"
style={{
order: 2,
maxWidth: "100vw",
backgroundColor: STANFORD_COLORS.CARDINAL_RED,
}}
rStyle={{
[MediaRule.MinWidth]: {
[BREAKPOINTS.TABLET]: {
order: 1,
},
},
}}
>
<RView
style={{
flexDirection: "row",
alignItems: "center",
}}
rStyle={containerRStyle}
>
<TopBarLinks itemStyle={{ color: STANFORD_COLORS.WHITE }} />
</RView>
</RView>
<RView
style={{ order: 3, overflow: "hidden", ...getBorderValue("Top") }}
rStyle={containerRStyle}
>
<TopSection />
</RView>
</RView>
</>
);
};
// Footer content that appears on every page
const SiteFooter: React.ElementType = ({ style, ...props }: any) => {
// TODO: ADD FONTS CREDIT
return (
<footer
css={{
backgroundColor: STANFORD_COLORS.CARDINAL_RED,
...style,
}}
{...props}
>
<RView rStyle={containerRStyle}>
<SectionStyle>
<FooterContent
style={{
color: STANFORD_COLORS.WHITE,
}}
/>
</SectionStyle>
</RView>
</footer>
);
};
const Layout: React.ElementType = (props: any) => {
const { children } = props;
return <RView rStyle={containerRStyle}>{children}</RView>;
};
// Everything
export default class MyApp extends App {
render(): JSX.Element {
const { Component, pageProps, router } = this.props;
let includeHeaderAndFooter = true;
if (router.query[STRINGS._MAIN_ONLY_QUERY] != null) {
includeHeaderAndFooter = false;
}
return (
<div
id="body-main"
css={{
width: "100%",
}}
>
<Global
styles={{
"body, button, input, optgroup, select, textarea": {
...FONTS.CONTENT,
},
"#tsd-logo-dataviz": {
display: "none",
},
a: {
color: COLORS.LINK.DEFAULT,
textDecoration: "none",
"&:visited": {
color: COLORS.LINK.VISITED,
},
"&:hover, &:focus, &:active": {
color: COLORS.LINK.HOVER,
textDecoration: "underline",
},
"&:focus": {
outline: "thin dotted",
},
"&:hover, &:active": {
outline: 0,
},
},
}}
/>
<Head>
<link
href="https://fonts.googleapis.com/css?family=Libre+Baskerville:400,700|PT+Serif:400,400i&display=swap"
rel="stylesheet"
/>
<link href="/static/fonts.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
{/* We have to embed Google Analytics this way (and not through react-ga) because react-ga requires
Next JS's javascript code to be running -- and we had to turn off the Next JS javascript code
on article pages in order to fix some integration issues with Ezoic.
*/}
<script
async
src="https://www.googletagmanager.com/gtag/js?id=UA-5773957-1"
></script>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-5773957-1');
`,
}}
/>
{/* Flytedesk Digital script */}
<script
type="text/javascript"
dangerouslySetInnerHTML={{
__html: `
(function (w, d, s, p) { let f = d.getElementsByTagName(s)[0], j = d.createElement(s); j.id = 'flytedigital'; j.async = true; j.src = 'https://digital.flytedesk.com/js/head.js#' + p; f.parentNode.insertBefore(j, f); })(window, document, 'script', '8b8311a6-73a1-4434-a650-866bea833079');
`,
}}
/>
{/* Accessibility button on all site pages */}
<script
type="text/javascript"
dangerouslySetInnerHTML={{
__html: `
(function(d){
var s = d.createElement("script");
/* uncomment the following line to override default position*/
s.setAttribute("data-position", 3);
/* uncomment the following line to override default size (values: small, large)*/
/* s.setAttribute("data-size", "small");*/
/* uncomment the following line to override default language (e.g., fr, de, es, he, nl, etc.)*/
/* s.setAttribute("data-language", "language");*/
/* uncomment the following line to override color set via widget (e.g., #053f67)*/
s.setAttribute("data-color", "#8C1516");
/* uncomment the following line to override type set via widget (1=person, 2=chair, 3=eye, 4=text)*/
/* s.setAttribute("data-type", "1");*/
s.setAttribute("data-statement_text:", "Our Accessibility Statement");
s.setAttribute("data-statement_url", "https://stanforddaily.com/accessibility/");
/* uncomment the following line to override support on mobile devices*/
/* s.setAttribute("data-mobile", true);*/
/* uncomment the following line to set custom trigger action for accessibility menu*/
/* s.setAttribute("data-trigger", "triggerId")*/
s.setAttribute("data-account", "r1mV0mjVt0");
s.setAttribute("src", "https://cdn.userway.org/widget.js");
(d.body || d.head).appendChild(s);
})
(document)
`,
}}
/>
{/* Content that appears on site pages */}
</Head>
{/* `body` `overflow: initial` is added in order for `position: "sticky"` below to work. */}
<Global
styles={css`
html {
font-size: 0.8em;
}
body {
overflow: initial;
}
.visible-mobile {
@media (min-width: ${BREAKPOINTS.TABLET}px) {
display: none;
}
}
.hidden-mobile {
@media (max-width: ${BREAKPOINTS.MAX_WIDTH.TABLET}px) {
display: none;
}
}
`}
/>
{includeHeaderAndFooter && (
<SiteHeader id="site-header" router={router} />
)}
<Layout>
<main id="main-content">
<Component {...pageProps} />
</main>
</Layout>
{includeHeaderAndFooter && <SiteFooter id="site-footer" />}
</div>
);
}
} | the_stack |
// Keyboard is in several identical (mirrored) banks.
const BANK_SIZE = 0x100;
const BANK_COUNT = 4;
const BEGIN_ADDR = 0x3800;
const END_ADDR = BEGIN_ADDR + BANK_SIZE*BANK_COUNT;
const KEY_DELAY_CLOCK_CYCLES = 50000;
// Whether to force a Shift key, and how.
enum ShiftState {
NEUTRAL, FORCE_DOWN, FORCE_UP,
}
// For each ASCII character or key we keep track of how to trigger it.
class KeyInfo {
public byteIndex: number;
public bitNumber: number;
public shiftForce: ShiftState;
constructor(byteIndex: number, bitNumber: number, shiftForce: ShiftState) {
this.byteIndex = byteIndex;
this.bitNumber = bitNumber;
this.shiftForce = shiftForce;
}
}
// A queued-up key.
class KeyActivity {
public keyInfo: KeyInfo;
public isPressed: boolean;
constructor(keyInfo: KeyInfo, isPressed: boolean) {
this.keyInfo = keyInfo;
this.isPressed = isPressed;
}
}
// Map from ASCII or special key to the info of which byte and bit it's mapped
// to, and whether to force Shift.
const keyMap = new Map<string, KeyInfo>();
// http://www.trs-80.com/trs80-zaps-internals.htm#keyboard13
keyMap.set("@", new KeyInfo(0, 0, ShiftState.FORCE_UP));
keyMap.set("`", new KeyInfo(0, 0, ShiftState.FORCE_DOWN));
keyMap.set("A", new KeyInfo(0, 1, ShiftState.FORCE_DOWN));
keyMap.set("B", new KeyInfo(0, 2, ShiftState.FORCE_DOWN));
keyMap.set("C", new KeyInfo(0, 3, ShiftState.FORCE_DOWN));
keyMap.set("D", new KeyInfo(0, 4, ShiftState.FORCE_DOWN));
keyMap.set("E", new KeyInfo(0, 5, ShiftState.FORCE_DOWN));
keyMap.set("F", new KeyInfo(0, 6, ShiftState.FORCE_DOWN));
keyMap.set("G", new KeyInfo(0, 7, ShiftState.FORCE_DOWN));
keyMap.set("H", new KeyInfo(1, 0, ShiftState.FORCE_DOWN));
keyMap.set("I", new KeyInfo(1, 1, ShiftState.FORCE_DOWN));
keyMap.set("J", new KeyInfo(1, 2, ShiftState.FORCE_DOWN));
keyMap.set("K", new KeyInfo(1, 3, ShiftState.FORCE_DOWN));
keyMap.set("L", new KeyInfo(1, 4, ShiftState.FORCE_DOWN));
keyMap.set("M", new KeyInfo(1, 5, ShiftState.FORCE_DOWN));
keyMap.set("N", new KeyInfo(1, 6, ShiftState.FORCE_DOWN));
keyMap.set("O", new KeyInfo(1, 7, ShiftState.FORCE_DOWN));
keyMap.set("P", new KeyInfo(2, 0, ShiftState.FORCE_DOWN));
keyMap.set("Q", new KeyInfo(2, 1, ShiftState.FORCE_DOWN));
keyMap.set("R", new KeyInfo(2, 2, ShiftState.FORCE_DOWN));
keyMap.set("S", new KeyInfo(2, 3, ShiftState.FORCE_DOWN));
keyMap.set("T", new KeyInfo(2, 4, ShiftState.FORCE_DOWN));
keyMap.set("U", new KeyInfo(2, 5, ShiftState.FORCE_DOWN));
keyMap.set("V", new KeyInfo(2, 6, ShiftState.FORCE_DOWN));
keyMap.set("W", new KeyInfo(2, 7, ShiftState.FORCE_DOWN));
keyMap.set("X", new KeyInfo(3, 0, ShiftState.FORCE_DOWN));
keyMap.set("Y", new KeyInfo(3, 1, ShiftState.FORCE_DOWN));
keyMap.set("Z", new KeyInfo(3, 2, ShiftState.FORCE_DOWN));
keyMap.set("a", new KeyInfo(0, 1, ShiftState.FORCE_UP));
keyMap.set("b", new KeyInfo(0, 2, ShiftState.FORCE_UP));
keyMap.set("c", new KeyInfo(0, 3, ShiftState.FORCE_UP));
keyMap.set("d", new KeyInfo(0, 4, ShiftState.FORCE_UP));
keyMap.set("e", new KeyInfo(0, 5, ShiftState.FORCE_UP));
keyMap.set("f", new KeyInfo(0, 6, ShiftState.FORCE_UP));
keyMap.set("g", new KeyInfo(0, 7, ShiftState.FORCE_UP));
keyMap.set("h", new KeyInfo(1, 0, ShiftState.FORCE_UP));
keyMap.set("i", new KeyInfo(1, 1, ShiftState.FORCE_UP));
keyMap.set("j", new KeyInfo(1, 2, ShiftState.FORCE_UP));
keyMap.set("k", new KeyInfo(1, 3, ShiftState.FORCE_UP));
keyMap.set("l", new KeyInfo(1, 4, ShiftState.FORCE_UP));
keyMap.set("m", new KeyInfo(1, 5, ShiftState.FORCE_UP));
keyMap.set("n", new KeyInfo(1, 6, ShiftState.FORCE_UP));
keyMap.set("o", new KeyInfo(1, 7, ShiftState.FORCE_UP));
keyMap.set("p", new KeyInfo(2, 0, ShiftState.FORCE_UP));
keyMap.set("q", new KeyInfo(2, 1, ShiftState.FORCE_UP));
keyMap.set("r", new KeyInfo(2, 2, ShiftState.FORCE_UP));
keyMap.set("s", new KeyInfo(2, 3, ShiftState.FORCE_UP));
keyMap.set("t", new KeyInfo(2, 4, ShiftState.FORCE_UP));
keyMap.set("u", new KeyInfo(2, 5, ShiftState.FORCE_UP));
keyMap.set("v", new KeyInfo(2, 6, ShiftState.FORCE_UP));
keyMap.set("w", new KeyInfo(2, 7, ShiftState.FORCE_UP));
keyMap.set("x", new KeyInfo(3, 0, ShiftState.FORCE_UP));
keyMap.set("y", new KeyInfo(3, 1, ShiftState.FORCE_UP));
keyMap.set("z", new KeyInfo(3, 2, ShiftState.FORCE_UP));
keyMap.set("0", new KeyInfo(4, 0, ShiftState.FORCE_UP));
keyMap.set("1", new KeyInfo(4, 1, ShiftState.FORCE_UP));
keyMap.set("2", new KeyInfo(4, 2, ShiftState.FORCE_UP));
keyMap.set("3", new KeyInfo(4, 3, ShiftState.FORCE_UP));
keyMap.set("4", new KeyInfo(4, 4, ShiftState.FORCE_UP));
keyMap.set("5", new KeyInfo(4, 5, ShiftState.FORCE_UP));
keyMap.set("6", new KeyInfo(4, 6, ShiftState.FORCE_UP));
keyMap.set("7", new KeyInfo(4, 7, ShiftState.FORCE_UP));
keyMap.set("8", new KeyInfo(5, 0, ShiftState.FORCE_UP));
keyMap.set("9", new KeyInfo(5, 1, ShiftState.FORCE_UP));
keyMap.set("_", new KeyInfo(4, 0, ShiftState.FORCE_DOWN)); // Simulate Shift-0, like trsemu.
keyMap.set("!", new KeyInfo(4, 1, ShiftState.FORCE_DOWN));
keyMap.set("\"", new KeyInfo(4, 2, ShiftState.FORCE_DOWN));
keyMap.set("#", new KeyInfo(4, 3, ShiftState.FORCE_DOWN));
keyMap.set("$", new KeyInfo(4, 4, ShiftState.FORCE_DOWN));
keyMap.set("%", new KeyInfo(4, 5, ShiftState.FORCE_DOWN));
keyMap.set("&", new KeyInfo(4, 6, ShiftState.FORCE_DOWN));
keyMap.set("'", new KeyInfo(4, 7, ShiftState.FORCE_DOWN));
keyMap.set("(", new KeyInfo(5, 0, ShiftState.FORCE_DOWN));
keyMap.set(")", new KeyInfo(5, 1, ShiftState.FORCE_DOWN));
keyMap.set(":", new KeyInfo(5, 2, ShiftState.FORCE_UP));
keyMap.set(";", new KeyInfo(5, 3, ShiftState.FORCE_UP));
keyMap.set(",", new KeyInfo(5, 4, ShiftState.FORCE_UP));
keyMap.set("-", new KeyInfo(5, 5, ShiftState.FORCE_UP));
keyMap.set(".", new KeyInfo(5, 6, ShiftState.FORCE_UP));
keyMap.set("/", new KeyInfo(5, 7, ShiftState.FORCE_UP));
keyMap.set("*", new KeyInfo(5, 2, ShiftState.FORCE_DOWN));
keyMap.set("+", new KeyInfo(5, 3, ShiftState.FORCE_DOWN));
keyMap.set("<", new KeyInfo(5, 4, ShiftState.FORCE_DOWN));
keyMap.set("=", new KeyInfo(5, 5, ShiftState.FORCE_DOWN));
keyMap.set(">", new KeyInfo(5, 6, ShiftState.FORCE_DOWN));
keyMap.set("?", new KeyInfo(5, 7, ShiftState.FORCE_DOWN));
keyMap.set("Enter", new KeyInfo(6, 0, ShiftState.NEUTRAL));
keyMap.set("\\", new KeyInfo(6, 1, ShiftState.NEUTRAL)); // Clear
keyMap.set("Escape", new KeyInfo(6, 2, ShiftState.NEUTRAL)); // Break
keyMap.set("ArrowUp", new KeyInfo(6, 3, ShiftState.NEUTRAL));
keyMap.set("ArrowDown", new KeyInfo(6, 4, ShiftState.NEUTRAL));
keyMap.set("ArrowLeft", new KeyInfo(6, 5, ShiftState.NEUTRAL));
keyMap.set("Backspace", new KeyInfo(6, 5, ShiftState.NEUTRAL)); // Left arrow
keyMap.set("ArrowRight", new KeyInfo(6, 6, ShiftState.NEUTRAL));
keyMap.set(" ", new KeyInfo(6, 7, ShiftState.NEUTRAL));
keyMap.set("Shift", new KeyInfo(7, 0, ShiftState.NEUTRAL));
export class Keyboard {
public static isInRange(address: number): boolean {
return address >= BEGIN_ADDR && address < END_ADDR;
}
// We queue up keystrokes so that we don't overwhelm the ROM polling routines.
public keyQueue: KeyActivity[] = [];
// Whether browser keys should be intercepted.
public interceptKeys = false;
public keyProcessMinClock: number = 0;
// 8 bytes, each a bitfield of keys currently pressed.
private keys = new Uint8Array(8);
private shiftForce = ShiftState.NEUTRAL;
// Release all keys.
public clearKeyboard(): void {
this.keys.fill(0);
this.shiftForce = ShiftState.NEUTRAL;
}
// Read a byte from the keyboard memory bank. This is an odd system where
// bits in the address map to the various bytes, and you can read the OR'ed
// addresses to read more than one byte at a time. For the last byte we fake
// the Shift key if necessary.
public readKeyboard(addr: number, clock: number): number {
addr = (addr - BEGIN_ADDR) % BANK_SIZE;
let b = 0;
// Dequeue if necessary.
if (clock > this.keyProcessMinClock) {
const keyWasPressed = this.processKeyQueue();
if (keyWasPressed) {
this.keyProcessMinClock = clock + KEY_DELAY_CLOCK_CYCLES;
}
}
// OR together the various bytes.
for (let i = 0; i < this.keys.length; i++) {
let keys = this.keys[i];
if ((addr & (1 << i)) !== 0) {
if (i === 7) {
// Modify keys based on the shift force.
switch (this.shiftForce) {
case ShiftState.NEUTRAL:
// Nothing.
break;
case ShiftState.FORCE_UP:
// On the Model III the first two bits are left and right shift,
// though we don't handle the right shift anywhere.
keys &= ~0x03;
break;
case ShiftState.FORCE_DOWN:
keys |= 0x01;
break;
}
}
b |= keys;
}
}
return b;
}
// Enqueue a key press or release.
public keyEvent(key: string, isPressed: boolean) {
// Look up the key info.
const keyInfo = keyMap.get(key);
if (keyInfo === undefined) {
if (key !== "Meta" && key !== "Control" && key !== "Alt" && key !== "Tab") {
console.log("Unknown key \"" + key + "\"");
}
} else {
// Append key to queue.
this.keyQueue.push(new KeyActivity(keyInfo, isPressed));
}
}
/**
* Simulate this text being entered by the user.
*/
public simulateKeyboardText(text: string): void {
for (let ch of text) {
if (ch === "\n" || ch === "\r") {
ch = "Enter";
}
this.keyEvent(ch, true);
this.keyEvent(ch, false);
}
}
// Dequeue the next key and set its bit. Return whether a key was processed.
private processKeyQueue(): boolean {
const keyActivity = this.keyQueue.shift();
if (keyActivity === undefined) {
return false;
}
this.shiftForce = keyActivity.keyInfo.shiftForce;
const bit = 1 << keyActivity.keyInfo.bitNumber;
if (keyActivity.isPressed) {
this.keys[keyActivity.keyInfo.byteIndex] |= bit;
} else {
this.keys[keyActivity.keyInfo.byteIndex] &= ~bit;
}
return true;
}
} | the_stack |
import { quickcheck } from './test'
import { token } from './token'
import * as scanner from './scanner'
import {
sourceScanner,
assertGotTok,
} from './scanner_test'
function numberBaseForToken(t :token) :int {
return (
t == token.INT_HEX ? 16 :
t == token.INT_OCT ? 8 :
t == token.INT_BIN ? 2 :
10
)
}
function assertGotI32Val(s :scanner.Scanner, t :token, expectedString :string) {
assertGotTok(s, t)
let base = numberBaseForToken(t)
if (isNaN(s.int32val)) {
assert(
false,
`expected int32 value but none was parsed (s.int32val=NaN)` +
` at ${s.sfile.position(s.pos)}`,
assertGotI32Val
)
} else if (base == 16) {
assert(
s.int32val.toString(base) === expectedString,
`expected int32 value ${expectedString}` +
` but got 0x${s.int32val.toString(base)}` +
` at ${s.sfile.position(s.pos)}`,
assertGotI32Val
)
} else {
assert(
s.int32val.toString(base) === expectedString,
`expected int32 value ${expectedString}` +
` but got ${s.int32val.toString(base)} (0x${s.int32val.toString(16)})` +
` at ${s.sfile.position(s.pos)}`,
assertGotI32Val
)
}
}
function assertGotF64Val(s :scanner.Scanner, expectedVal :number) {
assertGotTok(s, token.FLOAT)
assert(
!isNaN(s.floatval),
`expected float value but none was parsed (s.floatval=NaN)` +
` at ${s.sfile.position(s.pos)}`,
assertGotF64Val
)
assert(
s.floatval === expectedVal,
`expected float value ${expectedVal} but got ${s.floatval}` +
` at ${s.sfile.position(s.pos)}`,
assertGotF64Val
)
}
function assertGotI64Val(s :scanner.Scanner, t :token, expectedString :string) {
assertGotTok(s, t)
let base = numberBaseForToken(t)
if (!s.int64val) {
assert(
false,
`expected int64 value but none was parsed` +
` at ${s.sfile.position(s.pos)}`,
assertGotI64Val
)
} else if (base == 16) {
assert(
s.int64val.toString(base) === expectedString,
`expected int64 value ${expectedString}` +
` but got 0x${s.int64val.toString(base)}` +
` at ${s.sfile.position(s.pos)}`,
assertGotI64Val
)
} else {
assert(
s.int64val.toString(base) === expectedString,
`expected int64 value ${expectedString}` +
` but got ${s.int64val.toString(base)} (0x${s.int64val.toString(16)})` +
` at ${s.sfile.position(s.pos)}`,
assertGotI64Val
)
}
}
function assertGotInvalidInt(s :scanner.Scanner, t :token) {
let base = numberBaseForToken(t)
assertGotTok(s, t)
assert(
isNaN(s.int32val),
`expected invalid int but got` +
` int32val ${s.int32val.toString(base)} (0x${s.int32val.toString(16)})` +
` at ${s.sfile.position(s.pos)}`,
assertGotInvalidInt
)
assert(
s.int64val == null,
`expected invalid int` +
` but got int64val ${s.int64val ? s.int64val.toString(base) : '0'}`+
` (0x${s.int64val ? s.int64val.toString(16) : '0'})` +
` at ${s.sfile.position(s.pos)}`,
assertGotInvalidInt
)
}
function expectedStringFromSource(s :string, t :token) :string {
let base = numberBaseForToken(t)
if (s[0] == '+') {
s = s.substr(1) // remove "+" used to force parser into signed int
}
if (base != 10) {
// strip prefix, e.g. "0x"
s = (
s[0] == '-' ? '-' + s.substr(3) :
s.substr(2)
)
}
return (
s == '-0' ? '0' :
s[0] == '+' ? s.substr(1) :
s
)
}
function assertScanI32s(samples :[string,token][]) {
for (let sample of samples) {
let source = sample[0]
let expectToken = sample[1]
let expectString = expectedStringFromSource(source, expectToken)
let s = sourceScanner(source)
// console.log(`>> scan "${source}"`)
assertGotI32Val(s, expectToken, expectString)
}
}
function assertScanI64s(samples :[string,token][]) {
for (let sample of samples) {
let source = sample[0]
let expectToken = sample[1]
let expectString = expectedStringFromSource(source, expectToken)
let s = sourceScanner(source)
// console.log(`>> scan "${source}"`)
assertGotI64Val(s, expectToken, expectString)
}
}
function assertScanBigInts(samples :[string,token][]) {
for (let sample of samples) {
let source = sample[0]
let expectToken = sample[1]
let s = sourceScanner(source)
// console.log(`>> scan "${source}"`)
assertGotInvalidInt(s, expectToken)
}
}
function assertScanF64s(samples :string[]) {
for (let source of samples) {
let expectVal = parseFloat(source)
let s = sourceScanner(source)
// console.log(`>> scan "${source}" -> ${expectVal}`)
assertGotF64Val(s, expectVal)
}
}
// ===========================================================================
TEST('int/unsigned/base16', () => {
// unsigned 32-bit integers
assertScanI32s([
['0x0', token.INT_HEX],
['0x1', token.INT_HEX],
['0x123', token.INT_HEX],
['0xff0099', token.INT_HEX],
['0xdeadbeef', token.INT_HEX],
['0xffffffff', token.INT_HEX], // UINT32_MAX
])
// unsigned 64-bit integers
assertScanI64s([
// 64-bit integers
['0x100000000', token.INT_HEX], // UINT32_MAX + 1
['0x53e2d6238da3', token.INT_HEX],
['0x346dc5d638865', token.INT_HEX],
['0x20c49ba5e353f7', token.INT_HEX],
['0x147ae147ae147ae', token.INT_HEX],
['0xccccccccccccccc', token.INT_HEX],
['0xde0b6b3a763ffff', token.INT_HEX],
['0xde0b6b3a7640000', token.INT_HEX],
['0x7fffffffffffffff', token.INT_HEX], // SINT64_MAX
['0x8000000000000000', token.INT_HEX], // SINT64_MAX + 1
['0x8ac7230335dc1bff', token.INT_HEX], //
// largest number that fits in two i32 passes
['0xffffffffffffffff', token.INT_HEX], // 18446744073709551615 U64_MAX
])
// unsigned bit integers
assertScanBigInts([
// large integers
['0x10000000000000000', token.INT_HEX], // UINT64_MAX + 1
['0x10000000000000002', token.INT_HEX], // UINT64_MAX + 3
['0x100000000fffffffe', token.INT_HEX], // UINT64_MAX + UINT32_MAX
['0x100000000ffffffff', token.INT_HEX], // UINT64_MAX + UINT32_MAX + 1
['0x100000000fffffffd', token.INT_HEX], // UINT64_MAX + UINT32_MAX - 1
['0x29d42b64e76714244cb', token.INT_HEX],
])
})
TEST('int/unsigned/base10', () => {
// unsigned 32-bit integers
assertScanI32s([
['0', token.INT],
['1', token.INT],
['123', token.INT],
['4294967295', token.INT], // UINT32_MAX
])
// unsigned 64-bit integers
assertScanI64s([
['4294967296', token.INT], // UINT32_MAX + 1
['92233720368547', token.INT],
['922337203685477', token.INT],
['9223372036854775', token.INT],
['92233720368547758', token.INT],
['922337203685477580', token.INT],
['999999999999999999', token.INT],
['1000000000000000000', token.INT],
['9223372036854775807', token.INT], // SINT64_MAX
['9223372036854775808', token.INT], // SINT64_MAX + 1
['9999999994294967295', token.INT],
// largest number that fits in two i32 passes
['10000000000000000000', token.INT],
['10000000009999999999', token.INT],
['9999999999999999999', token.INT],
['9999999999800000000', token.INT],
['18446744073709551615', token.INT], // U64_MAX
])
// unsigned bit integers
assertScanBigInts([
['18446744073709551616', token.INT], // U64_MAX + 1
['18446744073709551618', token.INT], // U64_MAX + 3
['18446744078004518910', token.INT], // U64_MAX + U32_MAX
['18446744078004518911', token.INT], // U64_MAX + U32_MAX + 1
['18446744078004518909', token.INT], // U64_MAX + U32_MAX - 1
['90000000000000000000', token.INT],
['20000000000000000000', token.INT],
['22222222222222222222', token.INT],
['99999999999999999999', token.INT],
['12345678901234567890123', token.INT],
['99999999999999999999999999999999999',token.INT],
])
})
TEST('int/unsigned/base8', () => {
// unsigned 32-bit integers
assertScanI32s([
['0o0', token.INT_OCT],
['0o1', token.INT_OCT],
['0o123', token.INT_OCT],
['0o4671', token.INT_OCT],
['0o37777777777', token.INT_OCT], // UINT32_MAX
])
// unsigned 64-bit integers
assertScanI64s([
// 64-bit integers
['0o40000000000', token.INT_OCT], // UINT32_MAX + 1
['0o2476132610706643', token.INT_OCT], //
['0o32155613530704145', token.INT_OCT], //
['0o406111564570651767', token.INT_OCT], //
['0o5075341217270243656', token.INT_OCT], //
['0o63146314631463146314', token.INT_OCT], //
['0o67405553164730777777', token.INT_OCT], //
['0o67405553164731000000', token.INT_OCT], //
['0o777777777777777777777', token.INT_OCT], // I64_MAX
['0o1000000000000000000000', token.INT_OCT], // I64_MAX + 1
['0o1053071060146567015777', token.INT_OCT],
// largest number that fits in two i32 passes
['0o1777777777777777777777', token.INT_OCT], // U64_MAX
])
// unsigned bit integers
assertScanBigInts([
['0o2000000000000000000000', token.INT_OCT], // U64_MAX + 1
['0o2000000000037777777776', token.INT_OCT], // U64_MAX + U32_MAX
['0o2000000000037777777777', token.INT_OCT], // U64_MAX + U32_MAX + 1
['0o2000000000037777777775', token.INT_OCT], // U64_MAX + U32_MAX - 1
['0o7777777777777777777777', token.INT_OCT],
['0o10000000000000000000000', token.INT_OCT],
['0o2472412662347316120442313', token.INT_OCT],
])
})
TEST('int/unsigned/base2', () => {
// unsigned 32-bit integers
assertScanI32s([
['0b0', token.INT_BIN],
['0b1', token.INT_BIN],
['0b100', token.INT_BIN],
['0b111', token.INT_BIN],
['0b10101', token.INT_BIN],
['0b11111111111111111111111111111111', token.INT_BIN], // UINT32_MAX
])
// unsigned 64-bit integers
assertScanI64s([
// 64-bit integers
[ '0b100000000000000000000000000000000',
token.INT_BIN ], // UINT32_MAX + 1
[ '0b10100111110001011010110001000111000110110100011',
token.INT_BIN ],
[ '0b11010001101101110001011101011000111000100001100101',
token.INT_BIN ],
[ '0b100000110001001001101110100101111000110101001111110111',
token.INT_BIN ],
[ '0b101000111101011100001010001111010111000010100011110101110',
token.INT_BIN ],
[ '0b110011001100110011001100110011001100110011001100110011001100',
token.INT_BIN ],
[ '0b110111100000101101101011001110100111011000111111111111111111',
token.INT_BIN ],
[ '0b110111100000101101101011001110100111011001000000000000000000',
token.INT_BIN ],
[ '0b111111111111111111111111111111111111111111111111111111111111111',
token.INT_BIN ], // I64_MAX
[ '0b1000000000000000000000000000000000000000000000000000000000000000',
token.INT_BIN ], // I64_MAX + 1
[ '0b1000101011000111001000110000001100110101110111000001101111111111',
token.INT_BIN ], // largest number that fits in two i32 passes
[ '0b1111111111111111111111111111111111111111111111111111111111111111',
token.INT_BIN ], // U64_MAX
])
// unsigned bit integers
assertScanBigInts([
[ '0b10000000000000000000000000000000000000000000000000000000000000000',
token.INT_BIN], // U64_MAX + 1
[ '0b10000000000000000000000000000000011111111111111111111111111111110',
token.INT_BIN], // U64_MAX + U32_MAX
[ '0b10000000000000000000000000000000011111111111111111111111111111111',
token.INT_BIN], // U64_MAX + U32_MAX + 1
[ '0b10000000000000000000000000000000011111111111111111111111111111101',
token.INT_BIN], // U64_MAX + U32_MAX - 1
[
'0b10100111010100001010110110010011100111011001110001010000100100010011001011',
token.INT_BIN], // 12345678901234567890123
])
})
TEST('int/signed/base16', () => {
// signed 32-bit integers
assertScanI32s([
['-0x0', token.INT_HEX],
['+0x0', token.INT_HEX],
['-0x1', token.INT_HEX],
['+0x12c', token.INT_HEX],
['-0x12c', token.INT_HEX],
['+0xaff', token.INT_HEX],
['-0xaff', token.INT_HEX],
['-0x80000000', token.INT_HEX], // SINT32_MIN
['+0x7fffffff', token.INT_HEX], // SINT32_MAX
])
// signed 64-bit integers
assertScanI64s([
['-0x80000001', token.INT_HEX], // SINT32_MIN - 1
['+0x80000000', token.INT_HEX], // SINT32_MAX + 1
['-0x100000000', token.INT_HEX],
['-0x1000000000000000', token.INT_HEX],
['+0x1000000000000000', token.INT_HEX],
['-0xfffffffffffffff', token.INT_HEX],
['+0xfffffffffffffff', token.INT_HEX],
['-0x7fffffffffffffff', token.INT_HEX], // SINT64_MIN + 1
['-0x8000000000000000', token.INT_HEX], // SINT64_MIN
['+0x7fffffffffffffff', token.INT_HEX], // SINT64_MAX
])
// signed bit integers
assertScanBigInts([
['-0x8000000000000001', token.INT_HEX], // SINT64_MIN - 1
['-0x8000000000000002', token.INT_HEX], // SINT64_MIN - 2
['+0x8000000000000000', token.INT_HEX], // SINT64_MAX + 1
['+0x8000000000000001', token.INT_HEX], // SINT64_MAX + 2
['+0xffffffffffffffff', token.INT_HEX],
['-0xffffffffffffffff', token.INT_HEX],
['+0x1000000000000000f', token.INT_HEX],
['-0x1000000000000000f', token.INT_HEX],
['+0xcacacacacaccacacacacac', token.INT_HEX],
])
})
TEST('int/signed/base10', () => {
// signed 32-bit integers
assertScanI32s([
['-1', token.INT],
['+1', token.INT],
['-0', token.INT],
['+0', token.INT],
['-123', token.INT],
['+123', token.INT],
['-987', token.INT],
['-2147483648', token.INT], // SINT32_MIN
['+2147483647', token.INT], // SINT32_MAX
])
// signed 64-bit integers
assertScanI64s([
['-2147483649', token.INT], // SINT32_MIN - 1
['+2147483648', token.INT], // SINT32_MAX + 1
['-10000000000', token.INT],
['-92233720368547', token.INT],
['-9223372036854775807', token.INT], // SINT64_MIN + 1
['-9223372036854775808', token.INT], // SINT64_MIN
['+9223372036854775807', token.INT], // SINT64_MAX
])
// signed bit integers
assertScanBigInts([
['-9223372036854775809', token.INT], // SINT64_MIN - 1
['+9223372036854775808', token.INT], // SINT64_MAX + 1
['-9999999999999999999', token.INT],
['+9999999999999999999', token.INT],
['-999999999999999999999999', token.INT],
['+999999999999999999999999', token.INT],
])
})
TEST('int/signed/base8', () => {
// signed 32-bit integers
assertScanI32s([
['-0o1', token.INT_OCT],
['+0o1', token.INT_OCT],
['-0o0', token.INT_OCT],
['+0o0', token.INT_OCT],
['-0o173', token.INT_OCT], // -123
['+0o173', token.INT_OCT], // 123
['-0o1467', token.INT_OCT],
['-0o20000000000', token.INT_OCT], // SINT32_MIN
['+0o17777777777', token.INT_OCT], // SINT32_MAX
])
// signed 64-bit integers
assertScanI64s([
['-0o20000000001', token.INT_OCT], // SINT32_MIN - 1
['+0o20000000000', token.INT_OCT], // SINT32_MAX + 1
['+0o651341234707', token.INT_OCT],
['-0o777777777777777777777', token.INT_OCT], // SINT64_MIN + 1
['-0o1000000000000000000000', token.INT_OCT], // SINT64_MIN
['+0o777777777777777777777', token.INT_OCT], // SINT64_MAX
])
// signed bit integers
assertScanBigInts([
['-0o1000000000000000000001', token.INT_OCT], // SINT64_MIN - 1
['+0o1000000000000000000000', token.INT_OCT], // SINT64_MAX + 1
['+0o1000000000000000000001', token.INT_OCT], // SINT64_MAX + 2
['+0o7777777777777777777777', token.INT_OCT],
['+0o10000000000000000000000', token.INT_OCT],
['-0o10000000000000000000000', token.INT_OCT],
['-0o12345671234567123456712345', token.INT_OCT],
])
})
TEST('int/signed/base2', () => {
// signed 32-bit integers
assertScanI32s([
['-0b1', token.INT_BIN],
['+0b1', token.INT_BIN],
['-0b0', token.INT_BIN],
['+0b0', token.INT_BIN],
['-0b110', token.INT_BIN],
['+0b110', token.INT_BIN],
['-0b111001', token.INT_BIN],
['-0b10000000000000000000000000000000', token.INT_BIN], // SINT32_MIN
['+0b1111111111111111111111111111111', token.INT_BIN], // SINT32_MAX
])
// signed 64-bit integers
assertScanI64s([
['-0b10000000000000000000000000000001', token.INT_BIN], // SINT32_MIN - 1
['+0b10000000000000000000000000000000', token.INT_BIN], // SINT32_MAX + 1
['+0b110101010101010101010101010101010', token.INT_BIN],
['+0b1101111110000001111111000001111111', token.INT_BIN],
['-0b111111111111111111111111111111111111111111111111111111111111111',
token.INT_BIN], // SINT64_MIN + 1
['-0b1000000000000000000000000000000000000000000000000000000000000000',
token.INT_BIN], // SINT64_MIN
['+0b111111111111111111111111111111111111111111111111111111111111111',
token.INT_BIN], // SINT64_MAX
])
// signed bit integers
assertScanBigInts([
['-0b1000000000000000000000000000000000000000000000000000000000000001',
token.INT_BIN], // SINT64_MIN - 1
['+0b1000000000000000000000000000000000000000000000000000000000000000',
token.INT_BIN], // SINT64_MAX + 1
['-0b10000000000000000000000000000000000000000000000000000000000000000',
token.INT_BIN],
['+0b10000000000000000000000000000000000000000000000000000000000000000',
token.INT_BIN],
['-0b11111111111111111111111111111111111111111111111111111111111111111111',
token.INT_BIN],
['+0b11111111111111111111111111111111111111111111111111111111111111111111',
token.INT_BIN],
])
})
TEST('int/neg-base10-quickcheck', () => {
function negI64Gen(i :int) :string {
return '-9223372036854775' + (i >= 0 ? i.toString() : '')
}
// negative i64s
quickcheck([-1, 808], i => {
let src = negI64Gen(i)
let s = sourceScanner(src)
s.next()
return (
s.tok == token.INT &&
isNaN(s.int32val) &&
s.int64val != null &&
s.int64val.toString() === src
)
})
// negative bigs
quickcheck([809, 10000], i => {
let src = negI64Gen(i)
let s = sourceScanner(src)
s.next()
return (
s.tok == token.INT &&
isNaN(s.int32val) &&
s.int64val == null
)
})
})
TEST('float', () => {
assertScanF64s([
'1.0',
'0.',
'0.0',
'72.40',
'072.40',
'2.71828',
'1.e+0',
'6.67428e-11',
'1E6',
'.25',
'.12345E+5',
])
// negative
assertScanF64s([
'-1.0',
'-0.',
'-0.0',
'-72.40',
'-072.40',
'-2.71828',
'-1.e+0',
'-6.67428e-11',
'-1E6',
'-.25',
'-.12345E+5',
])
// + sign (simply for compatibility with signed int syntax)
assertScanF64s([
'+1.0',
'+0.',
'+0.0',
'+72.40',
'+072.40',
'+2.71828',
'+1.e+0',
'+6.67428e-11',
'+1E6',
'+.25',
'+.12345E+5',
])
}) | the_stack |
import * as types from './types';
import * as ts from 'typescript';
export interface ParsedData<T> {
/** only if valid */
data?: T;
/** only if error */
error?: ParseError;
}
/**
* Remove the comments from a json like text.
* Comments can be single line comments (starting with # or //) or multiline comments using / * * /
*
* This method replace comment content by whitespace rather than completely remove them to keep positions in json parsing error reporting accurate.
*/
function removeComments(jsonText: string): string {
let output = "";
const scanner = ts.createScanner(ts.ScriptTarget.ES5, /* skipTrivia */ false, ts.LanguageVariant.Standard, jsonText);
let token: ts.SyntaxKind;
while ((token = scanner.scan()) !== ts.SyntaxKind.EndOfFileToken) {
switch (token) {
case ts.SyntaxKind.SingleLineCommentTrivia:
case ts.SyntaxKind.MultiLineCommentTrivia:
// replace comments with whitespace to preserve original character positions
output += scanner.getTokenText().replace(/\S/g, " ");
break;
default:
output += scanner.getTokenText();
break;
}
}
return output;
}
/**
* Over JSON.parse:
* * allows BOM
* * allows // /* # comments
* * provides a typed error detail on parse error
*/
export function parse<T>(str: string): ParsedData<T> {
const content = removeComments(stripBOM(str));
try {
return { data: json_parse(content) };
}
catch (e) {
let error: { message: string; at: number } = e;
const indexToPosition = (index: number): { line: number, ch: number } => {
let beforeLines = splitlines(content.substr(0, index));
return {
line: Math.max(beforeLines.length - 1, 0),
ch: Math.max(beforeLines[beforeLines.length - 1].length - 1, 0)
};
}
let fromIndex = Math.max(error.at - 1, 0);
let toIndex = Math.min(error.at + 1, content.length);
return {
error: {
message: e.message,
from: indexToPosition(fromIndex),
to: indexToPosition(toIndex),
preview: content.substring(fromIndex, toIndex - 1)
}
}
}
}
export function stringify(object: Object, eol: string = '\n'): string {
var cache = [];
var value = JSON.stringify(object,
// fixup circular reference
function(key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
// Store value in our collection
cache.push(value);
}
return value;
},
// indent 2 spaces
2);
value = value.split('\n').join(eol) + eol;
cache = null;
return value;
}
export function parseErrorToCodeError(filePath: string, error: ParseError, source: types.CodeErrorSource): types.CodeError {
return {
source,
filePath,
from: error.from,
to: error.to,
message: error.message,
preview: error.preview,
level: 'error'
}
}
function stripBOM(str: string) {
// Catches EFBBBF (UTF-8 BOM) because the buffer-to-string
// conversion translates it to FEFF (UTF-16 BOM)
if (typeof str === 'string' && str.charCodeAt(0) === 0xFEFF) {
return str.slice(1);
}
return str;
}
function splitlines(string: string) { return string.split(/\r\n?|\n/); };
export interface ParseError {
message: string;
preview: string;
from: {
/** zero based */
line: number;
/** zero based */
ch: number
};
to: {
/** zero based */
line: number;
/** zero based */
ch: number
};
}
/**
* https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js
* AS IT IS. ONLY MODIFIED WITH TYPE ASSERTSIONS / ANNOTATIONS
*/
var json_parse: any = (function() {
"use strict";
// This is a function that can parse a JSON text, producing a JavaScript
// data structure. It is a simple, recursive descent parser. It does not use
// eval or regular expressions, so it can be used as a model for implementing
// a JSON parser in other languages.
// We are defining the function inside of another function to avoid creating
// global variables.
var at, // The index of the current character
ch, // The current character
escapee = {
'"': '"',
'\\': '\\',
'/': '/',
b: '\b',
f: '\f',
n: '\n',
r: '\r',
t: '\t'
},
text,
error = function(m) {
// Call error when something is wrong.
throw {
name: 'SyntaxError',
message: m,
at: at,
text: text
};
},
next = function(c?) {
// If a c parameter is provided, verify that it matches the current character.
if (c && c !== ch) {
error("Expected '" + c + "' instead of '" + ch + "'");
}
// Get the next character. When there are no more characters,
// return the empty string.
ch = text.charAt(at);
at += 1;
return ch;
},
number = function() {
// Parse a number value.
var number,
string = '';
if (ch === '-') {
string = '-';
next('-');
}
while (ch >= '0' && ch <= '9') {
string += ch;
next();
}
if (ch === '.') {
string += '.';
while (next() && ch >= '0' && ch <= '9') {
string += ch;
}
}
if (ch === 'e' || ch === 'E') {
string += ch;
next();
if (ch === '-' || ch === '+') {
string += ch;
next();
}
while (ch >= '0' && ch <= '9') {
string += ch;
next();
}
}
number = +string;
if (!isFinite(number)) {
error("Bad number");
} else {
return number;
}
},
string = function() {
// Parse a string value.
var hex,
i,
string = '',
uffff;
// When parsing for string values, we must look for " and \ characters.
if (ch === '"') {
while (next()) {
if (ch === '"') {
next();
return string;
}
if (ch === '\\') {
next();
if (ch === 'u') {
uffff = 0;
for (i = 0; i < 4; i += 1) {
hex = parseInt(next(), 16);
if (!isFinite(hex)) {
break;
}
uffff = uffff * 16 + hex;
}
string += String.fromCharCode(uffff);
} else if (typeof escapee[ch] === 'string') {
string += escapee[ch];
} else {
break;
}
} else {
string += ch;
}
}
}
error("Bad string");
},
white = function() {
// Skip whitespace.
while (ch && ch <= ' ') {
next();
}
},
word = function() {
// true, false, or null.
switch (ch) {
case 't':
next('t');
next('r');
next('u');
next('e');
return true;
case 'f':
next('f');
next('a');
next('l');
next('s');
next('e');
return false;
case 'n':
next('n');
next('u');
next('l');
next('l');
return null;
}
error("Unexpected '" + ch + "'");
},
value, // Place holder for the value function.
array = function() {
// Parse an array value.
var array = [];
if (ch === '[') {
next('[');
white();
if (ch === ']') {
next(']');
return array; // empty array
}
while (ch) {
array.push(value());
white();
if (ch === ']') {
next(']');
return array;
}
next(',');
white();
}
}
error("Bad array");
},
object = function() {
// Parse an object value.
var key,
object = {};
if (ch === '{') {
next('{');
white();
if (ch === '}') {
next('}');
return object; // empty object
}
while (ch) {
key = string();
white();
next(':');
if (Object.hasOwnProperty.call(object, key)) {
error('Duplicate key "' + key + '"');
}
object[key] = value();
white();
if (ch === '}') {
next('}');
return object;
}
next(',');
white();
}
}
error("Bad object");
};
value = function() {
// Parse a JSON value. It could be an object, an array, a string, a number,
// or a word.
white();
switch (ch) {
case '{':
return object();
case '[':
return array();
case '"':
return string();
case '-':
return number();
default:
return ch >= '0' && ch <= '9'
? number()
: word();
}
};
// Return the json_parse function. It will have access to all of the above
// functions and variables.
return function(source, reviver?) {
var result;
text = source;
at = 0;
ch = ' ';
result = value();
white();
if (ch) {
error("Syntax error");
}
// If there is a reviver function, we recursively walk the new structure,
// passing each name/value pair to the reviver function for possible
// transformation, starting with a temporary root object that holds the result
// in an empty key. If there is not a reviver function, we simply return the
// result.
return typeof reviver === 'function'
? (function walk(holder, key) {
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}({ '': result }, ''))
: result;
};
}()); | the_stack |
// @ts-ignore: babel-core package missing types.
import * as babel from "@babel/core";
import * as swc from "@swc/core";
import * as esbuild from "esbuild";
import {fs} from "mz";
import {exists} from "mz/fs";
import * as TypeScript from "typescript";
import run from "../script/run";
import * as sucrase from "../src/index";
import {FileInfo, loadProjectFiles} from "./loadProjectFiles";
async function main(): Promise<void> {
process.chdir(__dirname);
const benchmark = process.argv[2] || "jest";
if (benchmark === "jest") {
await benchmarkJest();
} else if (benchmark === "jest-diff") {
await benchmarkJestForDiff();
} else if (benchmark === "jest-dev") {
await benchmarkJestForDev();
} else if (benchmark === "project") {
await benchmarkProject();
} else if (benchmark === "sample") {
await benchmarkSample();
} else if (benchmark === "test") {
await benchmarkTest();
} else {
console.error(`Unrecognized benchmark: ${benchmark}`);
process.exitCode = 1;
}
}
/**
* Run a benchmark against similar tools for publishing in the README. This can
* be run by running "yarn benchmark" from the root Sucrase directory.
*
* The benchmark clones the Jest codebase at a fixed hash, mucks with the code
* to fix some compatibility issues, then runs it through Sucrase, swc, esbuild,
* tsc, and Babel.
*
* There are a few caveats that make it hard to come up with a completely fair
* comparison between tools:
*
* 1.) JIT warm-up
* Like all JavaScript code run in V8, Sucrase runs more slowly at first, then
* gets faster as the just-in-time compiler applies more optimizations. From a
* rough measurement, Sucrase is about 2x faster after running for 3 seconds
* than after running for 1 second. swc (written in Rust) and esbuild (written
* in Go) don't have this effect because they're pre-compiled, so comparing them
* with Sucrase gets significantly different results depending on how large of a
* codebase is being tested and whether each compiler is allowed a "warm up"
* period before the benchmark is run.
*
* For the benchmark shown in the README, we do NOT allow a warmup period, and
* we test on a fairly large codebase of ~360k lines of code. This is meant to
* showcase Sucrase's performance in a realistic scenario rather than focusing
* on best-case performance, but a downside is that a small change in benchmark
* details will give a different result. You can try out the behavior with
* warm-up by changing the options to have `warmUp: true`.
*
* 2.) Multi-threading
* This benchmark focuses on measuring the single-threaded performance of the
* each tool, even though esbuild and swc both have built-in mechanisms for
* running compilation in parallel. Transpiling a codebase is fundamentally easy
* to parallelize since you can split up the files among different workers in a
* worker pool, so even a tool without built-in parallelization support (like
* Sucrase) can be run optimally in parallel using a wrapper tool like Webpack's
* thread-loader. So when comparing tools, it seems fair and simpler to measure
* how much a single CPU core can compile, with the understanding that any tool
* can be run in parallel. That said, for many use cases it may certainly be
* more convenient to use a tool with built-in parallelization.
*
* 3.) Behavior equivalence
* Each tool has been configured to remove TS types, transpile JSX, and convert
* imports to CommonJS, and ideally not transform anything else. However, each
* tool has its own configuration and there are small differences in exactly
* which JS features are transformed. The "test" benchmark can be used to
* spot-check the output for various simple cases.
*/
async function benchmarkJest(): Promise<void> {
await benchmarkFiles({files: await getJestFiles(), numIterations: 3});
}
async function getJestFiles(): Promise<Array<FileInfo>> {
if (!(await exists("./sample/jest"))) {
await run("git clone https://github.com/facebook/jest.git ./sample/jest");
process.chdir("./sample/jest");
await run("git checkout 7430a7824421c122cd07035d800d22e1007408fa");
process.chdir("../..");
}
let files = await loadProjectFiles("./sample/jest");
// Babel doesn't support "import =" or "export =" syntax at all, but jest
// uses it, so hack the code to not use that syntax.
files = files.map(({path, code}) => ({
path,
code: code.replace(/import([^\n]*require)/g, "const$1").replace(/export =/g, "exports ="),
}));
// esbuild doesn't allow top-level await when outputting to CJS, so skip the
// one file in the Jest codebase that uses that syntax.
files = files.filter(
({path}) => !path.includes("jest/e2e/native-esm/__tests__/native-esm-tla.test.js"),
);
return files;
}
/**
* Run the Jest benchmark with JSON stdout so that external tools can read it.
*/
async function benchmarkJestForDiff(): Promise<void> {
await benchmarkFiles({
files: await getJestFiles(),
numIterations: 15,
warmUp: true,
sucraseOnly: true,
jsonOutput: true,
});
}
/**
* Run the Jest benchmark many times with warm-up to test Sucrase's performance
* in response to code changes.
*/
async function benchmarkJestForDev(): Promise<void> {
await benchmarkFiles({
files: await getJestFiles(),
numIterations: 15,
warmUp: true,
sucraseOnly: true,
});
}
/**
* Given a path to a project directory, discover all JS/TS files and determine
* the time needed to transpile them.
*/
async function benchmarkProject(): Promise<void> {
const projectPath = process.argv[3];
const files = await loadProjectFiles(projectPath);
await benchmarkFiles({files, numIterations: 1});
}
/**
* Benchmark 100 iterations of a 1000-line file that tries to be fairly
* representative of typical code.
*/
async function benchmarkSample(): Promise<void> {
const code = fs.readFileSync(`./sample/sample.tsx`).toString();
await benchmarkFiles({files: [{code, path: "sample.tsx"}], numIterations: 100, warmUp: true});
}
/**
* Run a small code snippet through all compilers and print the output so they
* can be spot-checked.
*/
async function benchmarkTest(): Promise<void> {
const code = `
// Imports should be transpiled to CJS.
import React from 'react';
// async/await should NOT be transpiled.
async function foo(): Promise<void> {
await bar();
}
// Classes should NOT be transpiled.
export default class App {
// Return types should be removed.
render(): JSX.Element {
// JSX should be transpiled.
return <div>This is a test</div>;
}
}
`;
await benchmarkFiles({files: [{code, path: "sample.tsx"}], numIterations: 1, printOutput: true});
}
interface BenchmarkOptions {
// File contents to process in each iteration.
files: Array<FileInfo>;
// Number of times to compile the entire list of files.
numIterations: number;
// If true, run each benchmark for a few seconds untimed before starting the
// timed portion. This leads to a more stable benchmark result, but is not
// necessarily representative of the speed that would be seen in a typical
// build system (where warm-up cost often matters).
warmUp?: boolean;
// If true, print the resulting source code whenever a file is compiled. This
// is useful to spot check the output to ensure that each compiler is
// configured similarly.
printOutput?: boolean;
// If true, stop after benchmarking Sucrase. This is useful when comparing
// Sucrase to itself in different scenarios rather than when comparing it with
// other tools.
sucraseOnly?: boolean;
// If true, rather than printing human-readable text to stdout, print JSON
// (one JSON line per benchmark, though currently this is only used with
// sucraseOnly, so in that case stdout as a whole is valid JSON), so that the
// timing results can be read by other tools.
jsonOutput?: boolean;
}
/**
* Run the specified benchmark on all transpiler tools. In most cases, we can
* parse as TSX, but .ts files might use `<type>value` cast syntax, so we need
* to disable JSX parsing in that case.
*/
async function benchmarkFiles(benchmarkOptions: BenchmarkOptions): Promise<void> {
if (!benchmarkOptions.jsonOutput) {
console.log(`Testing against ${numLines(benchmarkOptions)} LOC`);
}
/* eslint-disable @typescript-eslint/require-await */
await runBenchmark("Sucrase", benchmarkOptions, async (code: string, path: string) => {
return sucrase.transform(code, {
transforms: path.endsWith(".ts")
? ["imports", "typescript"]
: ["jsx", "imports", "typescript"],
}).code;
});
if (benchmarkOptions.sucraseOnly) {
return;
}
// To run swc in single-threaded mode, we call into it repeatedly using
// transformSync, which seems to have minimal overhead.
await runBenchmark("swc", benchmarkOptions, async (code: string, path: string) => {
return swc.transformSync(code, {
jsc: {
parser: {
syntax: "typescript",
tsx: !path.endsWith(".ts"),
dynamicImport: true,
decorators: true,
},
target: "es2019",
},
module: {
type: "commonjs",
},
}).code;
});
// esbuild's transformSync has significant overhead since it spins up an
// external process, so instead create a "service" process and communicate to
// it. One way to force a single-threaded behavior is to sequentially call
// transform on the service, but that seems to have some IPC overhead, so we
// instead make transform calls in parallel and use an env variable to enforce
// that the Go process only uses a single thread.
process.env.GOMAXPROCS = "1";
const esbuildService = await esbuild.startService();
try {
await runBenchmark("esbuild", benchmarkOptions, async (code: string, path: string) => {
return (
await esbuildService.transform(code, {
loader: path.endsWith(".ts") ? "ts" : "tsx",
format: "cjs",
})
).code;
});
} finally {
esbuildService.stop();
}
await runBenchmark("TypeScript", benchmarkOptions, async (code: string) => {
return TypeScript.transpileModule(code, {
compilerOptions: {
module: TypeScript.ModuleKind.CommonJS,
jsx: TypeScript.JsxEmit.React,
target: TypeScript.ScriptTarget.ESNext,
},
}).outputText;
});
await runBenchmark("Babel", benchmarkOptions, async (code: string, path: string) => {
return babel.transformSync(code, {
filename: path.endsWith(".ts") ? "sample.ts" : "sample.tsx",
presets: path.endsWith(".ts")
? ["@babel/preset-typescript"]
: ["@babel/preset-react", "@babel/preset-typescript"],
plugins: [
"@babel/plugin-transform-modules-commonjs",
"@babel/plugin-syntax-top-level-await",
"@babel/plugin-proposal-export-namespace-from",
["@babel/plugin-proposal-decorators", {legacy: true}],
],
}).code;
});
/* eslint-enable @typescript-eslint/require-await */
}
export default async function runBenchmark(
name: string,
benchmarkOptions: BenchmarkOptions,
runTrial: (code: string, path: string) => Promise<string>,
): Promise<void> {
if (benchmarkOptions.warmUp) {
const warmUpTimeNanos = 3e9;
const warmUpStart = process.hrtime.bigint();
while (process.hrtime.bigint() - warmUpStart < warmUpTimeNanos) {
for (const file of benchmarkOptions.files) {
await runTrial(file.code, file.path);
if (process.hrtime.bigint() - warmUpStart >= warmUpTimeNanos) {
break;
}
}
}
}
const startTime = process.hrtime.bigint();
// Collect promises and await them all at the end rather than awaiting them
// sequentially. For esbuild, this seems to significantly reduce IPC overhead.
// For all other compilers, this has no effect, and the Promise overhead seems
// to be tiny.
const promises: Array<Promise<unknown>> = [];
for (let i = 0; i < benchmarkOptions.numIterations; i++) {
for (const file of benchmarkOptions.files) {
if (benchmarkOptions.printOutput) {
promises.push(
(async () => {
const code = await runTrial(file.code, file.path);
console.log(`\n\n${name} output for ${file.path}:\n${code}\n`);
})(),
);
} else {
promises.push(runTrial(file.code, file.path));
}
}
}
await Promise.all(promises);
const totalTime = Number(process.hrtime.bigint() - startTime) / 1e9;
if (benchmarkOptions.jsonOutput) {
console.log(
JSON.stringify({
name,
totalTime,
linesPerSecond: Math.round(numLines(benchmarkOptions) / totalTime),
totalLines: numLines(benchmarkOptions),
}),
);
} else {
console.log(getSummary(name, totalTime, benchmarkOptions));
}
}
function getSummary(name: string, totalTime: number, benchmarkOptions: BenchmarkOptions): string {
let summary = name;
while (summary.length < 12) {
summary += " ";
}
summary += `${Math.round(totalTime * 100) / 100} seconds`;
while (summary.length < 28) {
summary += " ";
}
summary += `${Math.round(numLines(benchmarkOptions) / totalTime)} lines per second`;
return summary;
}
function numLines(benchmarkOptions: BenchmarkOptions): number {
let result = 0;
for (const file of benchmarkOptions.files) {
result += file.code.split("\n").length - 1;
}
return result * benchmarkOptions.numIterations;
}
main().catch((e) => {
console.error("Unhandled error:");
console.error(e);
process.exitCode = 1;
}); | the_stack |
import {Number2, Number3, Number4} from '../../types/GlobalTypes';
import {Vector2} from 'three/src/math/Vector2';
import {Vector3} from 'three/src/math/Vector3';
import {Vector4} from 'three/src/math/Vector4';
import {Quaternion} from 'three/src/math/Quaternion';
import {Object3D} from 'three/src/core/Object3D';
import {TimelineBuilder, Operation} from './TimelineBuilder';
import {PropertyTarget} from './PropertyTarget';
import {BaseNodeType} from '../../engine/nodes/_Base';
import {BaseParamType} from '../../engine/params/_Base';
import {ParamType} from '../../engine/poly/ParamType';
import {FloatParam} from '../../engine/params/Float';
import {Vector2Param} from '../../engine/params/Vector2';
import {Vector3Param} from '../../engine/params/Vector3';
import {Vector4Param} from '../../engine/params/Vector4';
import {TypeAssert} from '../../engine/poly/Assert';
import {AnimNodeEasing} from './Constant';
import {Poly} from '../../engine/Poly';
import {CoreType} from '../Type';
export type AnimPropertyTargetValue = number | Vector2 | Vector3 | Vector4 | Quaternion;
interface Object3DProps {
target_property: AnimPropertyTargetValue;
to_target: object;
property_names: string[];
}
const PROPERTY_SEPARATOR = '.';
export class TimelineBuilderProperty {
private _property_name: string | undefined;
private _target_value: AnimPropertyTargetValue | undefined;
constructor() {}
setName(name: string) {
this._property_name = name;
}
setTargetValue(value: AnimPropertyTargetValue) {
this._target_value = value;
}
name() {
return this._property_name;
}
targetValue() {
return this._target_value;
}
private _debug = false;
setDebug(debug: boolean) {
this._debug = debug;
}
private _printDebug(message: any) {
if (!this._debug) {
return;
}
console.log(message);
}
clone() {
const cloned = new TimelineBuilderProperty();
if (this._property_name) {
cloned.setName(this._property_name);
}
if (this._target_value != null) {
const new_target_value = CoreType.isNumber(this._target_value)
? this._target_value
: this._target_value.clone();
cloned.setTargetValue(new_target_value);
}
return cloned;
}
addToTimeline(timeline_builder: TimelineBuilder, timeline: gsap.core.Timeline, target: PropertyTarget) {
const objects = target.objects();
if (objects) {
this._populateWithObjects(objects, timeline_builder, timeline);
}
const node = target.node();
if (node) {
this._populateWithNode(node, timeline_builder, timeline);
}
}
private _populateWithObjects(objects: Object3D[], timeline_builder: TimelineBuilder, timeline: gsap.core.Timeline) {
this._printDebug(['_populateWithObjects', objects]);
if (!this._property_name) {
Poly.warn('no property name given');
return;
}
if (this._target_value == null) {
Poly.warn('no target value given');
return;
}
const operation = timeline_builder.operation();
const update_callback = timeline_builder.updateCallback();
for (let object3d of objects) {
// const target_property = (object3d as any)[this._property_name as any] as TargetValue;
// let to_target: object | null = null;
const props = this._sceneGraphProps(object3d, this._property_name);
if (props) {
let {target_property, to_target, property_names} = props;
const vars = this._commonVars(timeline_builder);
// add update_matrix
if (update_callback && update_callback.updateMatrix()) {
const old_matrix_auto_update = object3d.matrixAutoUpdate;
vars.onStart = () => {
object3d.matrixAutoUpdate = true;
};
vars.onComplete = () => {
object3d.matrixAutoUpdate = old_matrix_auto_update;
// we still need to update the matrix manually here,
// as (it is specially noticeable on short animations)
// the last step of the timeline will not have the matrix updated
// and the object will therefore look like it has not fully completed
// its animation.
if (!object3d.matrixAutoUpdate) {
object3d.updateMatrix();
}
};
}
// handle quaternions as a special case
if (target_property instanceof Quaternion && this._target_value instanceof Quaternion) {
const proxy = {value: 0};
const qTarget = target_property;
const qStart = new Quaternion().copy(target_property);
const qEnd = this._target_value;
vars.onUpdate = () => {
qTarget.slerpQuaternions(qStart, qEnd, proxy.value);
};
to_target = proxy;
vars.value = 1;
}
if (CoreType.isNumber(this._target_value)) {
if (CoreType.isNumber(target_property)) {
for (let property_name of property_names) {
vars[property_name] = this.withOp(target_property, this._target_value, operation);
}
}
} else {
if (!CoreType.isNumber(target_property)) {
for (let property_name of property_names) {
vars[property_name] = this.withOp(
target_property[property_name as 'x'],
this._target_value[property_name as 'x'],
operation
);
}
}
}
if (to_target) {
this._startTimeline(timeline_builder, timeline, vars, to_target);
}
}
}
}
private _sceneGraphProps(object: object, property_name: string): Object3DProps | undefined {
const elements = property_name.split(PROPERTY_SEPARATOR);
if (elements.length > 1) {
const first_element = elements.shift() as string;
const sub_object = (object as any)[first_element as any] as object;
if (sub_object) {
const sub_property_name = elements.join(PROPERTY_SEPARATOR);
return this._sceneGraphProps(sub_object, sub_property_name);
}
} else {
const target_property = (object as any)[property_name as any] as AnimPropertyTargetValue;
let to_target: object | null = null;
const property_names: string[] = [];
if (CoreType.isNumber(target_property)) {
to_target = object;
property_names.push(property_name);
} else {
to_target = target_property;
if (this._target_value instanceof Vector2) {
property_names.push('x', 'y');
}
if (this._target_value instanceof Vector3) {
property_names.push('x', 'y', 'z');
}
if (this._target_value instanceof Vector4) {
property_names.push('x', 'y', 'z', 'w');
}
if (this._target_value instanceof Quaternion) {
// is_quaternion = true;
}
}
return {
target_property: target_property,
to_target: to_target,
property_names: property_names,
};
}
}
private _populateWithNode(node: BaseNodeType, timeline_builder: TimelineBuilder, timeline: gsap.core.Timeline) {
this._printDebug(['_populateWithNode', node]);
const target_param = node.p[this._property_name as any] as BaseParamType;
this._printDebug(['target_param', target_param]);
if (!target_param) {
Poly.warn(`${this._property_name} not found on node ${node.path()}`);
return;
}
if (target_param) {
this._populateVarsForParam(target_param, timeline_builder, timeline);
}
}
private _populateVarsForParam(
param: BaseParamType,
timeline_builder: TimelineBuilder,
timeline: gsap.core.Timeline
) {
this._printDebug(['_populateVarsForParam', param]);
switch (param.type()) {
case ParamType.INTEGER: {
return this._populateVarsForParamInteger(param as FloatParam, timeline_builder, timeline);
}
case ParamType.FLOAT: {
return this._populateVarsForParamFloat(param as FloatParam, timeline_builder, timeline);
}
case ParamType.VECTOR2: {
return this._populateVarsForParamVector2(param as Vector2Param, timeline_builder, timeline);
}
case ParamType.VECTOR3: {
return this._populateVarsForParamVector3(param as Vector3Param, timeline_builder, timeline);
}
case ParamType.VECTOR4: {
return this._populateVarsForParamVector4(param as Vector4Param, timeline_builder, timeline);
}
}
this._printDebug(`param type cannot be animated (yet): '${param.type()}' '${param.path()}'`);
}
private _populateVarsForParamInteger(
param: FloatParam,
timeline_builder: TimelineBuilder,
timeline: gsap.core.Timeline
) {
if (!CoreType.isNumber(this._target_value)) {
Poly.warn('value is not a numbber', this._target_value);
return;
}
const vars = this._commonVars(timeline_builder);
const proxy = {num: param.value};
vars.onUpdate = () => {
param.set(proxy.num);
};
const operation = timeline_builder.operation();
vars.num = this.withOp(param.value, this._target_value, operation);
this._startTimeline(timeline_builder, timeline, vars, proxy);
}
private _populateVarsForParamFloat(
param: FloatParam,
timeline_builder: TimelineBuilder,
timeline: gsap.core.Timeline
) {
if (!CoreType.isNumber(this._target_value)) {
Poly.warn('value is not a numbber', this._target_value);
return;
}
const vars = this._commonVars(timeline_builder);
const proxy = {num: param.value};
vars.onUpdate = () => {
param.set(proxy.num);
};
const operation = timeline_builder.operation();
vars.num = this.withOp(param.value, this._target_value, operation);
this._startTimeline(timeline_builder, timeline, vars, proxy);
}
private _populateVarsForParamVector2(
param: Vector2Param,
timeline_builder: TimelineBuilder,
timeline: gsap.core.Timeline
) {
if (!(this._target_value instanceof Vector2)) {
return;
}
const vars = this._commonVars(timeline_builder);
const proxy = param.value.clone();
const proxy_array: Number2 = [0, 0];
vars.onUpdate = () => {
proxy.toArray(proxy_array);
param.set(proxy_array);
};
const operation = timeline_builder.operation();
vars.x = this.withOp(param.value.x, this._target_value.x, operation);
vars.y = this.withOp(param.value.y, this._target_value.y, operation);
this._startTimeline(timeline_builder, timeline, vars, proxy);
}
private _populateVarsForParamVector3(
param: Vector3Param,
timeline_builder: TimelineBuilder,
timeline: gsap.core.Timeline
) {
if (!(this._target_value instanceof Vector3)) {
return;
}
const vars = this._commonVars(timeline_builder);
const proxy = param.value.clone();
const proxy_array: Number3 = [0, 0, 0];
vars.onUpdate = () => {
proxy.toArray(proxy_array);
param.set(proxy_array);
};
const operation = timeline_builder.operation();
vars.x = this.withOp(param.value.x, this._target_value.x, operation);
vars.y = this.withOp(param.value.y, this._target_value.y, operation);
vars.z = this.withOp(param.value.z, this._target_value.z, operation);
this._startTimeline(timeline_builder, timeline, vars, proxy);
}
private _populateVarsForParamVector4(
param: Vector4Param,
timeline_builder: TimelineBuilder,
timeline: gsap.core.Timeline
) {
if (!(this._target_value instanceof Vector4)) {
return;
}
const vars = this._commonVars(timeline_builder);
const proxy = param.value.clone();
const proxy_array: Number4 = [0, 0, 0, 0];
vars.onUpdate = () => {
proxy.toArray(proxy_array);
param.set(proxy_array);
};
const operation = timeline_builder.operation();
vars.x = this.withOp(param.value.x, this._target_value.x, operation);
vars.y = this.withOp(param.value.y, this._target_value.y, operation);
vars.z = this.withOp(param.value.z, this._target_value.z, operation);
vars.w = this.withOp(param.value.w, this._target_value.w, operation);
this._startTimeline(timeline_builder, timeline, vars, proxy);
}
private withOp(current_value: number, value: number, operation: Operation) {
switch (operation) {
case Operation.SET:
return value;
case Operation.ADD:
return current_value + value;
case Operation.SUBSTRACT:
return current_value - value;
}
TypeAssert.unreachable(operation);
}
private _commonVars(timeline_builder: TimelineBuilder) {
const duration = timeline_builder.duration();
const vars: gsap.TweenVars = {duration: duration};
// easing
const easing = timeline_builder.easing() || AnimNodeEasing.NONE;
if (easing) {
vars.ease = easing;
}
// delay
const delay = timeline_builder.delay();
if (delay != null) {
vars.delay = delay;
}
// repeat
const repeat_params = timeline_builder.repeatParams();
if (repeat_params) {
vars.repeat = repeat_params.count;
vars.repeatDelay = repeat_params.delay;
vars.yoyo = repeat_params.yoyo;
}
return vars;
}
private _startTimeline(
timeline_builder: TimelineBuilder,
timeline: gsap.core.Timeline,
vars: gsap.TweenVars,
target: object
) {
const position = timeline_builder.position();
const position_param = position ? position.toParameter() : undefined;
timeline.to(target, vars, position_param);
}
} | the_stack |
import * as utils from './utils/utils';
import {UnitDomainPeriodGenerator} from './unit-domain-period-generator';
import {
ChartConfig,
ChartSettings,
DataSources,
UnitGuide,
Expression,
GPLSpec,
ScaleConfig,
ScaleGuide,
Unit
} from './definitions';
export class SpecConverter {
spec: ChartConfig;
dist: GPLSpec;
constructor(spec: ChartConfig) {
this.spec = spec;
this.dist = {
sources: <DataSources>{
'?': {
dims: {},
data: [{}]
},
'/': {
dims: {},
data: []
}
},
scales: {
// jscs:disable disallowQuotedKeysInObjects
'x_null': {type: 'ordinal', source: '?'},
'y_null': {type: 'ordinal', source: '?'},
'size_null': {type: 'size', source: '?'},
'color_null': {type: 'color', source: '?'},
'split_null': {type: 'value', source: '?'},
'pos:default': {type: 'ordinal', source: '?'},
'size:default': {type: 'size', source: '?'},
'label:default': {type: 'value', source: '?'},
'color:default': {type: 'color', source: '?'},
'split:default': {type: 'value', source: '?'}
// jscs:enable disallowQuotedKeysInObjects
},
settings: spec.settings
};
}
convert() {
var srcSpec = this.spec;
var gplSpec = this.dist;
this.ruleAssignSourceDims(srcSpec, gplSpec);
this.ruleAssignStructure(srcSpec, gplSpec);
this.ruleAssignSourceData(srcSpec, gplSpec);
this.ruleApplyDefaults(gplSpec);
return gplSpec;
}
ruleApplyDefaults(spec: GPLSpec) {
var settings = spec.settings || {};
var traverse = (node, iterator, parentNode) => {
iterator(node, parentNode);
(node.units || []).map((x) => traverse(x, iterator, node));
};
var iterator = (childUnit: Unit, root: Unit) => {
childUnit.namespace = 'chart';
childUnit.guide = utils.defaults(
(childUnit.guide || {}),
{
animationSpeed: settings.animationSpeed || 0,
utcTime: settings.utcTime || false
}
);
// leaf elements should inherit coordinates properties
if (root && !childUnit.hasOwnProperty('units')) {
childUnit = utils.defaults(childUnit, {x: root.x, y: root.y});
var parentGuide = utils.clone(root.guide) || {};
childUnit.guide.x = utils.defaults(childUnit.guide.x || {}, parentGuide.x);
childUnit.guide.y = utils.defaults(childUnit.guide.y || {}, parentGuide.y);
childUnit.expression.inherit = root.expression.inherit;
}
if (root && !(childUnit.guide && childUnit.guide.hasOwnProperty('obsoleteVerticalStackOrder'))) {
childUnit.guide = Object.assign(childUnit.guide || {}, {
obsoleteVerticalStackOrder: (root.guide || {}).obsoleteVerticalStackOrder
});
}
return childUnit;
};
traverse(spec.unit, iterator, null);
}
ruleAssignSourceData(srcSpec: ChartConfig, gplSpec: GPLSpec) {
var meta = srcSpec.spec.dimensions || {};
var dims = gplSpec.sources['/'].dims;
var reduceIterator = (row, key) => {
let rowKey = row[key];
if (utils.isObject(rowKey) && !utils.isDate(rowKey)) {
Object.keys(rowKey).forEach((k) => (row[key + '.' + k] = rowKey[k]));
}
return row;
};
gplSpec.sources['/'].data = srcSpec
.data
.map((rowN) => {
var row = (Object.keys(rowN).reduce(reduceIterator, rowN));
return (Object.keys(dims).reduce(
(r, k) => {
if (!r.hasOwnProperty(k)) {
r[k] = null;
}
if ((r[k] !== null) && meta[k] && (['period', 'time'].indexOf(meta[k].scale) >= 0)) {
r[k] = new Date(r[k]);
}
return r;
},
row));
});
}
ruleAssignSourceDims(srcSpec: ChartConfig, gplSpec: GPLSpec) {
var dims = srcSpec.spec.dimensions;
gplSpec.sources['/'].dims = Object
.keys(dims)
.reduce((memo, k) => {
memo[k] = {type: dims[k].type};
return memo;
}, {});
}
ruleAssignStructure(srcSpec: ChartConfig, gplSpec: GPLSpec) {
var walkStructure = (srcUnit: Unit) => {
var gplRoot = utils.clone(utils.omit(srcUnit, 'unit'));
this.ruleCreateScales(srcUnit, gplRoot, gplSpec.settings);
gplRoot.expression = this.ruleInferExpression(srcUnit);
if (srcUnit.unit) {
gplRoot.units = srcUnit.unit.map(walkStructure);
}
return gplRoot;
};
var root = walkStructure(srcSpec.spec.unit);
root.expression.inherit = false;
gplSpec.unit = root;
}
ruleCreateScales(srcUnit: Unit, gplRoot: Unit, settings: ChartSettings) {
var guide = srcUnit.guide || {};
['identity', 'color', 'size', 'label', 'x', 'y', 'split'].forEach((p) => {
if (srcUnit.hasOwnProperty(p)) {
gplRoot[p] = this.scalesPool(p, srcUnit[p], guide[p] || {}, settings);
}
});
}
ruleInferDim(dimName: string, guide: ScaleGuide) {
var r = dimName;
var dims = this.spec.spec.dimensions;
if (!dims.hasOwnProperty(r)) {
return r;
}
if (guide.hasOwnProperty('tickLabel')) {
r = `${dimName}.${guide.tickLabel}`;
} else if (dims[dimName].value) {
r = `${dimName}.${dims[dimName].value}`;
}
var myDims = this.dist.sources['/'].dims;
if (!myDims.hasOwnProperty(r)) {
myDims[r] = {type:myDims[dimName].type};
delete myDims[dimName];
}
return r;
}
scalesPool(scaleType: string, dimName: string, guide: ScaleGuide, settings: ChartSettings) {
var k = `${scaleType}_${dimName}`;
if (this.dist.scales.hasOwnProperty(k)) {
return k;
}
var dims = this.spec.spec.dimensions;
var item = {} as ScaleConfig;
if (scaleType === 'color' && dimName !== null) {
item = {
type: 'color',
source: '/',
dim: this.ruleInferDim(dimName, guide)
} as ScaleConfig;
if (guide.hasOwnProperty('brewer')) {
item.brewer = guide.brewer;
}
if (dims[dimName] && dims[dimName].hasOwnProperty('order')) {
item.order = dims[dimName].order;
}
if (guide.hasOwnProperty('min')) {
item.min = guide.min;
}
if (guide.hasOwnProperty('max')) {
item.max = guide.max;
}
if (guide.hasOwnProperty('nice')) {
item.nice = guide.nice;
}
}
if (scaleType === 'size' && dimName !== null) {
item = {
type: 'size',
source: '/',
dim: this.ruleInferDim(dimName, guide)
};
if (guide.hasOwnProperty('func')) {
item.func = guide.func;
}
if (guide.hasOwnProperty('min')) {
item.min = guide.min;
}
if (guide.hasOwnProperty('max')) {
item.max = guide.max;
}
if (guide.hasOwnProperty('minSize')) {
item.minSize = guide.minSize;
}
if (guide.hasOwnProperty('maxSize')) {
item.maxSize = guide.maxSize;
}
}
if (scaleType === 'label' && dimName !== null) {
item = {
type: 'value',
source: '/',
dim: this.ruleInferDim(dimName, guide)
};
}
if (scaleType === 'split' && dimName !== null) {
item = {
type: 'value',
source: '/',
dim: this.ruleInferDim(dimName, guide)
};
}
if (scaleType === 'identity' && dimName !== null) {
item = {
type: 'identity',
source: '/',
dim: this.ruleInferDim(dimName, guide)
};
}
if (dims.hasOwnProperty(dimName) && (scaleType === 'x' || scaleType === 'y')) {
item = {
type: dims[dimName].scale,
source: '/',
dim: this.ruleInferDim(dimName, guide)
};
if (dims[dimName].hasOwnProperty('order')) {
item.order = dims[dimName].order;
}
if (guide.hasOwnProperty('min')) {
item.min = guide.min;
}
if (guide.hasOwnProperty('max')) {
item.max = guide.max;
}
if (guide.hasOwnProperty('autoScale')) {
item.autoScale = guide.autoScale;
} else {
item.autoScale = true;
}
if (guide.hasOwnProperty('nice')) {
item.nice = guide.nice;
} else {
// #121763
// for backward compatibility with "autoScale" property
item.nice = item.autoScale;
}
if (guide.hasOwnProperty('niceInterval')) {
item.niceInterval = guide.niceInterval;
} else {
item.niceInterval = null;
}
if (guide.hasOwnProperty('tickPeriod')) {
item.period = guide.tickPeriod;
item.type = 'period';
}
if (guide.hasOwnProperty('tickPeriod') && guide.hasOwnProperty('timeInterval')) {
throw new Error('Use "tickPeriod" for period scale, "timeInterval" for time scale, but not both');
}
if (guide.hasOwnProperty('timeInterval')) {
item.period = guide.timeInterval;
item.type = 'time';
let gen = UnitDomainPeriodGenerator.get(item.period, {utc: settings.utcTime});
if (guide.hasOwnProperty('min')) {
item.min = gen.cast(new Date(guide.min));
}
if (guide.hasOwnProperty('max')) {
item.max = gen.cast(new Date(guide.max));
}
}
item.fitToFrameByDims = guide.fitToFrameByDims;
item.ratio = guide.ratio;
}
this.dist.scales[k] = item;
return k;
}
getScaleConfig(scaleType: string, dimName: string) {
var k = `${scaleType}_${dimName}`;
return this.dist.scales[k];
}
ruleInferExpression(srcUnit: Unit) {
var expr = {
operator: 'none',
params: []
} as Expression;
var g = srcUnit.guide || {};
var gx = g.x || {};
var gy = g.y || {};
var scaleX = this.getScaleConfig('x', srcUnit.x);
var scaleY = this.getScaleConfig('y', srcUnit.y);
if (srcUnit.type.indexOf('ELEMENT.') === 0) {
if (srcUnit.color) {
expr = {
operator: 'groupBy',
params: [
this.ruleInferDim(srcUnit.color, g.color || {})
]
};
}
} else if (srcUnit.type === 'COORDS.RECT') {
if (srcUnit.unit.length === 1 && srcUnit.unit[0].type === 'COORDS.RECT') {
// jshint ignore:start
// jscs:disable requireDotNotation
if (scaleX.period || scaleY.period) {
expr = {
operator: 'cross_period',
params: [
this.ruleInferDim(srcUnit.x, gx),
this.ruleInferDim(srcUnit.y, gy),
scaleX.period,
scaleY.period
]
};
} else {
expr = {
operator: 'cross',
params: [
this.ruleInferDim(srcUnit.x, gx),
this.ruleInferDim(srcUnit.y, gy)
]
};
}
// jscs:enable requireDotNotation
// jshint ignore:end
}
}
return Object.assign({inherit: true, source: '/'}, expr);
}
} | the_stack |
import styles from './LocalCustomFormatter.module.scss';
/* tslint:disable */
export const LocalCustomFormatter = (e, t, r, n, i, a, o) => {
"use strict";
Object.defineProperty(t, "__esModule", {
value: !0
});
var s = (b = {},
b["toLocaleString()"] = !0,
b["toLocaleDateString()"] = !0,
b["toLocaleTimeString()"] = !0,
b)
, l = r.__assign((_ = {},
_["toString()"] = !0,
_.cos = !0,
_.sin = !0,
_["Date()"] = !0,
_["Number()"] = !0,
_), s)
, u = r.__assign({}, l, (S = {},
S["=="] = !0,
S["!="] = !0,
S[">="] = !0,
S["<="] = !0,
S[">"] = !0,
S["<"] = !0,
S["+"] = !0,
S["-"] = !0,
S["*"] = !0,
S["/"] = !0,
S[":"] = !0,
S["?"] = !0,
S["||"] = !0,
S["&&"] = !0,
S))
, c = {
div: !0,
span: !0,
a: !0,
img: !0,
svg: !0,
button: !0,
path: !0
}
, f = (w = {
href: !0,
rel: !0,
src: !0,
class: !0,
target: !0,
title: !0,
role: !0
},
w.iconName = !0,
w.d = !0,
w.alt = !0,
w)
, d = {
defaultClick: !0,
executeFlow: !0
}
, g = {
"background-color": !0,
fill: !0,
"background-image": !0,
border: !0,
"border-bottom": !0,
"border-bottom-color": !0,
"border-bottom-style": !0,
"border-bottom-width": !0,
"border-color": !0,
"border-left": !0,
"border-left-color": !0,
"border-left-style": !0,
"border-left-width": !0,
"border-right": !0,
"border-right-color": !0,
"border-right-style": !0,
"border-right-width": !0,
"border-style": !0,
"border-top": !0,
"border-top-color": !0,
"border-top-style": !0,
"border-top-width": !0,
"border-width": !0,
outline: !0,
"outline-color": !0,
"outline-style": !0,
"outline-width": !0,
"border-bottom-left-radius": !0,
"border-bottom-right-radius": !0,
"border-radius": !0,
"border-top-left-radius": !0,
"border-top-right-radius": !0,
"box-decoration-break": !0,
"box-shadow": !0,
"box-sizing": !0,
"overflow-x": !0,
"overflow-y": !0,
"overflow-style": !0,
rotation: !0,
"rotation-point": !0,
opacity: !0,
cursor: !0,
height: !0,
"max-height": !0,
"max-width": !0,
"min-height": !0,
"min-width": !0,
width: !0,
"flex-grow": !0,
"flex-shrink": !0,
"flex-flow": !0,
"flex-direction": !0,
"flex-wrap": !0,
"flex-basic": !0,
flex: !0,
"align-items": !0,
"box-align": !0,
"box-direction": !0,
"box-flex": !0,
"box-flex-group": !0,
"box-lines": !0,
"box-ordinal-group": !0,
"box-orient": !0,
"box-pack": !0,
font: !0,
"font-family": !0,
"font-size": !0,
"font-style": !0,
"font-variant": !0,
"font-weight": !0,
"font-size-adjust": !0,
"font-stretch": !0,
"grid-columns": !0,
"grid-rows": !0,
margin: !0,
"margin-bottom": !0,
"margin-left": !0,
"margin-right": !0,
"margin-top": !0,
"column-count": !0,
"column-fill": !0,
"column-gap": !0,
"column-rule": !0,
"column-rule-color": !0,
"column-rule-style": !0,
"column-rule-width": !0,
"column-span": !0,
"column-width": !0,
columns: !0,
padding: !0,
"padding-bottom": !0,
"padding-left": !0,
"padding-right": !0,
"padding-top": !0,
bottom: !0,
clear: !0,
clip: !0,
display: !0,
float: !0,
left: !0,
overflow: !0,
position: !0,
right: !0,
top: !0,
visibility: !0,
"z-index": !0,
"border-collapse": !0,
"border-spacing": !0,
"caption-side": !0,
"empty-cells": !0,
"table-layout": !0,
color: !0,
direction: !0,
"letter-spacing": !0,
"line-height": !0,
"text-align": !0,
"text-decoration": !0,
"text-indent": !0,
"text-transform": !0,
"unicode-bidi": !0,
"vertical-align": !0,
"white-space": !0,
"word-spacing": !0,
"hanging-punctuation": !0,
"punctuation-trim": !0,
"text-align-last": !0,
"text-justify": !0,
"text-outline": !0,
"text-shadow": !0,
"text-wrap": !0,
"word-break": !0,
"word-wrap": !0
}
, p = ["http://", "https://", "mailto:"]
, m = "DateTime"
, h = "Boolean"
, y = (x = {},
x.Number = !0,
x.Text = !0,
x.Title = !0,
x[m] = !0,
x.User = !0,
x.Choice = !0,
x[h] = !0,
x.Note = !0,
x.Image = !0,
x.Hyperlink = !0,
x.Lookup = !0,
x._IsRecord = !0,
x)
, v = function() {
function e(e) {
this._params = e;
this._errorStrings = e.errorStrings || n.default
}
e.prototype.evaluate = function() {
var e, t = [];
try {
this._cfr = JSON.parse(this._params.fieldRendererFormat);
e = this._cfr;
this._createElementHtml(e, t, 0);
if (!this._fAria) {
var r = this._errorStrings.ariaError || "ariaError";
console.error(r)
}
} catch (r) {
var n = "Failure: " + ("string" == typeof r ? r : r.message);
console.error(n);
t = [];
e && e.debugMode && t.push(a.default.encodeText(n));
this._error = n
}
return t.join("")
}
;
e.prototype.errors = function() {
return this._error || ""
}
;
e.prototype._createElementHtml = function(e, t, r) {
e.elmType || this._err("elmTypeMissing");
var n = e.elmType.toLowerCase()
, i = "a" === n;
if (!c[n]) {
var a = "";
for (var s in c)
a += s + " ";
this._err("elmTypeInvalid", n, a)
}
t.push("<" + n + " ");
if (e.style) {
t.push('style="');
for (var l in e.style)
this._createStyleAttr(l, e.style[l], t);
t.push('" ')
}
var u = e.attributes;
if (0 === r) {
u || (u = {});
if (u.class) {
var f = u.class;
f === String(f) ? u.class = "sp-field-customFormatter " + f : u.class = {
operator: "+",
operands: ["sp-field-customFormatter ", f]
}
} else
u.class = "sp-field-customFormatter"
}
if (u) {
if (i) {
var g = u.rel;
u.rel = "noopener noreferrer " + (g || "")
}
u.iconName && !u.class && (u.class = "");
for (var p in u)
if (this._isValidAttr(p)) {
t.push(" " + p + '="');
var m = u[p];
this._createValue(m, t, "href" === p || "src" === p);
if ("class" === p.toLowerCase()) {
var h = u.iconName;
if (h) {
t.push(" ");
var y = [];
this._createValue(h, y, !1);
y[0] && t.push(o.getIconClassName(y[0]))
}
}
t.push('" ')
} else
console.log("ignoring non-approved attribute " + p)
}
if ("button" === n && e.customRowAction && d[e.customRowAction.action]) {
t.push(' data-iscustomformatter="true" ');
t.push(' data-actionname="' + e.customRowAction.action + '" ');
t.push(' data-actionparams="');
this._createValue(e.customRowAction.actionParams, t, !1, !1);
t.push('" ')
}
t.push(">");
if (e.txtContent)
this._createValue(e.txtContent, t, !1, !1, !0);
else if (e.children)
for (var v = 0; v < e.children.length; v++)
this._createElementHtml(e.children[v], t, r + 1);
t.push("</" + n + ">")
}
;
e.prototype._isValidAttr = function(e) {
var t = Boolean(f[e])
, r = Boolean(new RegExp("^aria-[a-z]+$","g").exec(e));
r && (this._fAria = !0);
return t || r
}
;
e.prototype._createStyleAttr = function(e, t, r) {
if (g[e]) {
r.push(e + ":");
this._createValue(t, r, !1, !0);
r.push(";")
} else
console.log("Unsupported style attribute: " + e)
}
;
e.prototype._createValue = function(e, t, r, n, i) {
var o = this._eval(e, i);
null !== o && void 0 !== o || (o = "");
var s = "<br/>"
, l = o instanceof Date ? o.toLocaleString() : o.toString()
, u = a.default.encodeText(l);
if (r) {
this._validateUrl(u) || this._err("invalidProtocol");
s = "%0D%0A"
}
n && !this._validateStyleValue(u) && this._err("invalidStyleValue", u);
u = u.replace(/\r\n|\r|\n/g, s);
t.push(u)
}
;
e.prototype._validateStyleValue = function(e) {
for (var t = ["(", ":", "&", ";", "!"], r = "rgba(" === (e = e.toLowerCase()).substr(0, 5) ? 5 : 0, n = 0; n < t.length; n++)
if (e.indexOf(t[n], r) >= 0)
return !1;
return !0
}
;
e.prototype._validateUrl = function(e) {
if (!e)
return !0;
e = e.trim().toLowerCase();
for (var t = 0; t < p.length; t++) {
var r = p[t];
if (e.substr(0, r.length) === r)
return !0
}
return !(e.indexOf(":") >= 0 || e.indexOf("\\") >= 0 || e.indexOf("\") >= 0)
}
;
e.prototype._eval = function(e, t) {
if (void 0 !== e) {
if (null === e)
return null;
if ("string" == typeof e) {
if (0 === e.indexOf("@currentField")) {
var r = this._params.currentFieldName;
if ("@currentField" === e)
return !t || this._params.rowSchema[r] !== m && "_IsRecord" !== this._params.rowSchema[r] ? this._evalJsonPath(this._params.row, r) : this._params.row[r];
if (e.indexOf(".") !== "@currentField".length)
return e;
var n = r + e.substr("@currentField".length);
return this._evalJsonPath(this._params.row, n)
}
if ("@me" === e && this._params.pageContextInfo)
return this._params.pageContextInfo.userLoginName;
if ("@now" === e)
return new Date;
if (0 === e.indexOf("[$") && "]" === e[e.length - 1]) {
var i = e.substr(2, e.length - 3);
return this._evalJsonPath(this._params.row, i)
}
return e
}
if ("number" == typeof e || "boolean" == typeof e)
return e;
var a = e
, o = a.operator
, c = a.operands;
o || this._err("operatorMissing", JSON.stringify(a));
if (!u[o]) {
var f = "";
for (var d in u)
f += d + " ";
this._err("operatorInvalid", o, f, JSON.stringify(a))
}
void 0 !== c && void 0 !== c[0] || this._err("operandMissing", JSON.stringify(a));
if (!l[o])
return ":" === o || "?" === o ? this._ternaryEval(a, this._eval(c[1]), this._eval(c[2]), this._eval(c[0])) : "+" === o || "*" === o || "||" === o || "&&" === o ? this._multiOpEval(a) : this._twoOpEval(a, this._eval(c[0]), o, this._eval(c[1]));
1 !== c.length && this._err("operandNOnly", 1..toString(), JSON.stringify(e));
if ("toString()" === o)
return this._toString(this._eval(c[0]));
if ("Number()" === o) {
g = this._eval(c[0]);
return Number(g)
}
if ("Date()" === o) {
g = this._eval(c[0]);
return new Date(g)
}
if ("cos" === o)
return Math.cos(this._eval(c[0]));
if ("sin" === o)
return Math.sin(this._eval(c[0]));
if (s[o]) {
var g = this._eval(c[0]);
if (!Boolean(g))
return "";
var p = new Date(g);
if ("toLocaleString()" === o)
return p.toLocaleString();
if ("toLocaleDateString()" === o)
return p.toLocaleDateString();
if ("toLocaleTimeString()" === o)
return p.toLocaleTimeString()
}
}
}
;
e.prototype._toString = function(e) {
return null === e || void 0 === e ? "" : e.toString()
}
;
e.prototype._ternaryEval = function(e, t, r, n) {
void 0 !== t && void 0 !== r && void 0 !== n || this._err("operandNOnly", 3..toString(), JSON.stringify(e));
return n ? t : r
}
;
e.prototype._multiOpEval = function(e) {
var t = e.operator
, r = e.operands;
(void 0 === r || r.length < 2) && this._err("operandNOnly", 2..toString(), JSON.stringify(e));
for (var n = this._eval(r[0]), i = 1; i < r.length; i++) {
var a = this._eval(r[i]);
n = this._twoOpEval(e, n, t, a)
}
return n
}
;
e.prototype._twoOpEval = function(e, t, r, n) {
void 0 !== t && void 0 !== n || this._err("operandNOnly", 2..toString(), JSON.stringify(e));
if ("==" === r)
return t === n;
if ("!=" === r)
return t !== n;
if (">=" === r)
return t >= n;
if ("<=" === r)
return t <= n;
if (">" === r)
return t > n;
if ("<" === r)
return t < n;
if ("||" === r)
return t || n;
if ("&&" === r)
return t && n;
if ("+" === r)
return this._doAddOrSubstract(e, t, n, !0);
if ("-" === r)
return this._doAddOrSubstract(e, t, n, !1);
if ("*" === r) {
this._validateIsNum(e, t);
this._validateIsNum(e, n);
return t * n
}
if ("/" === r) {
this._validateIsNum(e, t);
this._validateIsNum(e, n);
return t / n
}
throw ""
}
;
e.prototype._doAddOrSubstract = function(e, t, r, n) {
var i, a = t instanceof Date || r instanceof Date;
if (n)
i = t.valueOf() + r.valueOf();
else {
if (!a) {
this._validateIsNum(e, t);
this._validateIsNum(e, r)
}
i = t.valueOf() - r.valueOf()
}
return a ? new Date(i) : i
}
;
e.prototype._validateIsNum = function(e, t) {
"number" != typeof t && this._err("nan", t.toString(), JSON.stringify(e))
}
;
e.prototype._evalJsonPath = function(e, t) {
var r, n = e;
try {
var i = t.split(".")
, a = this._params.rowSchema
, o = a[i[0]];
r = i.length;
if ("Number" === o || o === m || o === h || "_IsRecord" === o) {
var s = o === h ? ".value" : "."
, l = i[0] + s;
null != n[l] && void 0 !== n[l] && (i[0] = l)
}
if (("Hyperlink" === o || "Image" === o) && 2 === r && "desc" === i[1])
return n[t];
a && o && (y[o] || this._err("unsupportedType", t));
for (var u = "User" === o, c = "Lookup" === o, f = 0; f < r; f++) {
n = n[i[f]];
(u || c) && 0 === f && this.isArray(n) && (n = n[0])
}
} catch (e) {
console.log("could not evaluate " + t);
return null
}
if (void 0 === n) {
var d = t + " was not found on the data object.";
console.log(d);
if (this._cfr.debugMode)
throw d
}
return 1 === r ? this._convertValue(n, t) : n
}
;
e.prototype._convertValue = function(e, t) {
var r = this._params.rowSchema;
if (!r || !r[t])
return e;
switch (r[t]) {
case "Text":
case "Title":
case "Note":
case "Choice":
case "Image":
case "Hyperlink":
case "Lookup":
case "_IsRecord":
return e;
case h:
return "1" === e || "0" !== e && e;
case "Number":
var n = void 0;
n = "string" == typeof e ? parseFloat(e.replace(/,/g, "")) : Number(e);
return isNaN(n) ? "" : n;
case m:
return "string" == typeof e ? Boolean(e) ? new Date(e) : null : e;
case "User":
this._err("userFieldError", t);
break;
default:
this._err("unsupportedType", t)
}
}
;
e.prototype.isArray = function(e) {
return "[object Array]" === Object.prototype.toString.call(e)
}
;
e.prototype._err = function(e) {
for (var t = [], r = 1; r < arguments.length; r++)
t[r - 1] = arguments[r];
var n = "";
if (this._errorStrings && e && this._errorStrings[e]) {
var a = this._errorStrings[e];
n = i.format.apply(i, [a].concat(t))
} else
e && (n = "FieldRenderer Error: " + e);
throw n
}
;
return e
}();
t.CustomFormatter = v;
var b, _, S, w, x
};
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed 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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
export const LocalHtmlEncoding = (e, t) => {
"use strict";
function r(e) {
return i[e]
}
Object.defineProperty(t, "__esModule", {
value: !0
});
var n = /[<>&'"\\]/g
, i = {
"<": "<",
">": ">",
"&": "&",
'"': """,
"'": "'",
"\\": "\"
}
, a = function() {
var e: { (): any; encodeText: any; };
e =(() => {
var _e: any = function() {};
_e.encodeText = function(e) {
return e ? e.replace(n, r) : ""
};
return _e;
})();
return e
}();
t.default = a
}; | the_stack |
import { Base } from "../class/Base.js"
import { ClassUnion, Mixin } from "../class/Mixin.js"
import { required, validateRequiredProperties } from "../class/RequiredProperty.js"
import { ChainedIterator, CI, concatIterable, map, uniqueOnly } from "../collection/Iterator.js"
import { DEBUG } from "../environment/Debug.js"
import { OnCycleAction, WalkContext, WalkStep } from "../graph/WalkDepth.js"
//---------------------------------------------------------------------------------------------------------------------
/**
* Type alias for formula ids. A synonym for `number`
*/
export type FormulaId = number
let FORMULA_ID : FormulaId = 0
//---------------------------------------------------------------------------------------------------------------------
/**
* Type alias for cycle variables. Just a synonym for `symbol`
*/
export type Variable = symbol
/**
* Type for cycle resolution value. It maps every variable to a formula.
*/
export type CycleResolutionValue = Map<Variable, FormulaId>
export type CycleResolutionFormulas = Set<Formula>
//---------------------------------------------------------------------------------------------------------------------
/**
* Pre-defined constant formula id. If assigned to some variable, specifies, that this variable should keep the value proposed by user
* (user input), or, if there's none, its previous value.
*/
export const CalculateProposed : FormulaId = FORMULA_ID++
// export const CalculatePure : FormulaId = FORMULA_ID++
//---------------------------------------------------------------------------------------------------------------------
/**
* Class, describing a formula, which is part of the cyclic set. Formula just specifies its input variables and output variable,
* it does not contain actual calculation.
*
* It is assumed that formula can only be "activated" if all of its inputs has value. It can be either a value from the previous iteration,
* a value provided by user, or an output value of some other formula. See [[VariableInputState]] and [[CycleResolutionInput]].
*/
export class Formula extends Base {
/**
* The id of the formula. It is assigned automatically, should not be changed.
*/
formulaId : FormulaId = FORMULA_ID++
/**
* A set of the input variables for this formula.
*/
inputs : Set<Variable> = new Set()
/**
* An output variable for this formula.
*/
output : Variable
}
//---------------------------------------------------------------------------------------------------------------------
export class VariableWalkContext extends WalkContext<Variable | Formula> {
cache : FormulasCache
collectNext (sourceNode : Variable | Formula, toVisit : WalkStep<Variable | Formula>[]) {
if (sourceNode instanceof Formula) {
toVisit.push({ node : sourceNode.output, from : sourceNode, label : undefined })
} else {
const formulas = this.cache.formulasByInput.get(sourceNode)
formulas && formulas.forEach(formula => toVisit.push({ node : formula, from : sourceNode, label : undefined }))
}
}
}
//---------------------------------------------------------------------------------------------------------------------
export class FormulasCache extends Mixin(
[ Base ],
(base : ClassUnion<typeof Base>) =>
class FormulasCache extends base {
/**
* A set of variables, which forms cyclic computation
*/
variables : Set<Variable> = new Set()
/**
* A set of formulas, which forms cyclic computation
*/
formulas : Set<Formula> = new Set()
$formulasByInput : Map<Variable, Set<Formula>> = undefined
$formulasByOutput : Map<Variable, Set<Formula>> = undefined
get formulasByInput () : Map<Variable, Set<Formula>> {
if (this.$formulasByInput !== undefined) return this.$formulasByInput
this.fillCache()
return this.$formulasByInput
}
get formulasByOutput () : Map<Variable, Set<Formula>> {
if (this.$formulasByOutput !== undefined) return this.$formulasByOutput
this.fillCache()
return this.$formulasByOutput
}
add (formula : Formula) {
this.$formulasByInput = undefined
this.$formulasByOutput = undefined
this.formulas.add(formula)
}
has (formula : Formula) : boolean {
return this.formulas.has(formula)
}
fillCache () {
this.$formulasByInput = new Map()
this.$formulasByOutput = new Map()
this.formulas.forEach(formula => {
let formulasByOutput = this.$formulasByOutput.get(formula.output)
if (!formulasByOutput) {
formulasByOutput = new Set()
this.$formulasByOutput.set(formula.output, formulasByOutput)
}
formulasByOutput.add(formula)
formula.inputs.forEach(input => {
let formulasByInput = this.$formulasByInput.get(input)
if (!formulasByInput) {
formulasByInput = new Set()
this.$formulasByInput.set(input, formulasByInput)
}
formulasByInput.add(formula)
})
})
}
allInputVariables () : Iterable<Variable> {
return uniqueOnly(concatIterable(map(this.formulas, formula => formula.inputs.values())))
}
isCyclic () : boolean {
let isCyclic : boolean = false
const walkContext = VariableWalkContext.new({ cache : this, onCycle : () => { isCyclic = true; return OnCycleAction.Cancel } })
walkContext.startFrom(Array.from(this.allInputVariables()))
return isCyclic
}
}
){}
//---------------------------------------------------------------------------------------------------------------------
export type GraphInputsHash = string
//---------------------------------------------------------------------------------------------------------------------
/**
* Abstract description of the cycle. Does not include the default formula resolution, only variables and formulas. See also [[CycleResolution]].
*/
export class CycleDescription extends FormulasCache {
}
//---------------------------------------------------------------------------------------------------------------------
/**
* Class describing the cycle resolution process. Requires the abstract cycle [[description]] and a set of default formulas.
*
* The resolution is performed with [[CycleResolution.resolve]] method.
*
* Resolution are memoized, based on the input. You should generally have a single instance of this class for a single set of default formulas,
* to accumulate the results and make resolution fast.
*/
export class CycleResolution extends Base {
/**
* Abstract cycle description for this resolution.
*/
description : CycleDescription = undefined
/**
* A set of default formulas for this resolution. Default formulas specifies how the calculation should be performed, if there's no user input
* for any variable (or there's input for all of them). Also, default formulas are preferred, if several formulas can be chosen to continue the resolution.
*/
defaultResolutionFormulas : CycleResolutionFormulas = new Set()
resolutionsByInputHash : Map<GraphInputsHash, CycleResolutionValue> = new Map()
// the caching space is 3^var_num might need to clear the memory at some time
clear () {
this.resolutionsByInputHash.clear()
}
/**
* This method accepts an input object and returns a cycle resolution.
* Resolution are memoized, based on the input.
*
* @param input
*/
resolve (input : CycleResolutionInput) : CycleResolutionValue {
const cached = this.resolutionsByInputHash.get(input.hash)
if (cached !== undefined) return cached
const resolution = this.buildResolution(input)
this.resolutionsByInputHash.set(input.hash, resolution)
return resolution
}
buildResolution (input : CycleResolutionInput) : CycleResolutionValue {
const walkContext = WalkState.new({ context : this, input })
const allResolutions = Array.from(walkContext.next()).map(state => {
return {
resolution : state.asResolution(),
nbrOfDefaultFormulas : Array.from(state.activatedFormulas.formulas).reduce(
(count : number, formula : Formula) => state.formulaIsDefault(formula) ? count + 1 : count,
0
),
unCoveredInputWeight : state.unCoveredInputWeight()
}
})
allResolutions.sort((res1, res2) => {
if (res1.unCoveredInputWeight < res2.unCoveredInputWeight) return -1
if (res1.unCoveredInputWeight > res2.unCoveredInputWeight) return 1
return res2.nbrOfDefaultFormulas - res1.nbrOfDefaultFormulas
})
if (allResolutions.length > 0)
return allResolutions[ 0 ].resolution
else
debugger // return default? or all-proposed?
}
}
/**
* Enumeration for various states of the input data for variables in the cycle. Individual members corresponds to binary bits and can be set simultaneously, like:
*
* ```ts
* const input : VariableInputState = VariableInputState.HasPreviousValue | VariableInputState.HasProposedValue
* ```
*/
export enum VariableInputState {
NoInput = 0,
/**
* This bit indicates that variable has some previous value, when resolution starts. It can be any non-`undefined` value, including `null`.
*/
HasPreviousValue = 1,
/**
* This bit indicates that variable has user input, when resolution starts. It can be any non-`undefined` value, including `null`.
*/
HasProposedValue = 2,
/**
* This bit indicates, that user intention is to keep this variable unchanged, if that is possible (does not contradict to other user input).
*/
KeepIfPossible = 4,
}
//---------------------------------------------------------------------------------------------------------------------
/**
* Class, describing the input data for a set of variables during cycle resolution.
*/
export class CycleResolutionInput extends Base {
/**
* A cycle resolution instance this input corresponds to.
*/
@required
context : CycleResolution = undefined
private input : Map<Variable, VariableInputState> = undefined
private $hash : GraphInputsHash = ''
get hash () : GraphInputsHash {
if (this.$hash !== '') return this.$hash
return this.$hash = this.buildHash()
}
get description () : CycleDescription { return this.context.description }
/**
* Returns the same result as calling [[CycleResolution.resolve]] on this input instance
*/
get resolution () : CycleResolutionValue {
return this.context.resolve(this)
}
initialize (...args) {
super.initialize(...args)
validateRequiredProperties(this)
this.input = new Map(
CI(this.description.variables).map(variable => [ variable, VariableInputState.NoInput ])
)
}
buildHash () : GraphInputsHash {
return String.fromCharCode(...CI(this.description.variables).inBatchesBySize(5).map(batch => this.batchToCharCode(batch)))
}
batchToCharCode (batch : Variable[]) : number {
return batch.reduceRight(
(charCode, variable, index) => charCode | (this.input.get(variable) << index * 3),
0
)
}
//---------------------
/**
* This method sets the [[HasProposedValue]] flag for the specified variable.
*
* @param variable
*/
addProposedValueFlag (variable : Variable) {
if (DEBUG) {
if (!this.description.variables.has(variable)) throw new Error('Unknown variable')
if (this.$hash !== '') throw new Error('Already hashed')
}
const input = this.input.get(variable)
this.input.set(variable, input | VariableInputState.HasProposedValue)
}
hasProposedValue (variable : Variable) : boolean {
return Boolean(this.input.get(variable) & VariableInputState.HasProposedValue)
}
hasProposedValueVars () : ChainedIterator<Variable> {
return CI(this.description.variables).filter(variable => this.hasProposedValue(variable))
}
//---------------------
/**
* This method sets the [[HasPreviousValue]] flag for the specified variable.
*
* @param variable
*/
addPreviousValueFlag (variable : Variable) {
if (DEBUG) {
if (!this.description.variables.has(variable)) throw new Error('Unknown variable')
if (this.$hash !== '') throw new Error('Already hashed')
}
const input = this.input.get(variable)
this.input.set(variable, input | VariableInputState.HasPreviousValue)
}
hasPreviousValue (variable : Variable) : boolean {
return Boolean(this.input.get(variable) & VariableInputState.HasPreviousValue)
}
hasPreviousValueVars () : ChainedIterator<Variable> {
return CI(this.description.variables).filter(variable => this.hasPreviousValue(variable))
}
//---------------------
/**
* This method sets the [[KeepIfPossible]] flag for the specified variable.
*
* @param variable
*/
addKeepIfPossibleFlag (variable : Variable) {
if (DEBUG) {
if (!this.description.variables.has(variable)) throw new Error('Unknown variable')
if (this.$hash !== '') throw new Error('Already hashed')
}
const input = this.input.get(variable)
this.input.set(variable, input | VariableInputState.KeepIfPossible)
}
keepIfPossible (variable : Variable) : boolean {
return Boolean(this.input.get(variable) & VariableInputState.KeepIfPossible)
}
keepIfPossibleVars () : ChainedIterator<Variable> {
return CI(this.description.variables).filter(variable => this.keepIfPossible(variable))
}
}
//---------------------------------------------------------------------------------------------------------------------
export class WalkState extends Base {
context : CycleResolution = undefined
input : CycleResolutionInput = undefined
previous : WalkState = undefined
activatedFormula : Formula = undefined
private $activatedFormulas : FormulasCache = undefined
get activatedFormulas () : FormulasCache {
if (this.$activatedFormulas !== undefined) return this.$activatedFormulas
const cache = FormulasCache.new({
variables : this.description.variables,
formulas : CI(this.thisAndPreviousStates()).map(state => state.activatedFormula).toSet()
})
return this.$activatedFormulas = cache
}
get description () : CycleDescription { return this.context.description }
* thisAndPreviousStates () : Iterable<WalkState> {
let current : WalkState = this
while (current && current.activatedFormula) {
yield current
current = current.previous
}
}
formulaHasProposedValueInInput (formula : Formula) : boolean {
return Array.from(formula.inputs).some(variable => this.input.hasProposedValue(variable))
}
// this method counts
unCoveredInputWeight () : number {
const proposedVars = map(this.input.hasProposedValueVars(), variable => { return { variable, isProposed : true }})
const keepIfPossibleVars = map(this.input.keepIfPossibleVars(), variable => { return { variable, isProposed : false }})
const allInputVars = CI([ proposedVars, keepIfPossibleVars ]).concat().uniqueOnlyBy(el => el.variable)
return allInputVars.reduce((totalWeight : number, { variable, isProposed }) => {
let weight = 0
//-----------------
const isOverwrittenByFormulas = this.activatedFormulas.formulasByOutput.get(variable)
if (isOverwrittenByFormulas) {
const formula = isOverwrittenByFormulas.size === 1 ? Array.from(isOverwrittenByFormulas)[ 0 ] : null
// the case, when some user input is overwritten with the default formula should be weighted less than
// its overwritten with regular formula
if (formula && this.formulaIsDefault(formula) && this.formulaHasProposedValueInInput(formula)) {
if (isProposed)
weight += 1e6
else
weight += 1e4
} else {
if (isProposed)
weight += 1e7
else
weight += 1e5
}
}
//-----------------
const usedInFormulas = this.activatedFormulas.formulasByInput.get(variable)
if (!(usedInFormulas && usedInFormulas.size > 0)) {
if (isProposed)
weight += 1e3
else
weight += 1e2
}
return totalWeight + weight
}, 0)
}
preferFormula (formula1 : Formula, formula2 : Formula) : -1 | 0 | 1 {
const allInputsHasProposed1 = this.formulaAllInputsHasProposed(formula1)
const allInputsHasProposed2 = this.formulaAllInputsHasProposed(formula2)
if (allInputsHasProposed1 && !allInputsHasProposed2) return -1
if (allInputsHasProposed2 && !allInputsHasProposed1) return 1
const countInputsWithProposedOrKeep1 = this.formulaCountInputsWithProposedOrKeep(formula1)
const countInputsWithProposedOrKeep2 = this.formulaCountInputsWithProposedOrKeep(formula2)
if (countInputsWithProposedOrKeep1 > countInputsWithProposedOrKeep2) return -1
if (countInputsWithProposedOrKeep1 < countInputsWithProposedOrKeep2) return 1
if (this.formulaIsDefault(formula1) && !this.formulaIsDefault(formula2)) return -1
if (this.formulaIsDefault(formula2) && !this.formulaIsDefault(formula1)) return 1
return 0
}
formulaIsDefault (formula : Formula) : boolean {
return this.context.defaultResolutionFormulas.has(formula)
}
formulaCountInputsWithProposedOrKeep (formula : Formula) : number {
let count : number = 0
Array.from(formula.inputs).forEach(variable => {
if (this.input.hasProposedValue(variable) || this.input.keepIfPossible(variable)) count++
})
return count
}
formulaAllInputsHasProposedOrKeep (formula : Formula) : boolean {
return Array.from(formula.inputs).every(variable => this.input.hasProposedValue(variable) || this.input.keepIfPossible(variable))
}
formulaAllInputsHasProposed (formula : Formula) : boolean {
return Array.from(formula.inputs).every(variable => this.input.hasProposedValue(variable))
}
formulaIsApplicable (formula : Formula) : boolean {
const everyFormulaInputHasValue = Array.from(formula.inputs).every(
variable => this.input.hasProposedValue(variable)
|| this.input.hasPreviousValue(variable)
|| this.activatedFormulas.formulasByOutput.has(variable)
)
const cache = FormulasCache.new({ formulas : new Set(this.activatedFormulas.formulas) })
cache.add(formula)
return everyFormulaInputHasValue && !cache.isCyclic()
}
formulaIsInsignificant (formula : Formula) : boolean {
const outputVariableAlreadyCalculated = this.activatedFormulas.formulasByOutput.has(formula.output)
const outputVariableHasPreviousValue = this.input.hasPreviousValue(formula.output)
return outputVariableAlreadyCalculated
|| outputVariableHasPreviousValue && Array.from(formula.inputs).some(
variable => !this.input.hasPreviousValue(variable) && !this.input.hasProposedValue(variable)
)
}
unvisitedFormulas () : Formula[] {
return Array.from(this.description.formulas).filter(formula => !this.activatedFormulas.has(formula))
}
*next () : Iterable<WalkState> {
const unvisitedFormulas = this.unvisitedFormulas()
unvisitedFormulas.sort(this.preferFormula.bind(this))
let isFinal : boolean = true
for (const formula of unvisitedFormulas) {
if (!this.formulaIsApplicable(formula) || this.formulaIsInsignificant(formula)) continue
const nextState = WalkState.new({
previous : this,
context : this.context,
input : this.input,
activatedFormula : formula
})
yield* nextState.next()
isFinal = false
}
if (isFinal) yield this
}
asResolution () : CycleResolutionValue {
return new Map(
CI(this.description.variables).map(variable => {
const formulas = this.activatedFormulas.formulasByOutput.get(variable)
if (formulas) {
for (const firstFormula of formulas) {
return [ variable, firstFormula.formulaId ]
}
}
return [ variable, CalculateProposed ]
})
)
}
} | the_stack |
'use strict';
import TypeScriptProject = require('../ts-worker/project');
import TypeScriptProjectConfig = require('../commons/projectConfig');
import FileSystemMock = require('./fileSystemMock');
import WorkingSetMock = require('./workingSetMock');
import utils = require('../commons/typeScriptUtils');
describe('TypeScriptProject', function () {
var fileSystemMock: FileSystemMock,
workingSetMock: WorkingSetMock,
typeScriptProject: TypeScriptProject;
beforeEach(function () {
fileSystemMock = new FileSystemMock(),
workingSetMock = new WorkingSetMock();
});
var defaultLibLocation = '/lib.d.ts';
function createProject(baseDir: string, config: TypeScriptProjectConfig, init = true) {
typeScriptProject = new TypeScriptProject(
baseDir,
$.extend({}, utils.typeScriptProjectConfigDefault, config),
fileSystemMock,
workingSetMock,
defaultLibLocation
);
if (init) {
typeScriptProject.init();
}
};
afterEach(function () {
if (typeScriptProject) {
typeScriptProject.dispose();
typeScriptProject = null;
}
fileSystemMock.dispose();
workingSetMock.dispose();
});
function expectToBeEqualArray(actual: any[], expected: any[]) {
expect(actual.sort()).toEqual(expected.sort());
}
function testWorkingSetOpenCorrespondance() {
var languageServiceHost = typeScriptProject.getLanguageServiceHost();
typeScriptProject.getProjectFilesSet().values.forEach(fileName => {
expect(languageServiceHost.getScriptIsOpen(fileName)).toBe(workingSetMock.files.indexOf(fileName) !== -1);
});
}
function getProjectFileContent(fileName: string) {
var snapshot = typeScriptProject.getLanguageServiceHost().getScriptSnapshot(fileName);
return snapshot.getText(0, snapshot.getLength());
}
describe('initialization', function () {
it('should collect every files in the file system corresponding to the \'sources\' section of the given config', function () {
fileSystemMock.setFiles({
'/root/file1.ts': '',
'/root/project/file2.ts': '',
'/root/project/src/file3.ts': '',
'/root/project/src/file4.ts': '',
'/root/project/src/dir/file5.ts': '',
'/root/project/src/dir/file6.other': ''
});
createProject('/root/project/', {
sources : [
'../file1.ts',
'src/**/*ts'
]
});
waits(20);
runs(function () {
expectToBeEqualArray(typeScriptProject.getProjectFilesSet().values, [
'/root/file1.ts',
'/root/project/src/file3.ts',
'/root/project/src/file4.ts',
'/root/project/src/dir/file5.ts'
]);
});
});
it('should collect every files referenced or imported by files in the source ', function () {
fileSystemMock.setFiles({
'/src/file1.ts': 'import test = require("../other/file3")',
'/src/file2.ts': '///<reference path="../other/file4.ts"/>',
'/other/file3.ts': '///<reference path="./file5.ts"/>',
'/other/file4.ts': '',
'/other/file5.ts': ''
});
createProject('/', {
sources : [
'src/**/*ts'
]
});
waits(20);
runs(function () {
expectToBeEqualArray(typeScriptProject.getProjectFilesSet().values, [
'/src/file1.ts',
'/src/file2.ts',
'/other/file3.ts',
'/other/file4.ts',
'/other/file5.ts'
]);
});
});
it('should collect files added if they match the \'sources\' section of the given config', function () {
createProject('/', {
sources : [
'src/**/*ts'
]
});
fileSystemMock.addFile('/src/file1.ts', '');
waits(20);
runs(function () {
expectToBeEqualArray(typeScriptProject.getProjectFilesSet().values, [
'/src/file1.ts'
]);
});
});
it('should collect referenced files from file added ', function () {
fileSystemMock.setFiles({
'/other/file3.ts': '///<reference path="./file5.ts"/>',
'/other/file4.ts': '',
'/other/file5.ts': ''
});
createProject('/', {
sources : [
'src/**/*ts'
]
});
fileSystemMock.addFile('/src/file1.ts', 'import test = require("../other/file3")');
waits(20);
runs(function () {
expectToBeEqualArray(typeScriptProject.getProjectFilesSet().values, [
'/src/file1.ts',
'/other/file3.ts',
'/other/file5.ts'
]);
});
});
it('should collect files added if they are referenced by another file ', function () {
fileSystemMock.setFiles({
'/src/file1.ts': 'import test = require("../other/file2")'
});
createProject('/', {
sources : [
'src/**/*ts'
]
});
fileSystemMock.addFile('/other/file2.ts', '');
waits(20);
runs(function () {
expectToBeEqualArray(typeScriptProject.getProjectFilesSet().values, [
'/src/file1.ts',
'/other/file2.ts'
]);
});
});
it('should remove files from project when they are deleted', function () {
fileSystemMock.setFiles({
'/src/file1.ts': '',
'/src/file2.ts': ''
});
createProject('/', {
sources : [
'src/**/*ts'
]
});
fileSystemMock.removeFile('/src/file1.ts');
waits(20);
runs(function () {
expectToBeEqualArray(typeScriptProject.getProjectFilesSet().values, [
'/src/file2.ts'
]);
});
});
it('should remove referenced files from the project when a source file referencing it is deleted', function () {
fileSystemMock.setFiles({
'/src/file1.ts': 'import test = require("../other/file3")',
'/src/file2.ts': '',
'/other/file3.ts': '///<reference path="./file5.ts"/>',
'/other/file5.ts': ''
});
createProject('/', {
sources : [
'src/**/*ts'
]
});
fileSystemMock.removeFile('/src/file1.ts');
waits(20);
runs(function () {
expectToBeEqualArray(typeScriptProject.getProjectFilesSet().values, [
'/src/file2.ts'
]);
});
});
it('should remove referenced files from the project when a source file referencing it is deleted, ' +
'only if it is not referenced by another file', function () {
fileSystemMock.setFiles({
'/src/file1.ts': 'import test = require("../other/file3")',
'/src/file2.ts': 'import test = require("../other/file3")',
'/other/file3.ts': ''
});
createProject('/', {
sources : [
'src/**/*ts'
]
});
fileSystemMock.removeFile('/src/file1.ts');
waits(20);
runs(function () {
expectToBeEqualArray(typeScriptProject.getProjectFilesSet().values, [
'/src/file2.ts',
'/other/file3.ts'
]);
});
});
it('should remove a referenced files from the project when deleted', function () {
fileSystemMock.setFiles({
'/src/file1.ts': 'import test = require("../other/file3")',
'/src/file2.ts': 'import test = require("../other/file3")',
'/other/file3.ts': ''
});
createProject('/', {
sources : [
'src/**/*ts'
]
});
fileSystemMock.removeFile('/other/file3.ts');
waits(20);
runs(function () {
expectToBeEqualArray(typeScriptProject.getProjectFilesSet().values, [
'/src/file1.ts',
'/src/file2.ts'
]);
});
});
it('recollect a referenced files from the project when deleted then readded', function () {
fileSystemMock.setFiles({
'/src/file1.ts': 'import test = require("../other/file3")',
'/src/file2.ts': 'import test = require("../other/file3")',
'/other/file3.ts': ''
});
createProject('/', {
sources : [
'src/**/*ts'
]
});
fileSystemMock.removeFile('/other/file3.ts');
fileSystemMock.addFile('/other/file3.ts', '');
waits(20);
runs(function () {
expectToBeEqualArray(typeScriptProject.getProjectFilesSet().values, [
'/src/file1.ts',
'/src/file2.ts',
'/other/file3.ts'
]);
});
});
it('should update project files when they change', function () {
fileSystemMock.setFiles({
'/src/file1.ts': ''
});
createProject('/', {
sources : [
'src/**/*ts'
]
});
fileSystemMock.updateFile('/src/file1.ts', 'hello');
waits(20);
runs(function () {
expect(getProjectFileContent('/src/file1.ts')).toBe('hello');
});
});
it('should collect a file reference when a file change', function () {
fileSystemMock.setFiles({
'/src/file1.ts': '',
'/other/file2.ts' : ''
});
createProject('/', {
sources : [
'src/**/*ts'
]
});
fileSystemMock.updateFile('/src/file1.ts', '///<reference path="../other/file2.ts"/>');
waits(20);
runs(function () {
expectToBeEqualArray(typeScriptProject.getProjectFilesSet().values, [
'/src/file1.ts',
'/other/file2.ts'
]);
});
});
it('should remove referenced files when a file change, and does not reference them anymore', function () {
fileSystemMock.setFiles({
'/src/file1.ts': '///<reference path="../other/file2.ts"/>',
'/other/file2.ts' : ''
});
createProject('/', {
sources : [
'src/**/*ts'
]
});
fileSystemMock.updateFile('/src/file1.ts', '');
waits(20);
runs(function () {
expectToBeEqualArray(typeScriptProject.getProjectFilesSet().values, [
'/src/file1.ts'
]);
});
});
it('should add the default library if noLib is not specified or false', function () {
fileSystemMock.setFiles({
'/src/file1.ts': '',
'/lib.d.ts': ''
});
createProject('/', {
sources : [
'src/**/*ts'
]
});
waits(20);
runs(function () {
expect(typeScriptProject.getProjectFilesSet().has(defaultLibLocation)).toBe(true);
});
});
it('should not add the default library if noLib is not specified or false', function () {
fileSystemMock.setFiles({
'/src/file1.ts': '',
'/lib.d.ts': ''
});
createProject('/', {
sources : [
'src/**/*ts'
],
noLib: true
});
waits(20);
runs(function () {
expect(typeScriptProject.getProjectFilesSet().has(defaultLibLocation)).toBeFalsy();
});
});
it('should create a new typescript factory instance if a typescript path is specified', function () {
fileSystemMock.setFiles({
'/typescript/typescriptServices.js' :
'var TypeScript = {\
Services: {\
TypeScriptServicesFactory: function () { \
return { \
createCoreServices: function () { return {} }, \
createPullLanguageService: function () { return { id:\'hello\'} }\
}\
}\
}\
};',
'/lib.d.ts': ''
});
createProject('/', {
sources : [
'src/**/*ts'
],
typescriptPath: '/typescript'
});
waits(50);
runs(function () {
expect(typeScriptProject.getLanguageService()).toEqual({id: 'hello'});
});
});
});
describe('update', function () {
beforeEach(function () {
fileSystemMock.setFiles({
'/src/file1.ts': 'import file3 = require(\'./file3\');',
'/src/file2.ts': '///<reference path="./file4.ts" />',
'/src/file3.ts': '',
'/src/file4.ts': '',
'/lib.d.ts': ''
});
createProject('/', {
target: 'es5',
sources : [
'src/file1.ts'
]
});
waits(20);
});
function updateProject(config: TypeScriptProjectConfig) {
typeScriptProject.update($.extend({}, utils.typeScriptProjectConfigDefault, config));
}
it('should update compilerOptions if compiler options does have changed', function () {
expect(typeScriptProject.getLanguageServiceHost().getCompilationSettings().codeGenTarget)
.toBe(TypeScript.LanguageVersion.EcmaScript5);
updateProject({
target: 'es3',
module: 'commonjs',
sources : [ 'src/file1.ts' ]
});
waits(20);
runs(function () {
expect(typeScriptProject.getLanguageServiceHost().getCompilationSettings().codeGenTarget)
.toBe(TypeScript.LanguageVersion.EcmaScript3);
});
});
it('should remove project files that are not included anymore in the source', function () {
expect(typeScriptProject.getProjectFilesSet().has('/src/file1.ts')).toBe(true);
updateProject({
target: 'es3',
module: 'commonjs',
sources : []
});
waits(20);
runs(function () {
expect(typeScriptProject.getProjectFilesSet().has('/src/file1.ts')).toBeFalsy();
});
});
it('should add project files that matches the new configuration', function () {
expect(typeScriptProject.getProjectFilesSet().has('/src/file2.ts')).toBeFalsy();
updateProject({
target: 'es3',
module: 'commonjs',
sources : [
'src/file2.ts'
]
});
waits(20);
runs(function () {
expect(typeScriptProject.getProjectFilesSet().has('/src/file2.ts')).toBe(true);
});
});
it('should remove project files that are not referenced anymore in the source', function () {
expect(typeScriptProject.getProjectFilesSet().has('/src/file3.ts')).toBe(true);
updateProject({
target: 'es3',
module: 'commonjs',
sources : [
'src/file2.ts'
]
});
waits(20);
runs(function () {
expect(typeScriptProject.getProjectFilesSet().has('/src/file3.ts')).toBeFalsy();
});
});
it('should add project files that are now referenced by a file in the sources', function () {
expect(typeScriptProject.getProjectFilesSet().has('/src/file4.ts')).toBeFalsy();
updateProject({
target: 'es3',
module: 'commonjs',
sources : [
'src/file2.ts'
]
});
waits(20);
runs(function () {
expect(typeScriptProject.getProjectFilesSet().has('/src/file4.ts')).toBe(true);
});
});
it('should remove default lib if the new config noLib properties is set to true', function () {
expect(typeScriptProject.getProjectFilesSet().has('/lib.d.ts')).toBe(true);
updateProject({
target: 'es3',
module: 'commonjs',
noLib: true,
sources : []
});
waits(20);
runs(function () {
expect(typeScriptProject.getProjectFilesSet().has('/lib.d.ts')).toBeFalsy();
});
});
it('should mark as `open` files that have been added and that are in the working set', function () {
expect(typeScriptProject.getProjectFilesSet().has('/src/file2.ts')).toBeFalsy();
workingSetMock.files = [
'/src/file1.ts',
'/src/file2.ts'
];
updateProject({
target: 'es3',
module: 'commonjs',
sources : [
'src/file2.ts'
]
});
waits(20);
runs(function () {
testWorkingSetOpenCorrespondance();
});
});
it('should reinitialize the project if typeScriptPath has changed', function () {
var spy = spyOn(typeScriptProject, 'init').andCallThrough();
expect(typeScriptProject.getProjectFilesSet().has('/src/file2.ts')).toBeFalsy();
updateProject({
target: 'es3',
typescriptPath: 'typescript',
sources : [
'src/file2.ts'
]
});
expect(spy).toHaveBeenCalled();
});
});
describe('getProjectFileKind', function () {
it('should return \'SOURCE\' if the file path match the \'sources\' section of the given config', function () {
fileSystemMock.setFiles({
'/src/file1.ts': ''
});
createProject('/', {
sources : [
'src/**/*ts'
]
});
waits(20);
runs(function () {
expect(typeScriptProject.getProjectFileKind('/src/file1.ts')).toBe(TypeScriptProject.ProjectFileKind.SOURCE);
});
});
it('should return \'REFERENCE\' if the file is a referenced file', function () {
fileSystemMock.setFiles({
'/src/file1.ts': '///<reference path="../other/file2.ts"/>',
'/other/file2.ts' : ''
});
createProject('/', {
sources : [
'src/**/*ts'
]
});
waits(20);
runs(function () {
expect(typeScriptProject.getProjectFileKind('/other/file2.ts')).toBe(TypeScriptProject.ProjectFileKind.REFERENCE);
});
});
it('should return \'NONE\' if the file is a nor a part of the project', function () {
fileSystemMock.setFiles({
'/src/file1.ts': '',
'/other/file2.ts' : ''
});
createProject('/', {
sources : [
'src/**/*ts'
]
});
waits(20);
runs(function () {
expect(typeScriptProject.getProjectFileKind('/other/file2.ts')).toBe(TypeScriptProject.ProjectFileKind.NONE);
});
});
});
describe('working set handling', function () {
beforeEach(function () {
fileSystemMock.setFiles({
'/src/file1.ts': '',
'/src/file2.ts': '',
'/src/file3.ts': '',
'/src/file4.ts': '',
'/src/file5.ts': ''
});
workingSetMock.files = [
'/src/file1.ts',
'/src/file2.ts'
];
createProject('/', {
sources : [
'src/**/*ts'
]
});
waits(20);
});
it('should mark as \'open\' every file of the working set', function () {
testWorkingSetOpenCorrespondance();
});
it('should mark as \'open\' every file added to working set', function () {
workingSetMock.addFiles(['/src/file3.ts', '/src/file4.ts']);
waits(20);
runs(function () {
testWorkingSetOpenCorrespondance();
});
});
it('should mark as \'closed\' every file removed from the working set', function () {
workingSetMock.removeFiles(['/src/file1.ts']);
waits(20);
runs(function () {
testWorkingSetOpenCorrespondance();
});
});
});
describe('file edition', function () {
beforeEach(function () {
fileSystemMock.setFiles({
'/src/file1.ts': ''
});
workingSetMock.files = [
'/src/file1.ts'
];
createProject('/', {
sources : [
'src/**/*ts'
]
});
});
it('should edit a script when a document corresponding to a project file\'s is edited', function () {
workingSetMock.documentEdited.dispatch({
path: '/src/file1.ts',
changeList: [{
from: {
ch: 0,
line: 0
},
to: {
ch: 0,
line: 0,
},
text: 'console.log(\'hello world\')',
removed: ''
}],
documentText : 'console.log(\'hello world\')'
});
waits(20);
runs(function () {
expect(getProjectFileContent('/src/file1.ts')).toBe('console.log(\'hello world\')');
workingSetMock.documentEdited.dispatch({
path: '/src/file1.ts',
changeList: [{
from: {
ch: 8,
line: 0
},
to: {
ch: 11,
line: 0,
},
text: 'warn',
removed: '',
}],
documentText : 'console.warn(\'hello world\')'
});
});
waits(20);
runs(function () {
expect(getProjectFileContent('/src/file1.ts')).toBe('console.warn(\'hello world\')');
});
});
it('should set script with given document content if change dispatched does not have \'to\' or \'from\' property ', function () {
workingSetMock.documentEdited.dispatch({
path: '/src/file1.ts',
changeList: [{
from: {
ch: 0,
line: 0
}
}],
documentText : 'console.log(\'hello world\')'
});
waits(20);
runs(function () {
expect(getProjectFileContent('/src/file1.ts')).toBe('console.log(\'hello world\')');
workingSetMock.documentEdited.dispatch({
path: '/src/file1.ts',
changeList: [{
to: {
ch: 11,
line: 0,
}
}],
documentText : 'console.warn(\'hello world\')'
});
});
waits(20);
runs(function () {
expect(getProjectFileContent('/src/file1.ts')).toBe('console.warn(\'hello world\')');
});
});
it('should set script with given document content if change dispatched are not coherent', function () {
workingSetMock.documentEdited.dispatch({
path: '/src/file1.ts',
changeList: [{
from: {
ch: 0,
line: 0
},
to: {
ch: 0,
line: 0,
},
text: 'console.log(\'hello world\')',
removed: ''
}],
documentText : 'console.warn(\'hello world\')'
});
waits(20);
runs(function () {
expect(getProjectFileContent('/src/file1.ts')).toBe('console.warn(\'hello world\')');
});
});
it('should revert a file when a document have been closed without saving', function () {
workingSetMock.documentEdited.dispatch({
path: '/src/file1.ts',
changeList: [{
from: {
ch: 0,
line: 0
},
to: {
ch: 0,
line: 0,
},
text: 'console.log(\'hello world\')',
removed: ''
}],
documentText : 'console.log(\'hello world\')'
});
workingSetMock.removeFiles(['/src/file1.ts']);
waits(20);
runs(function () {
expect(getProjectFileContent('/src/file1.ts')).toBe('');
});
});
});
}); | the_stack |
import Page = require('../../../../base/Page');
import Response = require('../../../../http/response');
import V1 = require('../../V1');
import { SerializableClass } from '../../../../interfaces';
/**
* Initialize the NetworkAccessProfileNetworkList
*
* PLEASE NOTE that this class contains beta products that are subject to change.
* Use them with caution.
*
* @param version - Version of the resource
* @param networkAccessProfileSid - The unique string that identifies the Network Access Profile resource
*/
declare function NetworkAccessProfileNetworkList(version: V1, networkAccessProfileSid: string): NetworkAccessProfileNetworkListInstance;
interface NetworkAccessProfileNetworkListInstance {
/**
* @param sid - sid of instance
*/
(sid: string): NetworkAccessProfileNetworkContext;
/**
* create a NetworkAccessProfileNetworkInstance
*
* @param opts - Options for request
* @param callback - Callback to handle processed record
*/
create(opts: NetworkAccessProfileNetworkListInstanceCreateOptions, callback?: (error: Error | null, item: NetworkAccessProfileNetworkInstance) => any): Promise<NetworkAccessProfileNetworkInstance>;
/**
* Streams NetworkAccessProfileNetworkInstance records from the API.
*
* This operation lazily loads records as efficiently as possible until the limit
* is reached.
*
* The results are passed into the callback function, so this operation is memory
* efficient.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param callback - Function to process each record
*/
each(callback?: (item: NetworkAccessProfileNetworkInstance, done: (err?: Error) => void) => void): void;
/**
* Streams NetworkAccessProfileNetworkInstance records from the API.
*
* This operation lazily loads records as efficiently as possible until the limit
* is reached.
*
* The results are passed into the callback function, so this operation is memory
* efficient.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param opts - Options for request
* @param callback - Function to process each record
*/
each(opts?: NetworkAccessProfileNetworkListInstanceEachOptions, callback?: (item: NetworkAccessProfileNetworkInstance, done: (err?: Error) => void) => void): void;
/**
* Constructs a network_access_profile_network
*
* @param sid - The SID of the resource to fetch
*/
get(sid: string): NetworkAccessProfileNetworkContext;
/**
* Retrieve a single target page of NetworkAccessProfileNetworkInstance records
* from the API.
*
* The request is executed immediately.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param callback - Callback to handle list of records
*/
getPage(callback?: (error: Error | null, items: NetworkAccessProfileNetworkPage) => any): Promise<NetworkAccessProfileNetworkPage>;
/**
* Retrieve a single target page of NetworkAccessProfileNetworkInstance records
* from the API.
*
* The request is executed immediately.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param targetUrl - API-generated URL for the requested results page
* @param callback - Callback to handle list of records
*/
getPage(targetUrl?: string, callback?: (error: Error | null, items: NetworkAccessProfileNetworkPage) => any): Promise<NetworkAccessProfileNetworkPage>;
/**
* Lists NetworkAccessProfileNetworkInstance records from the API as a list.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param callback - Callback to handle list of records
*/
list(callback?: (error: Error | null, items: NetworkAccessProfileNetworkInstance[]) => any): Promise<NetworkAccessProfileNetworkInstance[]>;
/**
* Lists NetworkAccessProfileNetworkInstance records from the API as a list.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param opts - Options for request
* @param callback - Callback to handle list of records
*/
list(opts?: NetworkAccessProfileNetworkListInstanceOptions, callback?: (error: Error | null, items: NetworkAccessProfileNetworkInstance[]) => any): Promise<NetworkAccessProfileNetworkInstance[]>;
/**
* Retrieve a single page of NetworkAccessProfileNetworkInstance records from the
* API.
*
* The request is executed immediately.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param callback - Callback to handle list of records
*/
page(callback?: (error: Error | null, items: NetworkAccessProfileNetworkPage) => any): Promise<NetworkAccessProfileNetworkPage>;
/**
* Retrieve a single page of NetworkAccessProfileNetworkInstance records from the
* API.
*
* The request is executed immediately.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param opts - Options for request
* @param callback - Callback to handle list of records
*/
page(opts?: NetworkAccessProfileNetworkListInstancePageOptions, callback?: (error: Error | null, items: NetworkAccessProfileNetworkPage) => any): Promise<NetworkAccessProfileNetworkPage>;
/**
* Provide a user-friendly representation
*/
toJSON(): any;
}
/**
* Options to pass to create
*
* @property network - The SID that identifies the Network resource
*/
interface NetworkAccessProfileNetworkListInstanceCreateOptions {
network: string;
}
/**
* Options to pass to each
*
* @property callback -
* Function to process each record. If this and a positional
* callback are passed, this one will be used
* @property done - Function to be called upon completion of streaming
* @property limit -
* Upper limit for the number of records to return.
* each() guarantees never to return more than limit.
* Default is no limit
* @property pageSize -
* Number of records to fetch per request,
* when not set will use the default value of 50 records.
* If no pageSize is defined but a limit is defined,
* each() will attempt to read the limit with the most efficient
* page size, i.e. min(limit, 1000)
*/
interface NetworkAccessProfileNetworkListInstanceEachOptions {
callback?: (item: NetworkAccessProfileNetworkInstance, done: (err?: Error) => void) => void;
done?: Function;
limit?: number;
pageSize?: number;
}
/**
* Options to pass to list
*
* @property limit -
* Upper limit for the number of records to return.
* list() guarantees never to return more than limit.
* Default is no limit
* @property pageSize -
* Number of records to fetch per request,
* when not set will use the default value of 50 records.
* If no page_size is defined but a limit is defined,
* list() will attempt to read the limit with the most
* efficient page size, i.e. min(limit, 1000)
*/
interface NetworkAccessProfileNetworkListInstanceOptions {
limit?: number;
pageSize?: number;
}
/**
* Options to pass to page
*
* @property pageNumber - Page Number, this value is simply for client state
* @property pageSize - Number of records to return, defaults to 50
* @property pageToken - PageToken provided by the API
*/
interface NetworkAccessProfileNetworkListInstancePageOptions {
pageNumber?: number;
pageSize?: number;
pageToken?: string;
}
interface NetworkAccessProfileNetworkPayload extends NetworkAccessProfileNetworkResource, Page.TwilioResponsePayload {
}
interface NetworkAccessProfileNetworkResource {
friendly_name: string;
identifiers: object[];
iso_country: string;
network_access_profile_sid: string;
sid: string;
url: string;
}
interface NetworkAccessProfileNetworkSolution {
networkAccessProfileSid?: string;
}
declare class NetworkAccessProfileNetworkContext {
/**
* Initialize the NetworkAccessProfileNetworkContext
*
* PLEASE NOTE that this class contains beta products that are subject to change.
* Use them with caution.
*
* @param version - Version of the resource
* @param networkAccessProfileSid - The unique string that identifies the Network Access Profile resource
* @param sid - The SID of the resource to fetch
*/
constructor(version: V1, networkAccessProfileSid: string, sid: string);
/**
* fetch a NetworkAccessProfileNetworkInstance
*
* @param callback - Callback to handle processed record
*/
fetch(callback?: (error: Error | null, items: NetworkAccessProfileNetworkInstance) => any): Promise<NetworkAccessProfileNetworkInstance>;
/**
* remove a NetworkAccessProfileNetworkInstance
*
* @param callback - Callback to handle processed record
*/
remove(callback?: (error: Error | null, items: NetworkAccessProfileNetworkInstance) => any): Promise<boolean>;
/**
* Provide a user-friendly representation
*/
toJSON(): any;
}
declare class NetworkAccessProfileNetworkInstance extends SerializableClass {
/**
* Initialize the NetworkAccessProfileNetworkContext
*
* PLEASE NOTE that this class contains beta products that are subject to change.
* Use them with caution.
*
* @param version - Version of the resource
* @param payload - The instance payload
* @param networkAccessProfileSid - The unique string that identifies the Network Access Profile resource
* @param sid - The SID of the resource to fetch
*/
constructor(version: V1, payload: NetworkAccessProfileNetworkPayload, networkAccessProfileSid: string, sid: string);
private _proxy: NetworkAccessProfileNetworkContext;
/**
* fetch a NetworkAccessProfileNetworkInstance
*
* @param callback - Callback to handle processed record
*/
fetch(callback?: (error: Error | null, items: NetworkAccessProfileNetworkInstance) => any): Promise<NetworkAccessProfileNetworkInstance>;
friendlyName: string;
identifiers: object[];
isoCountry: string;
networkAccessProfileSid: string;
/**
* remove a NetworkAccessProfileNetworkInstance
*
* @param callback - Callback to handle processed record
*/
remove(callback?: (error: Error | null, items: NetworkAccessProfileNetworkInstance) => any): Promise<boolean>;
sid: string;
/**
* Provide a user-friendly representation
*/
toJSON(): any;
url: string;
}
declare class NetworkAccessProfileNetworkPage extends Page<V1, NetworkAccessProfileNetworkPayload, NetworkAccessProfileNetworkResource, NetworkAccessProfileNetworkInstance> {
/**
* Initialize the NetworkAccessProfileNetworkPage
*
* PLEASE NOTE that this class contains beta products that are subject to change.
* Use them with caution.
*
* @param version - Version of the resource
* @param response - Response from the API
* @param solution - Path solution
*/
constructor(version: V1, response: Response<string>, solution: NetworkAccessProfileNetworkSolution);
/**
* Build an instance of NetworkAccessProfileNetworkInstance
*
* @param payload - Payload response from the API
*/
getInstance(payload: NetworkAccessProfileNetworkPayload): NetworkAccessProfileNetworkInstance;
/**
* Provide a user-friendly representation
*/
toJSON(): any;
}
export { NetworkAccessProfileNetworkContext, NetworkAccessProfileNetworkInstance, NetworkAccessProfileNetworkList, NetworkAccessProfileNetworkListInstance, NetworkAccessProfileNetworkListInstanceCreateOptions, NetworkAccessProfileNetworkListInstanceEachOptions, NetworkAccessProfileNetworkListInstanceOptions, NetworkAccessProfileNetworkListInstancePageOptions, NetworkAccessProfileNetworkPage, NetworkAccessProfileNetworkPayload, NetworkAccessProfileNetworkResource, NetworkAccessProfileNetworkSolution } | the_stack |
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js';
import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js';
import 'chrome://resources/cr_elements/cr_search_field/cr_search_field.js';
import 'chrome://resources/cr_elements/icons.m.js';
import 'chrome://resources/cr_elements/shared_style_css.m.js';
import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js';
import 'chrome://resources/polymer/v3_0/iron-list/iron-list.js';
import 'chrome://resources/polymer/v3_0/paper-spinner/paper-spinner-lite.js';
import '../settings_shared_css.js';
import './site_data_entry.js';
import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js';
import {assert} from 'chrome://resources/js/assert.m.js';
import {focusWithoutInk} from 'chrome://resources/js/cr/ui/focus_without_ink.m.js';
import {ListPropertyUpdateMixin} from 'chrome://resources/js/list_property_update_mixin.js';
import {WebUIListenerMixin} from 'chrome://resources/js/web_ui_listener_mixin.js';
import {html, microTask, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {BaseMixin, BaseMixinInterface} from '../base_mixin.js';
import {GlobalScrollTargetMixin} from '../global_scroll_target_mixin.js';
import {loadTimeData} from '../i18n_setup.js';
import {MetricsBrowserProxyImpl, PrivacyElementInteractions} from '../metrics_browser_proxy.js';
import {routes} from '../route.js';
import {Route, Router} from '../router.js';
import {LocalDataBrowserProxy, LocalDataBrowserProxyImpl, LocalDataItem} from './local_data_browser_proxy.js';
type FocusConfig = Map<string, string|(() => void)>;
type SelectedItem = {
item: LocalDataItem,
index: number,
};
type RepeaterEvent = {
model: SelectedItem,
};
interface SiteDataElement {
$: {
confirmDeleteDialog: CrDialogElement,
confirmDeleteThirdPartyDialog: CrDialogElement,
removeShowingSites: HTMLElement,
removeAllThirdPartyCookies: HTMLElement,
};
}
const SiteDataElementBase = ListPropertyUpdateMixin(
GlobalScrollTargetMixin(WebUIListenerMixin(BaseMixin(PolymerElement))));
class SiteDataElement extends SiteDataElementBase {
static get is() {
return 'site-data';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
/**
* The current filter applied to the cookie data list.
*/
filter: {
observer: 'onFilterChanged_',
notify: true,
type: String,
},
focusConfig: {
type: Object,
observer: 'focusConfigChanged_',
},
isLoading_: Boolean,
sites: {
type: Array,
value() {
return [];
},
},
/**
* GlobalScrollTargetMixin
*/
subpageRoute: {
type: Object,
value: routes.SITE_SETTINGS_SITE_DATA,
},
lastFocused_: Object,
listBlurred_: Boolean,
};
}
filter: string;
focusConfig: FocusConfig;
private isLoading_: boolean;
sites: Array<LocalDataItem>;
subpageRoute: Route;
private listBlurred_: boolean;
private browserProxy_: LocalDataBrowserProxy =
LocalDataBrowserProxyImpl.getInstance();
private lastSelected_: SelectedItem|null;
constructor() {
super();
/**
* When navigating to site data details sub-page, |lastSelected_| holds the
* site name as well as the index of the selected site. This is used when
* navigating back to site data in order to focus on the correct site.
*/
this.lastSelected_ = null;
}
ready() {
super.ready();
this.addWebUIListener('on-tree-item-removed', () => this.updateSiteList_());
}
/**
* Reload cookies when the site data page is visited.
*
* RouteObserverMixin
*/
currentRouteChanged(currentRoute: Route, previousRoute: Route) {
super.currentRouteChanged(currentRoute);
// Reload cookies on navigation to the site data page from a different
// page. Avoid reloading on repeated navigations to the same page, as these
// are likely search queries.
if (currentRoute === routes.SITE_SETTINGS_SITE_DATA &&
currentRoute !== previousRoute) {
this.isLoading_ = true;
// Needed to fix iron-list rendering issue. The list will not render
// correctly until a scroll occurs.
// See https://crbug.com/853906.
const ironList = this.shadowRoot!.querySelector('iron-list')!;
ironList.scrollToIndex(0);
this.browserProxy_.reloadCookies().then(() => this.updateSiteList_());
}
}
private focusConfigChanged_(_newConfig: FocusConfig, oldConfig: FocusConfig) {
// focusConfig is set only once on the parent, so this observer should only
// fire once.
assert(!oldConfig);
// Populate the |focusConfig| map of the parent <settings-animated-pages>
// element, with additional entries that correspond to subpage trigger
// elements residing in this element's Shadow DOM.
if (routes.SITE_SETTINGS_DATA_DETAILS) {
const onNavigatedTo = () => microTask.run(() => {
if (this.lastSelected_ === null || this.sites.length === 0) {
return;
}
const lastSelectedSite = this.lastSelected_.item.site;
const lastSelectedIndex = this.lastSelected_.index;
this.lastSelected_ = null;
const indexFromId =
this.sites.findIndex(site => site.site === lastSelectedSite);
// If the site is no longer in |sites|, use the index as a fallback.
// Since the sites are sorted, an alternative could be to select the
// site that comes next in sort order.
const indexFallback = lastSelectedIndex < this.sites.length ?
lastSelectedIndex :
this.sites.length - 1;
const index = indexFromId > -1 ? indexFromId : indexFallback;
this.focusOnSiteSelectButton_(index);
});
this.focusConfig.set(
routes.SITE_SETTINGS_DATA_DETAILS.path, onNavigatedTo);
}
}
private focusOnSiteSelectButton_(index: number) {
const ironList = this.shadowRoot!.querySelector('iron-list')!;
ironList.focusItem(index);
const siteToSelect = this.sites[index].site.replace(/[.]/g, '\\.');
const button =
this.$$(`#siteItem_${siteToSelect}`)!.shadowRoot!.querySelector(
'.subpage-arrow')!;
focusWithoutInk(assert(button));
}
private onFilterChanged_(_current: string, previous?: string) {
// Ignore filter changes which do not occur on the site data page. The
// site settings data details subpage expects the tree model to remain in
// the same state.
if (previous === undefined ||
Router.getInstance().getCurrentRoute() !==
routes.SITE_SETTINGS_SITE_DATA) {
return;
}
this.updateSiteList_();
}
/**
* Gather all the site data.
*/
private updateSiteList_() {
this.isLoading_ = true;
this.browserProxy_.getDisplayList(this.filter).then(localDataItems => {
this.updateList('sites', item => item.site, localDataItems);
this.isLoading_ = false;
this.fire('site-data-list-complete');
});
}
/**
* Returns the string to use for the Remove label.
* @param filter The current filter string.
*/
private computeRemoveLabel_(filter: string): string {
if (filter.length === 0) {
return loadTimeData.getString('siteSettingsCookieRemoveAll');
}
return loadTimeData.getString('siteSettingsCookieRemoveAllShown');
}
private onCloseDialog_() {
this.$.confirmDeleteDialog.close();
}
private onCloseThirdPartyDialog_() {
this.$.confirmDeleteThirdPartyDialog.close();
}
private onConfirmDeleteDialogClosed_() {
focusWithoutInk(assert(this.$.removeShowingSites));
}
private onConfirmDeleteThirdPartyDialogClosed_() {
focusWithoutInk(assert(this.$.removeAllThirdPartyCookies));
}
/**
* Shows a dialog to confirm the deletion of multiple sites.
*/
onRemoveShowingSitesTap_(e: Event) {
e.preventDefault();
this.$.confirmDeleteDialog.showModal();
}
/**
* Shows a dialog to confirm the deletion of cookies available
* in third-party contexts and associated site data.
*/
private onRemoveThirdPartyCookiesTap_(e: Event) {
e.preventDefault();
this.$.confirmDeleteThirdPartyDialog.showModal();
}
/**
* Called when deletion for all showing sites has been confirmed.
*/
private onConfirmDelete_() {
this.$.confirmDeleteDialog.close();
if (this.filter.length === 0) {
MetricsBrowserProxyImpl.getInstance().recordSettingsPageHistogram(
PrivacyElementInteractions.SITE_DATA_REMOVE_ALL);
this.browserProxy_.removeAll().then(() => {
this.sites = [];
});
} else {
MetricsBrowserProxyImpl.getInstance().recordSettingsPageHistogram(
PrivacyElementInteractions.SITE_DATA_REMOVE_FILTERED);
this.browserProxy_.removeShownItems();
// We just deleted all items found by the filter, let's reset the filter.
this.fire('clear-subpage-search');
}
}
/**
* Called when deletion of all third-party cookies and site data has been
* confirmed.
*/
private onConfirmThirdPartyDelete_() {
this.$.confirmDeleteThirdPartyDialog.close();
this.browserProxy_.removeAllThirdPartyCookies().then(() => {
this.updateSiteList_();
});
}
private onSiteClick_(event: RepeaterEvent) {
// If any delete button is selected, the focus will be in a bad state when
// returning to this page. To avoid this, the site select button is given
// focus. See https://crbug.com/872197.
this.focusOnSiteSelectButton_(event.model.index);
Router.getInstance().navigateTo(
routes.SITE_SETTINGS_DATA_DETAILS,
new URLSearchParams('site=' + event.model.item.site));
this.lastSelected_ = event.model;
}
private showRemoveThirdPartyCookies_(): boolean {
return loadTimeData.getBoolean('enableRemovingAllThirdPartyCookies') &&
this.sites.length > 0 && this.filter.length === 0;
}
}
customElements.define(SiteDataElement.is, SiteDataElement); | the_stack |
import { VueConstructor } from 'vue';
import _ from 'lodash';
import { schemeCategory10 } from 'd3-scale-chromatic';
import { checkEdgeConnectivity } from '@/store/dataflow/util';
import { showSystemMessage } from '@/common/util';
import { Node } from '@/components/node';
import Edge, { EdgeSave } from '@/components/edge/edge';
import Port from '@/components/port/port';
import store from '@/store';
import {
DataflowState,
CreateNodeOptions,
DiagramSave,
CreateNodeData,
} from '@/store/dataflow/types';
import { getConstructor } from '@/store/dataflow/node-types';
import { propagateNode, propagateNodes, propagatePort, topologicalOrder } from '@/store/dataflow/propagate';
import { getInitialState } from '@/store/dataflow';
import { InputPort, OutputPort } from '@/components/port';
import DataflowCanvas from '@/components/dataflow-canvas/dataflow-canvas';
export * from '@/store/dataflow/propagate';
const dataflow = (): DataflowState => store.state.dataflow;
export const getNode = (id: string): Node => {
const node = dataflow().nodes.find(diagramNode => diagramNode.id === id);
if (!node) {
console.error(`node ${id} not found`);
}
return node as Node;
};
const getCanvas = (): DataflowCanvas => {
if (!dataflow().canvas) {
console.error('getCanvas() called with undefined canvas');
}
return dataflow().canvas as DataflowCanvas;
};
const getNodeDataOnCreate = (options: CreateNodeOptions): CreateNodeData => {
const data: CreateNodeData = {};
if (options.dataflowX !== undefined && options.dataflowY !== undefined) {
data.dataflowX = options.dataflowX;
data.dataflowY = options.dataflowY;
} else if (options.dataflowCenterX !== undefined && options.dataflowCenterY !== undefined) {
data.dataflowCenterX = options.dataflowCenterX;
data.dataflowCenterY = options.dataflowCenterY;
}
return data;
};
const assignNodeId = (state: DataflowState): string => {
const nodeIds = new Set(state.nodes.map(node => node.id));
for (let id = 1;; id++) {
const newId = `node-${id}`;
if (!nodeIds.has(newId)) {
return newId;
}
}
};
const NODE_TYPE_COMPATIBILITY_MAP: { [type: string]: string } = {
'loopback-control': 'data-reservoir',
'player': 'series-player',
};
export const createNode = (state: DataflowState, options: CreateNodeOptions, nodeSave?: object): Node => {
// backward compatibility
if (options.type in NODE_TYPE_COMPATIBILITY_MAP) {
options.type = NODE_TYPE_COMPATIBILITY_MAP[options.type];
}
const constructor = getConstructor(options.type) as VueConstructor;
const id = assignNodeId(state);
const dataOnCreate = getNodeDataOnCreate(options);
const node: Node = new constructor({
data: {
id,
dataOnCreate,
...(nodeSave || {}),
},
store,
}) as Node;
if (node.nodeType !== options.type) {
console.error(`NODE_TYPE not set on node ${options.type}`);
}
getCanvas().addNode(node);
state.nodes.push(node);
if (options.activate) {
node.activate();
node.select();
}
return node;
};
/**
* Creates a new node X on an edge going from port a to b, and replace the connection (a, b) by
* (a, X) and (X, b). Note that (a, X) and (X, b) may not always be connectable, so the newly created edges may contain
* zero, one, or two edges.
*/
export const insertNodeOnEdge = (state: DataflowState, node: Node, edge: Edge):
{ createdEdges: Edge[], removedEdge: Edge } => {
const edgeSource = edge.source;
const edgeTarget = edge.target;
// Removes the existing edge first to avoid connectiviy check failing because of existing connection.
removeEdge(state, edge, false);
const nodeOutputPort = node.findConnectablePort(edgeTarget) as OutputPort;
const result: { createdEdges: Edge[], removedEdge: Edge } = {
createdEdges: [],
removedEdge: edge,
};
let e1: Edge | null = null;
let e2: Edge | null = null;
if (nodeOutputPort) {
e1 = createEdgeToNode(state, edge.source, node, false, { disableMessage: true });
e2 = createEdge(state, nodeOutputPort, edgeTarget, false, { disableMessage: true });
result.createdEdges = [e1, e2].filter(e => e !== null) as Edge[];
}
if (e1) {
propagatePort(edgeSource);
}
if (e2 && !e1) {
propagateNode(node);
}
return result;
};
export const createEdge = (state: DataflowState, sourcePort: OutputPort, targetPort: InputPort,
propagate: boolean, options?: { disableMessage: boolean }): Edge | null => {
const connectivity = checkEdgeConnectivity(sourcePort, targetPort);
if (!connectivity.connectable) {
if (!(options && options.disableMessage)) {
showSystemMessage(store, connectivity.reason, 'warn');
}
return null;
}
const edge = new Edge({
data: {
// always create edge from output port to input port
source: !sourcePort.isInput ? sourcePort : targetPort,
target: !sourcePort.isInput ? targetPort : sourcePort,
},
store,
});
sourcePort.addIncidentEdge(edge);
targetPort.addIncidentEdge(edge);
getCanvas().addEdge(edge);
if (propagate) {
propagateNode(edge.target.node);
}
return edge;
};
/**
* Creates an edge from the sourceNode to the targetPort. A connectable port is automatically found on the sourceNode.
*/
export const createEdgeFromNode = (state: DataflowState, sourceNode: Node, targetPort: InputPort,
propagate: boolean, options?: { disableMessage: boolean }): Edge | null => {
const sourcePort = sourceNode.findConnectablePort(targetPort) as OutputPort;
if (!sourcePort) {
if (!(options && options.disableMessage)) {
showSystemMessage(store, 'cannot find available port to connect', 'warn');
}
return null;
}
return createEdge(state, sourcePort, targetPort, propagate);
};
/**
* Creates an edge from the sourcePort to the targetNode. A connectable port is automatically found on the targetNode.
*/
export const createEdgeToNode = (state: DataflowState, sourcePort: OutputPort, targetNode: Node,
propagate: boolean, options?: { disableMessage: boolean }): Edge | null => {
const targetPort = targetNode.findConnectablePort(sourcePort) as InputPort;
if (!targetPort) {
if (!(options && options.disableMessage)) {
showSystemMessage(store, 'cannot find available port to connect', 'warn');
}
return null;
}
return createEdge(state, sourcePort, targetPort, propagate);
};
export const removeEdge = (state: DataflowState, edge: Edge, propagate: boolean) => {
edge.source.removeIncidentEdge(edge);
edge.target.removeIncidentEdge(edge);
if (propagate) {
propagateNode(edge.target.node);
}
getCanvas().removeEdge(edge, () => edge.$destroy());
};
export const removeNode = (state: DataflowState, node: Node, propagate: boolean): { removedEdges: Edge[] } => {
const outputNodes = node.getOutputNodes();
const edgesToRemove = node.getAllEdges();
for (const edge of edgesToRemove) {
removeEdge(state, edge, false);
}
if (propagate) {
propagateNodes(outputNodes);
}
_.pull(state.nodes, node);
getCanvas().removeNode(node, () => node.$destroy());
return { removedEdges: edgesToRemove };
};
// Returns removed nodes and edges.
export const removeSelectedNodes = (state: DataflowState): { removedNodes: Node[], removedEdges: Edge[] } => {
const affectedOutputNodes: Set<Node> = new Set();
const nodes = state.nodes.filter(node => node.isSelected);
for (const node of nodes) {
for (const toNode of node.getOutputNodes()) {
if (_.indexOf(nodes, toNode) === -1) {
affectedOutputNodes.add(toNode);
}
}
}
let removedEdges: Edge[] = [];
for (const node of nodes) {
removedEdges = removedEdges.concat(removeNode(state, node, false).removedEdges);
}
propagateNodes(Array.from(affectedOutputNodes));
return {
removedNodes: nodes,
removedEdges,
};
};
export const disconnectPort = (state: DataflowState, port: Port, propagate: boolean): Edge[] => {
const affectedNodes = port.isInput ? [port.node] : port.getConnectedNodes();
const removedEdges = port.getAllEdges();
for (const edge of removedEdges) {
removeEdge(state, edge, false);
}
if (propagate) {
propagateNodes(affectedNodes);
}
return removedEdges;
};
/**
* Resets the dataflow diagram by clearing the nodes and edges.
* If resetDiagramInfo is true, the diagram name and file name (saved diagram info) will also be cleared.
*/
export const resetDataflow = (resetDiagramInfo: boolean) => {
const state = store.state.dataflow;
for (const node of _.clone(state.nodes)) { // Make a clone to avoid mutating a list currently being traversed.
removeNode(state, node, false);
}
_.extend(state, _.omit(getInitialState(), 'canvas', !resetDiagramInfo ? [ 'diagramName', 'filename' ] : []));
};
export const serializeDiagram = (state: DataflowState): DiagramSave => {
const serializedEdges: EdgeSave[] = [];
for (const node of state.nodes) {
const edges = node.getOutputEdges();
for (const edge of edges) {
serializedEdges.push(edge.serialize());
}
}
return {
diagramName: state.diagramName,
nodes: state.nodes.map(node => node.serialize()),
edges: serializedEdges,
};
};
export const deserializeDiagram = (diagram: DiagramSave) => {
const state = store.state.dataflow;
// Turn on deserializing flag to avoid nodes trigger propagation.
state.isDeserializing = true;
const sources = diagram.nodes.map(nodeSave => {
const node = createNode(
state,
{ type: nodeSave.type },
nodeSave,
);
node.deserialize(nodeSave);
node.deactivate(); // Avoid all nodes being active.
return node;
}).filter(node => node.isPropagationSource);
state.numNodeLayers = _.max(diagram.nodes.map(node => node.layer)) || 0;
for (const edgeSave of diagram.edges) {
const sourceNode = state.nodes.find(node => node.id === edgeSave.sourceNodeId) as Node;
const targetNode = state.nodes.find(node => node.id === edgeSave.targetNodeId) as Node;
const sourcePort = sourceNode.getOutputPort(edgeSave.sourcePortId);
const targetPort = targetNode.getInputPort(edgeSave.targetPortId);
createEdge(state, sourcePort, targetPort, false);
}
state.isDeserializing = false;
propagateNodes(sources);
};
export const dataMutationBoundary = (visible: boolean) => {
const state = store.state.dataflow;
const visited = new Set<Node>();
const boundary = new Set<Node>();
const traverse = (node: Node, color: string) => {
if (visited.has(node)) {
return;
}
visited.add(node);
if (node.isDataMutated) {
boundary.add(node);
return;
}
node.setBoundaryColor(color);
for (const to of node.getOutputNodes()) {
traverse(to, color);
}
};
const order = topologicalOrder(state.nodes);
let colors: string[] = [];
order.forEach(node => {
if (!colors.length) {
colors = schemeCategory10.concat();
}
if (!visited.has(node)) {
traverse(node, visible ? colors.shift() as string : '');
}
});
for (const node of boundary) {
node.setBoundaryColor(visible ? 'black' : '');
}
}; | the_stack |
import { BlockPort } from "../Define/Port";
import { Block } from "../Define/Block";
import { BlockGraphDocunment, BlockDocunment } from "../Define/BlockDocunment";
import BaseBlocks from '../Blocks/BaseBlocks'
import logger from "../../utils/Logger";
import { BlockRunContextData } from "./BlockRunContextData";
import CommonUtils from "@/utils/CommonUtils";
import BlockServiceInstance from "@/sevices/BlockService";
/**
* 流图运行器
*/
export class BlockRunner {
public static TAG = '流图运行器';
/**
* 队列 FIFO
*/
public queue : Array<BlockRunContextData> = [];
/**
* 获取当前运行上下文
*/
public currentRunningContext : BlockRunContextData = null;
/**
* 获取当前运行的文档
*/
public currentDocunment : BlockDocunment = null;
/**
* 获取运行器状态
*/
public state : RunnerState = null;
/**
* 获取或设置是否单步执行
*/
public stepMode = false;
/**
* 主运行上下文
*/
public mainContext : BlockRunContextData = null;
/**
* 最大调用栈数,默认64
*/
public maxStackCount = 64;
/**
* 最大参数栈数,默认1024
*/
public maxParamStackCount = 1024;
/**
* 上下文
*/
public contexts : BlockRunContextData[] = [];
private loop : any = null;
private loopCount = 0;
/**
* 开始运行
*/
public start() {
this.state = 'running';
if(this.loop != null)
clearInterval(this.loop);
this.loopCount = 0;
this.loop = setInterval(() => this.mainloop(), 100);
}
/**
* 暂停运行
*/
public pause() {
clearInterval(this.loop);
this.loop = null;
this.state = 'stopped';
}
/**
* 停止运行
*/
public stop() {
this.pause();
this.clear();
}
/**
* 清空运行数据
*/
public clear() {
clearInterval(this.loop);
if(this.mainContext != null) {
this.destroyContext(this.mainContext);
this.mainContext = null;
}
if(this.currentDocunment != null) {
this.endAllBlockRun(this.currentDocunment);
this.currentDocunment = null;
}
if(this.contexts.length > 0) {
this.contexts.forEach((c) => {
c.stackCalls.empty();
});
this.contexts.empty();
}
this.queue.empty();
this.loop = null;
this.state = 'stopped';
this.currentRunningContext = null;
}
/**
* 向队列末尾添加一个任务
* @param startPort 起始节点
* @param workType 执行方式
*/
public push(startPort : BlockPort, parentContext : BlockRunContextData, workType : RunnerWorkType = 'connector') {
let data = new BlockRunContextData(this, startPort, parentContext, workType);
this.queue.push(data);
return data;
}
private shift() {
if(this.queue.length > 0)
return this.queue.shift();
return null;
}
private endRunningContext(runningContext : BlockRunContextData) {
runningContext.currentBlock = null;
runningContext.currentPort = null;
}
private destroyContext(runningContext : BlockRunContextData) {
if(runningContext.destroyed)
return;
runningContext.graphBlockParamStack.empty();
runningContext.graphParamStack.empty();
runningContext.childContext.forEach((c) => this.destroyContext(c));
runningContext.childContext.empty();
if(runningContext.parentContext != null) {
runningContext.parentContext.childContext.remove(runningContext);
this.testContextEnd(runningContext.parentContext);//子移除了,现在再次检查父级是不是被孤立的
runningContext.parentContext = null;
}
runningContext.destroyed = true;
//移除
this.contexts.remove(runningContext);
if(this.currentRunningContext === runningContext)
this.currentRunningContext = null;
}
private mainloop() {
if(this.loopCount < 0xffff) this.loopCount++;
else this.loopCount = 0;
//回收上下文
if(this.loopCount % 30 == 0) this.loopForReallocContexts();
//运行任务队列
this.currentRunningContext = this.shift();
//无任务,空闲
if(this.currentRunningContext == null) {
if(this.state != 'idle') {
this.state = 'idle';
if(typeof this.onRunnerIdle == 'function')
this.onRunnerIdle();
}
return;
}
this.state = 'running';
let currentPort = this.currentRunningContext.currentPort;
if(!currentPort) {
logger.warning(BlockRunner.TAG, `Context ${this.currentRunningContext.stackLevel} should be remove when destroy`);
return;
}
if(this.currentRunningContext.loopLifeTime > 0) {//周期允许
this.currentRunningContext.loopLifeTime--;
if(currentPort.paramType.isExecute()) {
//激活对应端口
if(this.currentRunningContext.workType == 'connector')
this.excuteContext(this.currentRunningContext, currentPort);
else {
currentPort.active(this.currentRunningContext);
if(this.currentRunningContext != null)
this.testContextEnd(this.currentRunningContext);
}
}
}else {
//队列周期已用完,任务将在下一个队列任务中运行
this.currentRunningContext.loopLifeTime = 5;
this.queue.push(this.currentRunningContext);
}
}
private excuteContext(runningContext : BlockRunContextData, currentPort : BlockPort) {
//激活下一个端口
if(currentPort.direction == 'output' && currentPort.connectedToPort.length > 0) {
if(this.stepMode) {//单步执行模式
let nextPort = currentPort.connectedToPort[0].port;
nextPort.parent.onPortConnectorActive.invoke(nextPort, currentPort.connectedToPort[0].connector);
this.markInterrupt(runningContext, nextPort, nextPort.parent);
} else {
//开始事件
if(runningContext.loopNotStart)
runningContext.loopNotStart = false;
//激活端口
let nextPort = currentPort.connectedToPort[0].port;
try{
nextPort.parent.onPortConnectorActive.invoke(nextPort, currentPort.connectedToPort[0].connector);
nextPort.active(runningContext);
}catch(e) {
logger.warning(BlockRunner.TAG, `Catch exception in context ${this.currentRunningContext.stackLevel} when active ` +
`port ${nextPort.getName()}\nStack: ${runningContext.printCallStack(false)}`);
}
this.testContextEnd(runningContext);
}
}
}
private testContextEnd(runningContext : BlockRunContextData) {
//检查上下文是否已经运行完毕,完毕则销毁对应上下文
if(runningContext.parentContext != null
&& !runningContext.loopForceInUse
&& !this.queue.contains(runningContext)
&& runningContext.childContext.length == 0) //没有子上下文才销毁
this.destroyContext(runningContext);
}
private loopForReallocContexts() {
this.contexts.forEach(c => this.testContextEnd(c));
}
/**
* 激活下一个连接点
* @param runningContext 当前运行上下文
* @param currentPort 当前连接节点
*/
public callNextConnectedPort(runningContext : BlockRunContextData, currentPort : BlockPort) {
if(currentPort.paramType.isExecute()) {
if(runningContext.loopLifeTime > 0) {
runningContext.loopLifeTime--;
this.excuteContext(runningContext, currentPort);
}else {
runningContext.loopLifeTime = 5;
this.endRunningContext(runningContext);
this.queue.push(runningContext);
runningContext.currentPort = currentPort;
}
}
}
/**
* 触发断点
* @param currentPort 当断点触发并继续运行后,流将会从该端口继续
* @param block 断点所在单元
* @return 如果断点已处理返回,true
*/
public markInterrupt(runningContext : BlockRunContextData, currentPort : BlockPort, block : Block) : boolean {
if(currentPort == null || currentPort.direction == 'input') {
if(typeof this.onRunnerBreakPoint == 'function') {
this.pause();
this.onRunnerBreakPoint(currentPort, block);
if(currentPort) {
//断点已触发,现在修改任务至下个节点
runningContext.currentPort = currentPort;
runningContext.workType = 'activator';
this.queue.push(runningContext);
}
return true;
}
}
return false;
}
/**
* 脚本调用结束
*/
public notifyEnd(runningContext : BlockRunContextData) {
if(typeof this.onRunnerEnd == 'function')
this.onRunnerEnd();
logger.log(BlockRunner.TAG, this.mainContext.printCallStack(true));
this.stop();
}
/**
* 开始运行脚本文档
*/
public executeStart(doc : BlockDocunment) {
let startBlock = doc.mainGraph.getOneBlockByGUID(BaseBlocks.getScriptBaseBlockIn().guid);
if(startBlock == null) {
this.lastError = '没有找到入口单元,无法运行脚本。请先添加一个入口单元';
return false;
}
this.contexts.empty();
this.mainContext = this.push(startBlock.outputPorts['START'], null, 'connector');
this.mainContext.graph = doc.mainGraph;
this.currentDocunment = doc;
//变量初始化以仅参数
this.prepareGraphVariables(this.mainContext, doc.mainGraph);
this.prepareGraphStack(this.mainContext, doc.mainGraph);
this.prepareAllBlockRun(this.mainContext, doc.mainGraph);
//开始运行
this.start();
return true;
}
/**
* 执行前准备文档中所有块数据
*/
public prepareAllBlockRun(runningContext : BlockRunContextData, graph : BlockGraphDocunment) {
if(!graph.blockPrepared) {
runningContext.graphBlockStack.empty();
graph.blocks.forEach((block) => {
block.currentRunner = this;
block.stack = runningContext.graphBlockStack.push({
variables: {}
}) - 1;
block.onStartRun.invoke(block);
});
graph.connectors.forEach((connector) => {
connector.paramChangedContext.empty();
});
graph.blockPrepared = true;
graph.lastRunContext = runningContext;
}
}
/**
* 初始化图表所有变量
* @param runningContext 当前运行上下文
* @param graph 当前图表
*/
public prepareGraphVariables(runningContext : BlockRunContextData, graph : BlockGraphDocunment) {
runningContext.graphParamStack.empty();
//初始化全部变量的栈
graph.variables.forEach((variable) => {
if(variable.static) {
variable.value = variable.defaultValue ? variable.defaultValue : null;
variable.stack = -1;
}else {
variable.stack = runningContext.graphParamStack.push(variable.defaultValue ? variable.defaultValue : null) - 1;
}
});
}
/**
* 准备图表的运行栈
* @param runningContext 当前运行上下文
* @param graph 当前图表
*/
public prepareGraphStack(runningContext : BlockRunContextData, graph : BlockGraphDocunment) {
runningContext.graph = graph;
runningContext.graphBlockParamStack.empty();
runningContext.graphBlockParamIndexs.empty();
runningContext.paramStackCreated = true;
graph.blocks.forEach((block) => {
block.allPorts.forEach((port) => {
if(!port.paramType.isExecute()) {
if(port.paramStatic)
port.stack = -2;
else if(port.paramRefPassing && port.direction == 'input')
port.stack = -1;
else
port.stack = runningContext.graphBlockParamIndexs.push(-1) - 1;
}
});
});
}
private prepareChildStack(context : BlockRunContextData, parentContext : BlockRunContextData) {
//将父级所有已经链接的出端口保存即时数据至子上下文中进行备用
parentContext.graph.blocks.forEach((block) => {
block.allPorts.forEach((port) => {
if(!port.paramType.isExecute() && port.stack >= 0) {
if(!port.paramRefPassing && port.direction === 'output' && port.isConnected()) {
context.graphBlockParamIndexs[port.stack] = context.pushParam(port.getValueCached(parentContext));
}
}
});
});
}
/**
* 清除图表的运行栈
* @param runningContext 当前运行上下文
* @param graph 当前图表
*/
public destroyGraphStack(runningContext : BlockRunContextData, graph : BlockGraphDocunment) {
if(runningContext.graph == graph) {
runningContext.graphBlockParamStack.empty();
runningContext.graphBlockParamIndexs.empty();
runningContext.paramStackCreated = false;
}
}
/**
* 结束后回收文档中所有块数据
*/
public endAllBlockRun(doc : BlockDocunment) {
let loop = function(graph : BlockGraphDocunment) {
graph.blocks.forEach((block) => {
block.currentRunner = null;
block.currentRunningContext = null;
block.stack = - 1;
});
graph.blockPrepared = false;
graph.lastRunContext = null;
graph.children.forEach((g) => loop(g));
}
loop(doc.mainGraph);
}
public activeInputPort(runningContext: BlockRunContextData, port: BlockPort) {
let block = port.parent;
if(!CommonUtils.isDefinedAndNotNull(runningContext)) {
logger.error(port.getName(), 'activeInputPort: Cannot execute port because runningContext was not provided.');
return;
}
//断点触发
if(block.breakpoint == 'enable' && runningContext.lastBreakPointPort != port) {
if(runningContext.runner.markInterrupt(runningContext, port, block))
return;
}
runningContext.lastPort = port;
runningContext.currentBlock = block;
//判断平台
if(!block.isPlatformSupport) {
block.throwError(`单元不支持当前平台 ${BlockServiceInstance.getCurrentPlatform()}\n` +
`它支持的平台有:${block.regData.supportPlatform.join('/')}。\n您可能需要在运行之前判断当前平台。`, port, 'error');
return;
}
//环路检测
if(block.currentRunningContext === runningContext && !port.forceNoCycleDetection) {
block.throwError('运行栈上存在环路:层级' + runningContext.stackLevel, port, 'error', true);
return;
}
//入栈
block.blockCurrentCreateNewContext = false;
block.pushBlockStack(runningContext, port);
//调用
block.enterBlock(port, runningContext);
block.onPortExecuteIn.invoke(block, port);
//出栈
block.popBlockStack(runningContext);
}
public activeOutputPortInNewContext(runningContext: BlockRunContextData, port: BlockPort) {
let block = port.parent;
if(port.direction !== 'output') {
logger.error(port.getName(),'activeOutputPortInNewContext: You try to execute port that is not a output port.');
return;
}
//新建上下文
let context = block.currentRunner.push(port, runningContext, 'connector');
//准备子上下文
this.prepareGraphStack(context, runningContext.graph);
this.prepareChildStack(context, runningContext);
block.blockCurrentCreateNewContext = true;
}
public activeOutputPort(runningContext: BlockRunContextData, port: BlockPort) {
if(port.executeInNewContext && CommonUtils.isDefinedAndNotNull(runningContext))
port.activeInNewContext();
else {
if(!CommonUtils.isDefinedAndNotNull(runningContext)) {
logger.error(port.getName(),'activeOutputPort: Cannot execute port because runningContext was not provided.');
return;
}
port.parent.leaveBlock(runningContext);
runningContext.lastPort = port;
runningContext.currentBlock = null;
runningContext.runner.callNextConnectedPort(runningContext, port);
}
}
public lastError = '';
/**
* 当运行队列空闲时触发回调
*/
public onRunnerIdle : () => void = null;
/**
* 当运行至断点时触发回调(如果要开启断点调试功能,此回调必须被赋值)
*/
public onRunnerBreakPoint : (currentPort : BlockPort, block : Block) => void = null;
/**
* 当脚本结束被调用时触发回调
*/
public onRunnerEnd : () => void = null;
}
/**
* 运行状态
*/
export type RunnerState = 'stopped'|'running'|'idle';
/**
* 执行连接方式。
* connector:激活下一个节点
* activator:直接激活当前节点
*/
export type RunnerWorkType = 'connector'|'activator'; | the_stack |
import { tint, shade, darken, lighten, mix, rem } from "polished";
import { createGlobalStyle } from "styled-components";
const colors = {
black: "#1d1d1d",
blue: "#00A1FF",
green: "#2DAF7E",
orange: "#EB9028",
purple: "#7776D2",
red: "#F65151",
yellow: "#FFE248",
};
export const lightTheme = {
space: {
0: 0,
1: rem(2),
2: rem(4),
3: rem(8),
4: rem(12),
5: rem(16),
6: rem(20),
7: rem(24),
8: rem(32),
9: rem(48),
10: rem(64),
},
radii: {
s: rem(2),
m: rem(4),
round: "50%",
},
fontSizes: {
body: {
s: rem(11),
m: rem(12),
l: rem(13),
xl: rem(16),
},
display: {
s: rem(40),
m: rem(60),
l: rem(80),
},
},
lineHeights: {
body: {
s: rem(14),
m: rem(15),
l: rem(16),
xl: rem(20),
},
display: {
s: rem(48),
m: rem(72),
l: rem(96),
},
},
colors: {
canvas: {
base: "#fff",
hover: tint(0.9, colors.purple),
active: tint(0.85, colors.purple),
elevated05: darken(0.05, "#fff"),
elevated10: darken(0.1, "#fff"),
},
codeblock: {
background: darken(0.05, "#fff"),
},
tooltip: {
background: darken(0.1, "#fff"),
active: darken(0.2, "#fff"),
},
text: {
base: colors.black,
},
textDimmed: {
base: tint(0.4, colors.black),
hover: tint(0.3, colors.black),
active: tint(0.2, colors.black),
},
divider: {
base: shade(0.1, "#fff"),
},
primary: {
base: colors.purple,
hover: shade(0.05, colors.purple),
active: shade(0.1, colors.purple),
contrast: "#fff",
},
secondary: {
base: colors.orange,
},
success: {
base: colors.green,
},
error: {
base: colors.red,
},
pending: {
base: colors.blue,
},
syntax: {
base: shade(0.3, colors.orange),
atom: tint(0.1, colors.black),
attrName: shade(0.3, colors.orange),
boolean: shade(0.3, colors.purple),
builtin: shade(0.3, colors.purple),
className: shade(0.3, mix(0.5, colors.green, colors.blue)),
comment: shade(0.3, colors.green),
constant: shade(0.3, colors.orange),
description: tint(0.6, colors.black),
function: tint(0.1, colors.black),
invalid: colors.red,
keyword: shade(0.3, colors.purple),
meta: tint(0.4, colors.black),
null: tint(0.4, colors.black),
number: shade(0.3, colors.green),
operator: tint(0.1, colors.black),
property: shade(0.3, colors.orange),
punctuation: tint(0.1, colors.black),
string: shade(0.2, colors.red),
variable: shade(0.3, colors.orange),
interface: shade(0.3, colors.purple),
enum: shade(0.3, colors.green),
union: shade(0.3, mix(0.5, colors.green, colors.blue)),
scalar: shade(0.2, colors.red),
input: shade(0.3, colors.green),
type: shade(0.3, colors.orange),
},
},
};
export const darkTheme = {
...lightTheme,
colors: {
canvas: {
base: colors.black,
hover: mix(0.9, colors.black, colors.purple),
active: mix(0.85, colors.black, colors.purple),
elevated05: lighten(0.075, colors.black),
elevated10: lighten(0.1, colors.black),
},
codeblock: {
background: lighten(0.03, colors.black),
},
tooltip: {
background: darken(0.03, colors.black),
active: lighten(0.03, colors.black),
},
text: {
base: lighten(0.8, colors.black),
},
textDimmed: {
base: lighten(0.7, colors.black),
hover: lighten(0.9, colors.black),
active: lighten(0.7, colors.black),
},
divider: {
base: lighten(0.15, colors.black),
},
primary: {
base: colors.purple,
hover: lighten(0.05, colors.purple),
active: lighten(0.1, colors.purple),
contrast: lighten(0.9, colors.black),
},
secondary: {
base: colors.yellow,
},
success: {
base: colors.green,
},
error: {
base: colors.red,
},
pending: {
base: colors.blue,
},
syntax: {
base: tint(0.2, colors.blue),
atom: tint(0.9, colors.black),
attrName: tint(0.2, colors.blue),
boolean: tint(0.2, colors.purple),
builtin: tint(0.2, colors.purple),
className: tint(0.2, mix(0.5, colors.green, colors.blue)),
comment: tint(0.3, colors.green),
constant: tint(0.2, colors.blue),
description: tint(0.6, colors.black),
function: tint(0.9, colors.black),
invalid: colors.red,
keyword: tint(0.2, colors.purple),
meta: colors.red,
null: tint(0.6, colors.black),
number: tint(0.3, colors.green),
operator: tint(0.9, colors.black),
property: tint(0.2, colors.blue),
punctuation: tint(0.9, colors.black),
string: tint(0.1, colors.orange),
variable: tint(0.2, colors.blue),
interface: tint(0.2, colors.purple),
enum: tint(0.3, colors.green),
union: tint(0.2, mix(0.5, colors.green, colors.blue)),
scalar: tint(0.1, colors.orange),
input: tint(0.2, colors.purple),
type: tint(0.2, colors.blue),
},
},
};
// Syntax highlighting for Prism and CodeMirror
// - Supported languages: JSON and GraphQL
// - Find out which tokens are necessary for supported languages here: https://prismjs.com/faq.html#how-do-i-know-which-tokens-i-can-style-for
// - Light theme based on: https://github.com/PrismJS/prism-themes/blob/master/themes/prism-vs.css
// - Dark theme based on: https://github.com/PrismJS/prism-themes/blob/master/themes/prism-vsc-dark-plus.css
export const GlobalStyle = createGlobalStyle`
/** Global styles for prism-react-renderer and codemirror */
.CodeMirror, code {
font-size: ${(p) => p.theme.fontSizes.body.m};
}
.cm-s-default,
.CodeMirror-gutters {
background: ${(p) => p.theme.colors.canvas.base};
border-color: ${(p) => p.theme.colors.canvas.base};
}
.CodeMirror-cursor {
border-color: ${(p) => p.theme.colors.text.base};
}
.CodeMirror-hints.default {
color: ${(p) => p.theme.colors.text.base};
background: ${(p) => p.theme.colors.tooltip.background};
border-color: ${(p) => p.theme.colors.tooltip.background};
}
.CodeMirror-hints.default > .CodeMirror-hint {
color: ${(p) => p.theme.colors.text.base};
}
.CodeMirror-hints.default > .CodeMirror-hint.CodeMirror-hint-active {
background: ${(p) => p.theme.colors.tooltip.active};
}
.CodeMirror-matchingbracket {
text-decoration: underline;
color: ${(p) => p.theme.colors.syntax.punctuation} !important;
}
.CodeMirror-selected {
background: ${(p) => p.theme.colors.canvas.elevated05};
}
.CodeMirror-focused .CodeMirror-selected {
background: ${(p) => p.theme.colors.codeblock.background};
}
.CodeMirror-line::selection,
.CodeMirror-line>span::selection,
.CodeMirror-line>span>span::selection {
background: ${(p) => p.theme.colors.codeblock.background};
}
.CodeMirror-line::-moz-selection,
.CodeMirror-line>span::-moz-selection,
.CodeMirror-line>span>span::-moz-selection {
background: ${(p) => p.theme.colors.codeblock.background};
}
.cm-s-default, [class*="language-"] {
color: ${(p) => p.theme.colors.syntax.base};
.token.comment, .cm-comment {
color: ${(p) => p.theme.colors.syntax.comment};
}
.token.punctuation, .cm-punctuation {
color: ${(p) => p.theme.colors.syntax.punctuation};
}
.token.number, .cm-number {
color: ${(p) => p.theme.colors.syntax.number};
}
.token.string, .cm-string, .cm-string-2 {
color: ${(p) => p.theme.colors.syntax.string};
}
.token.operator {
color: ${(p) => p.theme.colors.syntax.operator};
}
.token.keyword, .cm-keyword {
color: ${(p) => p.theme.colors.syntax.keyword};
}
.token.function {
color: ${(p) => p.theme.colors.syntax.function};
}
.token.constant {
color: ${(p) => p.theme.colors.syntax.constant};
}
.token.class-name, .cm-def {
color: ${(p) => p.theme.colors.syntax.className};
}
.token.boolean {
color: ${(p) => p.theme.colors.syntax.boolean};
}
.token.property, .cm-property {
color: ${(p) => p.theme.colors.syntax.property};
}
.token.variable, .cm-variable {
color: ${(p) => p.theme.colors.syntax.variable};
}
.token.attr-name, .cm-attribute {
color: ${(p) => p.theme.colors.syntax.attrName};
}
.cm-atom {
color: ${(p) => p.theme.colors.syntax.atom};
}
.cm-builtin {
color: ${(p) => p.theme.colors.syntax.builtin};
}
.cm-meta {
color: ${(p) => p.theme.colors.syntax.meta};
}
.cm-invalidchar {
color: ${(p) => p.theme.colors.syntax.base};
}
}
/* Modified version of - https://github.com/PrismJS/prism-themes/blob/master/themes/prism-material-dark.css */
code[class*="language-"], pre[class*="language-"] {
text-align: left;
white-space: pre;
word-spacing: normal;
word-break: normal;
word-wrap: normal;
font-family: Roboto Mono, monospace;
font-size: ${(p) => p.theme.fontSizes.body.m};
line-height: 1.5;
-moz-tab-size: 4;
-o-tab-size: 4;
tab-size: 4;
-webkit-hyphens: none;
-moz-hyphens: none;
-ms-hyphens: none;
hyphens: none;
}
:not(pre) > code[class*="language-"] {
white-space: normal;
border-radius: ${(p) => p.theme.radii.m};
padding: ${(p) => p.theme.space[1]};
}
pre[class*="language-"] {
overflow: auto;
position: relative;
padding: ${(p) => p.theme.space[3]};
margin-top: ${(p) => p.theme.space[3]};
margin-bottom: 0;
}
html {
scrollbar-color: rgba(255, 255, 255, 0.1) transparent;
scrollbar-width: thin;
}
html, body {
height: 100%;
}
body {
font-size: ${(p) => p.theme.fontSizes.body.m};
line-height: ${(p) => p.theme.lineHeights.body.m};
}
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track, ::-webkit-scrollbar-corner {
background: transparent;
}
::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.15);
}
::-webkit-scrollbar-thumb, ::-webkit-scrollbar-thumb:active {
background: rgba(255, 255, 255, 0.2);
}
`;
GlobalStyle.displayName = "GlobalStyle"; | the_stack |
import TreeNode from './tree-node'
import Stack from '../../sequences/stack'
import * as utils from '../../utils'
class BinarySearchTree<T> {
root: TreeNode<T> | null
private sz: number
private compare: utils.CompareFunction<T>
constructor(compareFunction?: utils.CompareFunction<T>) {
this.root = null
this.sz = 0
this.compare = compareFunction || utils.defaultCompare
}
/*****************************************************************************
INSPECTION
*****************************************************************************/
size(): number {
return this.sz
}
isEmpty(): boolean {
return this.size() === 0
}
// O(n)
height(): number {
return this.heightHelper(this.root)
}
// O(n) because we recurse on all nodes in the tree
private heightHelper(root: TreeNode<T> | null): number {
if (root === null) return 0
return Math.max(this.heightHelper(root.left), this.heightHelper(root.right)) + 1
}
/*****************************************************************************
SEARCHING
*****************************************************************************/
// All search operations can be implemented iteratively and in O(h) time.
// O(h) because we're just tracing a path down the tree
find(value: T): TreeNode<T> | null {
let cur = this.root
while (cur !== null && cur.value !== value) {
if (this.compare(value, cur.value) < 0) cur = cur.left
else cur = cur.right
}
return cur
}
// finds the min node in the subtree rooted at given root, or top-most parent by default
// O(h) because we're just tracing a path down the tree
findMin(root?: TreeNode<T> | null): TreeNode<T> | null {
let cur = root || this.root
while (cur && cur.left !== null) {
cur = cur.left
}
return cur
}
// finds the max node in the subtree rooted at given root, or top-most parent by default
// O(h) because we're just tracing a path down the tree
findMax(root?: TreeNode<T> | null): TreeNode<T> | null {
let cur = root || this.root
while (cur && cur.right !== null) {
cur = cur.right
}
return cur
}
// O(h) since we follow a path down the tree or up the tree
findSucessor(root: TreeNode<T>): TreeNode<T> | null {
// if the right child exists, the successor is the left-most node of the right-child
const rightChildExists = root.right !== null
if (rightChildExists) return this.findMin(root.right)
// otherwise, the successor is the lowest ancestor of the current node whose
// left child is also an ancestor of the current node
let cur = root
let parent = root.parent
// Go up the tree from cur until we find a node that is the left child of the parent.
// If the node is the right child of the parent that means we haven't crossed
// "up and over" to the successor side of the binary tree
while (parent !== null && cur === parent.right) {
cur = parent
parent = parent.parent
}
return parent
}
// O(h) since we follow a path down the tree or up the tree
findPredecessor(root: TreeNode<T>): TreeNode<T> | null {
// if the left child exists, the successor is the right-most node of the left-child
const leftChildExists = root.left !== null
if (leftChildExists) return this.findMax(root.left)
// otherwise, the successor is the lowest ancestor of the current node whose
// right child is also an ancestor of the current node
let cur = root
let parent = root.parent
// Go up the tree from cur until we find a node that is the right child of the parent
// If the node is the left child of the parent that means we haven't crossed
// "up and over" to the predecessor side of the binary tree
while (parent !== null && cur === parent.left) {
cur = parent
parent = parent.parent
}
return parent
}
/*****************************************************************************
INSERTION/DELETION
*****************************************************************************/
// O(h) time since we follow a path down the tree
insert(value: T): TreeNode<T> {
let parent: TreeNode<T> | null = null
let cur = this.root
// walk down our tree until cur pointer is null
while (cur !== null) {
parent = cur
if (this.compare(value, cur.value) < 0) cur = cur.left
else cur = cur.right
}
const newNode = new TreeNode(value, parent)
if (parent === null) {
// if the root was empty, just set the root pointer to newNode
this.root = newNode
} else if (newNode.value < parent.value) {
parent.left = newNode
} else {
parent.right = newNode
}
this.sz += 1
return newNode
}
// O(h) because in the worst case we have to find the successor of node.
// This means calling this.findMin() which takes O(h) time
remove(node: TreeNode<T>): void {
// cases:
// if node has no children, we simply remove it by modifying node.parent's pointer
// if node has one child, we promote the child to take node's place
// if node has two chldren, we replace node with node's successor to maintain BST invariant
if (node.left === null) {
// is node has just a right child, we replace node with it's right child which may
// or may not be null
this.transplant(node, node.right)
} else if (node.right === null) {
// if node has just a left child then we replace node with the left child
this.transplant(node, node.left)
} else {
// otherwise node has two children
const sucessor = this.findSucessor(node) // O(h)
if (node.right === sucessor) {
// if node's sucessor is the right child of node, then we replace node with
// the sucessor
this.transplant(node, sucessor)
// link nodes left subtree with sucessor
sucessor.left = node.left
sucessor.left.parent = sucessor
} else {
// otherwise, the sucessor lies within node's right subtree but is not
// node's immediate right child. then, replace the successor with it's own
// right child, and then replace node with the sucessor
// note: sucessor can't be null here. node has two children, so it
// definitely does have a sucessor
if (sucessor === null) throw new Error()
// before we transplant node with sucessor, transplant sucessor with IT's
// right subtree (sucessor subtree)
this.transplant(sucessor, sucessor.right)
// link node's right subtree with sucessor
sucessor.right = node.right
sucessor.right.parent = sucessor
this.transplant(node, sucessor)
// link node's left subtree with sucessor
sucessor.left = node.left
sucessor.left.parent = sucessor
}
}
this.sz -= 1
}
// Replaces the subtree rooted at u with the subtree rooted at v. Node u's
// parent now becomes node v's parent. Note that transplant does not update
// v.left or v.right
private transplant(u: TreeNode<T>, v: TreeNode<T> | null) {
if (u.parent === null) {
// then u is the root of the tree so set root pointer to point to v
this.root = v
} else if (u === u.parent.left) {
u.parent.left = v
} else {
u.parent.right = v
}
// set v's parent pointer to point to u's parent
if (v) v.parent = u.parent
}
/*****************************************************************************
READING
*****************************************************************************/
inorderTraversal(): { [Symbol.iterator](): Iterator<T> } {
let root = this.root
const stack = new Stack<TreeNode<T>>()
return {
[Symbol.iterator]: (): Iterator<T> => ({
next(): IteratorResult<T> {
// dig left
while (root !== null) {
stack.push(root)
root = root.left
}
// we're done exploring the left branch
if (stack.isEmpty()) {
// if stack is empty, we have no more nodes to process
return { value: null, done: true }
}
root = stack.pop()! // root is not null bc stack is not empty
const value = root.value
root = root.right
return {
value,
done: false,
}
},
}),
}
}
preorderTraversal(): { [Symbol.iterator](): Iterator<T> } {
let root = this.root
const stack = new Stack<TreeNode<T>>()
if (root !== null) stack.push(root)
return {
[Symbol.iterator]: (): Iterator<T> => ({
next(): IteratorResult<T> {
if (stack.isEmpty()) return { value: null, done: true }
root = stack.pop()! // root is non-null bc stack is not empty
const value = root.value
if (root.right !== null) stack.push(root.right)
if (root.left !== null) stack.push(root.left)
return {
value,
done: false,
}
},
}),
}
}
postorderTraversal(): { [Symbol.iterator](): Iterator<T> } {
let root = this.root
const stack1 = new Stack<TreeNode<T>>()
const stack2 = new Stack<TreeNode<T>>()
if (root !== null) stack1.push(root)
while (!stack1.isEmpty()) {
root = stack1.pop()! // non-null bc stack1 is not empty
stack2.push(root)
if (root.left !== null) stack1.push(root.left)
if (root.right !== null) stack1.push(root.right)
}
return {
[Symbol.iterator]: (): Iterator<T> => ({
next(): IteratorResult<T> {
if (stack2.isEmpty()) return { value: null, done: true }
const { value } = stack2.pop()! // non-null bc stack2 is not empty
return {
value,
done: false,
}
},
}),
}
}
}
export default BinarySearchTree | the_stack |
import eris from "eris";
import {
COLOR_EMOTES,
DEAD_COLOR_EMOTES,
GROUPING_DISABLED_EMOJI,
GROUPING_ENABLED_EMOJI,
GROUPING_TOGGLE_EMOJI,
LEAVE_EMOJI,
LobbyRegion,
SessionState,
} from "./constants";
import { orm } from "./database";
import AmongUsSession from "./database/among-us-session";
import SessionChannel, {
MUTE_IF_DEAD_CHANNELS,
SessionChannelType,
SILENCE_CHANNELS,
} from "./database/session-channel";
import { getMembersInChannel, isMemberAdmin } from "./listeners";
import { getRunnerForSession, PlayerData, PlayerDataFlags } from "./session-runner";
const LOADING = 0x36393f;
const INFO = 0x0a96de;
const ERROR = 0xfd5c5c;
const WARN = 0xed872d;
/**
* Creates a new loading message as response to the specified message
* and creates a new empty session with the specified region and code.
* The session does not start automatically and needs to be started using
* the session runner.
*/
export async function createEmptyNewSession(
msg: eris.Message,
region: LobbyRegion,
code: string
): Promise<AmongUsSession> {
console.log(`[+] Creating new AU session for ${code} on ${region}`);
const existing = await orm.em.findOne(AmongUsSession, {
region,
lobbyCode: code,
});
if (existing && getRunnerForSession(existing)) {
throw "The lobby " + code + " on " + region + " is already being monitored by Impostor.";
}
const message = await msg.channel.createMessage({
embed: {
color: LOADING,
description: `<a:loading:572067799535452171> Attempting to connect to lobby \`${code}\` on ${region}...`,
},
});
// Create a new session.
const session = new AmongUsSession();
session.guild = (msg.channel as eris.TextChannel).guild.id;
session.channel = msg.channel.id;
session.message = message.id;
session.user = msg.author.username;
session.creator = msg.author.id;
session.state = SessionState.LOBBY;
session.region = region;
session.lobbyCode = code;
session.groupImpostors = false;
await orm.em.persist(session);
await orm.em.flush();
return session;
}
/**
* Helper function that queries all stale sessions currently in the database
* and ensures that they are cleaned up. No attempt is done at reconnecting
* to the server.
*/
export async function cleanUpOldSessions(bot: eris.Client) {
const sessions = await orm.em.find(AmongUsSession, {}, ["channels"]);
for (const session of sessions) {
await cleanUpSession(bot, session);
}
}
/**
* Similar to cleanUpOldSessions, but for a single old session.
*/
async function cleanUpSession(bot: eris.Client, session: AmongUsSession) {
try {
await session.channels.init();
for (const channel of session.channels) {
await bot.deleteChannel(channel.channelId, "Among Us: Session is over.").catch(() => {});
}
await updateMessageWithSessionStale(bot, session);
} catch {
// ignored
}
await orm.em.removeAndFlush(session);
}
/**
* Moves all players in `idFrom` to `idTo`.
*/
async function moveAllPlayers(bot: eris.Client, session: AmongUsSession, idFrom: string, idTo: string) {
await Promise.all(
getMembersInChannel(idFrom).map(x =>
bot
.editGuildMember(session.guild, x, {
channelID: idTo,
})
.catch(() => {})
)
);
}
/**
* Moves all players currently in the silence channels of the given
* among us session to the relevant talking channel.
*/
export async function movePlayersToTalkingChannel(bot: eris.Client, session: AmongUsSession) {
await session.channels.init();
const talkingChannel = session.channels.getItems().find(x => x.type === SessionChannelType.TALKING)!;
const silenceChannels = session.channels.getItems().filter(x => SILENCE_CHANNELS.includes(x.type));
await Promise.all(silenceChannels.map(x => moveAllPlayers(bot, session, x.channelId, talkingChannel.channelId)));
}
/**
* Moves all players currently in the talking channel of the given
* among us session to the relevant silence channel.
*/
export async function movePlayersToSilenceChannel(bot: eris.Client, session: AmongUsSession) {
if (session.groupImpostors) {
await movePlayersToSilenceChannelGrouped(bot, session);
} else {
await movePlayersToSilenceChannelUngrouped(bot, session);
}
}
/**
* Moves all players currently in the talking channel to a common
* silence channel, except for any admins in the call, which get their
* own channel.
*/
export async function movePlayersToSilenceChannelUngrouped(bot: eris.Client, session: AmongUsSession) {
await session.channels.init();
const categoryChannel = session.channels.getItems().find(x => x.type === SessionChannelType.CATEGORY)!;
const talkingChannel = session.channels.getItems().find(x => x.type === SessionChannelType.TALKING)!;
const silenceChannel = session.channels.getItems().find(x => x.type === SessionChannelType.SILENCE)!;
const playersInTalkingChannel = getMembersInChannel(talkingChannel.channelId);
const normalPlayersInTalkingChannel = playersInTalkingChannel.filter(x => !isMemberAdmin(x));
// Figure out which admin players need to get their own channel.
const adminPlayersInTalkingChannel = playersInTalkingChannel.filter(isMemberAdmin);
const emptyAdminChannels = session.channels
.getItems()
.filter(x => x.type === SessionChannelType.ADMIN_SILENCE && getMembersInChannel(x.channelId).length === 0);
for (const adminId of adminPlayersInTalkingChannel) {
const appropriateAdminChannel = emptyAdminChannels.pop();
if (appropriateAdminChannel) {
await bot
.editGuildMember(session.guild, adminId, {
channelID: appropriateAdminChannel.channelId,
})
.catch(() => {});
continue;
}
// We need to create an admin channel for this user.
try {
bot.getDMChannel(adminId).then(channel =>
channel.createMessage(
`Hey there <@!${adminId}>! Since you're an administrator, I can't mute you through channel permissions. As such, I've created a special Muted channel just for you!`
)
);
} catch (e) {
// ignore
}
const adminChannel = await bot.createChannel(session.guild, "Muted (Admin)", 2, {
parentID: categoryChannel.channelId,
permissionOverwrites: [
{
type: "role",
id: session.guild,
deny: eris.Constants.Permissions.voiceSpeak | eris.Constants.Permissions.readMessages,
allow: 0,
},
],
});
session.channels.add(new SessionChannel(adminChannel.id, SessionChannelType.ADMIN_SILENCE));
await bot
.editGuildMember(session.guild, adminId, {
channelID: adminChannel.id,
})
.catch(() => {});
}
await orm.em.persistAndFlush(session);
// Move the normal players.
await Promise.all(
normalPlayersInTalkingChannel.map(id =>
bot
.editGuildMember(session.guild, id, {
channelID: silenceChannel.channelId,
})
.catch(() => {})
)
);
}
/**
* Moves all players currently in the talking channel to their own silence
* channel, except the players that
*/
export async function movePlayersToSilenceChannelGrouped(bot: eris.Client, session: AmongUsSession) {
await session.channels.init();
await session.links.init();
const runner = getRunnerForSession(session);
if (!runner) return;
const categoryChannel = session.channels.getItems().find(x => x.type === SessionChannelType.CATEGORY)!;
const talkingChannel = session.channels.getItems().find(x => x.type === SessionChannelType.TALKING)!;
const impostorChannel = session.channels.getItems().find(x => x.type === SessionChannelType.IMPOSTORS)!;
const impostorSnowflakes = session.links
.getItems()
.filter(x => runner.isImpostor(x.clientId))
.map(x => x.snowflake);
const playersInTalkingChannel = getMembersInChannel(talkingChannel.channelId);
const impostorsInTalkingChannel = playersInTalkingChannel.filter(x => impostorSnowflakes.includes(x));
const normalPlayersInTalkingChannel = playersInTalkingChannel.filter(x => !impostorSnowflakes.includes(x));
// Move impostors to the impostor channel.
for (const impostorId of impostorsInTalkingChannel) {
await bot
.editGuildMember(session.guild, impostorId, {
channelID: impostorChannel.channelId,
})
.catch(() => {});
}
// Move normal players to empty channels, or create if there are not enough.
const emptySilenceChannels = session.channels
.getItems()
.filter(
x => x.type === SessionChannelType.SINGLE_PLAYER_SILENCE && getMembersInChannel(x.channelId).length === 0
);
for (const user of normalPlayersInTalkingChannel) {
const appropriateChannel = emptySilenceChannels.pop();
if (appropriateChannel) {
await bot
.editGuildMember(session.guild, user, {
channelID: appropriateChannel.channelId,
})
.catch(() => {});
continue;
}
// We need to create a silence channel for this user.
const silenceChannel = await bot.createChannel(session.guild, "Muted", 2, {
parentID: categoryChannel.channelId,
permissionOverwrites: [
{
type: "role",
id: session.guild,
deny: eris.Constants.Permissions.voiceSpeak | eris.Constants.Permissions.readMessages,
allow: 0,
},
],
});
session.channels.add(new SessionChannel(silenceChannel.id, SessionChannelType.SINGLE_PLAYER_SILENCE));
await bot
.editGuildMember(session.guild, user, {
channelID: silenceChannel.id,
})
.catch(() => {});
}
await orm.em.persistAndFlush(session);
}
/**
* Mutes the specified player in all channels where people can normally talk.
*/
export async function mutePlayerInChannels(bot: eris.Client, session: AmongUsSession, snowflake: string) {
await session.channels.init();
for (const channel of session.channels.getItems().filter(x => MUTE_IF_DEAD_CHANNELS.includes(x.type))) {
await bot
.editChannelPermission(channel.channelId, snowflake, 0, eris.Constants.Permissions.voiceSpeak, "member")
.catch(() => {});
}
}
/**
* Unmutes the specified player from all channels where people can normally talk.
*/
export async function unmutePlayerInChannels(bot: eris.Client, session: AmongUsSession, snowflake: string) {
await session.channels.init();
for (const channel of session.channels.getItems().filter(x => MUTE_IF_DEAD_CHANNELS.includes(x.type))) {
await bot.deleteChannelPermission(channel.channelId, snowflake).catch(() => {});
}
}
/**
* Updates the message of the specified session with the notion
* that an error occurred during connecting. Does not remove the
* session itself.
*/
export async function updateMessageWithError(bot: eris.Client, session: AmongUsSession, error: string) {
await bot
.editMessage(session.channel, session.message, {
embed: {
color: ERROR,
title: `🎲 Among Us - Error`,
description: `${error}`,
},
})
.catch(() => {});
await bot.removeMessageReactions(session.channel, session.message).catch(() => {});
}
/**
* Updates the message of the specified session with the notion
* that the session is over because the lobby was closed. Does not
* remove the session itself.
*/
export async function updateMessageWithSessionOver(bot: eris.Client, session: AmongUsSession) {
await bot
.editMessage(session.channel, session.message, {
embed: {
color: ERROR,
title: `🎲 Among Us - Session Over`,
description: `${session.user} was hosting a game of [Among Us](http://www.innersloth.com/gameAmongUs.php) here, but the lobby closed.`,
},
})
.catch(() => {});
await bot.removeMessageReactions(session.channel, session.message).catch(() => {});
}
/**
* Updates the message of the specified session with the notion
* that the session is over because the bot restarted during the
* game and was not able to reconnect.
*/
export async function updateMessageWithSessionStale(bot: eris.Client, session: AmongUsSession) {
await bot
.editMessage(session.channel, session.message, {
embed: {
color: ERROR,
title: `🎲 Among Us - Session Over`,
description: `${session.user} was hosting a game of [Among Us](http://www.innersloth.com/gameAmongUs.php) here, but an unexpected error happened. Try again in a bit?`,
},
})
.catch(() => {});
await bot.removeMessageReactions(session.channel, session.message).catch(() => {});
}
/**
* Adds all the different crewmate color reactions to the message created by
* the bot, so that players can associate themselves with an ingame player.
*/
export async function addMessageReactions(bot: eris.Client, session: AmongUsSession) {
await bot.addMessageReaction(session.channel, session.message, GROUPING_TOGGLE_EMOJI);
await bot.addMessageReaction(session.channel, session.message, LEAVE_EMOJI);
for (const emote of Object.values(COLOR_EMOTES)) {
await bot.addMessageReaction(session.channel, session.message, emote);
}
}
/**
* Updates the message for the specified among us session to the
* relevant content for the current session state. Should be invoked
* after the state of the session was changed.
*/
export async function updateMessage(bot: eris.Client, session: AmongUsSession, playerData: PlayerData[]) {
if (session.state === SessionState.LOBBY) {
await updateMessageToLobby(bot, session, playerData);
}
if (session.state === SessionState.PLAYING || session.state === SessionState.DISCUSSING) {
await updateMessageToPlaying(bot, session, playerData);
}
}
/**
* Formats the list of players currently in the specified session, using
* the game data from the current session.
*/
function formatPlayerText(session: AmongUsSession, playerData: PlayerData[]) {
let playerText = "";
for (const p of playerData) {
const emoteMap = (p.statusBitField & PlayerDataFlags.DEAD) === 0 ? COLOR_EMOTES : DEAD_COLOR_EMOTES;
playerText += `<:${emoteMap[p.color]}> ${p.name}`;
const links = session.links.getItems().filter(x => x.clientId === "" + p.clientId);
if (links.length) {
playerText += ` (` + links.map(x => `<@!${x.snowflake}>`).join(", ") + `)`;
}
playerText += "\n";
}
return playerText.trim();
}
/**
* Updates the message of the specified session to the content that
* the match is currently ongoing.
*/
async function updateMessageToPlaying(bot: eris.Client, session: AmongUsSession, playerData: PlayerData[]) {
await session.channels.init();
const mainChannel = session.channels.getItems().find(x => x.type === SessionChannelType.TALKING)!;
const groupingText = session.groupImpostors
? `Impostors will be put in a shared voice channel and will be able to communicate during the game. Normal players will not be able to see who the impostors are. ${session.user} can react with <:${GROUPING_TOGGLE_EMOJI}> **after this round is over** to disable this.`
: `Want an extra challenge? Impostors can be automatically put in the same voice channel to allow them to communicate during the game. This will not reveal to the other players who the impostors are. ${session.user} can react with <:${GROUPING_TOGGLE_EMOJI}> **after this round is over** to enable this.`;
await bot
.editMessage(session.channel, session.message, {
embed: {
color: WARN,
title: `🎲 Among Us - ${session.region} - ${session.lobbyCode} (In Game)`,
description: `${session.user} is hosting a game of [Among Us](http://www.innersloth.com/gameAmongUs.php)! Join the voice channel <#${mainChannel.channelId}> or click [here](https://discord.gg/${mainChannel.invite}) to join the voice chat. ~~To join the Among Us lobby, select the **${session.region}** server and enter code \`${session.lobbyCode}\`.~~ The lobby is currently ongoing! You'll need to wait for the round to end before you can join.`,
fields: [
{
name: "Current Players",
value: formatPlayerText(session, playerData) || "_None_",
},
{
name: session.groupImpostors
? GROUPING_ENABLED_EMOJI + " Impostors Are Grouped"
: GROUPING_DISABLED_EMOJI + " Impostors Not Grouped",
value: groupingText,
},
],
footer: {
icon_url: bot.user.avatarURL.replace("jpg", "png"),
text:
"Reminder: the bot takes up a player spot! Found that last player? Use the X to have the bot leave.",
},
},
})
.catch(() => {});
}
/**
* Updates the message of the specified session to the content that the
* session is currently in the lobby and that players are free to join.
*/
async function updateMessageToLobby(bot: eris.Client, session: AmongUsSession, playerData: PlayerData[]) {
await session.channels.init();
await session.links.init();
const mainChannel = session.channels.getItems().find(x => x.type === SessionChannelType.TALKING)!;
const groupingText = session.groupImpostors
? `Impostors will be put in a shared voice channel and will be able to communicate during the game. Normal players will not be able to see who the impostors are. ${session.user} can react with <:${GROUPING_TOGGLE_EMOJI}> to disable this.`
: `Want an extra challenge? Impostors can be automatically put in the same voice channel to allow them to communicate during the game. This will not reveal to the other players who the impostors are. ${session.user} can react with <:${GROUPING_TOGGLE_EMOJI}> to enable this.`;
await bot
.editMessage(session.channel, session.message, {
embed: {
color: INFO,
title: `🎲 Among Us - ${session.region} - ${session.lobbyCode}`,
description: `${session.user} is hosting a game of [Among Us](http://www.innersloth.com/gameAmongUs.php)! Join the voice channel <#${mainChannel.channelId}> or click [here](https://discord.gg/${mainChannel.invite}) to join the voice chat. To join the Among Us lobby, select the **${session.region}** server and enter code \`${session.lobbyCode}\`.\n\nReact with your color to associate your Discord with your Among Us character! This will automatically mute you once you die and group you together with the other impostors if enabled.`,
fields: [
{
name: "Current Players",
value: formatPlayerText(session, playerData) || "_None_",
},
{
name: session.groupImpostors
? GROUPING_ENABLED_EMOJI + " Impostors Are Grouped"
: GROUPING_DISABLED_EMOJI + " Impostors Not Grouped",
value: groupingText,
},
],
footer: {
icon_url: bot.user.avatarURL.replace("jpg", "png"),
text:
"Reminder: the bot takes up a player spot! Found that last player? Use the X to have the bot leave.",
},
},
})
.catch(() => {});
} | the_stack |
const PointFlags = cc.Graphics.Types.PointFlags;
//@ts-ignore
const LineJoin = cc.Graphics.Types.LineJoin;
//@ts-ignore
const LineCap = cc.Graphics.Types.LineCap;
import { SmoothTrail } from './SmoothTrail';
cc.game.on(cc.game.EVENT_ENGINE_INITED, () => {
});
const MAX_VERTEX = 65535;
const MAX_INDICE = MAX_VERTEX * 2;
const PI = Math.PI;
const min = Math.min;
const max = Math.max;
const ceil = Math.ceil;
const acos = Math.acos;
const cos = Math.cos;
const sin = Math.sin;
const atan2 = Math.atan2;
function curveDivs(r, arc, tol) {
let da = acos(r / (r + tol)) * 2.0;
return max(2, ceil(arc / da));
}
function clamp(v, min, max) {
if (v < min) {
return min;
}
else if (v > max) {
return max;
}
return v;
}
//@ts-ignore
let gfx = cc.gfx;
let vfmtPosColorSdf = new gfx.VertexFormat([
{ name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 2 },
{ name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_UINT8, num: 4, normalize: true },
{ name: 'a_dist', type: gfx.ATTR_TYPE_FLOAT32, num: 1 },
]);
vfmtPosColorSdf.name = 'vfmtPosColorSdf';
export class SmoothTrailAssembler extends cc.Assembler {
_buffer = null;
_buffers = [];
_bufferOffset = 0;
_curColor = 0;
_trailBuff = null;
PATH_VERTEX: number = 2048;
constructor(graphics) {
// super(graphics);
super();
// this._buffer = null;
// this._buffers = [];
// this._bufferOffset = 0;
}
getVfmt() {
return vfmtPosColorSdf;
}
getVfmtFloatCount() {
return 4;
}
requestBuffer(dummy?: any) {
let buffer = {
indiceStart: 0,
vertexStart: 0,
meshbuffer: null,
ia: null
};
//@ts-ignore
let meshbuffer = new cc.MeshBuffer(cc.renderer._handle, this.getVfmt());
buffer.meshbuffer = meshbuffer;
//@ts-ignore
let ia = new cc.renderer.InputAssembler(meshbuffer._vb, meshbuffer._ib);
buffer.ia = ia;
this._buffers.push(buffer);
return buffer;
}
getBuffers() {
if (this._buffers.length === 0) {
this.requestBuffer();
}
return this._buffers;
}
clear(clean) {
this._bufferOffset = 0;
let datas = this._buffers;
if (clean) {
for (let i = 0, l = datas.length; i < l; i++) {
let data = datas[i];
data.meshbuffer.destroy();
data.meshbuffer = null;
}
datas.length = 0;
}
else {
for (let i = 0, l = datas.length; i < l; i++) {
let data = datas[i];
data.indiceStart = 0;
data.vertexStart = 0;
let meshbuffer = data.meshbuffer;
meshbuffer.reset();
}
}
}
fillBuffers(graphics, renderer) {
renderer._flush();
renderer.node = graphics.node;
renderer.material = graphics._materials[0];
let buffers = this.getBuffers();
for (let index = 0, length = buffers.length; index < length; index++) {
let buffer = buffers[index];
let meshbuffer = buffer.meshbuffer;
buffer.ia._count = buffer.indiceStart;
renderer._flushIA(buffer.ia);
meshbuffer.uploadData();
}
}
genBuffer(graphics, cverts) {
let buffers = this.getBuffers();
let buffer = buffers[this._bufferOffset];
let meshbuffer = buffer.meshbuffer;
let maxVertsCount = buffer.vertexStart + cverts;
if (maxVertsCount > MAX_VERTEX ||
maxVertsCount * 3 > MAX_INDICE) {
++this._bufferOffset;
maxVertsCount = cverts;
if (this._bufferOffset < buffers.length) {
buffer = buffers[this._bufferOffset];
}
else {
buffer = this.requestBuffer(graphics);
buffers[this._bufferOffset] = buffer;
}
meshbuffer = buffer.meshbuffer;
}
if (maxVertsCount > meshbuffer.vertexOffset) {
meshbuffer.requestStatic(cverts, cverts * 3);
}
this._buffer = buffer;
return buffer;
}
stroke(graphics) {
this._curColor = graphics._strokeColor._val;
this._flattenPaths(graphics._impl);
this._expandStroke(graphics);
graphics._impl._updatePathOffset = true;
}
fill(graphics) {
this._curColor = graphics._fillColor._val;
this._expandFill(graphics);
graphics._impl._updatePathOffset = true;
}
_expandStroke(graphics) {
let w = graphics.lineWidth * 0.5,
lineCap = graphics.lineCap,
lineJoin = graphics.lineJoin,
miterLimit = graphics.miterLimit;
let impl = graphics._impl;
let ncap = curveDivs(w, PI, impl._tessTol);
this._calculateJoins(impl, w, lineJoin, miterLimit);
let paths = impl._paths;
// Calculate max vertex usage.
let cverts = 0;
for (let i = impl._pathOffset, l = impl._pathLength; i < l; i++) {
let path = paths[i];
let pointsLength = path.points.length;
if (lineJoin === LineJoin.ROUND) cverts += (pointsLength + path.nbevel * (ncap + 2) + 1) * 2; // plus one for loop
else cverts += (pointsLength + path.nbevel * 5 + 1) * 2; // plus one for loop
if (!path.closed) {
// space for caps
if (lineCap === LineCap.ROUND) {
cverts += (ncap * 2 + 2) * 2;
} else {
cverts += (3 + 3) * 2;
}
}
}
let buffer = this.genBuffer(graphics, cverts),
meshbuffer = buffer.meshbuffer,
vData = meshbuffer._vData,
iData = meshbuffer._iData;
for (let i = impl._pathOffset, l = impl._pathLength; i < l; i++) {
let path = paths[i];
let pts = path.points;
let pointsLength = pts.length;
let offset = buffer.vertexStart;
let p0, p1;
let start, end, loop;
loop = path.closed;
if (loop) {
// Looping
p0 = pts[pointsLength - 1];
p1 = pts[0];
start = 0;
end = pointsLength;
} else {
// Add cap
p0 = pts[0];
p1 = pts[1];
start = 1;
end = pointsLength - 1;
}
p1 = p1 || p0;
if (!loop) {
// Add cap
let dPos = p1.sub(p0);
dPos.normalizeSelf();
let dx = dPos.x;
let dy = dPos.y;
if (lineCap === LineCap.BUTT)
this._buttCapStart(p0, dx, dy, w, 0);
else if (lineCap === LineCap.SQUARE)
this._buttCapStart(p0, dx, dy, w, w);
else if (lineCap === LineCap.ROUND)
this._roundCapStart(p0, dx, dy, w, ncap);
}
for (let j = start; j < end; ++j) {
if (lineJoin === LineJoin.ROUND) {
this._roundJoin(p0, p1, w, w, ncap);
}
else if ((p1.flags & (PointFlags.PT_BEVEL | PointFlags.PT_INNERBEVEL)) !== 0) {
this._bevelJoin(p0, p1, w, w);
}
else {
this._vset(p1.x + p1.dmx * w, p1.y + p1.dmy * w, 1);
this._vset(p1.x - p1.dmx * w, p1.y - p1.dmy * w, -1);
}
p0 = p1;
p1 = pts[j + 1];
}
if (loop) {
// Loop it
let floatCount = this.getVfmtFloatCount();
let vDataoOfset = offset * floatCount;
this._vset(vData[vDataoOfset], vData[vDataoOfset + 1], 1);
this._vset(vData[vDataoOfset + floatCount], vData[vDataoOfset + floatCount + 1], -1);
} else {
// Add cap
let dPos = p1.sub(p0);
dPos.normalizeSelf();
let dx = dPos.x;
let dy = dPos.y;
if (lineCap === LineCap.BUTT)
this._buttCapEnd(p1, dx, dy, w, 0);
else if (lineCap === LineCap.SQUARE)
this._buttCapEnd(p1, dx, dy, w, w);
else if (lineCap === LineCap.ROUND)
this._roundCapEnd(p1, dx, dy, w, ncap);
}
// stroke indices
let indicesOffset = buffer.indiceStart;
for (let start = offset + 2, end = buffer.vertexStart; start < end; start++) {
iData[indicesOffset++] = start - 2;
iData[indicesOffset++] = start - 1;
iData[indicesOffset++] = start;
}
buffer.indiceStart = indicesOffset;
}
}
_expandFill(graphics) {
//@ts-ignore
let Earcut = cc.Graphics.earcut;
let impl = graphics._impl;
let paths = impl._paths;
// Calculate max vertex usage.
let cverts = 0;
for (let i = impl._pathOffset, l = impl._pathLength; i < l; i++) {
let path = paths[i];
let pointsLength = path.points.length;
cverts += pointsLength;
}
let buffer = this.genBuffer(graphics, cverts),
meshbuffer = buffer.meshbuffer,
vData = meshbuffer._vData,
iData = meshbuffer._iData;
for (let i = impl._pathOffset, l = impl._pathLength; i < l; i++) {
let path = paths[i];
let pts = path.points;
let pointsLength = pts.length;
if (pointsLength === 0) {
continue;
}
// Calculate shape vertices.
let offset = buffer.vertexStart;
for (let j = 0; j < pointsLength; ++j) {
this._vset(pts[j].x, pts[j].y);
}
let indicesOffset = buffer.indiceStart;
if (path.complex) {
let earcutData = [];
let floatCount = this.getVfmtFloatCount();
for (let j = offset, end = buffer.vertexStart; j < end; j++) {
let vDataOffset = j * floatCount;
earcutData.push(vData[vDataOffset]);
earcutData.push(vData[vDataOffset + 1]);
}
let newIndices = Earcut(earcutData, null, 2);
if (!newIndices || newIndices.length === 0) {
continue;
}
for (let j = 0, nIndices = newIndices.length; j < nIndices; j++) {
iData[indicesOffset++] = newIndices[j] + offset;
}
}
else {
let first = offset;
for (let start = offset + 2, end = buffer.vertexStart; start < end; start++) {
iData[indicesOffset++] = first;
iData[indicesOffset++] = start - 1;
iData[indicesOffset++] = start;
}
}
buffer.indiceStart = indicesOffset;
}
}
_calculateJoins(impl, w, lineJoin, miterLimit) {
let iw = 0.0;
let w2 = w * w;
if (w > 0.0) {
iw = 1 / w;
}
// Calculate which joins needs extra vertices to append, and gather vertex count.
let paths = impl._paths;
for (let i = impl._pathOffset, l = impl._pathLength; i < l; i++) {
let path = paths[i];
let pts = path.points;
let ptsLength = pts.length;
let p0 = pts[ptsLength - 1];
let p1 = pts[0];
let nleft = 0;
path.nbevel = 0;
for (let j = 0; j < ptsLength; j++) {
let dmr2, cross, limit;
// perp normals
let dlx0 = p0.dy;
let dly0 = -p0.dx;
let dlx1 = p1.dy;
let dly1 = -p1.dx;
// Calculate extrusions
p1.dmx = (dlx0 + dlx1) * 0.5;
p1.dmy = (dly0 + dly1) * 0.5;
dmr2 = p1.dmx * p1.dmx + p1.dmy * p1.dmy;
if (dmr2 > 0.000001) {
let scale = 1 / dmr2;
if (scale > 600) {
scale = 600;
}
p1.dmx *= scale;
p1.dmy *= scale;
}
// Keep track of left turns.
cross = p1.dx * p0.dy - p0.dx * p1.dy;
if (cross > 0) {
nleft++;
p1.flags |= PointFlags.PT_LEFT;
}
// Calculate if we should use bevel or miter for inner join.
limit = max(11, min(p0.len, p1.len) * iw);
if (dmr2 * limit * limit < 1) {
p1.flags |= PointFlags.PT_INNERBEVEL;
}
// TODO: 2.4.4的commit,会导致INNERBEVEL渲染错误
// https://github.com/cocos-creator/engine/pull/7780/commits/06320339dae5419a6e96058344a35254429862f1
// Check whether dm length is too long
let dmwx = p1.dmx * w;
let dmwy = p1.dmy * w;
let dmlen2 = dmwx * dmwx + dmwy * dmwy;
// 设交点P到dm点的连线为S,和len、w围成三角形。S对应的角是O
// 只要O不是钝角,则dm点一定在线段内部。极限情况下O是直角,此时根据勾股定理求S的最大容忍值
if (dmlen2 > (p1.len * p1.len) + w2 && dmlen2 > (p0.len * p0.len) + w2) {
p1.flags |= PointFlags.PT_INNERBEVEL;
}
// Check to see if the corner needs to be beveled.
if (p1.flags & PointFlags.PT_CORNER) {
if (dmr2 * miterLimit * miterLimit < 1 || lineJoin === LineJoin.BEVEL || lineJoin === LineJoin.ROUND) {
p1.flags |= PointFlags.PT_BEVEL;
}
}
if ((p1.flags & (PointFlags.PT_BEVEL | PointFlags.PT_INNERBEVEL)) !== 0) {
path.nbevel++;
}
p0 = p1;
p1 = pts[j + 1];
}
}
}
// 通过判断收尾点是否相同,判定闭环,如果是,则弹出最后一个点
// 求每个点到下个点的距离、单位方向向量
_flattenPaths(impl) {
let paths = impl._paths;
for (let i = impl._pathOffset, l = impl._pathLength; i < l; i++) {
let path = paths[i];
let pts = path.points;
let p0 = pts[pts.length - 1];
let p1 = pts[0];
if (pts.length > 2 && p0.equals(p1)) {
path.closed = true;
pts.pop();
p0 = pts[pts.length - 1];
}
for (let j = 0, size = pts.length; j < size; j++) {
// Calculate segment direction and length
let dPos = p1.sub(p0);
p0.len = dPos.mag();
if (dPos.x || dPos.y)
dPos.normalizeSelf();
p0.dx = dPos.x;
p0.dy = dPos.y;
// Advance
p0 = p1;
p1 = pts[j + 1];
}
}
}
_chooseBevel(bevel, p0, p1, w) {
let x = p1.x;
let y = p1.y;
let x0, y0, x1, y1;
if (bevel !== 0) {
// INNERBEVEL模式,不经过dm点
x0 = x + p0.dy * w; // (x0, y0)是沿P0法线走w
y0 = y - p0.dx * w;
x1 = x + p1.dy * w; // (x1, y1)是沿P1法线走w
y1 = y - p1.dx * w;
} else {
x0 = x1 = x + p1.dmx * w; // (x0, y0), (x1, y1)都和dm点重合
y0 = y1 = y + p1.dmy * w;
}
return [x0, y0, x1, y1];
}
_buttCapStart(p, dx, dy, w, d) {
let px = p.x - dx * d;
let py = p.y - dy * d;
let dlx = dy;
let dly = -dx;
this._vset(px + dlx * w, py + dly * w, 1);
this._vset(px - dlx * w, py - dly * w, -1);
}
_buttCapEnd(p, dx, dy, w, d) {
let px = p.x + dx * d;
let py = p.y + dy * d;
let dlx = dy;
let dly = -dx;
this._vset(px + dlx * w, py + dly * w, 1);
this._vset(px - dlx * w, py - dly * w, -1);
}
_roundCapStart(p, dx, dy, w, ncap) {
let px = p.x;
let py = p.y;
let dlx = dy;
let dly = -dx;
for (let i = 0; i < ncap; i++) {
let a = i / (ncap - 1) * PI;
let ax = cos(a) * w,
ay = sin(a) * w;
this._vset(px - dlx * ax - dx * ay, py - dly * ax - dy * ay, 1);
this._vset(px, py, 0);
}
this._vset(px + dlx * w, py + dly * w, 1);
this._vset(px - dlx * w, py - dly * w, -1);
}
_roundCapEnd(p, dx, dy, w, ncap) {
let px = p.x;
let py = p.y;
let dlx = dy;
let dly = -dx;
this._vset(px + dlx * w, py + dly * w, 1);
this._vset(px - dlx * w, py - dly * w, -1);
for (let i = 0; i < ncap; i++) {
let a = i / (ncap - 1) * PI;
let ax = cos(a) * w,
ay = sin(a) * w;
this._vset(px, py, 0);
this._vset(px - dlx * ax + dx * ay, py - dly * ax + dy * ay, 1);
}
}
_roundJoin(p0, p1, lw, rw, ncap) {
let dlx0 = p0.dy;
let dly0 = -p0.dx;
let dlx1 = p1.dy;
let dly1 = -p1.dx;
let p1x = p1.x;
let p1y = p1.y;
if ((p1.flags & PointFlags.PT_LEFT) !== 0) {
let out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, lw);
let lx0 = out[0];
let ly0 = out[1];
let lx1 = out[2];
let ly1 = out[3];
let a0 = atan2(-dly0, -dlx0);
let a1 = atan2(-dly1, -dlx1);
if (a1 > a0) a1 -= PI * 2;
this._vset(lx0, ly0, 1);
this._vset(p1x - dlx0 * rw, p1.y - dly0 * rw, -1);
let n = clamp(ceil((a0 - a1) / PI) * ncap, 2, ncap);
for (let i = 0; i < n; i++) {
let u = i / (n - 1);
let a = a0 + u * (a1 - a0);
let rx = p1x + cos(a) * rw;
let ry = p1y + sin(a) * rw;
this._vset(p1x, p1y, 0);
this._vset(rx, ry, -1);
}
this._vset(lx1, ly1, 1);
this._vset(p1x - dlx1 * rw, p1y - dly1 * rw, -1);
} else {
let out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, -rw);
let rx0 = out[0];
let ry0 = out[1];
let rx1 = out[2];
let ry1 = out[3];
let a0 = atan2(dly0, dlx0);
let a1 = atan2(dly1, dlx1);
if (a1 < a0) a1 += PI * 2;
this._vset(p1x + dlx0 * rw, p1y + dly0 * rw, 1);
this._vset(rx0, ry0, -1);
let n = clamp(ceil((a1 - a0) / PI) * ncap, 2, ncap);
for (let i = 0; i < n; i++) {
let u = i / (n - 1);
let a = a0 + u * (a1 - a0);
let lx = p1x + cos(a) * lw;
let ly = p1y + sin(a) * lw;
this._vset(lx, ly, 1);
this._vset(p1x, p1y, 0);
}
this._vset(p1x + dlx1 * rw, p1y + dly1 * rw, 1);
this._vset(rx1, ry1, -1);
}
}
_bevelJoin(p0, p1, lw, rw) {
let rx0, ry0, rx1, ry1;
let lx0, ly0, lx1, ly1;
let dlx0 = p0.dy;
let dly0 = -p0.dx;
let dlx1 = p1.dy;
let dly1 = -p1.dx;
if (p1.flags & PointFlags.PT_LEFT) {
let out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, lw);
lx0 = out[0];
ly0 = out[1];
lx1 = out[2];
ly1 = out[3];
this._vset(lx0, ly0, 1);
this._vset(p1.x - dlx0 * rw, p1.y - dly0 * rw, -1);
this._vset(lx1, ly1, 1);
this._vset(p1.x - dlx1 * rw, p1.y - dly1 * rw, -1);
} else {
let out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, -rw);
rx0 = out[0];
ry0 = out[1];
rx1 = out[2];
ry1 = out[3];
this._vset(p1.x + dlx0 * lw, p1.y + dly0 * lw, 1);
this._vset(rx0, ry0, -1);
this._vset(p1.x + dlx1 * lw, p1.y + dly1 * lw, 1);
this._vset(rx1, ry1, -1);
}
}
// todo: loop reuse buff
// 目前在InjectAssembler后外部实现,需要拿进来
_vset(x, y, distance = 0) {
let buffer = this._buffer;
let meshbuffer = buffer.meshbuffer;
let dataOffset = buffer.vertexStart * this.getVfmtFloatCount();
let vData = meshbuffer._vData;
let uintVData = meshbuffer._uintVData;
vData[dataOffset] = x;
vData[dataOffset + 1] = y;
uintVData[dataOffset + 2] = this._curColor;
vData[dataOffset + 3] = distance;
buffer.vertexStart++;
meshbuffer._dirty = true;
}
strokeV2(graphics, sp, ep) {
// this._curColor = graphics._strokeColor._val;
// this._flattenPathsV2(graphics._impl, sp, ep); // move to outside
this._expandStrokeV2(graphics, sp, ep);
// 永远不更新PathOffset
// graphics._impl._updatePathOffset = true;
}
// 通过判断收尾点是否相同,判定闭环,如果是,则弹出最后一个点
// 求每个点到下个点的距离、单位方向向量
_flattenPathsV2(impl, sp, ep) {
let paths = impl._paths;
let i = impl._pathOffset;
let path = paths[i];
let pts = path.points;
// let p0 = pts[pts.length - 1];
// let p1 = pts[0];
// if (pts.length > 2 && p0.equals(p1)) {
// path.closed = true;
// pts.pop();
// p0 = pts[pts.length - 1];
// }
// for (let j = 0, size = pts.length; j < size; j++) {
// ep点的dx是要计算的
for (let j = sp; j <= ep; ++j) {
let p0 = pts[j];
let p1 = pts[j+1];
// Calculate segment direction and length
let dPos = p1.sub(p0);
p0.len = dPos.mag();
if (dPos.x || dPos.y)
dPos.normalizeSelf();
p0.dx = dPos.x;
p0.dy = dPos.y;
// Advance
// p0 = p1;
// p1 = pts[j + 1];
}
}
// 回滚一个点对应的Mesh
public RollBack(graphics, index: number): void {
let impl = graphics._impl;
let paths = impl._paths;
// Calculate max vertex usage.
// let cverts = 0;
let i = impl._pathOffset;
let path = paths[i];
// let pts = path.points;
let vertCount = path.vertCount;
let buffer = this._trailBuff;
let count = vertCount[index];
buffer.vertexStart -= count;
if (index > 0)
buffer.indiceStart -= count * 3;
this._vertexHead -= count;
impl.erase(index);
}
// Bevel: true, InnerBevel: false
// 尽量不要用InnerBevel
public HasSmoothCorner(graphics, sp: number): boolean {
let w = graphics.lineWidth * 0.5,
lineCap = graphics.lineCap,
lineJoin = graphics.lineJoin,
miterLimit = graphics.miterLimit;
let impl = graphics._impl;
let iw = 0.0;
let w2 = w * w;
if (w > 0.0) {
iw = 1 / w;
}
// Calculate which joins needs extra vertices to append, and gather vertex count.
let paths = impl._paths;
let i = impl._pathOffset;
let path = paths[i];
let pts = path.points;
let p0 = pts[sp];
let p1 = pts[sp+1];
let dmr2, cross, limit;
// perp normals
let dlx0 = p0.dy;
let dly0 = -p0.dx;
let dlx1 = p1.dy;
let dly1 = -p1.dx;
// Calculate extrusions
p1.dmx = (dlx0 + dlx1) * 0.5;
p1.dmy = (dly0 + dly1) * 0.5;
dmr2 = p1.dmx * p1.dmx + p1.dmy * p1.dmy;
if (dmr2 > 0.000001) {
let scale = 1 / dmr2;
if (scale > 600) {
scale = 600;
}
p1.dmx *= scale;
p1.dmy *= scale;
}
// // Keep track of left turns.
// cross = p1.dx * p0.dy - p0.dx * p1.dy;
// if (cross > 0) {
// nleft++;
// p1.flags |= PointFlags.PT_LEFT;
// }
// Calculate if we should use bevel or miter for inner join.
limit = max(11, min(p0.len, p1.len) * iw);
if (dmr2 * limit * limit < 1) {
return false;
// p1.flags |= PointFlags.PT_INNERBEVEL;
}
// TODO: 2.4.4的commit,会导致INNERBEVEL渲染错误
// https://github.com/cocos-creator/engine/pull/7780/commits/06320339dae5419a6e96058344a35254429862f1
// Check whether dm length is too long
let dmwx = p1.dmx * w;
let dmwy = p1.dmy * w;
let dmlen2 = dmwx * dmwx + dmwy * dmwy;
// 设交点P到dm点的连线为S,和len、w围成三角形。S对应的角是O
// 只要O不是钝角,则dm点一定在线段内部。极限情况下O是直角,此时根据勾股定理求S的最大容忍值
if (dmlen2 > (p1.len * p1.len) + w2 && dmlen2 > (p0.len * p0.len) + w2) {
return false;
// p1.flags |= PointFlags.PT_INNERBEVEL;
}
return true;
// Check to see if the corner needs to be beveled.
// if (p1.flags & PointFlags.PT_CORNER) {
// if (dmr2 * miterLimit * miterLimit < 1 || lineJoin === LineJoin.BEVEL || lineJoin === LineJoin.ROUND) {
// p1.flags |= PointFlags.PT_BEVEL;
// }
// }
// if ((p1.flags & (PointFlags.PT_BEVEL | PointFlags.PT_INNERBEVEL)) !== 0) {
// path.nbevel++;
// }
}
// stroke pntIndex -> pntIndex+1
_expandStrokeV2(graphics, sp, ep) {
let w = graphics.lineWidth * 0.5,
lineCap = graphics.lineCap,
lineJoin = graphics.lineJoin,
miterLimit = graphics.miterLimit;
let impl = graphics._impl;
let ncap = curveDivs(w, PI, impl._tessTol);
this._calculateJoinsV2(impl, w, lineJoin, miterLimit, sp, ep);
let paths = impl._paths;
// // Calculate max vertex usage.
// let cverts = 0;
// for (let i = impl._pathOffset, l = impl._pathLength; i < l; i++) {
// let path = paths[i];
// let pointsLength = path.points.length;
// if (lineJoin === LineJoin.ROUND) cverts += (pointsLength + path.nbevel * (ncap + 2) + 1) * 2; // plus one for loop
// else cverts += (pointsLength + path.nbevel * 5 + 1) * 2; // plus one for loop
// if (!path.closed) {
// // space for caps
// if (lineCap === LineCap.ROUND) {
// cverts += (ncap * 2 + 2) * 2;
// } else {
// cverts += (3 + 3) * 2;
// }
// }
// }
// TODO: 由于此时的cverts是动态增长的,buff预先分配2048,后续
// 1. 使用多个buff拼接实现更长的mesh
// 2. 用循环数组形式移除最老的verts
// 在cap start里应该完成这个事情
// let cverts = this.PATH_VERTEX;
// let buffer = this._trailBuff;
// if (!buffer) {
// buffer = this._trailBuff = this.genBuffer(graphics, cverts);
// }
// let // buffer = this.genBuffer(graphics, cverts),
// meshbuffer = buffer.meshbuffer,
// vData = meshbuffer._vData,
// iData = meshbuffer._iData;
let i = impl._pathOffset;
let path = paths[i];
let pts = path.points;
// let pointsLength = pts.length;
// let offset = buffer.vertexStart;
// let p0, p1;
// let start, end, loop;
// loop = path.closed;
// if (loop) {
// // Looping
// p0 = pts[pointsLength - 1];
// p1 = pts[0];
// start = 0;
// end = pointsLength;
// } else {
// // Add cap
// p0 = pts[0];
// p1 = pts[1];
// start = 1;
// end = pointsLength - 1;
// }
// p1 = p1 || p0;
// if (!loop) {
// // Add cap
// let dPos = p1.sub(p0);
// dPos.normalizeSelf();
// let dx = dPos.x;
// let dy = dPos.y;
// if (lineCap === LineCap.BUTT)
// this._buttCapStart(p0, dx, dy, w, 0);
// else if (lineCap === LineCap.SQUARE)
// this._buttCapStart(p0, dx, dy, w, w);
// else if (lineCap === LineCap.ROUND)
// this._roundCapStart(p0, dx, dy, w, ncap);
// }
let buffer = this._trailBuff;
for (let j = sp; j < ep; ++j) {
let preCount = buffer.vertexStart;
let p0 = pts[j];
let p1 = pts[j+1];
if (lineJoin === LineJoin.ROUND) {
this._roundJoin(p0, p1, w, w, ncap);
}
else if ((p1.flags & (PointFlags.PT_BEVEL | PointFlags.PT_INNERBEVEL)) !== 0) {
this._bevelJoin(p0, p1, w, w);
}
else {
this._vset(p1.x + p1.dmx * w, p1.y + p1.dmy * w, 1);
this._vset(p1.x - p1.dmx * w, p1.y - p1.dmy * w, -1);
}
//p0 = p1;
//p1 = pts[j + 1];
path.vertCount[j+1] = buffer.vertexStart - preCount;
}
// if (loop) {
// // Loop it
// let floatCount = this.getVfmtFloatCount();
// let vDataoOfset = offset * floatCount;
// this._vset(vData[vDataoOfset], vData[vDataoOfset + 1], 1);
// this._vset(vData[vDataoOfset + floatCount], vData[vDataoOfset + floatCount + 1], -1);
// } else {
// // Add cap
// let dPos = p1.sub(p0);
// dPos.normalizeSelf();
// let dx = dPos.x;
// let dy = dPos.y;
// if (lineCap === LineCap.BUTT)
// this._buttCapEnd(p1, dx, dy, w, 0);
// else if (lineCap === LineCap.SQUARE)
// this._buttCapEnd(p1, dx, dy, w, w);
// else if (lineCap === LineCap.ROUND)
// this._roundCapEnd(p1, dx, dy, w, ncap);
// }
this.FlushIndices(graphics);
}
protected FlushIndices(graphics) {
let buffer = this._trailBuff;
// if (!buffer) {
// let cverts = this.PATH_VERTEX;
// buffer = this._trailBuff = this.genBuffer(graphics, cverts);
// }
let // buffer = this.genBuffer(graphics, cverts),
meshbuffer = buffer.meshbuffer,
vData = meshbuffer._vData,
iData = meshbuffer._iData;
// todo: 连接前面的Mesh
// offset是更新前
// stroke indices
let indicesOffset = buffer.indiceStart;
let offset = this._vertexHead;
if (offset == this._pathVertexStart) {
// 如果是开头,不需要衔接其他内容
offset += 2;
}
for (let start = offset, end = buffer.vertexStart; start < end; start++) {
iData[indicesOffset++] = start - 2;
iData[indicesOffset++] = start - 1;
iData[indicesOffset++] = start;
}
this._vertexHead = buffer.vertexStart;
buffer.indiceStart = indicesOffset;
}
// todo: calculate range
_calculateJoinsV2(impl, w, lineJoin, miterLimit, sp, ep) {
let iw = 0.0;
let w2 = w * w;
if (w > 0.0) {
iw = 1 / w;
}
// Calculate which joins needs extra vertices to append, and gather vertex count.
let paths = impl._paths;
let i = impl._pathOffset;
let path = paths[i];
let pts = path.points;
let ptsLength = pts.length;
// let p0 = pts[ptsLength - 1];
// let p1 = pts[0];
let nleft = 0;
// path.nbevel = 0; // do not init
// for (let j = 0; j < ptsLength; j++) {
for (; sp < ep; ++sp) {
let p0 = pts[sp];
let p1 = pts[sp+1];
let dmr2, cross, limit;
// perp normals
let dlx0 = p0.dy;
let dly0 = -p0.dx;
let dlx1 = p1.dy;
let dly1 = -p1.dx;
// Calculate extrusions
p1.dmx = (dlx0 + dlx1) * 0.5;
p1.dmy = (dly0 + dly1) * 0.5;
dmr2 = p1.dmx * p1.dmx + p1.dmy * p1.dmy;
if (dmr2 > 0.000001) {
let scale = 1 / dmr2;
if (scale > 600) {
scale = 600;
}
p1.dmx *= scale;
p1.dmy *= scale;
}
// Keep track of left turns.
cross = p1.dx * p0.dy - p0.dx * p1.dy;
if (cross > 0) {
nleft++;
p1.flags |= PointFlags.PT_LEFT;
}
// Calculate if we should use bevel or miter for inner join.
limit = max(11, min(p0.len, p1.len) * iw);
if (dmr2 * limit * limit < 1) {
p1.flags |= PointFlags.PT_INNERBEVEL;
}
// TODO: 2.4.4的commit,会导致INNERBEVEL渲染错误
// https://github.com/cocos-creator/engine/pull/7780/commits/06320339dae5419a6e96058344a35254429862f1
// Check whether dm length is too long
let dmwx = p1.dmx * w;
let dmwy = p1.dmy * w;
let dmlen2 = dmwx * dmwx + dmwy * dmwy;
// 设交点P到dm点的连线为S,和len、w围成三角形。S对应的角是O
// 只要O不是钝角,则dm点一定在线段内部。极限情况下O是直角,此时根据勾股定理求S的最大容忍值
if (dmlen2 > (p1.len * p1.len) + w2 && dmlen2 > (p0.len * p0.len) + w2) {
p1.flags |= PointFlags.PT_INNERBEVEL;
}
// Check to see if the corner needs to be beveled.
if (p1.flags & PointFlags.PT_CORNER) {
if (dmr2 * miterLimit * miterLimit < 1 || lineJoin === LineJoin.BEVEL || lineJoin === LineJoin.ROUND) {
p1.flags |= PointFlags.PT_BEVEL;
}
}
if ((p1.flags & (PointFlags.PT_BEVEL | PointFlags.PT_INNERBEVEL)) !== 0) {
path.nbevel++;
}
}
}
public _pathVertexStart: number = 0;
public _vertexHead: number = 0;
public CapStart(graphics, sp: number) {
let cverts = this.PATH_VERTEX;
//let buffer = this._trailBuff;
//if (!buffer)
let buffer = this._trailBuff = this.genBuffer(graphics, cverts);
// 记录整条path的开始vertex
// 主要用于在strok时顺便初始化startCap的索引
this._vertexHead = this._pathVertexStart = buffer.vertexStart;
let impl = graphics._impl;
let i = impl._pathOffset;
let paths = impl._paths;
let path = paths[i];
let pts = path.points;
let w = graphics.lineWidth * 0.5,
lineCap = graphics.lineCap,
lineJoin = graphics.lineJoin,
miterLimit = graphics.miterLimit;
let ncap = curveDivs(w, PI, impl._tessTol);
// todo: dx, dy已经有了,不要再算,call flatten
let p0 = pts[sp];
let p1 = pts[sp+1];
// Add cap
let dPos = p1.sub(p0);
dPos.normalizeSelf();
let dx = dPos.x;
let dy = dPos.y;
let preCount = buffer.vertexStart;
if (lineCap === LineCap.BUTT)
this._buttCapStart(p0, dx, dy, w, 0);
else if (lineCap === LineCap.SQUARE)
this._buttCapStart(p0, dx, dy, w, w);
else if (lineCap === LineCap.ROUND)
this._roundCapStart(p0, dx, dy, w, ncap);
path.vertCount[sp] = buffer.vertexStart - preCount;
// 没必要,但是是幂等的
// this.FlushIndices(graphics);
}
public CapEnd(graphics, sp: number) {
let impl = graphics._impl;
let i = impl._pathOffset;
let paths = impl._paths;
let path = paths[i];
let pts = path.points;
let w = graphics.lineWidth * 0.5,
lineCap = graphics.lineCap,
lineJoin = graphics.lineJoin,
miterLimit = graphics.miterLimit;
let ncap = curveDivs(w, PI, impl._tessTol);
// todo: dx, dy已经有了,不要再算
let p0 = pts[sp];
let p1 = pts[sp+1];
let dPos = p1.sub(p0);
dPos.normalizeSelf();
let dx = dPos.x;
let dy = dPos.y;
if (lineCap === LineCap.BUTT)
this._buttCapEnd(p1, dx, dy, w, 0);
else if (lineCap === LineCap.SQUARE)
this._buttCapEnd(p1, dx, dy, w, w);
else if (lineCap === LineCap.ROUND)
this._roundCapEnd(p1, dx, dy, w, ncap);
this.FlushIndices(graphics);
console.log(`Mesh Size: ${this._vertexHead - this._pathVertexStart}`);
}
}
cc.Assembler.register(SmoothTrail, SmoothTrailAssembler); | the_stack |
import { workspace, Uri, ConfigurationTarget, TextDocument, WorkspaceConfiguration, ConfigurationScope } from 'vscode';
import { extensionId } from '../constants';
import { CSpellUserSettings } from '../client';
import { findConicalDocumentScope } from '../util/documentUri';
export { CSpellUserSettings } from '../client';
export { ConfigurationTarget } from 'vscode';
export const sectionCSpell = extensionId;
export interface InspectValues<T> {
defaultValue?: T;
globalValue?: T;
workspaceValue?: T;
workspaceFolderValue?: T;
}
export interface FullInspectValues<T> extends InspectValues<T> {
key: string;
defaultLanguageValue?: T;
globalLanguageValue?: T;
workspaceLanguageValue?: T;
workspaceFolderLanguageValue?: T;
languageIds?: string[];
}
export const GlobalTarget = ConfigurationTarget.Global;
export interface ConfigTargetWithOptionalResource {
target: ConfigurationTarget;
uri?: Uri;
configScope?: ConfigurationScope;
}
export interface ConfigTargetWithResource extends ConfigTargetWithOptionalResource {
uri: Uri;
}
export type ConfigTargetResourceFree = ConfigurationTarget.Global | ConfigurationTarget.Workspace;
export type ConfigTargetLegacy = ConfigTargetResourceFree | ConfigTargetWithResource | ConfigTargetWithOptionalResource;
export interface Inspect<T> extends FullInspectValues<T> {
key: string;
}
export type Scope = keyof InspectValues<CSpellUserSettings>;
export type ScopeResourceFree = 'defaultValue' | 'globalValue' | 'workspaceValue';
export interface ScopeValues {
Default: 'defaultValue';
Global: 'globalValue';
Workspace: 'workspaceValue';
Folder: 'workspaceFolderValue';
}
export const Scopes: ScopeValues = {
Default: 'defaultValue',
Global: 'globalValue',
Workspace: 'workspaceValue',
Folder: 'workspaceFolderValue',
};
export interface FullInspectScope {
scope: Scope;
resource: Uri | undefined;
}
export type InspectScope = FullInspectScope | ScopeResourceFree;
/**
* ScopeOrder from general to specific.
*/
const scopeOrder: Scope[] = ['defaultValue', 'globalValue', 'workspaceValue', 'workspaceFolderValue'];
const scopeToOrderIndex = new Map<string, number>(scopeOrder.map((s, i) => [s, i] as [string, number]));
export type InspectResult<T> = Inspect<T> | undefined;
export function getSectionName(subSection?: keyof CSpellUserSettings): string {
return [sectionCSpell, subSection].filter((a) => !!a).join('.');
}
export function getSettingsFromVSConfig(scope: GetConfigurationScope): CSpellUserSettings {
const config = getConfiguration(scope);
return config.get<CSpellUserSettings>(sectionCSpell, {});
}
export function getSettingFromVSConfig<K extends keyof CSpellUserSettings>(
subSection: K,
resource: GetConfigurationScope
): CSpellUserSettings[K] | undefined {
const config = getConfiguration(resource);
const settings = config.get<CSpellUserSettings>(sectionCSpell, {});
return settings[subSection];
}
/**
* Inspect a scoped setting. It will not merge values.
* @param subSection the cspell section
* @param scope the scope of the value. A resource is needed to get folder level settings.
*/
export function inspectScopedSettingFromVSConfig<K extends keyof CSpellUserSettings>(
subSection: K,
scope: InspectScope
): CSpellUserSettings[K] | undefined {
scope = normalizeScope(scope);
const ins = inspectSettingFromVSConfig(subSection, scope.resource);
return ins?.[scope.scope];
}
/**
* Inspect a scoped setting. It will not merge values.
* @param subSection the cspell section
* @param scope the scope of the value. A resource is needed to get folder level settings.
*/
export function getScopedSettingFromVSConfig<K extends keyof CSpellUserSettings>(
subSection: K,
scope: InspectScope
): CSpellUserSettings[K] | undefined {
return findScopedSettingFromVSConfig(subSection, scope).value;
}
/**
* Inspect a scoped setting. It will not merge values.
* @param subSection the cspell section
* @param scope the scope of the value. A resource is needed to get folder level settings.
*/
export function findScopedSettingFromVSConfig<K extends keyof CSpellUserSettings>(
subSection: K,
scope: InspectScope
): FindBestConfigResult<K> {
scope = normalizeScope(scope);
const ins = inspectSettingFromVSConfig(subSection, scope.resource);
return findBestConfig(ins, scope.scope);
}
export function inspectSettingFromVSConfig<K extends keyof CSpellUserSettings>(
subSection: K,
scope: GetConfigurationScope
): Inspect<CSpellUserSettings[K]> {
return inspectConfigByScopeAndKey(scope, subSection);
}
export function setSettingInVSConfig<K extends keyof CSpellUserSettings>(
subSection: K,
value: CSpellUserSettings[K],
configTarget: ConfigTargetLegacy
): Promise<void> {
const nTarget = normalizeTarget(configTarget);
const target = extractTarget(nTarget);
const uri = extractTargetUri(nTarget);
const section = getSectionName(subSection);
const config = getConfiguration(uri);
return Promise.resolve(config.update(section, value, target));
}
/**
* @deprecationMessage Use inspectConfigKey -- this is not guaranteed to work in the future.
* @deprecated true
*/
export function inspectConfig(scope: GetConfigurationScope): Inspect<CSpellUserSettings> {
const config = getConfiguration(scope);
const settings = config.inspect<CSpellUserSettings>(sectionCSpell) || { key: sectionCSpell };
return settings;
}
export function inspectConfigByScopeAndKey<K extends keyof CSpellUserSettings>(
scope: GetConfigurationScope,
key: K
): Inspect<CSpellUserSettings[K]> {
const config = getConfiguration(scope);
const sectionKey = [sectionCSpell, key].join('.');
const settings = config.inspect<CSpellUserSettings[K]>(sectionKey) || { key: sectionKey };
return settings;
}
function inspectConfigByKey<K extends keyof CSpellUserSettings>(config: WorkspaceConfiguration, key: K): Inspect<CSpellUserSettings[K]> {
const sectionKey = [sectionCSpell, key].join('.');
const settings = config.inspect<CSpellUserSettings[K]>(sectionKey) || { key: sectionKey };
return settings;
}
type InspectByKeys<T> = {
[K in keyof T]?: Inspect<T[K]>;
};
type InspectCSpellSettings = InspectByKeys<CSpellUserSettings>;
export function inspectConfigKeys(scope: GetConfigurationScope, keys: readonly (keyof InspectCSpellSettings)[]): InspectCSpellSettings {
const config = getConfiguration(scope);
const r: InspectCSpellSettings = {};
for (const k of keys) {
const x: InspectCSpellSettings = { [k]: inspectConfigByKey(config, k) };
Object.assign(r, x);
}
return r;
}
export function isGlobalLevelTarget(target: ConfigTargetLegacy): boolean {
return (
(isConfigTargetWithOptionalResource(target) && target.target === ConfigurationTarget.Global) ||
target === ConfigurationTarget.Global
);
}
export function isWorkspaceLevelTarget(target: ConfigTargetLegacy): boolean {
return isConfigTargetWithOptionalResource(target) && target.target === ConfigurationTarget.Workspace;
}
export function isFolderLevelTarget(target: ConfigTargetLegacy): boolean {
return isConfigTargetWithResource(target) && target.target === ConfigurationTarget.WorkspaceFolder;
}
export function isConfigTargetWithResource(target: ConfigTargetLegacy): target is ConfigTargetWithResource {
return isConfigTargetWithOptionalResource(target) && target.uri !== undefined;
}
export function isConfigTargetWithOptionalResource(target: ConfigTargetLegacy): target is ConfigTargetWithOptionalResource {
return typeof target === 'object' && target.target !== undefined;
}
export function getConfigurationTargetFromLegacy(target: ConfigTargetLegacy): ConfigurationTarget {
return typeof target === 'object' ? target.target : target;
}
type TargetToScopeMap = {
[ConfigurationTarget.Global]: 'globalValue';
[ConfigurationTarget.Workspace]: 'workspaceValue';
[ConfigurationTarget.WorkspaceFolder]: 'workspaceFolderValue';
};
const targetToScopeMap: TargetToScopeMap = {
[ConfigurationTarget.Global]: 'globalValue',
[ConfigurationTarget.Workspace]: 'workspaceValue',
[ConfigurationTarget.WorkspaceFolder]: 'workspaceFolderValue',
};
type ConfigTargetToName = {
[key in ConfigurationTarget]: string;
};
const configTargetToName: ConfigTargetToName = {
[ConfigurationTarget.Global]: 'user',
[ConfigurationTarget.Workspace]: 'workspace',
[ConfigurationTarget.WorkspaceFolder]: 'folder',
};
export function configurationTargetToName(target: ConfigurationTarget): string {
return configTargetToName[target];
}
export function configTargetToScope(target: ConfigTargetLegacy): InspectScope {
if (isConfigTargetWithOptionalResource(target)) {
return {
scope: toScope(target.target),
resource: target.uri || undefined,
};
}
return targetToScopeMap[target];
}
export function toScope(target: ConfigurationTarget): Scope {
return targetToScopeMap[target];
}
export function extractScope(inspectScope: InspectScope): Scope {
if (isFullInspectScope(inspectScope)) {
return inspectScope.scope;
}
return inspectScope;
}
function isFullInspectScope(scope: InspectScope): scope is FullInspectScope {
return typeof scope === 'object';
}
function normalizeScope(scope: InspectScope): FullInspectScope {
if (isFullInspectScope(scope)) {
return {
scope: scope.scope,
resource: scope.scope === Scopes.Folder ? normalizeResourceUri(scope.resource) : undefined,
};
}
return { scope, resource: undefined };
}
function normalizeResourceUri(uri: Uri | null | undefined): Uri | undefined {
if (uri) {
const folder = workspace.getWorkspaceFolder(uri);
return folder?.uri;
}
return undefined;
}
export interface FindBestConfigResult<K extends keyof CSpellUserSettings> {
scope: Scope;
value: CSpellUserSettings[K];
}
function findBestConfig<K extends keyof CSpellUserSettings>(config: Inspect<CSpellUserSettings[K]>, scope: Scope): FindBestConfigResult<K> {
for (let p = scopeToOrderIndex.get(scope)!; p >= 0; p -= 1) {
const k = scopeOrder[p];
const v = config[k];
if (v !== undefined) {
return { scope: k, value: v };
}
}
return { scope: 'defaultValue', value: undefined };
}
export function isGlobalTarget(target: ConfigTargetLegacy): boolean {
return extractTarget(target) === ConfigurationTarget.Global;
}
export function createTargetForUri(target: ConfigurationTarget, uri: Uri): ConfigTargetWithResource {
return {
target,
uri,
};
}
export function createTargetForDocument(target: ConfigurationTarget, doc: TextDocument): ConfigTargetWithResource {
return createTargetForUri(target, doc.uri);
}
export function extractTarget(target: ConfigTargetLegacy): ConfigurationTarget {
return isConfigTargetWithOptionalResource(target) ? target.target : target;
}
export function extractTargetUri(target: ConfigTargetLegacy): Uri | undefined {
return isConfigTargetWithOptionalResource(target) ? target.uri : undefined;
}
export type GetConfigurationScope = ConfigurationScope | undefined;
export function getConfiguration(scope: GetConfigurationScope): WorkspaceConfiguration {
return workspace.getConfiguration(undefined, normalizeConfigurationScope(scope));
}
export function normalizeTarget(target: ConfigTargetLegacy): ConfigTargetWithOptionalResource {
if (isConfigTargetWithOptionalResource(target)) return target;
return {
target,
uri: undefined,
};
}
type ConfigKeys = keyof CSpellUserSettings;
export function calculateConfigForTarget(
target: ConfigurationTarget,
scope: GetConfigurationScope,
keys: readonly ConfigKeys[],
useMergeInspect: boolean
): CSpellUserSettings {
const s: CSpellUserSettings = {};
const inspectResult = inspectConfigKeys(scope, keys);
const fn = useMergeInspect ? assignExtractAndMerge : assignExtract;
for (const k of keys) {
fn(s, target, k, inspectResult);
}
return s;
}
function assignExtractAndMerge<K extends keyof InspectCSpellSettings>(
dest: CSpellUserSettings,
target: ConfigurationTarget,
k: K,
s: InspectCSpellSettings
) {
const v = s[k] as FullInspectValues<CSpellUserSettings[K]>;
const m = mergeInspect<CSpellUserSettings[K]>(target, v);
if (m !== undefined) {
dest[k] = m;
}
}
function assignExtract<K extends keyof InspectCSpellSettings>(
dest: CSpellUserSettings,
target: ConfigurationTarget,
k: K,
s: InspectCSpellSettings
) {
const v = s[k] as FullInspectValues<CSpellUserSettings[K]>;
const m = extractInspect<CSpellUserSettings[K]>(target, v);
if (m !== undefined) {
dest[k] = m;
}
}
function extractInspect<T>(target: ConfigurationTarget, value: FullInspectValues<T> | undefined): T | undefined {
if (value === undefined) return undefined;
switch (target) {
case ConfigurationTarget.Global:
return value.globalLanguageValue ?? value.globalValue;
case ConfigurationTarget.Workspace:
return value.workspaceLanguageValue ?? value.workspaceValue;
case ConfigurationTarget.WorkspaceFolder:
return value.workspaceFolderLanguageValue ?? value.workspaceFolderValue;
}
}
function mergeInspect<T>(target: ConfigurationTarget, value: FullInspectValues<T> | undefined): T | undefined {
if (value === undefined) return undefined;
let t: T | undefined = mergeValues(value.defaultValue, value.defaultLanguageValue, value.globalValue, value.globalLanguageValue);
if (target === ConfigurationTarget.Global) return t;
t = mergeValues(t, value.workspaceValue, value.workspaceLanguageValue);
if (target === ConfigurationTarget.Workspace) return t;
t = mergeValues(t, value.workspaceFolderValue, value.workspaceFolderLanguageValue);
if (target !== ConfigurationTarget.WorkspaceFolder) throw new Error(`Unknown Config Target "${target}"`);
return t;
}
function mergeValues<T>(...v: T[]): T | undefined {
let m: T | undefined = undefined;
for (const t of v) {
if (t === undefined) continue;
if (typeof m !== 'object' || typeof t !== 'object' || Array.isArray(t) || Array.isArray(m)) {
m = t;
continue;
}
m = Object.assign({}, m, t);
}
return m;
}
/**
* Update VS Code Configuration for the Extension
* @param target - configuration level
* @param scope - the configuration scope / context
* @param keys - keys needed for the update function.
* @param updateFn - A function that will return the fields to be updated.
* @returns
*/
export function updateConfig(
target: ConfigurationTarget,
scope: GetConfigurationScope,
keys: readonly ConfigKeys[],
updateFn: (c: Partial<CSpellUserSettings>) => Partial<CSpellUserSettings>,
useMerge: boolean
): Promise<void> {
const cfg = calculateConfigForTarget(target, scope, keys, useMerge);
const updated = updateFn(cfg);
const config = getConfiguration(scope);
const p = Object.entries(updated).map(([key, value]) => config.update(`${extensionId}.${key}`, value, target));
return Promise.all(p).then();
}
interface UriLike {
readonly authority: string;
readonly fragment: string;
readonly path: string;
readonly query: string;
readonly scheme: string;
}
interface HasUri {
uri: Uri | UriLike;
}
function normalizeConfigurationScope(scope: GetConfigurationScope): GetConfigurationScope {
if (isUriLike(scope)) return findConicalDocumentScope(fixUri(scope));
if (isHasUri(scope)) {
if (isUri(scope.uri)) return scope;
return {
...scope,
uri: fixUri(scope.uri),
};
}
return scope;
}
/**
* Fix any Uri's that are not VS Code Specific Uri instances.
* The Configuration is very picky and will break if it is not a VS Code instance.
* @param scope - A ConfigurationScope
* @returns
*/
function fixUri(scope: UriLike | Uri): Uri {
if (isUri(scope)) return scope;
return Uri.parse(scope.toString());
}
function isUriLike(possibleUri: unknown): possibleUri is UriLike {
if (!possibleUri || typeof possibleUri !== 'object') return false;
const uri = <UriLike>possibleUri;
return (
uri.authority !== undefined &&
uri.fragment !== undefined &&
uri.path != undefined &&
uri.query != undefined &&
uri.scheme != undefined
);
}
function isUri(uri: unknown): uri is Uri {
return uri instanceof Uri;
}
function isHasUri(scope: unknown): scope is HasUri {
if (!scope || typeof scope !== 'object') return false;
const h = <HasUri>scope;
return h.uri !== undefined;
}
export const __testing__ = {
mergeInspect,
}; | the_stack |
import assert from 'assert';
import { Request, Response, NextFunction } from 'express';
import * as crypto from 'crypto';
import * as util from 'util';
import '../types';
import * as db from './db';
import * as model from '../model/user';
import { makeRandom } from './random';
import { NotFoundError, ForbiddenError, BadRequestError, InternalError } from './errors';
import * as I18n from './i18n';
import * as Config from '../config';
export function hashPassword(salt : string, password : string) : Promise<string> {
return util.promisify(crypto.pbkdf2)(password, salt, 10000, 32, 'sha1')
.then((buffer) => buffer.toString('hex'));
}
export const OAuthScopes = new Set([
'profile', // minimum scope: see the user's profile
'user-read', // read active commands and devices
'user-read-results', // read results of active commands
'user-exec-command', // execute thingtalk (includes web almond access)
'user-sync', // cloud sync (dump credentials)
'developer-read', // read unapproved devices (equivalent to a developer key)
'developer-upload', // upload new devices
'developer-admin', // modify thingpedia organization settings, add/remove members
] as const);
export type OAuthScopes = Parameters<(typeof OAuthScopes)['has']>[0];
export function isAuthenticated<T extends Request>(req : T) : req is T & { user : Express.User } {
if (!req.user)
return false;
// no need for 2fa when using OAuth tokens
if (req.authInfo && req.authInfo.authMethod === 'oauth2')
return true;
// no need for 2fa when 2fa is not setup
if (req.user.totp_key === null)
return true;
return !!req.session.completed2fa;
}
const INVALID_USERNAMES = new Set('admin,moderator,administrator,mod,sys,system,community,info,you,name,username,user,nickname,discourse,discourseorg,discourseforum,support,hp,account-created,password-reset,admin-login,confirm-admin,account-created,activate-account,confirm-email-token,authorize-email,stanfordalmond,almondstanford,almond,root,noreply,stanford'.split(','));
const MAX_USERNAME_LENGTH = 60;
function validateUsername(username : string) {
if (username.length > MAX_USERNAME_LENGTH ||
INVALID_USERNAMES.has(username.toLowerCase()) ||
/[^\w.-]/.test(username) ||
/\.(js|json|css|htm|html|xml|jpg|jpeg|png|gif|bmp|ico|tif|tiff|woff)$/i.test(username))
return false;
return true;
}
export enum DeveloperStatus {
USER,
DEVELOPER,
ORG_ADMIN,
}
export enum Role {
ADMIN = 1, // allows to view and manipulate users
BLOG_EDITOR = 2, // allows to edit blogs
THINGPEDIA_ADMIN = 4, // allows to view/edit/approve thingpedia entries (devices, datasets, strings, entities, examples, etc)
TRUSTED_DEVELOPER = 8, // allows to approve their own device
DISCOURSE_ADMIN = 16, // admin of the community forum (through SSO)
NLP_ADMIN = 32, // admin of datasets, mturk, and training
// all privileges
ROOT = 63,
// all roles that grant access to /admin hierarchy
ALL_ADMIN = 1+2+4+32,
}
export enum ProfileFlags {
VISIBLE_ORGANIZATION_PROFILE = 1,
SHOW_HUMAN_NAME = 2,
SHOW_EMAIL = 4,
SHOW_PROFILE_PICTURE = 8,
}
export const GOOGLE_SCOPES = ['openid','profile','email'].join(' ');
export const GITHUB_SCOPES = ['read:user', 'user:email'].join(' ');
export {
MAX_USERNAME_LENGTH,
validateUsername,
};
export interface RegisterOptions {
username : string;
human_name ?: string;
email : string;
email_verified ?: boolean;
password : string;
locale : string;
timezone : string;
developer_org ?: number;
developer_status ?: number;
roles ?: number;
profile_flags ?: number;
}
interface I18nReq {
_(x : string) : string;
}
export async function register(dbClient : db.Client, req : I18nReq, options : RegisterOptions) {
const usernameRows = await model.getByName(dbClient, options.username);
if (usernameRows.length > 0)
throw new BadRequestError(req._("A user with this name already exists."));
const emailRows = await model.getByEmail(dbClient, options.email);
if (emailRows.length > 0)
throw new BadRequestError(req._("A user with this email already exists."));
const salt = makeRandom();
const cloudId = makeRandom(8);
const authToken = makeRandom();
const storageKey = makeRandom();
const hash = await hashPassword(salt, options.password);
const created = await model.create(dbClient, {
username: options.username,
human_name: options.human_name || null,
password: hash,
email: options.email,
email_verified: options.email_verified || false,
locale: options.locale,
timezone: options.timezone,
salt: salt,
cloud_id: cloudId,
auth_token: authToken,
storage_key: storageKey,
developer_org: options.developer_org || null,
developer_status: options.developer_status || 0,
roles: options.roles || 0,
profile_flags: options.profile_flags || 0,
});
// readback the record from the db to retrieve the full profile
return model.get(dbClient, created.id);
}
export function recordLogin(dbClient : db.Client, userId : number) {
return model.recordLogin(dbClient, userId);
}
export async function update(dbClient : db.Client, user : db.WithID<Partial<model.Row>>, oldpassword : string|undefined, password : string) {
if (user.salt && user.password) {
if (!oldpassword || user.password !== await hashPassword(user.salt, oldpassword))
throw new ForbiddenError('Invalid old password');
}
const salt = makeRandom();
const newhash = await hashPassword(salt, password);
await model.update(dbClient, user.id, {
salt: salt,
password: newhash
});
user.salt = salt;
user.password = newhash;
}
export async function resetPassword(dbClient : db.Client, user : db.WithID<Partial<model.Row>>, password : string) {
const salt = makeRandom();
const newhash = await hashPassword(salt, password);
await model.update(dbClient, user.id, { salt: salt,
password: newhash });
user.salt = salt;
user.password = newhash;
}
export async function makeDeveloper(dbClient : db.Client, userId : number, orgId : number|null, status : DeveloperStatus = DeveloperStatus.ORG_ADMIN) {
if (orgId !== null) {
await model.update(dbClient, userId, {
developer_org: orgId,
developer_status: status,
});
} else {
await model.update(dbClient, userId, {
developer_org: null,
developer_status: 0,
});
}
}
export function requireLogIn(req : Request, res : Response, next : NextFunction) {
if (isAuthenticated(req)) {
next();
return;
}
if (req.method === 'GET' || req.method === 'HEAD') {
if (!req.originalUrl.startsWith('/me/api') &&
!req.originalUrl.startsWith('/me/recording') &&
!req.originalUrl.startsWith('/me/ws'))
req.session.redirect_to = req.originalUrl;
if (req.user)
res.redirect('/user/2fa/login');
else
res.redirect('/user/login');
} else {
res.status(401).render('login_required',
{ page_title: req._("Thingpedia - Error") });
}
}
export function requireRole(role : Role) {
if (role === undefined)
throw new TypeError(`invalid requireRole call`);
return function(req : Request, res : Response, next : NextFunction) {
if ((req.user!.roles & role) !== role) {
res.status(403).render('error', {
page_title: req._("Thingpedia - Error"),
message: req._("You do not have permission to perform this operation.")
});
} else {
next();
}
};
}
export function requireAnyRole(roleset : number) {
return function(req : Request, res : Response, next : NextFunction) {
if ((req.user!.roles & roleset) === 0) {
res.status(403).render('error', {
page_title: req._("Thingpedia - Error"),
message: req._("You do not have permission to perform this operation.")
});
} else {
next();
}
};
}
export function requireDeveloper(required ?: DeveloperStatus) {
if (required === undefined)
required = 1; // DEVELOPER
return function(req : Request, res : Response, next : NextFunction) {
if (req.user!.developer_org === null || req.user!.developer_status < required!) {
res.status(403).render('error', {
page_title: req._("Thingpedia - Error"),
message: req._("You do not have permission to perform this operation.")
});
} else {
next();
}
};
}
export function requireScope(scope : OAuthScopes) {
assert(OAuthScopes.has(scope));
return function(req : Request, res : Response, next : NextFunction) {
if (!req.authInfo) {
next();
return;
}
if (req.authInfo.scope.indexOf(scope) < 0) {
res.status(403).json({error:'invalid scope'});
return;
}
next();
};
}
export function getAnonymousUser(locale : string) {
if (!I18n.get(locale, false))
throw new NotFoundError();
return db.withClient((dbClient) => {
const lang = I18n.localeToLanguage(locale);
return model.getByName(dbClient, 'anonymous' +
(lang === 'en' ? '': '-' + lang));
}).then(([user]) => user);
}
export function anonymousLogin(req : Request, res : Response, next : NextFunction) {
if (req.user) {
next();
return;
}
if (!Config.ENABLE_ANONYMOUS_USER) {
res.status(401).render('login_required',
{ page_title: req._("Thingpedia - Error") });
return;
}
getAnonymousUser(req.locale).then((user) => {
if (!user)
throw new InternalError('E_INVALID_CONFIG', 'Invalid configuration (missing anonymous user)');
req.login(user, next);
}).catch((e) => next(e));
} | the_stack |
import * as vscode from 'vscode';
import * as fs from 'fs';
import * as querystring from 'querystring';
import * as path from 'path';
import * as child_process from 'child_process';
import {parseMDtoHTML} from './markdownUtils';
import {parseADtoHTML} from './asciidocUtils';
import * as scaffoldUtils from './scaffoldUtils';
import { TreeNode } from './nodeProvider';
import { handleExtFilePath, handleProjectFilePath } from './commandHandler';
import * as download from 'download';
import { didactManager } from './didactManager';
import { parse } from 'node-html-parser';
import { addNewTutorialWithNameAndCategoryForDidactUri, delay, getCachedOutputChannel, getCurrentFileSelectionPath, getDefaultUrl, getInsertLFForCLILinkSetting, getLinkTextForCLILinkSetting, getValue, getWorkspacePath, registerTutorialWithCategory, rememberOutputChannel } from './utils';
const tmp = require('tmp');
const fetch = require('node-fetch');
const url = require('url-parse');
// command IDs
export const SCAFFOLD_PROJECT_COMMAND = 'vscode.didact.scaffoldProject';
export const OPEN_TUTORIAL_COMMAND = 'vscode.didact.openTutorial';
export const START_DIDACT_COMMAND = 'vscode.didact.startDidact';
export const START_TERMINAL_COMMAND = 'vscode.didact.startTerminalWithName';
export const SEND_TERMINAL_SOME_TEXT_COMMAND = 'vscode.didact.sendNamedTerminalAString';
export const SEND_TERMINAL_SOME_TEXT_COMMAND_NO_LF = 'vscode.didact.sendNamedTerminalAStringNoLF';
export const REQUIREMENT_CHECK_COMMAND = 'vscode.didact.requirementCheck';
export const EXTENSION_REQUIREMENT_CHECK_COMMAND = 'vscode.didact.extensionRequirementCheck';
export const WORKSPACE_FOLDER_EXISTS_CHECK_COMMAND = 'vscode.didact.workspaceFolderExistsCheck';
export const CREATE_WORKSPACE_FOLDER_COMMAND = 'vscode.didact.createWorkspaceFolder';
export const RELOAD_DIDACT_COMMAND = 'vscode.didact.reload';
export const VALIDATE_ALL_REQS_COMMAND = 'vscode.didact.validateAllRequirements';
export const GATHER_ALL_REQS_COMMAND = 'vscode.didact.gatherAllRequirements';
export const GATHER_ALL_COMMANDS = 'vscode.didact.gatherAllCommands';
export const VIEW_OPEN_TUTORIAL_MENU = 'vscode.didact.view.tutorial.open';
export const REGISTER_TUTORIAL = 'vscode.didact.register'; // name, uri, category
export const REFRESH_DIDACT_VIEW = 'vscode.didact.view.refresh';
export const SEND_TERMINAL_KEY_SEQUENCE = 'vscode.didact.sendNamedTerminalCtrlC';
export const CLOSE_TERMINAL = 'vscode.didact.closeNamedTerminal';
export const CLI_SUCCESS_COMMAND = 'vscode.didact.cliCommandSuccessful';
export const OPEN_NAMED_OUTPUTCHANNEL_COMMAND = 'vscode.didact.openNamedOutputChannel';
export const SEND_TO_NAMED_OUTPUTCHANNEL_COMMAND = 'vscode.didact.sendTextToNamedOutputChannel';
export const VALIDATE_COMMAND_IDS = 'vscode.didact.verifyCommands';
export const TEXT_TO_CLIPBOARD_COMMAND = 'vscode.didact.copyToClipboardCommand';
export const COPY_FILE_URL_TO_WORKSPACE_COMMAND = 'vscode.didact.copyFileURLtoWorkspaceCommand';
export const DIDACT_OUTPUT_CHANNEL = 'Didact Activity';
export const FILE_TO_CLIPBOARD_COMMAND = 'vscode.didact.copyFileTextToClipboardCommand';
export const PASTE_TO_ACTIVE_EDITOR_COMMAND = 'vscode.didact.copyClipboardToActiveTextEditor';
export const PASTE_TO_EDITOR_FOR_FILE_COMMAND = 'vscode.didact.copyClipboardToEditorForFile';
export const PASTE_TO_NEW_FILE_COMMAND = 'vscode.didact.copyClipboardToNewFile';
export const REFRESH_DIDACT = 'vscode.didact.refresh';
export const CLEAR_DIDACT_REGISTRY = 'vscode.didact.registry.clear';
export const ADD_TUTORIAL_TO_REGISTRY = 'vscode.didact.registry.addJson';
export const ADD_TUTORIAL_URI_TO_REGISTRY = 'vscode.didact.registry.addUri';
export const REMOVE_TUTORIAL_BY_NAME_AND_CATEGORY_FROM_REGISTRY = 'vscode.didact.view.tutorial.remove';
export const OPEN_TUTORIAL_HEADING_FROM_VIEW = "vscode.didact.view.tutorial.heading.open";
export const PROCESS_VSCODE_LINK = "vscode.didact.processVSCodeLink";
export const CREATE_SEND_TO_TERMINAL_LINK_FROM_SELECTED_TEXT = "vscode.didact.copyTextToCLI";
export const OPEN_URI_WITH_LINE_AND_OR_COLUMN = "vscode.didact.openUriWithLineAndOrColumn";
export const EXTENSION_ID = "redhat.vscode-didact";
const commandPrefix = 'didact://?commandId';
// note that this MUST be also updated in the main.js file
const requirementCommandLinks = [
'didact://?commandId=vscode.didact.extensionRequirementCheck',
'didact://?commandId=vscode.didact.requirementCheck',
'didact://?commandId=vscode.didact.workspaceFolderExistsCheck',
'didact://?commandId=vscode.didact.cliCommandSuccessful'
];
type StringVoidUndefinedTypeAlias = string | void | undefined;
// stashed extension context
let extContext : vscode.ExtensionContext;
export let didactOutputChannel: vscode.OutputChannel;
// stashed Didact URI
let _didactFileUri : vscode.Uri | undefined = undefined;
// exposed for testing purposes
export function getContext() : vscode.ExtensionContext {
return extContext;
}
export function initialize(inContext: vscode.ExtensionContext): void {
extContext = inContext;
// set up the didact output channel
didactOutputChannel = vscode.window.createOutputChannel(DIDACT_OUTPUT_CHANNEL);
}
// use the json to model the folder/file structure to be created in the vscode workspace
export async function scaffoldProjectFromJson(jsonpath:vscode.Uri): Promise<void> {
sendTextToOutputChannel(`Scaffolding project from json: ${jsonpath}`);
if (getWorkspacePath()) {
let testJson : any;
if (jsonpath) {
const jsoncontent = fs.readFileSync(jsonpath.fsPath, 'utf8');
testJson = JSON.parse(jsoncontent);
} else {
testJson = scaffoldUtils.createSampleProject();
}
await scaffoldUtils.createFoldersFromJSON(testJson, jsonpath)
.catch( (error) => {
throw new Error(`Error found while scaffolding didact project: ${error}`);
});
} else {
throw new Error('No workspace folder. Workspace must have at least one folder before Didact scaffolding can begin.');
}
}
// quick and dirty workaround for an empty workspace - creates a folder in the user's temporary store
export async function createTemporaryFolderAsWorkspaceRoot(requirement: string | undefined): Promise<void> {
sendTextToOutputChannel(`Creating temporary folder as workspace root`);
// if the workspace is empty, we will create a temporary one for the user
const tmpobj = tmp.dirSync();
const rootUri : vscode.Uri = vscode.Uri.file(`${tmpobj.name}`);
vscode.workspace.updateWorkspaceFolders(0,undefined, {uri: rootUri});
sendTextToOutputChannel(`-- created ${tmpobj.name}`);
if (requirement) {
if (rootUri) {
postRequirementsResponseMessage(requirement, true);
} else {
postRequirementsResponseMessage(requirement, false);
}
}
}
// utility command to start a named terminal so we have a handle to it
export async function startTerminal(...rest: any[]): Promise<void>{ //name:string, path: vscode.Uri) {
let name : string | undefined = undefined;
let uri : vscode.Uri | undefined = undefined;
if (rest) {
try {
for(const arg of rest) {
if (typeof arg === 'string' ) {
name = arg;
} else if (typeof arg === 'object' ) {
uri = arg as vscode.Uri;
}
}
} catch (error) {
throw new Error(error);
}
}
if (name) {
const oldTerm = findTerminal(name);
if (oldTerm) {
oldTerm.show();
return;
}
}
let terminal : vscode.Terminal | undefined = undefined;
if (name && uri) {
sendTextToOutputChannel(`Starting terminal ${name} with uri ${uri}`);
terminal = vscode.window.createTerminal({
name: `${name}`,
cwd: `${uri.fsPath}`
});
} else if (name) {
terminal = vscode.window.createTerminal({
name: `${name}`
});
} else {
terminal = vscode.window.createTerminal();
}
if (terminal) {
terminal.show();
}
}
export async function showAndSendText(terminal: vscode.Terminal, text:string, sendLF = true): Promise<void> {
if (terminal) {
terminal.show();
terminal.sendText(text, sendLF);
}
}
export async function showAndSendCtrlC(terminal: vscode.Terminal): Promise<void>{
if (terminal) {
terminal.show();
await vscode.commands.executeCommand("workbench.action.terminal.sendSequence", { text : "\x03" });
}
}
export async function killTerminal(terminal: vscode.Terminal): Promise<void>{
if (terminal) {
terminal.show();
await vscode.commands.executeCommand("workbench.action.terminal.kill");
}
}
export function findTerminal(name: string) : vscode.Terminal | undefined {
try {
for(const localTerm of vscode.window.terminals){
if(localTerm.name === name){
return localTerm;
}
}
} catch {
return undefined;
}
return undefined;
}
// send a message to a named terminal
export async function sendTerminalText(name:string, text:string, sendLF = true): Promise<void> {
let terminal : vscode.Terminal | undefined = findTerminal(name);
if (!terminal) {
terminal = vscode.window.createTerminal(name);
}
if (terminal) {
showAndSendText(terminal, text, sendLF);
}
const msg = `Sent terminal ${name} the text ${text}`;
if (sendLF) {
sendTextToOutputChannel(msg + ` with LF`);
} else {
sendTextToOutputChannel(msg);
}
}
export async function sendTerminalTextNoLF(name:string, text:string): Promise<void> {
return sendTerminalText(name, text, false);
}
export async function sendTerminalCtrlC(name:string): Promise<void> {
const terminal : vscode.Terminal | undefined = findTerminal(name);
if (!terminal) {
throw new Error(`No terminal found with name ${name} to send a Ctrl+C`);
} else {
showAndSendCtrlC(terminal);
sendTextToOutputChannel(`Sent terminal ${name} a Ctrl+C`);
}
}
export async function closeTerminal(name:string): Promise<void>{
const terminal : vscode.Terminal | undefined = findTerminal(name);
if (!terminal) {
throw new Error(`No terminal found with name ${name} to close`);
} else {
await killTerminal(terminal).then( () => {
if (terminal) {
terminal.dispose();
}
});
sendTextToOutputChannel(`Closed terminal ${name}`);
}
}
// reset the didact window to use the default set in the settings
export async function openDidactWithDefault(): Promise<void>{
sendTextToOutputChannel(`Starting Didact window with default`);
didactManager.setContext(extContext);
const configuredPath : string | undefined = getDefaultUrl();
if (configuredPath) {
try {
const vsUri = vscode.Uri.parse(configuredPath);
if (vsUri) {
_didactFileUri = vsUri;
}
} catch (error) {
console.log(error);
}
}
if (_didactFileUri) {
await didactManager.create(_didactFileUri);
} else {
const errStr = `No default didact URL provided when opening default tutorial. Check setting to ensure path is provided.`;
sendTextToOutputChannel(errStr);
vscode.window.showErrorMessage(errStr);
}
}
function processExtensionFilePath(value: string | undefined) : vscode.Uri | undefined {
if (value) {
const extUri = handleExtFilePath(value);
if (extUri) {
return extUri;
} else if (extContext.extensionPath === undefined) {
return undefined;
}
return vscode.Uri.file(
path.resolve(extContext.extensionPath, value)
);
}
return undefined;
}
export function handleVSCodeDidactUriParsingForPath(uri:vscode.Uri) : vscode.Uri | undefined {
let out : vscode.Uri | undefined = undefined;
// handle extension/extFilePath, workspace, https, and http
if (uri) {
const query = querystring.parse(uri.query);
if (query.extension) {
const value = getValue(query.extension);
out = processExtensionFilePath(value);
} else if (query.extFilePath) {
const value = getValue(query.extFilePath);
out = processExtensionFilePath(value);
} else if (query.workspace) {
const value = getValue(query.workspace);
if (value) {
if (vscode.workspace.workspaceFolders) {
const workspace = vscode.workspace.workspaceFolders[0];
const rootPath = workspace.uri.fsPath;
out = vscode.Uri.file(path.resolve(rootPath, value));
}
}
} else if (query.https) {
const value = getValue(query.https);
if (value) {
out = vscode.Uri.parse(`https://${value}`);
}
} else if (query.http) {
const value = getValue(query.http);
if (value) {
out = vscode.Uri.parse(`http://${value}`);
}
} else if (uri.fsPath) {
out = uri;
} else {
out = vscode.Uri.parse(uri.toString());
}
}
return out;
}
export async function revealOrStartDidactByURI(uri : vscode.Uri, viewColumn? : string) : Promise <void> {
if (!uri) {
uri = await getCurrentFileSelectionPath();
}
if (uri) {
const parentPanel = didactManager.getByUri(uri);
if (parentPanel) {
parentPanel._panel?.reveal();
await parentPanel.refreshPanel();
} else {
await startDidact(uri, viewColumn);
}
}
}
// open the didact window with the didact file passed in via Uri
export async function startDidact(uri: vscode.Uri, viewColumn?: string): Promise<void>{
if (!uri) {
uri = await getCurrentFileSelectionPath();
}
// if column passed, convert to viewcolumn enum
let actualColumn : vscode.ViewColumn = vscode.ViewColumn.Active;
if (viewColumn) {
actualColumn = (<any>vscode.ViewColumn)[viewColumn];
}
sendTextToOutputChannel(`Starting Didact window with ${uri}`);
const out : vscode.Uri | undefined = handleVSCodeDidactUriParsingForPath(uri);
if (!out) {
const errmsg = `--Error: No Didact file found when parsing URI ${uri}`;
sendTextToOutputChannel(errmsg);
vscode.window.showErrorMessage(errmsg);
return;
} else {
_didactFileUri = out;
}
console.log(`--Retrieved file URI ${_didactFileUri}`);
sendTextToOutputChannel(`--Retrieved file URI ${_didactFileUri}`);
didactManager.setContext(extContext);
await didactManager.create(_didactFileUri, actualColumn);
}
// very basic requirements testing -- check to see if the results of a command executed at CLI returns a known result
// example: testCommand = mvn --version, testResult = 'Apache Maven'
export async function requirementCheck(requirement: string, testCommand: string, testResult: string) : Promise<boolean> {
try {
sendTextToOutputChannel(`Validating requirement ${testCommand} exists in VS Code workbench`);
const result = child_process.execSync(testCommand);
if (result.includes(testResult)) {
sendTextToOutputChannel(`--Requirement ${testCommand} exists in VS Code workbench: true`);
postRequirementsResponseMessage(requirement, true);
return true;
} else {
sendTextToOutputChannel(`--Requirement ${testCommand} exists in VS Code workbench: false`);
postRequirementsResponseMessage(requirement, false);
return false;
}
} catch (error) {
sendTextToOutputChannel(`--Requirement ${testCommand} exists in VS Code workbench: false`);
postRequirementsResponseMessage(requirement, false);
}
return false;
}
// even more basic CLI check - tests to see if CLI command returns zero meaning it executed successfully
export async function cliExecutionCheck(requirement: string, testCommand: string) : Promise<boolean> {
try {
sendTextToOutputChannel(`Validating requirement ${testCommand} exists in VS Code workbench`);
const options = {
timeout: 15000 // adding timeout for network calls
};
const result = child_process.execSync(testCommand, options);
if (result) {
sendTextToOutputChannel(`--CLI command ${testCommand} returned code 0 and result ${result.toString()}`);
postRequirementsResponseMessage(requirement, true);
return true;
}
} catch (error) {
sendTextToOutputChannel(`--CLI command ${testCommand} failed with error ${error.status}`);
postRequirementsResponseMessage(requirement, false);
}
return false;
}
// very basic requirements testing -- check to see if the extension Id is installed in the user workspace
export async function extensionCheck(requirement: string, extensionId: string) : Promise<boolean> {
sendTextToOutputChannel(`Validating extension ${extensionId} exists in VS Code workbench`);
const testExt = vscode.extensions.getExtension(extensionId);
if (testExt) {
sendTextToOutputChannel(`--Extension ${extensionId} exists in VS Code workbench: true`);
postRequirementsResponseMessage(requirement, true);
return true;
} else {
sendTextToOutputChannel(`--Extension ${extensionId} exists in VS Code workbench: false`);
postRequirementsResponseMessage(requirement, false);
return false;
}
}
// very basic test -- check to see if the workspace has at least one root folder
export async function validWorkspaceCheck(requirement: string) : Promise<boolean> {
sendTextToOutputChannel(`Validating workspace has at least one root folder`);
const wsPath = getWorkspacePath();
if (wsPath) {
sendTextToOutputChannel(`--Workspace has at least one root folder: true`);
postRequirementsResponseMessage(requirement, true);
return true;
} else {
sendTextToOutputChannel(`--Workspace has at least one root folder: false`);
postRequirementsResponseMessage(requirement, false);
return false;
}
}
// dispose of and reload the didact window with the latest Uri
export async function reloadDidact(): Promise<void>{
sendTextToOutputChannel(`Reloading Didact window`);
didactManager.active()?.dispose();
await vscode.commands.executeCommand(START_DIDACT_COMMAND, _didactFileUri);
}
export async function refreshDidactWindow(): Promise<void>{
sendTextToOutputChannel(`Refreshing Didact window`);
await didactManager.active()?.refreshPanel();
}
// send a message back to the webview - used for requirements testing mostly
function postRequirementsResponseMessage(requirement: string, booleanResponse: boolean): void {
if (requirement) {
didactManager.active()?.postRequirementsResponseMessage(requirement, booleanResponse);
}
}
function showFileUnavailable(error : any): void {
if (_didactFileUri) {
vscode.window.showErrorMessage(`File at ${_didactFileUri.toString()} is unavailable`);
}
console.log(error);
}
// retrieve the didact content to render as HTML
export async function getWebviewContent() : Promise<string|void> {
if (!_didactFileUri) {
const configuredUri : string | undefined = getDefaultUrl();
if (configuredUri) {
_didactFileUri = vscode.Uri.parse(configuredUri);
}
}
if (_didactFileUri) {
if (_didactFileUri.scheme === 'file') {
return loadFileWithRetry(_didactFileUri);
} else if (_didactFileUri.scheme === 'http' || _didactFileUri.scheme === 'https'){
return loadFileFromHTTPWithRetry(_didactFileUri);
}
}
return undefined;
}
async function loadFileWithRetry ( uri:vscode.Uri ) : Promise<StringVoidUndefinedTypeAlias> {
return getDataFromFile(uri).catch( async () => {
await delay(3000);
return getDataFromFile(uri).catch( async (error) => {
showFileUnavailable(error);
});
});
}
async function loadFileFromHTTPWithRetry ( uri:vscode.Uri ) : Promise<StringVoidUndefinedTypeAlias> {
const urlToFetch = uri.toString();
return getDataFromUrl(urlToFetch).catch( async () => {
await delay(3000);
return getDataFromUrl(urlToFetch).catch( async (error) => {
showFileUnavailable(error);
});
});
}
export function isAsciiDoc(inUri? : string) : boolean {
let uriToTest : vscode.Uri | undefined;
if (inUri) {
uriToTest = vscode.Uri.parse(inUri);
} else if (!_didactFileUri) {
const strToTest : string | undefined = vscode.workspace.getConfiguration().get('didact.defaultUrl');
if (strToTest) {
uriToTest = vscode.Uri.parse(strToTest);
}
} else {
uriToTest = _didactFileUri;
}
if (uriToTest && uriToTest.fsPath) {
const extname = path.extname(uriToTest.fsPath);
if (extname.localeCompare('.adoc') === 0) {
return true;
}
}
return false;
}
// retrieve didact text from a file - exported for test
export async function getDataFromFile(uri:vscode.Uri) : Promise<string|undefined> {
try {
const content = fs.readFileSync(uri.fsPath, 'utf8');
const extname = path.extname(uri.fsPath);
if (extname.localeCompare('.adoc') === 0) {
let baseDir : string | undefined = undefined;
if (uri.scheme.trim().startsWith('file')) {
baseDir = path.dirname(uri.fsPath);
}
return parseADtoHTML(content, baseDir);
} else if (extname.localeCompare('.md') === 0) {
return parseMDtoHTML(content);
} else {
throw new Error(`Unknown file type encountered: ${extname}`);
}
} catch (error) {
throw new Error(error);
}
}
// retrieve didact text from a url
export async function getDataFromUrl(inurl:string) : Promise<string> {
try {
const response = await fetch(inurl);
const content = await response.text();
const tempVSUri = vscode.Uri.parse(inurl);
const extname = path.extname(tempVSUri.fsPath);
if (extname.localeCompare('.adoc') === 0) {
return parseADtoHTML(content);
} else if (extname.localeCompare('.md') === 0) {
return parseMDtoHTML(content);
} else {
throw new Error(`Unknown file type encountered: ${extname}`);
}
} catch (error) {
throw new Error(error);
}
}
export function validateAllRequirements(): void {
sendTextToOutputChannel(`Validating all requirements specified in Didact tutorial`);
didactManager.active()?.postTestAllRequirementsMessage();
}
export function collectElements(tagname: string, html? : string | undefined) : any[] {
const elements: any[] = [];
if (!html) {
html = didactManager.active()?.getCurrentHTML();
}
if (html) {
const document = parse(html);
const links = document.querySelectorAll(tagname);
for (let element of links.values()) {
elements.push(element);
}
}
return elements;
}
export function gatherAllRequirementsLinks() : any[] {
const requirements = [];
if (didactManager.active()?.getCurrentHTML()) {
const links = collectElements("a", didactManager.active()?.getCurrentHTML());
for (let element of links.values()) {
if (element.getAttribute('href')) {
const href = element.getAttribute('href');
for(const check of requirementCommandLinks) {
if (href.startsWith(check)) {
requirements.push(href);
break;
}
}
}
}
}
return requirements;
}
export function gatherAllCommandsLinks(): any[] {
const commandLinks = [];
if (didactManager.active()?.getCurrentHTML()) {
const links = collectElements("a", didactManager.active()?.getCurrentHTML());
for (let element of links.values()) {
if (element.getAttribute('href')) {
const href = element.getAttribute('href');
if (href.startsWith(commandPrefix)) {
commandLinks.push(href);
}
}
}
}
return commandLinks;
}
export async function openTutorialFromView(node: TreeNode) : Promise<void> {
if (node && node.uri) {
sendTextToOutputChannel(`Opening tutorial from Didact view (${node.uri})`);
const vsUri = getActualUri(node.uri);
if (vsUri) {
await startDidact(vsUri);
}
}
}
export async function registerTutorial(name : string, sourceUri : string, category : string) : Promise<void> {
sendTextToOutputChannel(`Registering Didact tutorial with name (${name}), category (${category}, and sourceUri (${sourceUri})`);
await registerTutorialWithCategory(name, sourceUri, category);
}
export async function sendTextToOutputChannel(msg: string, channel?: vscode.OutputChannel) : Promise<void> {
// set up the didact output channel if it's not set up
if (!didactOutputChannel) {
didactOutputChannel = vscode.window.createOutputChannel(DIDACT_OUTPUT_CHANNEL);
}
if (!channel && didactOutputChannel) {
channel = didactOutputChannel;
}
if (channel) {
if (!msg.endsWith('\n')) {
msg = `${msg} \n`;
}
channel.append(msg);
} else {
console.log('[' + msg + ']');
}
}
async function openDidactOutputChannel() : Promise<void> {
if (!didactOutputChannel) {
didactOutputChannel = vscode.window.createOutputChannel(DIDACT_OUTPUT_CHANNEL);
}
didactOutputChannel.show();
}
// exported for testing
export async function validateDidactCommands(commands : any[], sendToConsole = false) : Promise<boolean> {
let allOk = true;
if (commands && commands.length > 0) {
sendTextToOutputChannel(`Starting validation...`);
const vsCommands : string[] = await vscode.commands.getCommands(true);
for(const command of commands) {
// validate all commands we found
const parsedUrl = new url(command, true);
const query = parsedUrl.query;
if (query.commandId) {
const commandId = getValue(query.commandId);
if (commandId) {
const foundCommand = validateCommand(commandId, vsCommands);
if (!foundCommand) {
// unexpected result - let the user know
const msg = `--Missing Command ID ${commandId}.`;
if (sendToConsole) {
console.log(msg);
} else {
await sendTextToOutputChannel(msg);
}
allOk = false;
}
}
}
}
}
return allOk;
}
// exported for testing
export function validateCommand(commandId:string, vsCommands:string[]) : boolean {
if (commandId) {
const foundCommand : string | undefined = vsCommands.find( function (command) {
return command === commandId;
});
if (foundCommand) {
return true;
}
}
return false;
}
export async function validateCommandIDsInSelectedFile(didactUri: vscode.Uri) : Promise<void> {
if (didactUri) {
await vscode.commands.executeCommand(START_DIDACT_COMMAND, didactUri);
}
const commands: any[] = gatherAllCommandsLinks();
let allOk = false;
await openDidactOutputChannel();
if (commands && commands.length > 0) {
allOk = await validateDidactCommands(commands);
if (allOk) {
sendTextToOutputChannel(`--Command IDs: OK`);
sendTextToOutputChannel(`Validation Result: SUCCESS (${commands.length} Commands Validated)`);
} else {
sendTextToOutputChannel(`Validation Result: FAILURE`);
sendTextToOutputChannel(`-- Note that command IDs not found may be due to a missing extension or simply an invalid ID.`);
}
} else {
sendTextToOutputChannel(`Validation Result: FAILURE - No command IDs found in current Didact file`);
}
}
export async function placeTextOnClipboard(clipText: string): Promise<void>{
await vscode.env.clipboard.writeText(clipText).then( () => {
sendTextToOutputChannel(`Text sent to clipboard: "${clipText}"`);
});
}
// exported for testing
export async function downloadAndUnzipFile(httpFileUrl : string, installFolder : string, dlFilename? : string, extractFlag = false, ignoreOverwrite = false): Promise<any> {
let filename = '';
if (!dlFilename) {
const fileUrl = new url(httpFileUrl);
const pathname = fileUrl.pathname;
if (pathname) {
filename = pathname.substring(pathname.lastIndexOf('/')+1);
}
} else {
filename = dlFilename;
}
const downloadFile : string = path.resolve(installFolder, filename);
let overwriteFile = false;
if (extractFlag && !ignoreOverwrite) {
const answer = await vscode.window.showQuickPick([
'Yes',
'No'
], {
canPickMany: false,
placeHolder: `The archive ${filename} may overwrite folders and files in the workspace. Are you sure?`
});
if (answer === 'No') {
sendTextToOutputChannel(`Copy and unzip of file ${filename} was canceled.`);
return null;
}
if (answer === 'Yes') {
overwriteFile = true;
}
} else if (!extractFlag && !ignoreOverwrite) {
try {
const pathUri = vscode.Uri.file(downloadFile);
try {
const contents = await vscode.workspace.fs.readFile(pathUri);
if (contents) {
const answer = await vscode.window.showQuickPick([
'Yes',
'No'
], {
canPickMany: false,
placeHolder: `The file ${filename} already exists. Do you want to overwrite it?`
});
if (answer === 'No') {
sendTextToOutputChannel(`Copy of file ${filename} was canceled.`);
return null;
}
if (answer === 'Yes') {
overwriteFile = true;
}
} else {
overwriteFile = true; // file doesn't exist
}
} catch (error) {
// ignore error, it means the file does not exist
overwriteFile = true;
}
} catch (error) {
// ignore error, it means the file does not exist
overwriteFile = true;
}
}
if (overwriteFile || ignoreOverwrite) {
try {
const downloadResult: boolean = await downloadAndExtract(httpFileUrl, installFolder, filename, extractFlag);
console.log(`Downloaded ${downloadFile} : ${downloadResult}`);
sendTextToOutputChannel(`Downloaded ${downloadFile}`);
return downloadFile;
} catch ( error ) {
console.log(error);
sendTextToOutputChannel(`Failed to download file: ${error}`);
return error;
}
}
}
export async function copyFileFromURLtoLocalURI(httpurl : any, fileName? : string, fileuri? : string, unzip = false): Promise<void>{
let projectFilePath = '';
if (fileuri && fileuri.length > 0) {
projectFilePath = fileuri.trim();
}
let dlFileName = '';
if (fileName) {
dlFileName = fileName;
}
const filepathUri = handleProjectFilePath(projectFilePath);
if (filepathUri) {
await downloadAndUnzipFile(httpurl, filepathUri.fsPath, dlFileName, unzip);
}
}
async function downloadAndExtract(link : string, installFolder : string, dlFilename? : string, extractFlag?: boolean) : Promise<boolean> {
const myStatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
let downloadSettings;
if (dlFilename) {
downloadSettings = {
filename: `${dlFilename}`,
extract: extractFlag
};
} else {
downloadSettings = {
extract: extractFlag
};
}
sendTextToOutputChannel('Downloading from: ' + link);
await download(link, installFolder, downloadSettings)
.on('response', (response: { headers: { [x: string]: any; }; }) => {
sendTextToOutputChannel(`Bytes to transfer: ${response.headers['content-length']}`);
}).on('downloadProgress', (progress: { total: number; transferred: number; }) => {
const incr = progress.total > 0 ? Math.floor(progress.transferred / progress.total * 100) : 0;
const percent = Math.round(incr);
const message = `Download progress: ${progress.transferred} / ${progress.total} (${percent}%)`;
const tooltip = `Download progress for ${installFolder}`;
updateStatusBarItem(myStatusBarItem, message, tooltip);
}).then(async () => {
myStatusBarItem.dispose();
return true;
}).catch((error:any) => {
console.log(error);
});
myStatusBarItem.dispose();
return false;
}
function updateStatusBarItem(sbItem : vscode.StatusBarItem, text: string, tooltip : string): void {
if (text) {
sbItem.text = text;
sbItem.tooltip = tooltip;
sbItem.show();
} else {
sbItem.hide();
}
}
export function openNamedOutputChannel(name?: string | undefined): vscode.OutputChannel | undefined {
let channel: vscode.OutputChannel | undefined;
if (!name || name === DIDACT_OUTPUT_CHANNEL) {
if (!didactOutputChannel) {
didactOutputChannel = vscode.window.createOutputChannel(DIDACT_OUTPUT_CHANNEL);
}
channel = didactOutputChannel;
} else {
channel = getCachedOutputChannel(name);
if (!channel) {
channel = vscode.window.createOutputChannel(name);
rememberOutputChannel(channel);
}
}
if (channel) {
channel.show();
}
return channel;
}
export function sendTextToNamedOutputChannel(message: string, channelName?: string): void {
if (!message){
throw new Error('There was no text given for the output channel.');
}
let channel: vscode.OutputChannel | undefined = didactOutputChannel;
if (channelName) {
channel = openNamedOutputChannel(channelName);
}
sendTextToOutputChannel(message, channel);
if (!channelName || channelName === DIDACT_OUTPUT_CHANNEL) {
didactOutputChannel.show();
}
}
function showErrorMessage(msg : string) : void {
sendTextToOutputChannel(msg);
vscode.window.showErrorMessage(msg);
}
export async function copyFileTextToClipboard(uri: vscode.Uri) : Promise<void> {
const testUri : vscode.Uri = uri;
const out : vscode.Uri | undefined = handleVSCodeDidactUriParsingForPath(testUri);
if (!out) {
const errmsg = `ERROR: No file found when parsing path ${uri}`;
showErrorMessage(errmsg);
throw new Error(errmsg);
} else {
let content : string | undefined = undefined;
if (out.scheme === 'file') {
try {
content = fs.readFileSync(out.fsPath, 'utf8');
} catch(error) {
showFileUnavailable(error);
}
} else if (out.scheme === 'http' || out.scheme === 'https'){
const urlToFetch = out.toString();
try {
const response = await fetch(urlToFetch);
content = await response.text();
} catch(error) {
showFileUnavailable(error);
}
} else {
const errmsg = `ERROR: Unsupported scheme/protocol when parsing path ${uri}`;
showErrorMessage(errmsg);
throw new Error(errmsg);
}
if (content) {
await placeTextOnClipboard(content);
}
}
}
export async function pasteClipboardToActiveEditorOrPreviouslyUsedOne() : Promise<void> {
let currentEditor : vscode.TextEditor | undefined = vscode.window.activeTextEditor;
if (!currentEditor) {
await vscode.commands.executeCommand('workbench.action.openPreviousRecentlyUsedEditor');
currentEditor = vscode.window.activeTextEditor;
}
if (currentEditor) {
const textFromClipboard = await vscode.env.clipboard.readText();
if (textFromClipboard) {
await currentEditor.insertSnippet(new vscode.SnippetString(textFromClipboard));
} else {
await vscode.window.showWarningMessage(`No text found on clipboard`);
}
} else {
await vscode.window.showWarningMessage(`No active text editor found to paste from clipboard`);
}
}
export async function findOpenEditorForFileURI(uri: vscode.Uri) : Promise<vscode.TextEditor | undefined> {
for (let editor of vscode.window.visibleTextEditors.values()) {
if (editor.document.uri === uri) {
return editor;
}
}
return undefined;
}
export async function pasteClipboardToEditorForFile(uri: vscode.Uri) : Promise<void> {
let editorForFile : vscode.TextEditor | undefined = await findOpenEditorForFileURI(uri);
if (!editorForFile) {
try {
await vscode.commands.executeCommand('vscode.open', uri, vscode.ViewColumn.Beside);
editorForFile = vscode.window.activeTextEditor;
} catch (error) {
await vscode.window.showWarningMessage(`No editor found for file ${uri.fsPath}. ${error}`);
console.log(error);
}
}
if (editorForFile) {
await pasteClipboardToActiveEditorOrPreviouslyUsedOne();
}
}
export async function pasteClipboardToNewTextFile() : Promise<void> {
await vscode.commands.executeCommand('workbench.action.files.newUntitledFile');
await pasteClipboardToActiveEditorOrPreviouslyUsedOne();
}
function getTimeElementsForMD(content : string) : any[] {
return collectElements("[time]", content);
}
function getTimeElementsForAdoc(content : string) : any[] {
return collectElements("div[class*='time=']", content);
}
function processTimeTotalForMD(content : string) : number {
let total = 0;
let elements : any[] = getTimeElementsForMD(content);
if (elements && elements.length > 0) {
elements.forEach(element => {
const timeAttr = element.getAttribute("time");
if (timeAttr) {
const timeValue = Number(timeAttr);
if (!Number.isNaN(timeValue) && timeValue > 0) {
total += timeValue;
}
}
});
}
return total;
}
function processTimeTotalForAdoc(content : string) : number {
let total = 0;
let elements : any[] = getTimeElementsForAdoc(content);
if (elements && elements.length > 0) {
elements.forEach(element => {
const classAttr : string = element.getAttribute("class");
const splitArray : string[] = classAttr.split(' ');
splitArray.forEach(chunk => {
if (chunk.startsWith('time=')) {
const splitTime = chunk.split('=')[1];
const timeValue = Number(splitTime);
if (!Number.isNaN(timeValue) && timeValue > 0) {
total += timeValue;
}
}
});
});
}
return total;
}
export async function computeTimeForDidactFileUri(uri: vscode.Uri) : Promise<number> {
if (uri) {
let content : StringVoidUndefinedTypeAlias = undefined;
if (uri.scheme === 'file') {
content = await loadFileWithRetry(uri);
} else if (uri.scheme === 'http' || uri.scheme === 'https'){
content = await loadFileFromHTTPWithRetry(uri);
}
const isAdoc = isAsciiDoc(uri.toString());
if (content && !isAdoc) {
return processTimeTotalForMD(content);
} else if (content && isAdoc) {
return processTimeTotalForAdoc(content);
}
}
return -1;
}
export async function getTimeElementsForDidactFileUri(uri: vscode.Uri) : Promise<any[] | undefined> {
if (uri) {
let content : string | undefined | void = undefined;
if (uri.scheme === 'file') {
content = await loadFileWithRetry(uri);
} else if (uri.scheme === 'http' || uri.scheme === 'https'){
content = await loadFileFromHTTPWithRetry(uri);
}
if (content && !isAsciiDoc(uri.toString())) {
return getTimeElementsForMD(content);
} else if (content && isAsciiDoc(uri.toString())) {
return getTimeElementsForAdoc(content);
}
}
return undefined;
}
export function getActualUri(uriString : string | undefined ) : vscode.Uri | undefined {
let actualUri : vscode.Uri | undefined;
if (uriString && !uriString?.startsWith(`http`)) {
actualUri = vscode.Uri.file(uriString);
} else if (uriString) {
actualUri = vscode.Uri.parse(uriString);
}
return actualUri;
}
function validateUriHasPath(textToValidate : string) : vscode.Uri | undefined {
try {
const uriToValidate = vscode.Uri.parse(textToValidate, true);
return handleVSCodeDidactUriParsingForPath(uriToValidate);
} catch (error) {
// just return
}
return undefined;
}
export async function handleVSCodeUri(uri:vscode.Uri | undefined) : Promise<void> {
let uriToProcess : vscode.Uri | undefined = uri;
if (!uriToProcess) {
// try clipboard
const textFromClipboard = await vscode.env.clipboard.readText();
const pathFromClipboard = validateUriHasPath(textFromClipboard);
if (textFromClipboard && pathFromClipboard) {
uriToProcess = vscode.Uri.parse(textFromClipboard);
}
if (!uriToProcess) {
await vscode.window.showInputBox({prompt: `Paste in the link from the web`}).then((textValueInput) => {
if (textValueInput && validateUriHasPath(textValueInput)) {
uriToProcess = vscode.Uri.parse(textValueInput);
} else {
const msg = `No parseable Didact file uri discovered in text provided '${textValueInput}'`;
sendTextToOutputChannel(msg);
vscode.window.showWarningMessage(msg);
}
});
}
}
if (uriToProcess) {
const query = querystring.parse(uriToProcess.query);
if (query.commandId && query.commandId === ADD_TUTORIAL_URI_TO_REGISTRY && query.https && query.name && query.category) {
const out : vscode.Uri | undefined = handleVSCodeDidactUriParsingForPath(uriToProcess);
if (out) {
const tutname : string | undefined = getValue(query.name);
const tutcat : string | undefined = getValue(query.category);
await addNewTutorialWithNameAndCategoryForDidactUri(out, tutname, tutcat);
} else {
const msg = `No parseable Didact file uri discovered in URI sent via vscode link '${uriToProcess.toString()}'`;
sendTextToOutputChannel(msg);
vscode.window.showWarningMessage(msg);
}
} else {
await vscode.commands.executeCommand(START_DIDACT_COMMAND, uriToProcess);
}
}
}
// for testing purposes
export function getDidactLinkForSelectedText(selectedText : string, isAdoc : boolean) : string {
const encodedText = encodeURI(selectedText);
const linkText = getLinkTextForCLILinkSetting();
const linkUseLF = getInsertLFForCLILinkSetting();
let commandToUse = 'vscode.didact.sendNamedTerminalAString';
if(!linkUseLF) {
commandToUse = 'vscode.didact.sendNamedTerminalAStringNoLF';
}
let templatedLink = ` ([${linkText}](didact://?commandId=${commandToUse}&text=newTerminal$$${encodedText}))`;
if (isAdoc) {
templatedLink = ` link:didact://?commandId=${commandToUse}&text=newTerminal$$${encodedText}[(${linkText})]`;
}
return templatedLink;
}
export async function convertSelectionToCLILinkAndInsertAfterSelection() : Promise<void> {
const editor = vscode.window.activeTextEditor;
if (editor) {
if (!editor.selections || editor.selections.length === 0) {
vscode.window.showInformationMessage("There is no selected text!");
return;
}
const selection = vscode.window.activeTextEditor?.selection;
const selectedText = vscode.window.activeTextEditor?.document.getText(selection);
if (selectedText && selectedText.trim().length > 0) {
const isAdoc = isAsciiDoc(editor.document.uri?.toString());
const templatedLink = getDidactLinkForSelectedText(selectedText, isAdoc);
await insertTextAtFirstWhitespacePastCurrentSelection(templatedLink);
}
}
}
async function insertTextAtFirstWhitespacePastCurrentSelection(replacementText : string) {
const editor = vscode.window.activeTextEditor;
if (editor) {
editor.edit(function (edit) {
const selection = editor.selections[0];
if (!selection.isEmpty) {
const pos = findOpeningCommentAfterPosition(selection.end);
if (pos) {
edit.insert(pos, replacementText);
}
}
});
}
}
function findOpeningCommentAfterPosition(pos: vscode.Position): vscode.Position | undefined {
const editor = vscode.window.activeTextEditor;
if (editor) {
const document = editor.document;
const text = editor.document.getText(new vscode.Range(pos.line, pos.character,
document.lineCount - 1, document.lineAt(document.lineCount - 1).text.length));
let offset = text.search(/(\s)/g);
if (offset === -1) {
return;
}
offset += document.offsetAt(pos);
return document.positionAt(offset);
}
return undefined;
}
export async function openFileAtLineAndColumn(uri: vscode.Uri, line? : number, column? : vscode.ViewColumn) : Promise<void> {
let editorForFile : vscode.TextEditor | undefined = await findOpenEditorForFileURI(uri);
if (!editorForFile) {
try {
let actualColumn : vscode.ViewColumn = vscode.ViewColumn.Active;
if (column) {
actualColumn = (<any>vscode.ViewColumn)[column];
}
const openedDoc = await vscode.workspace.openTextDocument(uri);
await vscode.window.showTextDocument(openedDoc, actualColumn);
editorForFile = vscode.window.activeTextEditor;
} catch (error) {
await vscode.window.showWarningMessage(`Issues encountered opening ${uri.fsPath} at column ${column}. ${error}`);
console.log(error);
return;
}
}
if (line && editorForFile) {
// account for the fact that the line index is zero-based but the line numbers in the editor start at 1
let trueLine = line-1;
if (trueLine < 0) {
trueLine = 0;
}
try {
await vscode.commands.executeCommand('revealLine', { lineNumber: trueLine, at: 'top' });
} catch (error) {
await vscode.window.showWarningMessage(`Issues encountered opening ${uri.fsPath} at column ${column} and line ${line}. ${error}`);
console.log(error);
}
}
} | the_stack |
import assert from 'assert';
import Node, { SourceRange } from './base';
import { FunctionDef } from './function_def';
import {
Invocation,
DeviceSelector,
InputParam,
} from './invocation';
import { BooleanExpression } from './boolean_expression';
import * as legacy from './legacy';
import {
Value,
VarRefValue
} from './values';
import {
iterateSlots2InputParams,
recursiveYieldArraySlots,
makeScope,
ArrayIndexSlot,
FieldSlot,
AbstractSlot,
OldSlot,
ScopeMap,
InvocationLike,
} from './slots';
import Type from '../type';
import NodeVisitor from './visitor';
import { TokenStream } from '../new-syntax/tokenstream';
import List from '../utils/list';
import {
SyntaxPriority,
addParenthesis
} from './syntax_priority';
import arrayEquals from './array_equals';
import { getScalarExpressionName } from '../utils';
import { UnserializableError } from "../utils/errors";
function primitiveArrayEquals<T>(a1 : T[]|null, a2 : T[]|null) : boolean {
if (a1 === a2)
return true;
if (!a1 || !a2)
return false;
if (a1.length !== a2.length)
return false;
for (let i = 0; i < a1.length; i++) {
if (a1[i] !== a2[i])
return false;
}
return true;
}
/**
* A stream, table, or action expression.
*/
export abstract class Expression extends Node {
schema : FunctionDef|null;
constructor(location : SourceRange|null,
schema : FunctionDef|null) {
super(location);
this.schema = schema;
}
// syntactic priority of this expression (to emit the right parenthesis)
abstract get priority() : SyntaxPriority;
abstract toLegacy(into_params ?: InputParam[], scope_params ?: string[]) : legacy.Stream|legacy.Table|legacy.Action;
abstract clone() : Expression;
abstract toSource() : TokenStream;
abstract equals(other : Expression) : boolean;
optimize() : Expression {
return this;
}
/**
* Iterate all slots (scalar value nodes) in this expression.
*
* @param scope - available names for parameter passing
* @deprecated Use {@link Ast.Table.iterateSlots2} instead.
*/
abstract iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]>;
/**
* Iterate all slots (scalar value nodes) in this expression.
*
* @param scope - available names for parameter passing
*/
abstract iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]>;
}
// move parameter-passing from regular parameters to join parameters
// when converting back to the legacy AST nodes
function moveInputParams(in_params : InputParam[], into_params : InputParam[], scope_params : string[]) : InputParam[] {
return in_params.filter((ip) => {
if ((ip.value instanceof VarRefValue && !scope_params.includes(ip.value.name) && !ip.value.name.startsWith('__const_')) || ip.value.isEvent) {
into_params.push(ip);
return false;
} else {
return true;
}
});
}
export class FunctionCallExpression extends Expression {
name : string;
in_params : InputParam[];
constructor(location : SourceRange|null,
name : string,
in_params : InputParam[],
schema : FunctionDef|null) {
super(location, schema);
assert(typeof name === 'string');
this.name = name;
assert(Array.isArray(in_params));
this.in_params = in_params;
}
get priority() : SyntaxPriority {
return SyntaxPriority.Primary;
}
toString() : string {
const in_params = this.in_params && this.in_params.length > 0 ? this.in_params.toString() : '';
return `FunctionCallExpression(${this.name}, ${in_params})`;
}
toSource() : TokenStream {
return List.concat(this.name, '(', List.join(this.in_params.map((ip) => ip.toSource()), ','), ')');
}
equals(other : Expression) : boolean {
return other instanceof FunctionCallExpression &&
this.name === other.name &&
arrayEquals(this.in_params, other.in_params);
}
toLegacy(into_params : InputParam[] = [], scope_params : string[] = []) : legacy.VarRefTable|legacy.VarRefStream|legacy.TimerStream|legacy.AtTimerStream|legacy.VarRefAction {
const schema = this.schema!;
if (schema.functionType === 'stream') {
if (this.name === 'timer') {
const base = this.in_params.find((ip) => ip.name === 'base')!;
const interval = this.in_params.find((ip) => ip.name === 'interval')!;
const frequency = this.in_params.find((ip) => ip.name === 'frequency');
return new legacy.TimerStream(this.location, base.value, interval.value,
frequency ? frequency.value : null, this.schema);
} else if (this.name === 'attimer') {
const time = this.in_params.find((ip) => ip.name === 'time')!;
const expiration_date = this.in_params.find((ip) => ip.name === 'expiration_date');
let timevalue : Value[];
if (time.value instanceof Value.Array)
timevalue = time.value.value;
else
timevalue = [time.value];
return new legacy.AtTimerStream(this.location, timevalue,
expiration_date ? expiration_date.value : null, this.schema);
} else {
return new legacy.VarRefStream(this.location, this.name, this.in_params, this.schema);
}
} else if (schema.functionType === 'query') {
return new legacy.VarRefTable(this.location, this.name, moveInputParams(this.in_params, into_params, scope_params), this.schema);
} else {
return new legacy.VarRefAction(this.location, this.name, moveInputParams(this.in_params, into_params, scope_params), this.schema);
}
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitFunctionCallExpression(this)) {
for (const in_param of this.in_params)
in_param.visit(visitor);
}
visitor.exit(this);
}
clone() : FunctionCallExpression {
return new FunctionCallExpression(
this.location,
this.name,
this.in_params.map((p) => p.clone()),
this.schema ? this.schema.clone() : null
);
}
*iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> {
for (const in_param of this.in_params)
yield [this.schema, in_param, this, scope];
return [this, makeScope(this)];
}
*iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> {
return yield* iterateSlots2InputParams(this, scope);
}
}
export class InvocationExpression extends Expression {
invocation : Invocation;
constructor(location : SourceRange|null,
invocation : Invocation,
schema : FunctionDef|null) {
super(location, schema);
assert(invocation instanceof Invocation);
this.invocation = invocation;
}
get priority() : SyntaxPriority {
return SyntaxPriority.Primary;
}
toSource() : TokenStream {
return this.invocation.toSource();
}
equals(other : Expression) : boolean {
return other instanceof InvocationExpression &&
this.invocation.selector.equals(other.invocation.selector) &&
this.invocation.channel === other.invocation.channel &&
arrayEquals(this.invocation.in_params, other.invocation.in_params);
}
toLegacy(into_params : InputParam[] = [], scope_params : string[] = []) : legacy.InvocationTable|legacy.InvocationAction {
const schema = this.schema!;
assert(schema.functionType !== 'stream');
if (schema.functionType === 'query') {
const clone = this.invocation.clone();
clone.in_params = moveInputParams(clone.in_params, into_params, scope_params);
return new legacy.InvocationTable(this.location, clone, this.schema);
} else {
return new legacy.InvocationAction(this.location, this.invocation, this.schema);
}
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitInvocationExpression(this))
this.invocation.visit(visitor);
visitor.exit(this);
}
clone() : InvocationExpression {
return new InvocationExpression(
this.location,
this.invocation.clone(),
this.schema ? this.schema.clone() : null
);
}
*iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> {
return yield* this.invocation.iterateSlots(scope);
}
*iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> {
return yield* this.invocation.iterateSlots2(scope);
}
}
export class FilterExpression extends Expression {
expression : Expression;
filter : BooleanExpression;
constructor(location : SourceRange|null,
expression : Expression,
filter : BooleanExpression,
schema : FunctionDef|null) {
super(location, schema);
assert(expression instanceof Expression);
this.expression = expression;
assert(filter instanceof BooleanExpression);
this.filter = filter;
}
get priority() : SyntaxPriority {
return SyntaxPriority.Filter;
}
toSource() : TokenStream {
return List.concat(addParenthesis(this.priority, this.expression.priority,
this.expression.toSource()), 'filter', this.filter.toSource());
}
equals(other : Expression) : boolean {
return other instanceof FilterExpression &&
this.expression.equals(other.expression) &&
this.filter.equals(other.filter);
}
toLegacy(into_params : InputParam[] = [], scope_params : string[] = []) : legacy.FilteredTable|legacy.EdgeFilterStream {
const schema = this.schema!;
assert(schema.functionType !== 'action');
if (schema.functionType === 'query')
return new legacy.FilteredTable(this.location, this.expression.toLegacy(into_params, scope_params) as legacy.Table, this.filter, this.schema);
else
return new legacy.EdgeFilterStream(this.location, this.expression.toLegacy(into_params, scope_params) as legacy.Stream, this.filter, this.schema);
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitFilterExpression(this)) {
this.expression.visit(visitor);
this.filter.visit(visitor);
}
visitor.exit(this);
}
clone() : FilterExpression {
return new FilterExpression(
this.location,
this.expression.clone(),
this.filter.clone(),
this.schema ? this.schema.clone() : null
);
}
*iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> {
const [prim, newScope] = yield* this.expression.iterateSlots(scope);
yield* this.filter.iterateSlots(this.expression.schema, prim, newScope);
return [prim, newScope];
}
*iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> {
const [prim, newScope] = yield* this.expression.iterateSlots2(scope);
yield* this.filter.iterateSlots2(this.expression.schema, prim, newScope);
return [prim, newScope];
}
}
export class MonitorExpression extends Expression {
expression : Expression;
args : string[]|null;
constructor(location : SourceRange|null,
expression : Expression,
args : string[]|null,
schema : FunctionDef|null) {
super(location, schema);
assert(expression instanceof Expression);
this.expression = expression;
assert(args === null || (Array.isArray(args) && args.length > 0));
this.args = args;
}
get priority() : SyntaxPriority {
return SyntaxPriority.Primary;
}
toSource() : TokenStream {
if (this.args === null) {
return List.concat('monitor', '(', this.expression.toSource(), ')');
} else {
return List.concat('monitor', '(',
List.join(this.args.map((a) => List.singleton(a)), ','),
'of', this.expression.toSource(), ')');
}
}
equals(other : Expression) : boolean {
return other instanceof MonitorExpression &&
this.expression.equals(other.expression) &&
primitiveArrayEquals(this.args, other.args);
}
toLegacy(into_params : InputParam[] = [], scope_params : string[] = []) : legacy.MonitorStream {
const el = this.expression.toLegacy(into_params, scope_params);
assert(el instanceof legacy.Table);
return new legacy.MonitorStream(this.location, el, this.args, this.schema);
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitMonitorExpression(this))
this.expression.visit(visitor);
visitor.exit(this);
}
clone() : MonitorExpression {
return new MonitorExpression(
this.location,
this.expression.clone(),
this.args ? this.args.map((a) => a) : null,
this.schema ? this.schema.clone() : null
);
}
*iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> {
return yield* this.expression.iterateSlots(scope);
}
*iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> {
return yield* this.expression.iterateSlots2(scope);
}
}
export class BooleanQuestionExpression extends Expression {
expression : Expression;
booleanExpression : BooleanExpression;
constructor(location : SourceRange|null,
expression : Expression,
booleanExpression : BooleanExpression,
schema : FunctionDef|null) {
super(location, schema);
this.expression = expression;
this.booleanExpression = booleanExpression;
}
get priority() : SyntaxPriority {
return SyntaxPriority.Projection;
}
toSource() : TokenStream {
return List.concat('[', this.booleanExpression.toSource(), ']', 'of',
addParenthesis(this.priority, this.expression.priority, this.expression.toSource()));
}
equals(other : Expression) : boolean {
return other instanceof BooleanQuestionExpression &&
this.expression.equals(other.expression) &&
this.booleanExpression.equals(other.booleanExpression);
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitBooleanQuestionExpression(this)) {
this.expression.visit(visitor);
this.booleanExpression.visit(visitor);
}
visitor.exit(this);
}
toLegacy(into_params : InputParam[] = [], scope_params : string[] = []) : legacy.Table|legacy.Stream {
throw new UnserializableError('Boolean question expression');
}
clone() : BooleanQuestionExpression {
return new BooleanQuestionExpression(
this.location,
this.expression.clone(),
this.booleanExpression.clone(),
this.schema
);
}
*iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> {
const [prim, newScope] = yield* this.expression.iterateSlots(scope);
yield* this.booleanExpression.iterateSlots(this.expression.schema, prim, newScope);
return [prim, newScope];
}
*iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> {
const [prim, newScope] = yield* this.expression.iterateSlots2(scope);
yield* this.booleanExpression.iterateSlots2(this.expression.schema, prim, newScope);
return [prim, newScope];
}
}
export class ProjectionExpression extends Expression {
expression : Expression;
args : string[];
computations : Value[];
aliases : Array<string|null>;
constructor(location : SourceRange|null,
expression : Expression,
args : string[],
computations : Value[],
aliases : Array<string|null>,
schema : FunctionDef|null) {
super(location, schema);
assert(expression instanceof Expression);
this.expression = expression;
assert(Array.isArray(args));
// if there is a *, it's the only name projected
assert(args.every((x) => x !== '*') || args.length === 1);
this.args = args;
this.computations = computations;
this.aliases = aliases;
assert(this.args.length > 0 || this.computations.length > 0);
assert(this.computations.length === this.aliases.length);
}
get priority() : SyntaxPriority {
return SyntaxPriority.Projection;
}
toSource() : TokenStream {
const allprojections : TokenStream[] = this.args.map((a) => List.join(a.split('.').map((n) => List.singleton(n)), '.'));
for (let i = 0; i < this.computations.length; i++) {
const value = this.computations[i];
const alias = this.aliases[i];
if (alias)
allprojections.push(List.concat(value.toSource(), 'as', alias));
else
allprojections.push(value.toSource());
}
return List.concat('[', List.join(allprojections, ','), ']', 'of',
addParenthesis(this.priority, this.expression.priority, this.expression.toSource()));
}
equals(other : Expression) : boolean {
return other instanceof ProjectionExpression &&
this.expression.equals(other.expression) &&
primitiveArrayEquals(this.args, other.args) &&
arrayEquals(this.computations, other.computations);
}
toLegacy(into_params : InputParam[] = [], scope_params : string[] = []) : legacy.Table|legacy.Stream {
const schema = this.schema!;
assert(schema.functionType !== 'action');
const inner = this.expression.toLegacy(into_params, scope_params);
const names = this.args.slice();
if (schema.functionType === 'query') {
let table = inner as legacy.Table;
if (this.computations.length > 0) {
for (let i = 0; i < this.computations.length; i++) {
const value = this.computations[i];
const alias = this.aliases[i];
table = new legacy.ComputeTable(this.location, table, value, alias, table.schema);
names.push(alias || getScalarExpressionName(value));
}
}
if (names[0] === '*')
return table;
return new legacy.ProjectionTable(this.location, table, names, this.schema);
} else {
let stream = inner as legacy.Stream;
if (this.computations.length > 0) {
for (let i = 0; i < this.computations.length; i++) {
const value = this.computations[i];
const alias = this.aliases[i];
stream = new legacy.ComputeStream(this.location, stream, value, alias, stream.schema);
names.push(alias || getScalarExpressionName(value));
}
}
if (names[0] === '*')
return stream;
return new legacy.ProjectionStream(this.location, stream, names, this.schema);
}
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitProjectionExpression(this))
this.expression.visit(visitor);
visitor.exit(this);
}
clone() : ProjectionExpression {
return new ProjectionExpression(
this.location,
this.expression.clone(),
this.args.slice(),
this.computations.map((v) => v.clone()),
this.aliases.slice(),
this.schema ? this.schema.clone() : null
);
}
*iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> {
const [prim, nestedScope] = yield* this.expression.iterateSlots(scope);
const newScope : ScopeMap = {};
for (const name of this.args)
newScope[name] = nestedScope[name];
return [prim, newScope];
}
*iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> {
const [prim, nestedScope] = yield* this.expression.iterateSlots2(scope);
for (let i = 0; i < this.computations.length; i++)
yield* recursiveYieldArraySlots(new ArrayIndexSlot(prim, nestedScope, this.computations[i].getType(), this.computations, 'computations', i));
const newScope : ScopeMap = {};
for (const name of this.args)
newScope[name] = nestedScope[name];
return [prim, newScope];
}
}
export class AliasExpression extends Expression {
expression : Expression;
name : string;
constructor(location : SourceRange|null,
expression : Expression,
name : string,
schema : FunctionDef|null) {
super(location, schema);
assert(expression instanceof Expression);
this.expression = expression;
assert(typeof name === 'string');
this.name = name;
}
get priority() : SyntaxPriority {
return SyntaxPriority.Alias;
}
toSource() : TokenStream {
return List.concat(addParenthesis(this.priority, this.expression.priority,
this.expression.toSource()), 'as', this.name);
}
equals(other : Expression) : boolean {
return other instanceof AliasExpression &&
this.expression.equals(other.expression) &&
this.name === other.name;
}
toLegacy(into_params : InputParam[] = [], scope_params : string[] = []) : legacy.AliasTable|legacy.AliasStream {
const el = this.expression.toLegacy(into_params, scope_params);
if (el instanceof legacy.Table) {
return new legacy.AliasTable(this.location, el, this.name, this.schema);
} else {
assert(el instanceof legacy.Stream);
return new legacy.AliasStream(this.location, el, this.name, this.schema);
}
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitAliasExpression(this))
this.expression.visit(visitor);
visitor.exit(this);
}
clone() : AliasExpression {
return new AliasExpression(
this.location,
this.expression.clone(),
this.name,
this.schema ? this.schema.clone() : null
);
}
*iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> {
return yield* this.expression.iterateSlots(scope);
}
*iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> {
return yield* this.expression.iterateSlots2(scope);
}
}
export class AggregationExpression extends Expression {
expression : Expression;
field : string;
operator : string;
overload : Type[]|null;
// TODO
alias = null;
constructor(location : SourceRange|null,
expression : Expression,
field : string,
operator : string,
schema : FunctionDef|null,
overload : Type[]|null = null) {
super(location, schema);
assert(expression instanceof Expression);
this.expression = expression;
assert(typeof field === 'string');
this.field = field;
assert(typeof operator === 'string');
this.operator = operator;
this.overload = overload;
}
get priority() : SyntaxPriority {
return SyntaxPriority.Primary;
}
toSource() : TokenStream {
if (this.field === '*') {
return List.concat(this.operator, '(', this.expression.toSource(), ')');
} else {
const field = List.join(this.field.split('.').map((n) => List.singleton(n)), '.');
return List.concat(this.operator, '(', field, 'of',
this.expression.toSource(), ')');
}
}
equals(other : Expression) : boolean {
return other instanceof AggregationExpression &&
this.expression.equals(other.expression) &&
this.field === other.field &&
this.operator === other.operator;
}
toLegacy(into_params : InputParam[] = [], scope_params : string[] = []) : legacy.AggregationTable {
const el = this.expression.toLegacy(into_params, scope_params);
assert(el instanceof legacy.Table);
return new legacy.AggregationTable(this.location, el, this.field, this.operator, null, this.schema);
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitAggregationExpression(this))
this.expression.visit(visitor);
visitor.exit(this);
}
clone() : AggregationExpression {
return new AggregationExpression(
this.location,
this.expression.clone(),
this.field,
this.operator,
this.schema ? this.schema.clone() : null,
this.overload
);
}
*iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> {
return yield* this.expression.iterateSlots(scope);
}
*iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> {
return yield* this.expression.iterateSlots2(scope);
}
}
export class SortExpression extends Expression {
expression : Expression;
value : Value;
direction : 'asc'|'desc';
constructor(location : SourceRange|null,
expression : Expression,
value : Value,
direction : 'asc'|'desc',
schema : FunctionDef|null) {
super(location, schema);
assert(expression instanceof Expression);
this.expression = expression;
this.value = value;
assert(direction === 'asc' || direction === 'desc');
this.direction = direction;
}
get priority() : SyntaxPriority {
return SyntaxPriority.Primary;
}
toSource() : TokenStream {
return List.concat('sort', '(', this.value.toSource(), ' ', this.direction, 'of',
this.expression.toSource(), ')');
}
equals(other : Expression) : boolean {
return other instanceof SortExpression &&
this.expression.equals(other.expression) &&
this.value.equals(other.value) &&
this.direction === other.direction;
}
toLegacy(into_params : InputParam[] = [], scope_params : string[] = []) : legacy.SortedTable {
const el = this.expression.toLegacy(into_params, scope_params);
assert(el instanceof legacy.Table);
if (this.value instanceof VarRefValue) {
return new legacy.SortedTable(this.location, el, this.value.name, this.direction, this.schema);
} else {
return new legacy.SortedTable(this.location,
new legacy.ComputeTable(this.location, el, this.value, null, this.schema),
getScalarExpressionName(this.value), this.direction, this.schema);
}
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitSortExpression(this)) {
this.expression.visit(visitor);
this.value.visit(visitor);
}
visitor.exit(this);
}
clone() : SortExpression {
return new SortExpression(
this.location,
this.expression.clone(),
this.value.clone(),
this.direction,
this.schema ? this.schema.clone() : null
);
}
*iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> {
return yield* this.expression.iterateSlots(scope);
}
*iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> {
const [prim, innerScope] = yield* this.expression.iterateSlots2(scope);
yield* recursiveYieldArraySlots(new FieldSlot(prim, innerScope, Type.Number, this, 'sort', 'value'));
return [prim, innerScope];
}
}
export class IndexExpression extends Expression {
expression : Expression;
indices : Value[];
constructor(location : SourceRange|null,
expression : Expression,
indices : Value[],
schema : FunctionDef|null) {
super(location, schema);
assert(expression instanceof Expression);
this.expression = expression;
assert(Array.isArray(indices));
this.indices = indices;
}
get priority() : SyntaxPriority {
return SyntaxPriority.Index;
}
toSource() : TokenStream {
return List.concat(addParenthesis(this.priority, this.expression.priority, this.expression.toSource()),
'[', List.join(this.indices.map((i) => i.toSource()), ','), ']');
}
equals(other : Expression) : boolean {
return other instanceof IndexExpression &&
this.expression.equals(other.expression) &&
arrayEquals(this.indices, other.indices);
}
toLegacy(into_params : InputParam[] = [], scope_params : string[] = []) : legacy.IndexTable {
const el = this.expression.toLegacy(into_params, scope_params);
assert(el instanceof legacy.Table);
return new legacy.IndexTable(this.location, el, this.indices, this.schema);
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitIndexExpression(this)) {
this.expression.visit(visitor);
for (const index of this.indices)
index.visit(visitor);
}
visitor.exit(this);
}
clone() : IndexExpression {
return new IndexExpression(
this.location,
this.expression.clone(),
this.indices.map((i) => i.clone()),
this.schema ? this.schema.clone() : null
);
}
*iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> {
return yield* this.expression.iterateSlots(scope);
}
*iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> {
const [prim, innerScope] = yield* this.expression.iterateSlots2(scope);
for (let i = 0; i < this.indices.length; i++)
yield* recursiveYieldArraySlots(new ArrayIndexSlot(prim, innerScope, Type.Number, this.indices, 'expression.index', i));
return [prim, innerScope];
}
}
export class SliceExpression extends Expression {
expression : Expression;
base : Value;
limit : Value;
constructor(location : SourceRange|null,
expression : Expression,
base : Value,
limit : Value,
schema : FunctionDef|null) {
super(location, schema);
assert(expression instanceof Expression);
this.expression = expression;
assert(base instanceof Value);
this.base = base;
assert(limit instanceof Value);
this.limit = limit;
}
get priority() : SyntaxPriority {
return SyntaxPriority.Index;
}
toSource() : TokenStream {
return List.concat(addParenthesis(this.priority, this.expression.priority, this.expression.toSource()),
'[', this.base.toSource(), ':', this.limit.toSource(), ']');
}
equals(other : Expression) : boolean {
return other instanceof SliceExpression &&
this.expression.equals(other.expression) &&
this.base.equals(other.base) &&
this.limit.equals(other.limit);
}
toLegacy(into_params : InputParam[] = [], scope_params : string[] = []) : legacy.SlicedTable {
const el = this.expression.toLegacy(into_params, scope_params);
assert(el instanceof legacy.Table);
return new legacy.SlicedTable(this.location, el, this.base, this.limit, this.schema);
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitSliceExpression(this)) {
this.expression.visit(visitor);
this.base.visit(visitor);
this.limit.visit(visitor);
}
visitor.exit(this);
}
clone() : SliceExpression {
return new SliceExpression(
this.location,
this.expression.clone(),
this.base.clone(),
this.limit.clone(),
this.schema ? this.schema.clone() : null
);
}
*iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> {
return yield* this.expression.iterateSlots(scope);
}
*iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> {
const [prim, innerScope] = yield* this.expression.iterateSlots2(scope);
yield* recursiveYieldArraySlots(new FieldSlot(prim, innerScope, Type.Number, this, 'slice', 'base'));
yield* recursiveYieldArraySlots(new FieldSlot(prim, innerScope, Type.Number, this, 'slice', 'limit'));
return [prim, innerScope];
}
}
/**
* Evaluates a list of expressions, passing the result of the previous one
* to the next.
*
* In syntax, the expressions are separated by "=>"
*/
export class ChainExpression extends Expression {
expressions : Expression[];
constructor(location : SourceRange|null,
expressions : Expression[],
schema : FunctionDef|null) {
super(location, schema);
assert(Array.isArray(expressions));
this.expressions = expressions;
}
get priority() : SyntaxPriority {
return SyntaxPriority.Chain;
}
get first() : Expression {
return this.expressions[0];
}
set first(expr : Expression) {
this.expressions[0] = expr;
}
get last() : Expression {
return this.expressions[this.expressions.length-1];
}
set last(expr : Expression) {
this.expressions[this.expressions.length-1] = expr;
}
get lastQuery() : Expression|null {
const expressions = this.expressions;
const last = expressions[expressions.length-1];
if (last.schema!.functionType === 'action') {
if (expressions.length === 1)
return null;
else
return expressions[expressions.length-2];
} else {
return last;
}
}
setLastQuery(expr : Expression) {
const expressions = this.expressions;
const last = expressions[expressions.length-1];
if (last.schema!.functionType === 'action') {
if (expressions.length === 1)
expressions.unshift(expr);
else
expressions[expressions.length-2] = expr;
} else {
expressions[expressions.length-1] = expr;
}
}
toSource() : TokenStream {
return List.join(this.expressions.map((exp) => exp.toSource()), '=>');
}
equals(other : Expression) : boolean {
return other instanceof ChainExpression &&
arrayEquals(this.expressions, other.expressions);
}
toLegacy(into_params : InputParam[] = [], scope_params : string[] = []) : legacy.Stream|legacy.Table|legacy.Action {
if (this.expressions.length === 1)
return this.expressions[0].toLegacy(into_params, scope_params);
// note: schemas and parameter passing work differently in old thingtalk
// table/stream join and new thingtalk chain expressions
// so this is not a perfect conversion
const first = this.expressions[0];
if (first.schema!.functionType === 'stream') {
const fl = first.toLegacy(into_params, scope_params);
assert(fl instanceof legacy.Stream);
if (this.expressions.length > 2) {
const newIntoParams : InputParam[] = [];
const sl = this.expressions[1].toLegacy(newIntoParams, scope_params);
assert(sl instanceof legacy.Table);
const rest : legacy.Table = this.expressions.slice(2).reduce((al, b) => {
const newIntoParams : InputParam[] = [];
const bl = b.toLegacy(newIntoParams, scope_params);
assert(bl instanceof legacy.Table);
const joinParams = newIntoParams.filter((ip) => {
if (ip.value instanceof VarRefValue) {
if (al.schema!.hasArgument(ip.value.name)) {
return true;
} else {
into_params.push(ip);
return false;
}
} else { // $event
return true;
}
});
return new legacy.JoinTable(null, al, bl, joinParams, b.schema);
}, sl);
const joinParams = newIntoParams.filter((ip) => {
if (ip.value instanceof VarRefValue) {
if (fl.schema!.hasArgument(ip.value.name)) {
return true;
} else {
into_params.push(ip);
return false;
}
} else { // $event
return true;
}
});
return new legacy.JoinStream(this.location, fl, rest, joinParams, this.expressions[this.expressions.length-1].schema);
} else {
const newIntoParams : InputParam[] = [];
const rest = this.expressions[1].toLegacy(newIntoParams, scope_params);
assert(rest instanceof legacy.Table);
const joinParams = newIntoParams.filter((ip) => {
if (ip.value instanceof VarRefValue) {
if (fl.schema!.hasArgument(ip.value.name)) {
return true;
} else {
into_params.push(ip);
return false;
}
} else { // $event
return true;
}
});
return new legacy.JoinStream(this.location, fl, rest, joinParams, this.expressions[1].schema);
}
} else {
const fl = this.expressions[0].toLegacy(into_params, scope_params);
assert(fl instanceof legacy.Table);
return this.expressions.slice(1).reduce((al, b) => {
const newIntoParams : InputParam[] = [];
let bl = b.toLegacy(newIntoParams, scope_params);
if (bl instanceof legacy.Action) {
// this can occur with chain expressions in assignments
assert(bl instanceof legacy.VarRefAction);
// this is a hack! we generate a table that calls an action
bl = new legacy.VarRefTable(bl.location, bl.name, bl.in_params, bl.schema);
}
assert(bl instanceof legacy.Table);
const joinParams = newIntoParams.filter((ip) => {
if (ip.value instanceof VarRefValue) {
if (al.schema!.hasArgument(ip.value.name)) {
return true;
} else {
into_params.push(ip);
return false;
}
} else { // $event
return true;
}
});
return new legacy.JoinTable(null, al, bl, joinParams, b.schema);
}, fl);
}
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitChainExpression(this)) {
for (const expr of this.expressions)
expr.visit(visitor);
}
visitor.exit(this);
}
clone() : ChainExpression {
return new ChainExpression(
this.location,
this.expressions.map((ex) => ex.clone()),
this.schema ? this.schema.clone() : null
);
}
*iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> {
const newScope : ScopeMap = {};
for (const expr of this.expressions) {
[, scope] = yield* expr.iterateSlots(scope);
Object.assign(newScope, scope);
}
return [null, newScope];
}
*iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> {
const newScope : ScopeMap = {};
for (const expr of this.expressions) {
[, scope] = yield* expr.iterateSlots2(scope);
Object.assign(newScope, scope);
}
return [null, newScope];
}
}
export class JoinExpression extends Expression {
lhs : Expression;
rhs : Expression;
constructor(location : SourceRange|null,
left : Expression,
right : Expression,
schema : FunctionDef|null) {
super(location, schema);
this.lhs = left;
this.rhs = right;
}
get priority() : SyntaxPriority {
return SyntaxPriority.Join;
}
toSource() : TokenStream {
return List.concat(
addParenthesis(this.priority, this.lhs.priority, this.lhs.toSource()),
'join',
addParenthesis(this.priority, this.rhs.priority, this.rhs.toSource())
);
}
equals(other : Expression) : boolean {
return other instanceof JoinExpression &&
this.lhs.equals(other.lhs) && this.rhs.equals(other.rhs);
}
toLegacy(into_params : InputParam[] = [], scope_params : string[] = []) : legacy.Table {
throw new UnserializableError('Join expression');
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitJoinExpression(this)) {
this.lhs.visit(visitor);
this.rhs.visit(visitor);
}
visitor.exit(this);
}
clone() : JoinExpression {
return new JoinExpression(
this.location,
this.lhs.clone(),
this.rhs.clone(),
this.schema ? this.schema.clone() : null
);
}
*iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> {
const [, leftScope] = yield* this.lhs.iterateSlots(scope);
const [, rightScope] = yield* this.rhs.iterateSlots(scope);
const newScope : ScopeMap = {};
Object.assign(newScope, leftScope, rightScope);
return [null, newScope];
}
*iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> {
const [, leftScope] = yield* this.lhs.iterateSlots2(scope);
const [, rightScope] = yield* this.rhs.iterateSlots2(scope);
const newScope : ScopeMap = {};
Object.assign(newScope, leftScope, rightScope);
return [null, newScope];
}
} | the_stack |
// Notes - Hypermerge.front will not emit a doc if it is empty - even if its supposed to be
export const EXT = "hypermerge"
type FeedFn = (f: Feed<Uint8Array>) => void
interface Swarm {
join(dk: Buffer): void
leave(dk: Buffer): void
on: Function
}
import Queue from "capstone/Queue"
import * as JsonBuffer from "../../logic/JsonBuffer"
import * as Base58 from "bs58"
import * as crypto from "hypercore/lib/crypto"
import { hypercore, Feed, Peer, discoveryKey } from "./hypercore"
import * as Backend from "automerge/backend"
import { Change } from "automerge/backend"
import { BackendManager } from "./backend"
import { FrontendManager } from "./frontend"
import * as Debug from "debug"
export { Feed, Peer } from "./hypercore"
export { Patch, Doc, EditDoc, ChangeFn } from "automerge/frontend"
export { BackendManager, FrontendManager }
Debug.formatters.b = Base58.encode
const HypercoreProtocol: Function = require("hypercore-protocol")
const ram: Function = require("random-access-memory")
const raf: Function = require("random-access-file")
const log = Debug("hypermerge")
export interface Keys {
publicKey: Buffer
secretKey?: Buffer
}
export interface FeedData {
actorId: string
writable: Boolean
changes: Change[]
}
export interface Options {
path?: string
storage?: Function
}
export interface LedgerData {
docId: string
actorIds: string[]
}
export class Hypermerge {
path?: string
storage: Function
ready: Promise<undefined>
joined: Set<Buffer> = new Set()
feeds: Map<string, Feed<Uint8Array>> = new Map()
feedQs: Map<string, Queue<FeedFn>> = new Map()
feedPeers: Map<string, Set<Peer>> = new Map()
docs: Map<string, BackendManager> = new Map()
feedSeq: Map<string, number> = new Map()
ledger: Feed<LedgerData>
docMetadata: Map<string, string[]> = new Map() // Map of Sets - FIXME
swarm?: Swarm
id: Buffer
constructor(opts: Options) {
this.path = opts.path || "default"
this.storage = opts.storage || (opts.path ? raf : ram)
this.ledger = hypercore(this.storageFn("ledger"), { valueEncoding: "json" })
this.id = this.ledger.id
this.ready = new Promise((resolve, reject) => {
this.ledger.ready(() => {
log("Ledger ready: size", this.ledger.length)
if (this.ledger.length > 0) {
this.ledger.getBatch(0, this.ledger.length, (err, data) => {
data.forEach(d => {
let old = this.docMetadata.get(d.docId) || []
this.docMetadata.set(d.docId, old.concat(d.actorIds))
})
resolve()
})
} else {
resolve()
}
})
})
}
createDocumentFrontend<T>(keys: Keys): FrontendManager<T> {
const back = this.createDocument(keys)
const front = new FrontendManager<T>(back.docId, back.docId)
front.back = back
front.on("request", back.applyLocalChange)
back.on("patch", front.patch)
return front
}
createDocument(keys: Keys): BackendManager {
const docId = Base58.encode(keys.publicKey)
log("Create", docId)
const doc = new BackendManager(this, docId, Backend.init())
this.docs.set(docId, doc)
this.initFeed(doc, keys)
return doc
}
private addMetadata(docId: string, actorId: string) {
this.ready.then(() => {
let ld: LedgerData = { docId: docId, actorIds: [actorId] }
let old = this.docMetadata.get(docId) || []
if (!old.includes(actorId)) {
this.docMetadata.set(docId, old.concat(ld.actorIds))
this.ledger.append(ld)
}
})
}
openDocument(docId: string): BackendManager {
let doc = this.docs.get(docId) || new BackendManager(this, docId)
if (!this.docs.has(docId)) {
this.docs.set(docId, doc)
this.addMetadata(docId, docId)
this.loadDocument(doc)
this.join(docId)
}
return doc
}
openDocumentFrontend<T>(docId: string): FrontendManager<T> {
const back = this.openDocument(docId)
const front = new FrontendManager<T>(back.docId)
front.back = back
front.once("needsActorId", back.initActor)
front.on("request", back.applyLocalChange)
back.on("actorId", front.setActorId)
back.on("ready", front.init)
back.on("patch", front.patch)
return front
}
joinSwarm(swarm: Swarm) {
if (this.swarm) {
throw new Error("joinSwarm called while already swarming")
}
this.swarm = swarm
for (let dk of this.joined) {
this.swarm.join(dk)
}
}
private feedData(doc: BackendManager, actorId: string): Promise<FeedData> {
return new Promise((resolve, reject) => {
this.getFeed(doc, actorId, feed => {
const writable = feed.writable
if (feed.length > 0) {
feed.getBatch(0, feed.length, (err, datas) => {
const changes = datas.map(JsonBuffer.parse)
if (err) {
reject(err)
}
this.feedSeq.set(actorId, datas.length)
resolve({ actorId, writable, changes })
})
} else {
resolve({ actorId, writable, changes: [] })
}
})
})
}
private allFeedData(doc: BackendManager): Promise<FeedData[]> {
return Promise.all(doc.actorIds().map(key => this.feedData(doc, key)))
}
writeChange(doc: BackendManager, actorId: string, change: Change) {
const feedLength = this.feedSeq.get(actorId) || 0
const ok = feedLength + 1 === change.seq
log(`write actor=${actorId} seq=${change.seq} feed=${feedLength} ok=${ok}`)
this.feedSeq.set(actorId, feedLength + 1)
this.getFeed(doc, actorId, feed => {
feed.append(JsonBuffer.bufferify(change), err => {
if (err) {
throw new Error("failed to append to feed")
}
})
})
}
private loadDocument(doc: BackendManager) {
return this.ready.then(() =>
this.allFeedData(doc).then(feedData => {
const writer = feedData
.filter(f => f.writable)
.map(f => f.actorId)
.shift()
const changes = ([] as Change[]).concat(...feedData.map(f => f.changes))
doc.init(changes, writer)
}),
)
}
private join = (actorId: string) => {
const dk = discoveryKey(Base58.decode(actorId))
if (this.swarm && !this.joined.has(dk)) {
this.swarm.join(dk)
}
this.joined.add(dk)
}
private leave = (actorId: string) => {
const dk = discoveryKey(Base58.decode(actorId))
if (this.swarm && this.joined.has(dk)) {
this.swarm.leave(dk)
}
this.joined.delete(dk)
}
private getFeed = (doc: BackendManager, actorId: string, cb: FeedFn) => {
const publicKey = Base58.decode(actorId)
const dk = discoveryKey(publicKey)
const dkString = Base58.encode(dk)
const q = this.feedQs.get(dkString) || this.initFeed(doc, { publicKey })
q.push(cb)
}
private storageFn(path: string): Function {
return (name: string) => {
return this.storage(this.path + "/" + path + "/" + name)
}
}
initActorFeed(doc: BackendManager): string {
log("initActorFeed", doc.docId)
const keys = crypto.keyPair()
const actorId = Base58.encode(keys.publicKey)
this.initFeed(doc, keys)
return actorId
}
sendToPeer(peer: Peer, data: any) {
peer.stream.extension(EXT, Buffer.from(JSON.stringify(data)))
}
actorIds(doc: BackendManager): string[] {
return this.docMetadata.get(doc.docId) || []
}
feed(actorId: string): Feed<Uint8Array> {
const publicKey = Base58.decode(actorId)
const dk = discoveryKey(publicKey)
const dkString = Base58.encode(dk)
return this.feeds.get(dkString)!
}
peers(doc: BackendManager): Peer[] {
return ([] as Peer[]).concat(
...this.actorIds(doc).map(actorId => [
...(this.feedPeers.get(actorId) || []),
]),
)
}
private closeFeed = (actorId: string) => {
this.feed(actorId).close()
}
private initFeed(doc: BackendManager, keys: Keys): Queue<FeedFn> {
const { publicKey, secretKey } = keys
const actorId = Base58.encode(publicKey)
const storage = this.storageFn(actorId)
const dk = discoveryKey(publicKey)
const dkString = Base58.encode(dk)
const feed: Feed<Uint8Array> = hypercore(storage, publicKey, {
secretKey,
})
const q = new Queue<FeedFn>()
const peers = new Set()
this.feeds.set(dkString, feed)
this.feedQs.set(dkString, q)
this.feedPeers.set(actorId, peers)
this.addMetadata(doc.docId, actorId)
log("init feed", actorId)
feed.ready(() => {
this.feedSeq.set(actorId, 0)
doc.broadcastMetadata()
this.join(actorId)
feed.on("peer-remove", (peer: Peer) => {
peers.delete(peer)
doc.emit("peer-remove", peer)
})
feed.on("peer-add", (peer: Peer) => {
peer.stream.on("extension", (ext: string, buf: Buffer) => {
if (ext === EXT) {
const msg: string[] = JSON.parse(buf.toString())
log("EXT", msg)
// getFeed -> initFeed -> join()
msg.forEach(actorId => this.getFeed(doc, actorId, _ => {}))
}
})
peers.add(peer)
doc.messageMetadata(peer)
doc.emit("peer-add", peer)
})
let remoteChanges: Change[] = []
feed.on("download", (idx, data) => {
remoteChanges.push(JSON.parse(data))
})
feed.on("sync", () => {
doc.applyRemoteChanges(remoteChanges)
remoteChanges = []
})
this.feedQs.get(dkString)!.subscribe(f => f(feed))
feed.on("close", () => {
log("closing feed", actorId)
this.feeds.delete(dkString)
this.feedQs.delete(dkString)
this.feedPeers.delete(actorId)
this.feedSeq.delete(actorId)
})
doc.emit("feed", feed)
})
return q
}
stream = (opts: any): any => {
const stream = HypercoreProtocol({
live: true,
id: this.ledger.id,
encrypt: false,
timeout: 10000,
extensions: [EXT],
})
let add = (dk: Buffer) => {
const feed = this.feeds.get(Base58.encode(dk))
if (feed) {
log("replicate feed!", Base58.encode(dk))
feed.replicate({
stream,
live: true,
})
}
}
stream.on("feed", (dk: Buffer) => add(dk))
add(opts.channel || opts.discoveryKey)
return stream
}
releaseHandle(doc: BackendManager) {
const actorIds = doc.actorIds()
this.docs.delete(doc.docId)
actorIds.map(this.leave)
actorIds.map(this.closeFeed)
}
} | the_stack |
'use strict';
import { Chart, Types, BaseChartConfig, ChartData, Colors } from '../common/types';
import Base from '../common/Base';
import errorWrap from '../common/errorWrap';
import rectTooltip, { TooltipConfig } from '../common/rectTooltip';
import rectLegend, { LegendConfig } from '../common/rectLegend';
import { GuideConfig } from '../common/guide';
import { LabelConfig } from '../common/label';
import themes from '../themes/index';
import { pxToNumber, numberDecimal } from '../common/common';
import geomStyle, { GeomStyleConfig } from '../common/geomStyle';
import './index.scss';
// 3.x代码
export interface WfunnelConfig extends BaseChartConfig {
colors?: Colors;
legend?: LegendConfig | boolean;
tooltip?: TooltipConfig | boolean;
guide?: GuideConfig;
pyramid?: boolean;
label?: LabelConfig | boolean;
direction?: string;
align?: string;
percent?: Types.LooseObject | boolean;
geomStyle?: GeomStyleConfig;
}
export class Funnel extends Base<WfunnelConfig> {
chartName = 'G2Funnel';
getDefaultConfig(): WfunnelConfig {
return {
colors: themes.order_10,
legend: {
position: 'top',
align: '',
nameFormatter: null, // 可以强制覆盖,手动设置label
},
tooltip: {
titleFormatter: null,
nameFormatter: null,
valueFormatter: null,
},
label: false,
pyramid: false,
// 主方向,从上到下(vertical)、从左到右(horizontal)
direction: 'vertical',
// 排列位置 start,center,end
align: 'center',
// 尖顶漏斗图
percent: true,
};
}
init(chart: Chart, config: WfunnelConfig, data: any) {
const defs: Record<string, Types.ScaleOption> = {
type: {
type: 'cat',
},
};
chart.scale(defs);
chart.interaction('element-active');
chart.axis(false);
chart.data(data);
// 设置图例
rectLegend(this, chart, config, null, true);
// tooltip
rectTooltip(
this,
chart,
config,
{
showTitle: false,
showMarkers: false,
showCrosshairs: false,
},
null,
{
showTitle: false,
showMarkers: false,
showCrosshairs: false,
},
);
// 根据传入的 direction 和 align 设置坐标系,并绘制图形
const drawType = `${config.direction}-${config.align}`;
let geom = null;
const fontSize1 = pxToNumber(themes['widgets-font-size-1']);
let percentOffsetX = 0;
let percentOffsetY = 0;
const funnelShape = config.align === 'center' && config.pyramid ? 'pyramid' : 'funnel';
switch (drawType) {
case 'vertical-left':
case 'vertical-start':
chart.coordinate('rect').transpose().scale(1, -1);
geom = chart.interval()
.position('x*y')
.shape(funnelShape)
.color('x', config.colors);
percentOffsetX = 3 * fontSize1;
break;
case 'vertical-center':
chart.coordinate('rect').transpose().scale(1, -1);
geom = chart.interval()
.adjust([{
type: 'symmetric',
}])
.position('x*y')
.shape(funnelShape)
.color('x', config.colors);
break;
case 'vertical-right':
case 'vertical-end':
chart.coordinate('rect').transpose().scale(-1, -1);
geom = chart.interval()
.position('x*y')
.shape(funnelShape)
.color('x', config.colors);
percentOffsetX = -3 * fontSize1;
break;
case 'horizontal-top':
case 'horizontal-start':
chart.coordinate('rect').reflect('y');
geom = chart.interval()
.position('x*y')
.shape(funnelShape)
.color('x', config.colors);
percentOffsetY = 3 * fontSize1;
break;
case 'horizontal-center':
geom = chart.interval()
.position('x*y')
.shape(funnelShape)
.color('x', config.colors)
.adjust([{
type: 'symmetric',
}]);
break;
// case 'horizontal-bottom':
// case 'horizontal-end':
// 和 default 时相同
default:
geom = chart.interval()
.position('x*y')
.shape(funnelShape)
.color('x', config.colors);
percentOffsetY = -3 * fontSize1;
}
geomStyle(geom, config.geomStyle);
// TODO 自定义label
if(config.label) {
let temp = {};
temp = config.label || {};
geom.label('y',
{
offset: pxToNumber(themes['widgets-font-size-1']),
labelLine: {
style: {
lineWidth: 1,
stroke: themes['widgets-axis-line'],
},
},
...temp,
});
}
// 绘制辅助线,辅助背景区域
renderGuide(chart, config, data, percentOffsetX, percentOffsetY);
}
}
function renderGuide(chart: Chart, config: WfunnelConfig, data: ChartData, percentOffsetX: number, percentOffsetY: number) {
// 中间标签文本
chart.annotation().clear(true);
let configPercent = config.percent;
if (!configPercent) {
return;
}
if (configPercent === true) {
configPercent = {};
}
const {
labelFormatter,
offsetX = 0,
offsetY = 0,
top = true,
style = {}
} = configPercent;
const positionY = config.align === 'center' ? 'median' : 'start';
data.forEach((d: { y: any; x: any; }, i: any) => {
let content = `${numberDecimal(100 * d.y / data[0].y)}%`;
if (labelFormatter) {
content = labelFormatter(d.y / data[0].y, d, i);
}
chart.annotation().text({
top,
position: [
d.x,
positionY,
],
offsetX: percentOffsetX + offsetX,
offsetY: percentOffsetY + offsetY,
content: content, // 显示的文本内容
style: {
fill: themes['widgets-label-text'],
fontSize: pxToNumber(themes['widgets-font-size-1']),
textAlign: 'center',
shadowBlur: 2,
shadowColor: 'rgba(255, 255, 255, .3)',
...style,
},
});
});
}
const Wfunnel: typeof Funnel = errorWrap(Funnel);
export default Wfunnel;
// export default /*#__PURE__*/ errorWrap(g2Factory('G2Funnel', {
// getDefaultConfig() {
// return {
// colors: themes.order_10,
// padding: ['auto', 0, 'auto', 0],
// legend: {
// align: 'left',
// nameFormatter: null, // 可以强制覆盖,手动设置label
// },
// tooltip: {
// nameFormatter: null,
// valueFormatter: null,
// },
// // 主方向,从上到下(vertical)、从左到右(horizontal)
// direction: 'vertical',
// // 排列位置 start,center,end
// align: 'center',
// // 尖顶漏斗图
// pyramid: false,
// label: false,
// percent: false,
// };
// },
// beforeInit(props) {
// const { config } = props;
// const newConfig = merge({}, this.defaultConfig, config);
// // TODO 处理padding
// return Object.assign({}, props, {
// padding: defaultPadding(props.padding || config.padding, newConfig, ...this.defaultConfig.padding),
// config: newConfig,
// });
// },
// init(chart, userConfig, data) {
// const config = userConfig;
// // 设置数据度量
// const defs = {
// type: {
// type: 'cat',
// },
// };
// chart.source(data, defs);
// // 漏斗图目前看没有轴
// chart.axis(false);
// // 设置图例
// rectLegend(this, chart, config, null, true);
// // tooltip
// rectTooltip(this, chart, config, {
// showTitle: false,
// crosshairs: null,
// });
// // 根据传入的 direction 和 align 设置坐标系,并绘制图形
// const drawType = `${config.direction}-${config.align}`;
// let geom = null;
// const fontSize1 = pxToNumber(themes['widgets-font-size-1']);
// let percentOffsetX = 0;
// let percentOffsetY = 0;
// switch (drawType) {
// case 'vertical-left':
// case 'vertical-start':
// chart.coord('rect').transpose().scale(1, -1);
// geom = chart.interval();
// percentOffsetX = 3 * fontSize1;
// break;
// case 'vertical-center':
// chart.coord('rect').transpose().scale(1, -1);
// geom = chart.intervalSymmetric();
// break;
// case 'vertical-right':
// case 'vertical-end':
// chart.coord('rect').transpose().scale(-1, -1);
// geom = chart.interval();
// percentOffsetX = -3 * fontSize1;
// break;
// case 'horizontal-top':
// case 'horizontal-start':
// chart.coord('rect').reflect('y');
// geom = chart.interval();
// percentOffsetY = 3 * fontSize1;
// break;
// case 'horizontal-center':
// geom = chart.intervalSymmetric();
// break;
// // case 'horizontal-bottom':
// // case 'horizontal-end':
// // 和 default 时相同
// default:
// geom = chart.interval();
// percentOffsetY = -3 * fontSize1;
// }
// const funnelShape = (config.align === 'center' && config.pyramid) ? 'pyramid' : 'funnel';
// geom.position('x*y').shape(funnelShape).color('x', config.colors);
// label(geom, config, 'y', {
// offset: pxToNumber(themes['widgets-font-size-1']),
// labelLine: {
// lineWidth: 1,
// stroke: themes['widgets-axis-line'],
// },
// });
// const geomStyle = config.geomStyle || {};
// geom.style('x*y*type*extra', {
// ...geomStyle,
// });
// renderGuide(chart, config, data, percentOffsetX, percentOffsetY);
// chart.render();
// },
// changeData(chart, config, data) {
// chart.changeData(data);
// const drawType = `${config.direction}-${config.align}`;
// const fontSize1 = pxToNumber(themes['widgets-font-size-1']);
// let percentOffsetX = 0;
// let percentOffsetY = 0;
// switch (drawType) {
// case 'vertical-left':
// case 'vertical-start':
// percentOffsetX = 3 * fontSize1;
// break;
// case 'vertical-center':
// break;
// case 'vertical-right':
// case 'vertical-end':
// percentOffsetX = -3 * fontSize1;
// break;
// case 'horizontal-top':
// case 'horizontal-start':
// percentOffsetY = 3 * fontSize1;
// break;
// case 'horizontal-center':
// break;
// // case 'horizontal-bottom':
// // case 'horizontal-end':
// // 和 default 时相同
// default:
// percentOffsetY = -3 * fontSize1;
// }
// renderGuide(chart, config, data, percentOffsetX, percentOffsetY);
// },
// })); | the_stack |
import React from "react";
import type {LayoutChangeEvent, NativeScrollEvent, NativeSyntheticEvent, ScrollViewComponent} from "react-native";
import {Animated, FlatList, StyleSheet, Text, TouchableWithoutFeedback, View} from "react-native";
import {Triangle} from "./Triangle";
import type {Props} from "./type";
import type {Props as TriangleProps} from "./Triangle";
/**
* An enhanced React Native <FlatList> component to provide auto-scrolling functionality.
* Auto-scrolling will only be enabled if:
* 1. the scrollTop is at the end of the list; or
* 2. the user has scrolled back and/or past the end of the list
* This is to prevent auto-scrolling from annoying the user when the user tries to scroll and look for something in the list.
*/
interface State {
enabledAutoScrollToEnd: boolean;
newItemCount: number;
alertY: Animated.Value;
isEndOfList: boolean;
}
export class AutoScrollFlatList<T> extends React.PureComponent<Props<T>, State> {
static displayName = "AutoScrollFlatList";
static defaultProps: Pick<Props<any>, "threshold" | "showScrollToEndIndicator" | "showNewItemAlert" | "autoScrollDisabled"> = {
threshold: 0,
showScrollToEndIndicator: true,
showNewItemAlert: true,
autoScrollDisabled: false,
};
private readonly listRef: React.RefObject<FlatList<T>> = React.createRef();
private flatListHeight: number = 0;
private flatListWidth: number = 0;
private contentHeight: number = 0;
private contentWidth: number = 0;
private scrollTop: number = 0;
constructor(props: Props<T>) {
super(props);
this.state = {
enabledAutoScrollToEnd: props.autoScrollDisabled ? false : true,
newItemCount: 0,
alertY: new Animated.Value(0),
isEndOfList: true,
};
}
componentDidUpdate(prevProps: Readonly<Props<T>>, prevState: Readonly<State>) {
const {data, filteredDataForNewItemCount} = this.props;
const {enabledAutoScrollToEnd, newItemCount, alertY} = this.state;
const filteredPrevData = filteredDataForNewItemCount ? filteredDataForNewItemCount(prevProps.data ?? []) : prevProps.data ?? [];
const filteredData = filteredDataForNewItemCount ? filteredDataForNewItemCount(data ?? []) : data ?? [];
if (!enabledAutoScrollToEnd && filteredData.length > filteredPrevData.length) {
const newCount = prevState.newItemCount + filteredData.length - filteredPrevData.length;
this.setState({newItemCount: newCount});
if (newCount === 1) {
alertY.setValue(-30);
Animated.timing(alertY, {
toValue: 10,
duration: 250,
useNativeDriver: false,
}).start();
}
} else if (enabledAutoScrollToEnd && newItemCount) {
this.setState({newItemCount: 0});
}
}
/**
* Exposing FlatList Methods To AutoScrollFlatList's Ref
*/
scrollToEnd = (params: {animated: boolean} = {animated: true}) => {
const offset = this.props.horizontal ? this.contentWidth - this.flatListWidth : this.contentHeight - this.flatListHeight;
this.setState({newItemCount: 0});
this.scrollToOffset({offset, animated: params.animated});
};
scrollToIndex = (params: {index: number; viewOffset?: number; viewPosition?: number; animated?: boolean}) => {
this.listRef.current?.scrollToIndex(params);
};
scrollToItem = (params: {item: T; viewPosition?: number; animated: boolean}) => {
this.listRef.current?.scrollToItem(params);
};
scrollToOffset = (params: {offset: number; animated?: boolean}) => {
this.listRef.current?.scrollToOffset(params);
};
recordInteraction = () => {
this.listRef.current?.recordInteraction();
};
flashScrollIndicators = () => {
this.listRef.current?.flashScrollIndicators();
};
getScrollableNode = (): any => {
return this.listRef.current?.getScrollableNode();
};
getNativeScrollRef = (): React.RefObject<View> | React.RefObject<ScrollViewComponent> | null | undefined => {
return this.listRef.current?.getNativeScrollRef();
};
getScrollResponder = (): JSX.Element | null | undefined => {
return this.listRef.current?.getScrollResponder();
};
isAutoScrolling = () => this.state.enabledAutoScrollToEnd;
render() {
/**
* Need to force a refresh for the FlatList by changing the key when numColumns changes.
* Ref: https://stackoverflow.com/questions/44291781/dynamically-changing-number-of-columns-in-react-native-flat-list
*/
const {contentContainerStyle, threshold, showScrollToEndIndicator, showNewItemAlert, newItemAlertRenderer, indicatorContainerStyle, indicatorComponent, numColumns, ...restProps} = this.props;
const {enabledAutoScrollToEnd, newItemCount, alertY, isEndOfList} = this.state;
return (
<View style={styles.container}>
<FlatList {...restProps} ref={this.listRef} key={numColumns} numColumns={numColumns} contentContainerStyle={contentContainerStyle ?? styles.contentContainer} onLayout={this.onLayout} onContentSizeChange={this.onContentSizeChange} onScroll={this.onScroll} />
{showNewItemAlert && !enabledAutoScrollToEnd && newItemCount > 0 && (
<TouchableWithoutFeedback onPress={() => this.scrollToEnd()}>{newItemAlertRenderer ? newItemAlertRenderer(newItemCount, alertY) : this.renderDefaultNewItemAlertComponent(newItemCount, alertY)}</TouchableWithoutFeedback>
)}
{showScrollToEndIndicator && !enabledAutoScrollToEnd && !isEndOfList && <TouchableWithoutFeedback onPress={() => this.scrollToEnd()}>{indicatorComponent ?? this.renderDefaultIndicatorComponent()}</TouchableWithoutFeedback>}
</View>
);
}
/**
* Private Methods
*/
private getTriangleDirection = (): TriangleProps["direction"] => {
const {inverted, horizontal, triangleDirection} = this.props;
let direction: TriangleProps["direction"];
if (horizontal) {
if (inverted) {
direction = "left";
} else {
direction = "right";
}
} else {
if (inverted) {
direction = "up";
} else {
direction = "down";
}
}
return triangleDirection ?? direction;
};
private getScrollToEndIndicatorPosition = () => {
const {inverted, horizontal} = this.props;
return {
top: inverted && !horizontal ? 20 : undefined,
bottom: inverted && !horizontal ? undefined : 20,
left: inverted && horizontal ? 30 : undefined,
right: inverted && horizontal ? undefined : 20,
};
};
private onLayout = (event: LayoutChangeEvent) => {
this.flatListHeight = event.nativeEvent.layout.height;
this.flatListWidth = event.nativeEvent.layout.width;
if (this.listRef.current && this.state.enabledAutoScrollToEnd) {
this.scrollToEnd();
}
// User-defined onLayout event
this.props.onLayout?.(event);
};
private onContentSizeChange = (width: number, height: number) => {
this.contentHeight = height;
this.contentWidth = width;
if (this.state.enabledAutoScrollToEnd) {
this.scrollToEnd();
}
// User-defined onContentSizeChange event
this.props.onContentSizeChange?.(width, height);
};
private onScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
/**
* Default behavior: if scrollTop is at the end of <Flatlist>, autoscroll will be enabled.
* CAVEAT: Android has precision error here from 4 decimal places, therefore we need to use Math.floor() to make sure the calculation is correct on Android.
*/
const prevScrollTop = this.scrollTop;
this.scrollTop = this.props.horizontal ? event.nativeEvent.contentOffset.x : event.nativeEvent.contentOffset.y;
const isScrollingDown = prevScrollTop <= this.scrollTop;
const scrollEnd = this.props.horizontal ? this.contentWidth - this.flatListWidth : this.contentHeight - this.flatListHeight;
const isEndOfList = this.scrollTop + this.props.threshold >= Math.floor(scrollEnd);
this.setState({isEndOfList, enabledAutoScrollToEnd: this.props.autoScrollDisabled ? false : (this.state.enabledAutoScrollToEnd && isScrollingDown) || isEndOfList}, () => {
// User-defined onScroll event
this.props.onScroll?.(event);
});
/**
* Need to check if event.persist is defined before using to account for usage in react-native-web
*/
event.persist?.();
};
private renderDefaultNewItemAlertComponent = (newItemCount: number, translateY: Animated.Value) => {
const {inverted, horizontal, newItemAlertMessage, newItemAlertContainerStyle, newItemAlertTextStyle} = this.props;
const direction = this.getTriangleDirection();
const message = newItemAlertMessage ? newItemAlertMessage(newItemCount) : `${direction === "left" ? " " : ""}${newItemCount} new item${newItemCount > 1 ? "s" : ""}`;
const position = inverted && !horizontal ? {bottom: translateY} : {top: translateY};
return (
<Animated.View style={[styles.newItemAlert, newItemAlertContainerStyle, position]}>
{direction === "left" && <Triangle size={4} direction={direction} />}
<Text style={[styles.alertMessage, newItemAlertTextStyle]}>{message}</Text>
{direction !== "left" && <Triangle size={4} direction={direction} />}
</Animated.View>
);
};
private renderDefaultIndicatorComponent = () => {
const {indicatorContainerStyle} = this.props;
return (
<View style={indicatorContainerStyle ?? [styles.scrollToEndIndicator, this.getScrollToEndIndicatorPosition()]}>
<Triangle direction={this.getTriangleDirection()} />
</View>
);
};
}
const styles = StyleSheet.create({
container: {
flex: 1,
overflow: "hidden",
},
contentContainer: {
alignItems: "stretch",
paddingVertical: 8,
paddingHorizontal: 8,
},
scrollToEndIndicator: {
position: "absolute",
width: 30,
height: 30,
justifyContent: "center",
alignItems: "center",
borderWidth: 1,
borderColor: "#000000",
borderRadius: 5,
backgroundColor: "#ffffff",
},
newItemAlert: {
position: "absolute",
alignSelf: "center",
flexDirection: "row",
alignItems: "center",
borderRadius: 10,
borderWidth: StyleSheet.hairlineWidth,
borderColor: "#000000",
backgroundColor: "#ffffff",
paddingVertical: 3,
paddingHorizontal: 8,
},
alertMessage: {
marginRight: 4,
},
}); | the_stack |
import * as tf from '../index';
import {ALL_ENVS, describeWithFlags} from '../jasmine_util';
import {expectArraysClose, expectArraysEqual} from '../test_util';
describeWithFlags('nonMaxSuppression', ALL_ENVS, () => {
it('select from three clusters', async () => {
const boxes = tf.tensor2d(
[
0, 0, 1, 1, 0, 0.1, 1, 1.1, 0, -0.1, 1, 0.9,
0, 10, 1, 11, 0, 10.1, 1, 11.1, 0, 100, 1, 101
],
[6, 4]);
const scores = tf.tensor1d([0.9, 0.75, 0.6, 0.95, 0.5, 0.3]);
const maxOutputSize = 3;
const iouThreshold = 0.5;
const scoreThreshold = 0;
const indices = tf.image.nonMaxSuppression(
boxes, scores, maxOutputSize, iouThreshold, scoreThreshold);
expect(indices.shape).toEqual([3]);
expectArraysEqual(await indices.data(), [3, 0, 5]);
});
it('select from three clusters flipped coordinates', async () => {
const boxes = tf.tensor2d(
[
1, 1, 0, 0, 0, 0.1, 1, 1.1, 0, .9, 1, -0.1,
0, 10, 1, 11, 1, 10.1, 0, 11.1, 1, 101, 0, 100
],
[6, 4]);
const scores = tf.tensor1d([0.9, 0.75, 0.6, 0.95, 0.5, 0.3]);
const maxOutputSize = 3;
const iouThreshold = 0.5;
const scoreThreshold = 0;
const indices = tf.image.nonMaxSuppression(
boxes, scores, maxOutputSize, iouThreshold, scoreThreshold);
expect(indices.shape).toEqual([3]);
expectArraysEqual(await indices.data(), [3, 0, 5]);
});
it('select at most two boxes from three clusters', async () => {
const boxes = tf.tensor2d(
[
0, 0, 1, 1, 0, 0.1, 1, 1.1, 0, -0.1, 1, 0.9,
0, 10, 1, 11, 0, 10.1, 1, 11.1, 0, 100, 1, 101
],
[6, 4]);
const scores = tf.tensor1d([0.9, 0.75, 0.6, 0.95, 0.5, 0.3]);
const maxOutputSize = 2;
const iouThreshold = 0.5;
const scoreThreshold = 0;
const indices = tf.image.nonMaxSuppression(
boxes, scores, maxOutputSize, iouThreshold, scoreThreshold);
expect(indices.shape).toEqual([2]);
expectArraysEqual(await indices.data(), [3, 0]);
});
it('select at most thirty boxes from three clusters', async () => {
const boxes = tf.tensor2d(
[
0, 0, 1, 1, 0, 0.1, 1, 1.1, 0, -0.1, 1, 0.9,
0, 10, 1, 11, 0, 10.1, 1, 11.1, 0, 100, 1, 101
],
[6, 4]);
const scores = tf.tensor1d([0.9, 0.75, 0.6, 0.95, 0.5, 0.3]);
const maxOutputSize = 30;
const iouThreshold = 0.5;
const scoreThreshold = 0;
const indices = tf.image.nonMaxSuppression(
boxes, scores, maxOutputSize, iouThreshold, scoreThreshold);
expect(indices.shape).toEqual([3]);
expectArraysEqual(await indices.data(), [3, 0, 5]);
});
it('select single box', async () => {
const boxes = tf.tensor2d([0, 0, 1, 1], [1, 4]);
const scores = tf.tensor1d([0.9]);
const maxOutputSize = 3;
const iouThreshold = 0.5;
const scoreThreshold = 0;
const indices = tf.image.nonMaxSuppression(
boxes, scores, maxOutputSize, iouThreshold, scoreThreshold);
expect(indices.shape).toEqual([1]);
expectArraysEqual(await indices.data(), [0]);
});
it('select from ten identical boxes', async () => {
const boxes = tf.tensor2d([0, 0, 1, 1], [1, 4]);
const scores = tf.tensor1d([0.9]);
const maxOutputSize = 3;
const iouThreshold = 0.5;
const scoreThreshold = 0;
const indices = tf.image.nonMaxSuppression(
boxes, scores, maxOutputSize, iouThreshold, scoreThreshold);
expect(indices.shape).toEqual([1]);
expectArraysEqual(await indices.data(), [0]);
});
it('select from ten identical boxes', async () => {
const numBoxes = 10;
const corners = new Array(numBoxes)
.fill(0)
.map(_ => [0, 0, 1, 1])
.reduce((arr, curr) => arr.concat(curr));
const boxes = tf.tensor2d(corners, [numBoxes, 4]);
const scores = tf.tensor1d(Array(numBoxes).fill(0.9));
const maxOutputSize = 3;
const iouThreshold = 0.5;
const scoreThreshold = 0;
const indices = tf.image.nonMaxSuppression(
boxes, scores, maxOutputSize, iouThreshold, scoreThreshold);
expect(indices.shape).toEqual([1]);
expectArraysEqual(await indices.data(), [0]);
});
it('inconsistent box and score shapes', () => {
const boxes = tf.tensor2d(
[
0, 0, 1, 1, 0, 0.1, 1, 1.1, 0, -0.1, 1, 0.9,
0, 10, 1, 11, 0, 10.1, 1, 11.1, 0, 100, 1, 101
],
[6, 4]);
const scores = tf.tensor1d([0.9, 0.75, 0.6, 0.95, 0.5]);
const maxOutputSize = 30;
const iouThreshold = 0.5;
const scoreThreshold = 0;
expect(
() => tf.image.nonMaxSuppression(
boxes, scores, maxOutputSize, iouThreshold, scoreThreshold))
.toThrowError(/scores has incompatible shape with boxes/);
});
it('invalid iou threshold', () => {
const boxes = tf.tensor2d([0, 0, 1, 1], [1, 4]);
const scores = tf.tensor1d([0.9]);
const maxOutputSize = 3;
const iouThreshold = 1.2;
const scoreThreshold = 0;
expect(
() => tf.image.nonMaxSuppression(
boxes, scores, maxOutputSize, iouThreshold, scoreThreshold))
.toThrowError(/iouThreshold must be in \[0, 1\]/);
});
it('empty input', async () => {
const boxes = tf.tensor2d([], [0, 4]);
const scores = tf.tensor1d([]);
const maxOutputSize = 3;
const iouThreshold = 0.5;
const scoreThreshold = 0;
const indices = tf.image.nonMaxSuppression(
boxes, scores, maxOutputSize, iouThreshold, scoreThreshold);
expect(indices.shape).toEqual([0]);
expectArraysEqual(await indices.data(), []);
});
it('accepts a tensor-like object', async () => {
const boxes = [[0, 0, 1, 1], [0, 1, 1, 2]];
const scores = [1, 2];
const indices = tf.image.nonMaxSuppression(boxes, scores, 10);
expect(indices.shape).toEqual([2]);
expect(indices.dtype).toEqual('int32');
expectArraysEqual(await indices.data(), [1, 0]);
});
});
describeWithFlags('nonMaxSuppressionAsync', ALL_ENVS, () => {
it('select from three clusters', async () => {
const boxes = tf.tensor2d(
[
0, 0, 1, 1, 0, 0.1, 1, 1.1, 0, -0.1, 1, 0.9,
0, 10, 1, 11, 0, 10.1, 1, 11.1, 0, 100, 1, 101
],
[6, 4]);
const scores = tf.tensor1d([0.9, 0.75, 0.6, 0.95, 0.5, 0.3]);
const maxOutputSize = 3;
const iouThreshold = 0.5;
const scoreThreshold = 0;
const indices = await tf.image.nonMaxSuppressionAsync(
boxes, scores, maxOutputSize, iouThreshold, scoreThreshold);
expect(indices.shape).toEqual([3]);
expectArraysEqual(await indices.data(), [3, 0, 5]);
});
it('accepts a tensor-like object', async () => {
const boxes = [[0, 0, 1, 1], [0, 1, 1, 2]];
const scores = [1, 2];
const indices = await tf.image.nonMaxSuppressionAsync(boxes, scores, 10);
expect(indices.shape).toEqual([2]);
expect(indices.dtype).toEqual('int32');
expectArraysEqual(await indices.data(), [1, 0]);
});
});
describeWithFlags('cropAndResize', ALL_ENVS, () => {
it('1x1-bilinear', async () => {
const image: tf.Tensor4D = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]);
const boxes: tf.Tensor2D = tf.tensor2d([0, 0, 1, 1], [1, 4]);
const boxInd: tf.Tensor1D = tf.tensor1d([0], 'int32');
const output =
tf.image.cropAndResize(image, boxes, boxInd, [1, 1], 'bilinear', 0);
expect(output.shape).toEqual([1, 1, 1, 1]);
expectArraysClose(await output.data(), [2.5]);
});
it('1x1-nearest', async () => {
const image: tf.Tensor4D = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]);
const boxes: tf.Tensor2D = tf.tensor2d([0, 0, 1, 1], [1, 4]);
const boxInd: tf.Tensor1D = tf.tensor1d([0], 'int32');
const output =
tf.image.cropAndResize(image, boxes, boxInd, [1, 1], 'nearest', 0);
expect(output.shape).toEqual([1, 1, 1, 1]);
expectArraysClose(await output.data(), [4.0]);
});
it('1x1Flipped-bilinear', async () => {
const image: tf.Tensor4D = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]);
const boxes: tf.Tensor2D = tf.tensor2d([1, 1, 0, 0], [1, 4]);
const boxInd: tf.Tensor1D = tf.tensor1d([0], 'int32');
const output =
tf.image.cropAndResize(image, boxes, boxInd, [1, 1], 'bilinear', 0);
expect(output.shape).toEqual([1, 1, 1, 1]);
expectArraysClose(await output.data(), [2.5]);
});
it('1x1Flipped-nearest', async () => {
const image: tf.Tensor4D = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]);
const boxes: tf.Tensor2D = tf.tensor2d([1, 1, 0, 0], [1, 4]);
const boxInd: tf.Tensor1D = tf.tensor1d([0], 'int32');
const output =
tf.image.cropAndResize(image, boxes, boxInd, [1, 1], 'nearest', 0);
expect(output.shape).toEqual([1, 1, 1, 1]);
expectArraysClose(await output.data(), [4.0]);
});
it('3x3-bilinear', async () => {
const image: tf.Tensor4D = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]);
const boxes: tf.Tensor2D = tf.tensor2d([0, 0, 1, 1], [1, 4]);
const boxInd: tf.Tensor1D = tf.tensor1d([0], 'int32');
const output =
tf.image.cropAndResize(image, boxes, boxInd, [3, 3], 'bilinear', 0);
expect(output.shape).toEqual([1, 3, 3, 1]);
expectArraysClose(await output.data(), [1, 1.5, 2, 2, 2.5, 3, 3, 3.5, 4]);
});
it('3x3-nearest', async () => {
const image: tf.Tensor4D = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]);
const boxes: tf.Tensor2D = tf.tensor2d([0, 0, 1, 1], [1, 4]);
const boxInd: tf.Tensor1D = tf.tensor1d([0], 'int32');
const output =
tf.image.cropAndResize(image, boxes, boxInd, [3, 3], 'nearest', 0);
expect(output.shape).toEqual([1, 3, 3, 1]);
expectArraysClose(await output.data(), [1, 2, 2, 3, 4, 4, 3, 4, 4]);
});
it('3x3Flipped-bilinear', async () => {
const image: tf.Tensor4D = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]);
const boxes: tf.Tensor2D = tf.tensor2d([1, 1, 0, 0], [1, 4]);
const boxInd: tf.Tensor1D = tf.tensor1d([0], 'int32');
const output =
tf.image.cropAndResize(image, boxes, boxInd, [3, 3], 'bilinear', 0);
expect(output.shape).toEqual([1, 3, 3, 1]);
expectArraysClose(await output.data(), [4, 3.5, 3, 3, 2.5, 2, 2, 1.5, 1]);
});
it('3x3Flipped-nearest', async () => {
const image: tf.Tensor4D = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]);
const boxes: tf.Tensor2D = tf.tensor2d([1, 1, 0, 0], [1, 4]);
const boxInd: tf.Tensor1D = tf.tensor1d([0], 'int32');
const output =
tf.image.cropAndResize(image, boxes, boxInd, [3, 3], 'nearest', 0);
expect(output.shape).toEqual([1, 3, 3, 1]);
expectArraysClose(await output.data(), [4, 4, 3, 4, 4, 3, 2, 2, 1]);
});
it('3x3to2x2-bilinear', async () => {
const image: tf.Tensor4D =
tf.tensor4d([1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 3, 3, 1]);
const boxes: tf.Tensor2D =
tf.tensor2d([0, 0, 1, 1, 0, 0, 0.5, 0.5], [2, 4]);
const boxInd: tf.Tensor1D = tf.tensor1d([0, 0], 'int32');
const output =
tf.image.cropAndResize(image, boxes, boxInd, [2, 2], 'bilinear', 0);
expect(output.shape).toEqual([2, 2, 2, 1]);
expectArraysClose(await output.data(), [1, 3, 7, 9, 1, 2, 4, 5]);
});
it('3x3to2x2-nearest', async () => {
const image: tf.Tensor4D =
tf.tensor4d([1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 3, 3, 1]);
const boxes: tf.Tensor2D =
tf.tensor2d([0, 0, 1, 1, 0, 0, 0.5, 0.5], [2, 4]);
const boxInd: tf.Tensor1D = tf.tensor1d([0, 0], 'int32');
const output =
tf.image.cropAndResize(image, boxes, boxInd, [2, 2], 'nearest', 0);
expect(output.shape).toEqual([2, 2, 2, 1]);
expectArraysClose(await output.data(), [1, 3, 7, 9, 1, 2, 4, 5]);
});
it('3x3to2x2Flipped-bilinear', async () => {
const image: tf.Tensor4D =
tf.tensor4d([1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 3, 3, 1]);
const boxes: tf.Tensor2D =
tf.tensor2d([1, 1, 0, 0, 0.5, 0.5, 0, 0], [2, 4]);
const boxInd: tf.Tensor1D = tf.tensor1d([0, 0], 'int32');
const output =
tf.image.cropAndResize(image, boxes, boxInd, [2, 2], 'bilinear', 0);
expect(output.shape).toEqual([2, 2, 2, 1]);
expectArraysClose(await output.data(), [9, 7, 3, 1, 5, 4, 2, 1]);
});
it('3x3to2x2Flipped-nearest', async () => {
const image: tf.Tensor4D =
tf.tensor4d([1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 3, 3, 1]);
const boxes: tf.Tensor2D =
tf.tensor2d([1, 1, 0, 0, 0.5, 0.5, 0, 0], [2, 4]);
const boxInd: tf.Tensor1D = tf.tensor1d([0, 0], 'int32');
const output =
tf.image.cropAndResize(image, boxes, boxInd, [2, 2], 'nearest', 0);
expect(output.shape).toEqual([2, 2, 2, 1]);
expectArraysClose(await output.data(), [9, 7, 3, 1, 5, 4, 2, 1]);
});
it('3x3-BoxisRectangular', async () => {
const image: tf.Tensor4D = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]);
const boxes: tf.Tensor2D = tf.tensor2d([0, 0, 1, 1.5], [1, 4]);
const boxInd: tf.Tensor1D = tf.tensor1d([0], 'int32');
const output =
tf.image.cropAndResize(image, boxes, boxInd, [3, 3], 'bilinear', 0);
expect(output.shape).toEqual([1, 3, 3, 1]);
expectArraysClose(
await output.data(), [1, 1.75, 0, 2, 2.75, 0, 3, 3.75, 0]);
});
it('3x3-BoxisRectangular-nearest', async () => {
const image: tf.Tensor4D = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]);
const boxes: tf.Tensor2D = tf.tensor2d([0, 0, 1, 1.5], [1, 4]);
const boxInd: tf.Tensor1D = tf.tensor1d([0], 'int32');
const output =
tf.image.cropAndResize(image, boxes, boxInd, [3, 3], 'nearest', 0);
expect(output.shape).toEqual([1, 3, 3, 1]);
expectArraysClose(await output.data(), [1, 2, 0, 3, 4, 0, 3, 4, 0]);
});
it('2x2to3x3-Extrapolated', async () => {
const val = -1;
const image: tf.Tensor4D = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]);
const boxes: tf.Tensor2D = tf.tensor2d([-1, -1, 1, 1], [1, 4]);
const boxInd: tf.Tensor1D = tf.tensor1d([0], 'int32');
const output =
tf.image.cropAndResize(image, boxes, boxInd, [3, 3], 'bilinear', val);
expect(output.shape).toEqual([1, 3, 3, 1]);
expectArraysClose(
await output.data(), [val, val, val, val, 1, 2, val, 3, 4]);
});
it('2x2to3x3-Extrapolated-Float', async () => {
const val = -1.5;
const image: tf.Tensor4D = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]);
const boxes: tf.Tensor2D = tf.tensor2d([-1, -1, 1, 1], [1, 4]);
const boxInd: tf.Tensor1D = tf.tensor1d([0], 'int32');
const output =
tf.image.cropAndResize(image, boxes, boxInd, [3, 3], 'bilinear', val);
expect(output.shape).toEqual([1, 3, 3, 1]);
expectArraysClose(
await output.data(), [val, val, val, val, 1, 2, val, 3, 4]);
});
it('2x2to3x3-NoCrop', async () => {
const val = -1.0;
const image: tf.Tensor4D = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]);
const boxes: tf.Tensor2D = tf.tensor2d([], [0, 4]);
const boxInd: tf.Tensor1D = tf.tensor1d([], 'int32');
const output =
tf.image.cropAndResize(image, boxes, boxInd, [3, 3], 'bilinear', val);
expect(output.shape).toEqual([0, 3, 3, 1]);
expectArraysClose(await output.data(), []);
});
it('MultipleBoxes-DifferentBoxes', async () => {
const image: tf.Tensor4D =
tf.tensor4d([1, 2, 3, 4, 5, 6, 7, 8], [2, 2, 2, 1]);
const boxes: tf.Tensor2D =
tf.tensor2d([0, 0, 1, 1.5, 0, 0, 1.5, 1], [2, 4]);
const boxInd: tf.Tensor1D = tf.tensor1d([0, 1], 'int32');
const output =
tf.image.cropAndResize(image, boxes, boxInd, [3, 3], 'bilinear', 0);
expect(output.shape).toEqual([2, 3, 3, 1]);
expectArraysClose(
await output.data(),
[1, 1.75, 0, 2, 2.75, 0, 3, 3.75, 0, 5, 5.5, 6, 6.5, 7, 7.5, 0, 0, 0]);
});
it('MultipleBoxes-DifferentBoxes-Nearest', async () => {
const image: tf.Tensor4D =
tf.tensor4d([1, 2, 3, 4, 5, 6, 7, 8], [2, 2, 2, 1]);
const boxes: tf.Tensor2D = tf.tensor2d([0, 0, 1, 1.5, 0, 0, 2, 1], [2, 4]);
const boxInd: tf.Tensor1D = tf.tensor1d([0, 1], 'int32');
const output =
tf.image.cropAndResize(image, boxes, boxInd, [3, 3], 'nearest', 0);
expect(output.shape).toEqual([2, 3, 3, 1]);
expectArraysClose(
await output.data(),
[1, 2, 0, 3, 4, 0, 3, 4, 0, 5, 6, 6, 7, 8, 8, 0, 0, 0]);
});
}); | the_stack |
import { ArrayExt } from '@lumino/algorithm';
import { ISignal, Signal } from '@lumino/signaling';
export class Selection<T> {
constructor(sequence: ReadonlyArray<T>, options: Selection.IOptions = {}) {
this._array = sequence;
this._insertBehavior = options.insertBehavior || 'select-item-if-needed';
this._removeBehavior = options.removeBehavior || 'select-item-after';
}
/**
* A signal emitted when the current item is changed.
*
* #### Notes
* This signal is emitted when the currently selected item is changed either
* through user or programmatic interaction.
*
* Notably, this signal is not emitted when the index of the current item
* changes due to other items being inserted, removed, or moved, but the
* current item remains the same. It is only emitted when the actual current
* item is changed.
*/
get selectionChanged(): ISignal<
Selection<T>,
Selection.ISelectionChangedArgs<T>
> {
return this._selectionChanged;
}
/**
* Adjust for setting an item.
*
* This should be called *after* the set.
*
* @param index - The index set.
* @param oldValue - The old value at the index.
*/
adjustSelectionForSet(index: number): void {
// We just need to send a signal if the currentValue changed.
// Get the current index and value.
const pi = this.index;
const pv = this.value;
// Exit early if this doesn't affect the selection
if (index !== pi) {
return;
}
this._updateSelectedValue();
const cv = this.value;
// The previous item is now null, since it is no longer in the array.
this._previousValue = null;
// Send signal if there was a change
if (pv !== cv) {
// Emit the current changed signal.
this._selectionChanged.emit({
previousIndex: pi,
previousValue: pv,
currentIndex: pi,
currentValue: cv,
});
}
}
/**
* Get the currently selected item.
*
* #### Notes
* This will be `null` if no item is selected.
*/
get value(): T | null {
return this._value;
}
/**
* Set the currently selected item.
*
* #### Notes
* If the item does not exist in the vector, the currentValue will be set to
* `null`. This selects the first entry equal to the desired item.
*/
set value(value: T | null) {
if (value === null || this._array === null) {
this.index = null;
} else {
this.index = ArrayExt.firstIndexOf(this._array, value);
}
}
/**
* Get the index of the currently selected item.
*
* #### Notes
* This will be `null` if no item is selected.
*/
get index(): number | null {
return this._index;
}
/**
* Set the index of the currently selected tab.
*
* @param index - The index to select.
*
* #### Notes
* If the value is out of range, the index will be set to `null`, which
* indicates no item is selected.
*/
set index(index: number | null) {
// Coerce the value to an index.
let i;
if (index !== null && this._array !== null) {
i = Math.floor(index);
if (i < 0 || i >= this._array.length) {
i = null;
}
} else {
i = null;
}
// Bail early if the index will not change.
if (this._index === i) {
return;
}
// Look up the previous index and item.
const pi = this._index;
const pv = this._value;
// Update the state
this._index = i;
this._updateSelectedValue();
this._previousValue = pv;
// Emit the current changed signal.
this._selectionChanged.emit({
previousIndex: pi,
previousValue: pv,
currentIndex: i,
currentValue: this._value,
});
}
/**
* Get the selection behavior when inserting a tab.
*/
get insertBehavior(): Selection.InsertBehavior {
return this._insertBehavior;
}
/**
* Set the selection behavior when inserting a tab.
*/
set insertBehavior(value: Selection.InsertBehavior) {
this._insertBehavior = value;
}
/**
* Get the selection behavior when removing a tab.
*/
get removeBehavior(): Selection.RemoveBehavior {
return this._removeBehavior;
}
/**
* Set the selection behavior when removing a tab.
*/
set removeBehavior(value: Selection.RemoveBehavior) {
this._removeBehavior = value;
}
/**
* Adjust the current index for a tab insert operation.
*
* @param i - The new index of the inserted item.
* @param j - The inserted item.
*
* #### Notes
* This method accounts for the tab bar's insertion behavior when adjusting
* the current index and emitting the changed signal. This should be called
* after the insertion.
*/
adjustSelectionForInsert(i: number, item: T): void {
// Lookup commonly used variables.
const cv = this._value;
const ci = this._index;
const bh = this._insertBehavior;
// Handle the behavior where the new item is always selected,
// or the behavior where the new item is selected if needed.
if (
bh === 'select-item' ||
(bh === 'select-item-if-needed' && ci === null)
) {
this._index = i;
this._value = item;
this._previousValue = cv;
this._selectionChanged.emit({
previousIndex: ci,
previousValue: cv,
currentIndex: i,
currentValue: item,
});
return;
}
// Otherwise, silently adjust the current index if needed.
if (ci !== null && ci >= i) {
this._index!++;
}
}
/**
* Clear the selection and history.
*/
clearSelection(): void {
// Get the current index and item.
const pi = this._index;
const pv = this._value;
// Reset the current index and previous item.
this._index = null;
this._value = null;
this._previousValue = null;
// If no item was selected, there's nothing else to do.
if (pi === null) {
return;
}
// Emit the current changed signal.
this._selectionChanged.emit({
previousIndex: pi,
previousValue: pv,
currentIndex: this._index,
currentValue: this._value,
});
}
/**
* Adjust the current index for an item remove operation.
*
* @param i - The former index of the removed item.
* @param item - The removed item.
*
* #### Notes
* This method accounts for the remove behavior when adjusting the current
* index and emitting the changed signal. It should be called after the item
* is removed.
*/
adjustSelectionForRemove(i: number, item: T | null): void {
// If we have no selection, there is nothing to do
if (this._index === null) {
return;
}
// Lookup commonly used variables.
const ci = this._index;
const bh = this._removeBehavior;
// Silently adjust the index if the current item is not removed.
if (ci !== i) {
if (ci > i) {
this._index!--;
}
return;
}
// No item gets selected if the vector is empty.
if (!this._array || this._array.length === 0) {
// Reset the current index and previous item.
this._index = null;
this._value = null;
this._previousValue = null;
this._selectionChanged.emit({
previousIndex: i,
previousValue: item,
currentIndex: this._index,
currentValue: this._value,
});
return;
}
// Handle behavior where the next sibling item is selected.
if (bh === 'select-item-after') {
this._index = Math.min(i, this._array.length - 1);
this._updateSelectedValue();
this._previousValue = null;
this._selectionChanged.emit({
previousIndex: i,
previousValue: item,
currentIndex: this._index,
currentValue: this._value,
});
return;
}
// Handle behavior where the previous sibling item is selected.
if (bh === 'select-item-before') {
this._index = Math.max(0, i - 1);
this._updateSelectedValue();
this._previousValue = null;
this._selectionChanged.emit({
previousIndex: i,
previousValue: item,
currentIndex: this._index,
currentValue: this._value,
});
return;
}
// Handle behavior where the previous history item is selected.
if (bh === 'select-previous-item') {
if (this._previousValue) {
this.value = this._previousValue;
} else {
this._index = Math.min(i, this._array.length - 1);
this._updateSelectedValue();
}
this._previousValue = null;
this._selectionChanged.emit({
previousIndex: i,
previousValue: item,
currentIndex: this._index,
currentValue: this.value,
});
return;
}
// Otherwise, no item gets selected.
this._index = null;
this._value = null;
this._previousValue = null;
this._selectionChanged.emit({
previousIndex: i,
previousValue: item,
currentIndex: this._index,
currentValue: this._value,
});
}
/**
* Set the current value based on the current index.
*/
private _updateSelectedValue(): void {
const i = this._index;
this._value = i !== null && this._array ? this._array[i] : null;
}
private _array: ReadonlyArray<T> | null = null;
private _index: number | null;
private _value: T | null = null;
private _previousValue: T | null = null;
private _insertBehavior: Selection.InsertBehavior;
private _removeBehavior: Selection.RemoveBehavior;
private _selectionChanged = new Signal<
Selection<T>,
Selection.ISelectionChangedArgs<T>
>(this);
}
export namespace Selection {
/**
* An options object for creating a tab bar.
*/
export interface IOptions {
/**
* The selection behavior when inserting a tab.
*
* The default is `'select-tab-if-needed'`.
*/
insertBehavior?: Selection.InsertBehavior;
/**
* The selection behavior when removing a tab.
*
* The default is `'select-tab-after'`.
*/
removeBehavior?: Selection.RemoveBehavior;
}
/**
* The arguments object for the `currentChanged` signal.
*/
export interface ISelectionChangedArgs<T> {
/**
* The previously selected index.
*/
previousIndex: number | null;
/**
* The previous selected item.
*/
previousValue: T | null;
/**
* The currently selected index.
*/
currentIndex: number | null;
/**
* The currently selected item.
*/
currentValue: T | null;
}
/**
* A type alias for the selection behavior on item insert.
*/
export type InsertBehavior =
/**
* The selected item will not be changed.
*/
| 'none'
/**
* The inserted item will be selected.
*/
| 'select-item'
/**
* The inserted item will be selected if the current item is null.
*/
| 'select-item-if-needed';
/**
* A type alias for the selection behavior on item remove.
*/
export type RemoveBehavior =
/**
* No item will be selected.
*/
| 'none'
/**
* The item after the removed item will be selected if possible.
*/
| 'select-item-after'
/**
* The item before the removed item will be selected if possible.
*/
| 'select-item-before'
/**
* The previously selected item will be selected if possible.
*/
| 'select-previous-item';
} | the_stack |
import {defaultsDeep} from 'lodash';
import * as _joint from 'jointjs';
// Loaded joint additions
import '../../shared/support/shared-shapes';
const joint: any = _joint;
const ERROR_MARKER_SIZE = {width: 20, height: 20};
const START_NODE_SIZE = {width: 15, height: 15};
const END_NODE_SIZE = {width: 20, height: 20};
const PORT_RADIUS = 7;
export const NODE_ROUNDED_CORNER = 8;
export const NODE_ROUNDED_CORNER_PALETTE = 3;
export const IMAGE_W = 180;
export const IMAGE_H = 64;
export const CONTROL_GROUP_TYPE = 'control nodes';
export const TASK_GROUP_TYPE = 'task';
export const START_NODE_TYPE = 'START';
export const END_NODE_TYPE = 'END';
export const SYNC_NODE_TYPE = 'SYNC';
export const TaskAppShape = joint.shapes.basic.Generic.extend({
defaults: defaultsDeep(
{
type: joint.shapes.flo.NODE_TYPE,
position: {x: 0, y: 0},
size: {width: IMAGE_W, height: IMAGE_H},
attrs: {
'.': {magnet: false},
'.box': {
refWidth: 1,
refHeight: 1,
rx: NODE_ROUNDED_CORNER,
ry: NODE_ROUNDED_CORNER
},
'.palette-entry-name-label': {
refX: 10, // jointjs specific: relative position to ref'd element
refY: 0.5,
'y-alignment': 'middle',
ref: '.box' // jointjs specific: element for ref-x, ref-y
},
'.name-label': {
refX: 0.5,
refY: 0.5,
'y-alignment': 'middle',
'x-alignment': 'middle',
ref: '.box'
},
'.type-label': {
refX: '50%',
refY: 0.5,
refY2: 2,
'y-alignment': 'top',
'x-alignment': 'middle',
ref: '.box', // jointjs specific: element for ref-x, ref-y
text: 'UNRESOLVED'
},
'.type-label-bg': {
ref: '.type-label',
refX: -10,
refY: -3,
refWidth: 20,
rx: 11,
ry: 11,
refHeight: 6
},
'.error-marker': {
width: ERROR_MARKER_SIZE.width,
height: ERROR_MARKER_SIZE.height,
ref: '.box',
refX: '100%',
refX2: -ERROR_MARKER_SIZE.width,
refY: 0
},
'.output-port': {
port: 'output',
magnet: true
},
'.port-outer-circle-output': {
ref: '.box',
refCx: '50%',
refCy: '100%',
r: PORT_RADIUS,
class: 'port-outer-circle-output flo-port'
},
'.port-inner-circle-output': {
ref: '.box',
refCx: '50%',
refCy: '100%',
r: PORT_RADIUS - 4,
class: 'port-inner-circle-output flo-port-inner-circle'
},
'.input-port': {
port: 'input',
magnet: true
},
'.port-outer-circle-input': {
ref: '.box',
refCx: '50%',
refCy: 0,
r: PORT_RADIUS,
class: 'port-outer-circle-input flo-port'
},
'.port-inner-circle-input': {
ref: '.box',
refCx: '50%',
refCy: 0,
r: PORT_RADIUS - 4,
class: 'port-inner-circle-input flo-port-inner-circle'
},
'.select-outline': {
ref: '.box',
refWidth: 1,
refHeight: 1,
rx: NODE_ROUNDED_CORNER,
ry: NODE_ROUNDED_CORNER
},
'.options-handle': {
text: 'Options',
ref: '.box',
refX: 0,
refY: -5,
yAlignment: 'bottom'
},
'.delete-handle': {
text: 'Delete',
ref: '.box',
refX: '100%',
refY: -5,
yAlignment: 'bottom',
textAnchor: 'end'
},
'.shape': {}
}
},
joint.shapes.basic.Generic.prototype.defaults
)
});
export const BatchStartShape = joint.shapes.basic.Generic.extend({
defaults: defaultsDeep(
{
size: START_NODE_SIZE,
attrs: {
'.start-outer': {
magnet: true,
port: 'output',
r: START_NODE_SIZE.width / 2,
refCx: 0.5,
refCy: 0.5
},
'.start-inner': {
r: START_NODE_SIZE.width / 4,
refCx: 0.5,
refCy: 0.5
},
'.select-outline': {
r: START_NODE_SIZE.width / 2,
refCx: 0.5,
refCy: 0.5
},
'.name-label': {
ref: '.start-outer',
refX: 0.5,
refY: -5,
xAlignment: 'middle',
yAlignment: 'bottom'
},
'.options-handle': {
ref: '.start-outer',
text: 'Options',
refX: '100%',
refX2: 10,
refY: '50%',
yAlignment: 'middle'
},
'.error-marker': {
width: ERROR_MARKER_SIZE.width,
height: ERROR_MARKER_SIZE.height,
ref: '.start-outer',
refX: '100%',
refY: 0
},
'.shape': {}
}
},
joint.shapes.basic.Generic.prototype.defaults
)
});
export const BatchEndShape = joint.shapes.basic.Generic.extend({
defaults: defaultsDeep(
{
size: END_NODE_SIZE,
attrs: {
'.end-inner': {
refRx: '35%',
refRy: '35%',
refCx: 0.5,
refCy: 0.5
},
'.end-outer': {
refRx: '50%',
refRy: '50%',
refCx: 0.5,
refCy: 0.5,
magnet: true,
port: 'input'
},
'.name-label': {
refX: '50%',
refY: '100%',
refY2: 15,
xAlignment: 'middle',
yAlignment: 'top',
ref: '.end-outer'
},
'.select-outline': {
refRx: '50%',
refRy: '50%',
refCx: 0.5,
refCy: 0.5
},
'.error-marker': {
width: ERROR_MARKER_SIZE.width,
height: ERROR_MARKER_SIZE.height,
ref: '.shape',
refX: '100%',
refY: '100%'
// refX2: - ERROR_MARKER_SIZE.width,
},
'.shape': {}
}
},
joint.shapes.basic.Generic.prototype.defaults
)
});
export const BatchSyncShape = joint.shapes.basic.Generic.extend({
defaults: defaultsDeep(
{
type: joint.shapes.flo.NODE_TYPE,
size: {width: 50, height: 20},
attrs: {
'.box': {
refRx: '20%',
refRy: '50%',
refWidth: '100%',
refHeight: '100%'
},
'.select-outline': {
refRx: '20%',
refRy: '50%',
refWidth: '100%',
refHeight: '100%'
},
'.name-label': {
refX: '50%',
refY: '50%',
xAlignment: 'middle',
yAlignment: 'middle',
ref: '.box'
},
'.palette-entry-name-label': {
refX: '50%',
refY: '50%',
xAlignment: 'middle',
yAlignment: 'middle',
ref: '.box'
},
'.delete-handle': {
text: 'Delete',
ref: '.box',
refX: '100%',
refY: -5,
yAlignment: 'bottom',
textAnchor: 'end'
},
'.error-marker': {
width: ERROR_MARKER_SIZE.width,
height: ERROR_MARKER_SIZE.height,
ref: '.box',
refX: '100%',
refX2: -5 - ERROR_MARKER_SIZE.width,
refY: 5
},
'.output-port': {
port: 'output',
magnet: true
},
'.port-outer-circle-output': {
ref: '.box',
refCx: '50%',
refCy: '100%',
r: PORT_RADIUS,
class: 'port-outer-circle-output flo-port'
},
'.port-inner-circle-output': {
ref: '.box',
refCx: '50%',
refCy: '100%',
r: PORT_RADIUS - 3,
class: 'port-inner-circle-output flo-port-inner-circle'
},
'.input-port': {
port: 'input',
magnet: true
},
'.port-outer-circle-input': {
ref: '.box',
refCx: '50%',
refCy: 0,
r: PORT_RADIUS,
class: 'port-outer-circle-input flo-port'
},
'.port-inner-circle-input': {
ref: '.box',
refCx: '50%',
refCy: 0,
r: PORT_RADIUS - 3,
class: 'port-inner-circle-input flo-port-inner-circle'
},
'.shape': {}
}
},
joint.shapes.basic.Generic.prototype.defaults
)
});
export const BatchLink = joint.shapes.flo.Link.extend({
toolMarkup: [
'<g class="link-tool composed-task">',
'<g class="tool-remove" event="remove">',
'<rect class="link-tools-container" width="47" height="22" transform="translate(-11 -11)"/>',
'<circle r="11" />',
'<path transform="scale(.8) translate(-16, -16)" d="M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 ' +
'16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z"/>',
'<titleModal>Remove link.</titleModal>',
'</g>',
'<g class="tool-options" event="link:options">',
'<circle r="11" transform="translate(25)"/>',
'<path fill="white" transform="scale(.7) translate(20, -16)" d="M31.229,17.736c0.064-0.571,0.104-1.148,0.104-' +
'1.736s-0.04-1.166-0.104-1.737l-4.377-1.557c-0.218-0.716-0.504-1.401-0.851-2.05l1.993-4.192c-0.725-0.91-' +
'1.549-1.734-2.458-2.459l-4.193,1.994c-0.647-0.347-1.334-0.632-2.049-0.849l-1.558-4.378C17.165,0.708,16.588,' +
'0.667,16,0.667s-1.166,0.041-1.737,0.105L12.707,5.15c-0.716,0.217-1.401,0.502-2.05,0.849L6.464,4.005C5.554,' +
'4.73,4.73,5.554,4.005,6.464l1.994,4.192c-0.347,0.648-0.632,1.334-0.849,2.05l-4.378,1.557C0.708,14.834,0.667,' +
'15.412,0.667,16s0.041,1.165,0.105,1.736l4.378,1.558c0.217,0.715,0.502,1.401,0.849,2.049l-1.994,4.193c0.725,' +
'0.909,1.549,1.733,2.459,2.458l4.192-1.993c0.648,0.347,1.334,0.633,2.05,0.851l1.557,4.377c0.571,0.064,1.148,' +
'0.104,1.737,0.104c0.588,0,1.165-0.04,1.736-0.104l1.558-4.377c0.715-0.218,1.399-0.504,2.049-0.851l4.193,' +
'1.993c0.909-0.725,1.733-1.549,2.458-2.458l-1.993-4.193c0.347-0.647,0.633-1.334,0.851-2.049L31.229,17.736zM16,' +
'20.871c-2.69,0-4.872-2.182-4.872-4.871c0-2.69,2.182-4.872,4.872-4.872c2.689,0,4.871,2.182,4.871,4.872C20.871,' +
'18.689,18.689,20.871,16,20.871z"/>',
'<titleModal>Properties</titleModal>',
'</g>',
'</g>'
].join(''),
arrowheadMarkup: [
'<g class="marker-arrowhead-group marker-arrowhead-group-<%= end %>">',
'<path class="marker-arrowhead" end="<%= end %>" d="M 16 0 L 0 8 L 16 16 z" />',
'</g>'
].join(''),
vertexMarkup: [
'<g class="marker-vertex-group" transform="translate(<%= x %>, <%= y %>)">',
'<circle class="marker-vertex" idx="<%= idx %>" r="8" />',
'<path class="marker-vertex-remove-area" idx="<%= idx %>" d="M16,5.333c-7.732,0-14,4.701-14,10.5c0,1.982,0.741,' +
'3.833,2.016,5.414L2,25.667l5.613-1.441c2.339,1.317,5.237,2.107,8.387,2.107c7.732,0,14-4.701,14-10.5C30,10.034,' +
'23.732,5.333,16,5.333z" transform="translate(5, -33)"/>',
'<path class="marker-vertex-remove" idx="<%= idx %>" transform="scale(.8) translate(8.5, -37)" d="M24.778,21.419 ' +
'19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 ' +
'10.946,24.248 16.447,18.746 21.948,24.248z">',
'<titleModal>Remove vertex.</titleModal>',
'</path>',
'</g>'
].join(''),
defaults: defaultsDeep(
{
attrs: {
'.connection': {'stroke-linecap': 'round'},
'.marker-target': {d: 'M 5 0 L 0.67, 2.5 L 5 5 z', 'stroke-width': 3},
props: {}
}
},
joint.shapes.flo.Link.prototype.defaults
)
}); | the_stack |
import {
ActionTypes,
Activity,
ActivityTypes,
CardFactory,
Channels,
ConversationState,
InputHints,
MemoryStorage,
StatePropertyAccessor,
StatusCodes,
TeamsChannelAccount,
TestAdapter,
tokenExchangeOperationName,
verifyStateOperationName,
} from "botbuilder-core";
import { DialogSet, DialogState, DialogTurnStatus } from "botbuilder-dialogs";
import {
TeamsBotSsoPrompt,
TeamsBotSsoPromptTokenResponse,
OnBehalfOfUserCredential,
ErrorWithCode,
ErrorCode,
TeamsBotSsoPromptSettings,
loadConfiguration,
Configuration,
} from "../../../../src";
import { assert, expect, use as chaiUse } from "chai";
import * as chaiPromises from "chai-as-promised";
import * as sinon from "sinon";
import mockedEnv from "mocked-env";
import { AccessToken } from "@azure/identity";
import { promisify } from "util";
import { TeamsInfo } from "botbuilder";
chaiUse(chaiPromises);
let mockedEnvRestore: () => void;
describe("TeamsBotSsoPrompt Tests - Node", () => {
const sleep = promisify(setTimeout);
const clientId = "fake_client_id";
const clientSecret = "fake_client_secret";
const tenantId = "fake_tenant";
const userPrincipalName = "fake_userPrincipalName";
const authorityHost = "fake_authority_host";
const initiateLoginEndpoint = "fake_initiate_login_endpoint";
const applicationIdUri = "fake_application_id_uri";
const TeamsBotSsoPromptId = "TEAMS_BOT_SSO_PROMPT";
const requiredScopes: string[] = ["User.Read"];
const expiresOnTimestamp = 12345678;
const invokeResponseActivityType = "invokeResponse";
const id = "fake_id";
const exchangeToken = "fake_exchange_token";
/**
* {
* "aud": "test_audience",
* "iss": "https://login.microsoftonline.com/test_aad_id/v2.0",
* "iat": 1537231048,
* "nbf": 1537231048,
* "exp": 1537234948,
* "aio": "test_aio",
* "name": "Teams App Framework SDK Unit Test",
* "oid": "11111111-2222-3333-4444-555555555555",
* "preferred_username": "test@microsoft.com",
* "rh": "test_rh",
* "scp": "access_as_user",
* "sub": "test_sub",
* "tid": "test_tenant_id",
* "uti": "test_uti",
* "ver": "2.0"
* }
*/
const ssoToken =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJ0ZXN0X2F1ZGllbmNlIiwiaXNzIjoiaHR0cHM6Ly9sb2dpbi5taWNyb3NvZnRvbmxpbmUuY29tL3Rlc3RfYWFkX2lkL3YyLjAiLCJpYXQiOjE1MzcyMzEwNDgsIm5iZiI6MTUzNzIzMTA0OCwiZXhwIjoxNTM3MjM0OTQ4LCJhaW8iOiJ0ZXN0X2FpbyIsIm5hbWUiOiJNT0RTIFRvb2xraXQgU0RLIFVuaXQgVGVzdCIsIm9pZCI6IjExMTExMTExLTIyMjItMzMzMy00NDQ0LTU1NTU1NTU1NTU1NSIsInByZWZlcnJlZF91c2VybmFtZSI6InRlc3RAbWljcm9zb2Z0LmNvbSIsInJoIjoidGVzdF9yaCIsInNjcCI6ImFjY2Vzc19hc191c2VyIiwic3ViIjoidGVzdF9zdWIiLCJ0aWQiOiJ0ZXN0X3RlbmFudF9pZCIsInV0aSI6InRlc3RfdXRpIiwidmVyIjoiMi4wIn0.SshbL1xuE1aNZD5swrWOQYgTR9QCNXkZqUebautBvKM";
const ssoTokenExpiration = "2018-09-18T01:42:28.000Z";
const timeoutValue = 50;
const sleepTimeOffset: number = timeoutValue + 20;
enum SsoLogInResult {
Success = "Success",
Fail = "Fail",
}
const sandbox = sinon.createSandbox();
beforeEach(function () {
mockedEnvRestore = mockedEnv({
INITIATE_LOGIN_ENDPOINT: initiateLoginEndpoint,
M365_CLIENT_ID: clientId,
M365_CLIENT_SECRET: clientSecret,
M365_TENANT_ID: tenantId,
M365_AUTHORITY_HOST: authorityHost,
M365_APPLICATION_ID_URI: applicationIdUri,
});
// Mock onBehalfOfUserCredential implementation
const onBehalfOfUserCredentialStub_GetToken = sandbox.stub(
OnBehalfOfUserCredential.prototype,
"getToken"
);
onBehalfOfUserCredentialStub_GetToken.onCall(0).callsFake(async () => {
throw new ErrorWithCode(
"The user or administrator has not consented to use the application\nFail to get access token because user has not consent scope.",
ErrorCode.UiRequiredError
);
});
onBehalfOfUserCredentialStub_GetToken.onCall(1).callsFake(async () => {
return new Promise<AccessToken>((resolve) => {
resolve({
token: exchangeToken,
expiresOnTimestamp: expiresOnTimestamp,
});
});
});
sandbox.stub(TeamsInfo, "getMember").callsFake(async () => {
const account: TeamsChannelAccount = {
id: "fake_id",
name: "fake_name",
userPrincipalName: userPrincipalName,
};
return account;
});
});
afterEach(function () {
sandbox.restore();
mockedEnvRestore();
});
it("teams bot sso prompt should be able to sign user in and get exchange tokens when consent", async function () {
this.timeout(500);
const adapter: TestAdapter = await initializeTestEnv();
await adapter
.send("Hello")
.assertReply((activity) => {
// Assert bot send out OAuthCard
assertTeamsSsoOauthCardActivity(activity);
// Mock Teams sends signin/tokenExchange message with SSO token back to the bot
mockTeamsSendsTokenExchangeInvokeActivityWithSsoToken(adapter, activity);
})
.assertReply((activity) => {
// User has not consent. Assert bot send out 412
assert.strictEqual(activity.type, invokeResponseActivityType);
assert.strictEqual(activity.value.status, StatusCodes.PRECONDITION_FAILED);
assert.strictEqual(
activity.value.body.failureDetail,
"The bot is unable to exchange token. Ask for user consent."
);
// Mock Teams sends signin/verifyState message after user consent back to the bot
const invokeActivity: Partial<Activity> = createReply(ActivityTypes.Invoke, activity);
invokeActivity.name = verifyStateOperationName;
adapter.send(invokeActivity);
})
.assertReply((activity) => {
// Assert bot send out OAuthCard gain to get SSO token
assertTeamsSsoOauthCardActivity(activity);
// Mock Teams sends signin/tokenExchange message with SSO token back to the bot
mockTeamsSendsTokenExchangeInvokeActivityWithSsoToken(adapter, activity);
})
.assertReply((activity) => {
// Assert bot send out invoke response status 200 to Teams to signal verifivation invoke has been received
assert.strictEqual(activity.type, invokeResponseActivityType);
assert.strictEqual(activity.value.status, StatusCodes.OK);
})
.assertReply((activity) => {
// Assert bot send out invoke response status 200 to Teams to signal token response request invoke has been received
assert.strictEqual(activity.type, invokeResponseActivityType);
assert.strictEqual(activity.value.status, StatusCodes.OK);
assert.strictEqual(activity.value.body.id, id);
})
.assertReply(SsoLogInResult.Success)
.assertReply((activity) => {
// Assert prompt result has exchanged token and sso token.
const result = JSON.parse(activity.text as string) as TeamsBotSsoPromptTokenResponse;
assert.strictEqual(result.token, exchangeToken);
assert.strictEqual(result.ssoToken, ssoToken);
assert.strictEqual(result.ssoTokenExpiration, ssoTokenExpiration);
});
});
it("teams bot sso prompt should timeout with teams verification invoke activity when wait a long time", async function () {
const adapter: TestAdapter = await initializeTestEnv(timeoutValue);
await adapter
.send("Hello")
.assertReply((activity) => {
// Assert bot send out OAuthCard
assertTeamsSsoOauthCardActivity(activity);
// Mock Teams sends signin/tokenExchange message with SSO token back to the bot
mockTeamsSendsTokenExchangeInvokeActivityWithSsoToken(adapter, activity);
})
.assertReply(async (activity) => {
// User has not consent. Assert bot send out 412
assert.strictEqual(activity.type, invokeResponseActivityType);
assert.strictEqual(activity.value.status, StatusCodes.PRECONDITION_FAILED);
assert.strictEqual(
activity.value.body.failureDetail,
"The bot is unable to exchange token. Ask for user consent."
);
await sleep(sleepTimeOffset);
// Mock Teams sends signin/verifyState message after user consent back to the bot after timeout
const invokeActivity: Partial<Activity> = createReply(ActivityTypes.Invoke, activity);
invokeActivity.name = verifyStateOperationName;
adapter.send(invokeActivity);
})
.assertReply(SsoLogInResult.Fail);
});
it("teams bot sso prompt should timeout with token exchange activity when wait a long time", async function () {
const adapter: TestAdapter = await initializeTestEnv(timeoutValue);
await adapter
.send("Hello")
.assertReply(async (activity) => {
// Assert bot send out OAuthCard
assertTeamsSsoOauthCardActivity(activity);
await sleep(sleepTimeOffset);
// Mock Teams sends signin/tokenExchange message with SSO token back to the bot
mockTeamsSendsTokenExchangeInvokeActivityWithSsoToken(adapter, activity);
})
.assertReply(SsoLogInResult.Fail);
});
it("teams bot sso prompt should timeout with message activity when wait a long time", async function () {
const adapter: TestAdapter = await initializeTestEnv(timeoutValue);
await adapter
.send("Hello")
.assertReply(async (activity) => {
// Assert bot send out OAuthCard
assertTeamsSsoOauthCardActivity(activity);
await sleep(sleepTimeOffset);
// Mock message activity sent to the bot
const messageActivity: Partial<Activity> = createReply(ActivityTypes.Message, activity);
messageActivity.text = "message sent to bot.";
adapter.send(messageActivity);
})
.assertReply(SsoLogInResult.Fail);
});
it("teams bot sso prompt should end on invalid message when endOnInvalidMessage default to true", async function () {
const adapter: TestAdapter = await initializeTestEnv(undefined);
await adapter
.send("Hello")
.assertReply((activity) => {
// Assert bot send out OAuthCard
assertTeamsSsoOauthCardActivity(activity);
// Mock User send invalid message
const messageActivity = createReply(ActivityTypes.Message, activity);
messageActivity.text = "user sends invalid message during auth flow";
adapter.send(messageActivity);
})
.assertReply(SsoLogInResult.Fail);
});
it("teams bot sso prompt should not end on invalid message when endOnInvalidMessage set to false", async function () {
const adapter: TestAdapter = await initializeTestEnv(undefined, false);
await adapter
.send("Hello")
.assertReply((activity) => {
// Assert bot send out OAuthCard
assertTeamsSsoOauthCardActivity(activity);
// Mock User send invalid message, wchich should be ignored.
const messageActivity = createReply(ActivityTypes.Message, activity);
messageActivity.text = "user sends invalid message during auth flow";
adapter.send(messageActivity);
// Mock Teams sends signin/tokenExchange message with SSO token back to the bot
mockTeamsSendsTokenExchangeInvokeActivityWithSsoToken(adapter, activity);
})
.assertReply((activity) => {
// User has not consent. Assert bot send out 412
assert.strictEqual(activity.type, invokeResponseActivityType);
assert.strictEqual(activity.value.status, StatusCodes.PRECONDITION_FAILED);
assert.strictEqual(
activity.value.body.failureDetail,
"The bot is unable to exchange token. Ask for user consent."
);
// Mock Teams sends signin/verifyState message after user consent back to the bot
const invokeActivity: Partial<Activity> = createReply(ActivityTypes.Invoke, activity);
invokeActivity.name = verifyStateOperationName;
adapter.send(invokeActivity);
})
.assertReply((activity) => {
// Assert bot send out OAuthCard gain to get SSO token
assertTeamsSsoOauthCardActivity(activity);
// Mock Teams sends signin/tokenExchange message with SSO token back to the bot
mockTeamsSendsTokenExchangeInvokeActivityWithSsoToken(adapter, activity);
})
.assertReply((activity) => {
// Assert bot send out invoke response status 200 to Teams to signal verifivation invoke has been received
assert.strictEqual(activity.type, invokeResponseActivityType);
assert.strictEqual(activity.value.status, StatusCodes.OK);
})
.assertReply((activity) => {
// Assert bot send out invoke response status 200 to Teams to signal token response request invoke has been received
assert.strictEqual(activity.type, invokeResponseActivityType);
assert.strictEqual(activity.value.status, StatusCodes.OK);
assert.strictEqual(activity.value.body.id, id);
})
.assertReply(SsoLogInResult.Success)
.assertReply((activity) => {
// Assert prompt result has exchanged token and sso token.
const result = JSON.parse(activity.text as string) as TeamsBotSsoPromptTokenResponse;
assert.strictEqual(result.token, exchangeToken);
assert.strictEqual(result.ssoToken, ssoToken);
assert.strictEqual(result.ssoTokenExpiration, ssoTokenExpiration);
});
});
it("teams bot sso prompt should only work in MS Teams Channel", async function () {
const adapter: TestAdapter = await initializeTestEnv(undefined, undefined, Channels.Test);
await adapter.send("Hello").catch((error) => {
assert.strictEqual(
error.message,
"Teams Bot SSO Prompt is only supported in MS Teams Channel"
);
});
});
it("create TeamsBotSsoPrompt instance should throw InvalidParameter error with invalid scopes", async function () {
const invalidScopes = [1, 2];
const settings: any = {
scopes: invalidScopes,
};
loadConfiguration();
expect(() => {
new TeamsBotSsoPrompt(TeamsBotSsoPromptId, settings);
})
.to.throw(ErrorWithCode, "The type of scopes is not valid, it must be string or string array")
.with.property("code", ErrorCode.InvalidParameter);
});
function createReply(type: ActivityTypes, activity: Partial<Activity>): Partial<Activity> {
return {
type: type,
from: { id: activity.recipient!.id, name: activity.recipient!.name },
recipient: { id: activity.from!.id, name: activity.from!.name },
replyToId: activity.id,
serviceUrl: activity.serviceUrl,
channelId: activity.channelId,
conversation: {
isGroup: activity.conversation!.isGroup,
id: activity.conversation!.id,
name: activity.conversation!.name,
conversationType: "personal",
tenantId: tenantId,
},
};
}
function assertTeamsSsoOauthCardActivity(activity: Partial<Activity>): void {
assert.isArray(activity.attachments);
assert.strictEqual(activity.attachments?.length, 1);
assert.strictEqual(activity.attachments![0].contentType, CardFactory.contentTypes.oauthCard);
assert.strictEqual(activity.inputHint, InputHints.AcceptingInput);
assert.strictEqual(activity.attachments![0].content.buttons[0].type, ActionTypes.Signin);
assert.strictEqual(activity.attachments![0].content.buttons[0].title, "Teams SSO Sign In");
assert.strictEqual(
activity.attachments![0].content.tokenExchangeResource.uri,
applicationIdUri + "/access_as_user"
);
assert.strictEqual(
activity.attachments![0].content.buttons[0].value,
`${initiateLoginEndpoint}?scope=${encodeURI(
requiredScopes.join(" ")
)}&clientId=${clientId}&tenantId=${tenantId}&loginHint=${userPrincipalName}`
);
}
function mockTeamsSendsTokenExchangeInvokeActivityWithSsoToken(
adapter: TestAdapter,
activity: Partial<Activity>
): void {
const invokeActivity: Partial<Activity> = createReply(ActivityTypes.Invoke, activity);
invokeActivity.name = tokenExchangeOperationName;
invokeActivity.value = {
id: id,
token: ssoToken,
};
adapter.send(invokeActivity);
}
/**
* Initialize dialogs, adds teamsBotSsoPrompt in dialog set and initialize testAdapter for test case.
* @param timeout_value positive number set to teamsSsoPromptSettings.timeout property
* @param endOnInvalidMessage boolean value set to teamsSsoPromptSettings.endOnInvalidMessage property
* @param channelId value set to dialog context activity channel. Defaults to `Channels.MSteams`.
*/
async function initializeTestEnv(
timeout_value?: number,
endOnInvalidMessage?: boolean,
channelId?: Channels,
config?: Configuration
): Promise<TestAdapter> {
// Create new ConversationState with MemoryStorage
const convoState: ConversationState = new ConversationState(new MemoryStorage());
// Create a DialogState property, DialogSet and TeamsBotSsoPrompt
const dialogState: StatePropertyAccessor<DialogState> =
convoState.createProperty("dialogState");
const dialogs: DialogSet = new DialogSet(dialogState);
const settings: TeamsBotSsoPromptSettings = {
scopes: requiredScopes,
timeout: timeout_value,
endOnInvalidMessage: endOnInvalidMessage,
};
loadConfiguration(config);
dialogs.add(new TeamsBotSsoPrompt(TeamsBotSsoPromptId, settings));
// Initialize TestAdapter.
const adapter: TestAdapter = new TestAdapter(async (turnContext) => {
const dc = await dialogs.createContext(turnContext);
dc.context.activity.channelId = channelId === undefined ? Channels.Msteams : channelId;
const results = await dc.continueDialog();
if (results.status === DialogTurnStatus.empty) {
await dc.beginDialog(TeamsBotSsoPromptId);
} else if (results.status === DialogTurnStatus.complete) {
if (results.result?.token) {
await turnContext.sendActivity(SsoLogInResult.Success);
const resultStr = JSON.stringify(results.result);
await turnContext.sendActivity(resultStr);
} else {
await turnContext.sendActivity(SsoLogInResult.Fail);
}
}
await convoState.saveChanges(turnContext);
});
return adapter;
}
}); | the_stack |
import { EntryStorage, BrowserStorage } from "../models/storage";
import { Encryption } from "../models/encryption";
import * as CryptoJS from "crypto-js";
import { OTPType, OTPAlgorithm } from "../models/otp";
import { ActionContext } from "vuex";
export class Accounts implements Module {
async getModule() {
const cachedPassphrase = await this.getCachedPassphrase();
const encryption: Encryption = new Encryption(cachedPassphrase);
const shouldShowPassphrase = await EntryStorage.hasEncryptionKey();
const entries = shouldShowPassphrase ? [] : await this.getEntries();
return {
state: {
entries,
encryption,
OTPType,
OTPAlgorithm,
shouldShowPassphrase,
sectorStart: false, // Should display timer circles?
sectorOffset: 0, // Offset in seconds for animations
second: 0, // Offset in seconds for math
filter: true,
siteName: await this.getSiteName(),
showSearch: false,
exportData: await EntryStorage.getExport(entries),
exportEncData: await EntryStorage.getExport(entries, true),
key: await BrowserStorage.getKey(),
wrongPassword: false,
initComplete: false,
},
getters: {
shouldFilter(
state: AccountsState,
getters: { matchedEntries: string[] }
) {
return (
localStorage.smartFilter !== "false" &&
getters.matchedEntries.length
);
},
matchedEntries: (state: AccountsState) => {
return this.matchedEntries(state.siteName, state.entries);
},
currentlyEncrypted(state: AccountsState) {
for (const entry of state.entries) {
if (entry.secret === null) {
return true;
}
}
return false;
},
entries(state: AccountsState) {
const pinnedEntries = state.entries.filter((entry) => entry.pinned);
const unpinnedEntries = state.entries.filter(
(entry) => !entry.pinned
);
return [...pinnedEntries, ...unpinnedEntries];
},
},
mutations: {
stopFilter(state: AccountsState) {
state.filter = false;
},
showSearch(state: AccountsState) {
state.showSearch = true;
},
updateCodes(state: AccountsState) {
let second = new Date().getSeconds();
if (localStorage.offset) {
// prevent second from negative
second += Number(localStorage.offset) + 60;
}
second = second % 60;
state.second = second;
let currentlyEncrypted = false;
for (const entry of state.entries) {
if (entry.secret === null) {
currentlyEncrypted = true;
}
}
if (
!state.sectorStart &&
state.entries.length > 0 &&
!currentlyEncrypted
) {
state.sectorStart = true;
state.sectorOffset = -second;
}
// if (second > 25) {
// app.class.timeout = true;
// } else {
// app.class.timeout = false;
// }
// if (second < 1) {
// const entries = app.entries as OTP[];
// for (let i = 0; i < entries.length; i++) {
// if (entries[i].type !== OTPType.hotp &&
// entries[i].type !== OTPType.hhex) {
// entries[i].generate();
// }
// }
// }
const entries = state.entries as OTPEntryInterface[];
for (let i = 0; i < entries.length; i++) {
if (
entries[i].type !== OTPType.hotp &&
entries[i].type !== OTPType.hhex
) {
entries[i].generate();
}
}
},
loadCodes(state: AccountsState, newCodes: OTPEntryInterface[]) {
state.entries = newCodes;
},
moveCode(state: AccountsState, opts: { from: number; to: number }) {
state.entries.splice(
opts.to,
0,
state.entries.splice(opts.from, 1)[0]
);
for (let i = 0; i < state.entries.length; i++) {
if (state.entries[i].index !== i) {
state.entries[i].index = i;
}
}
},
pinEntry(state: AccountsState, entry: OTPEntryInterface) {
state.entries[entry.index].pinned = !entry.pinned;
},
updateExport(
state: AccountsState,
exportData: { [k: string]: OTPEntryInterface }
) {
state.exportData = exportData;
},
updateEncExport(
state: AccountsState,
exportData: { [k: string]: OTPEntryInterface }
) {
state.exportEncData = exportData;
},
updateKeyExport(
state: AccountsState,
key: { enc: string; hash: string } | null
) {
state.key = key;
},
wrongPassword(state: AccountsState) {
state.wrongPassword = true;
},
initComplete(state: AccountsState) {
state.initComplete = true;
},
},
actions: {
deleteCode: async (
state: ActionContext<AccountsState, {}>,
hash: string
) => {
const index = state.state.entries.findIndex(
(entry) => entry.hash === hash
);
if (index > -1) {
state.state.entries.splice(index, 1);
}
state.commit(
"updateExport",
await EntryStorage.getExport(state.state.entries)
);
state.commit(
"updateEncExport",
await EntryStorage.getExport(state.state.entries, true)
);
},
addCode: async (
state: ActionContext<AccountsState, {}>,
entry: OTPEntryInterface
) => {
state.state.entries.unshift(entry);
state.commit(
"updateExport",
await EntryStorage.getExport(state.state.entries)
);
state.commit(
"updateEncExport",
await EntryStorage.getExport(state.state.entries, true)
);
},
applyPassphrase: async (
state: ActionContext<AccountsState, {}>,
password: string
) => {
if (!password) {
return;
}
state.commit("currentView/changeView", "LoadingPage", { root: true });
const encKey = await BrowserStorage.getKey();
if (!encKey) {
// --- migrate to key
// verify current password
state.state.encryption.updateEncryptionPassword(password);
await state.dispatch("updateEntries");
if (state.getters.currentlyEncrypted) {
state.commit("style/hideInfo", true, { root: true });
return;
}
// gen key
const wordArray = CryptoJS.lib.WordArray.random(120);
const encKey = CryptoJS.AES.encrypt(wordArray, password).toString();
const encKeyHash = await new Promise(
(resolve: (value: string) => void) => {
const iframe = document.getElementById("argon-sandbox");
const message = {
action: "hash",
value: wordArray.toString(),
};
if (iframe) {
window.addEventListener("message", (response) => {
resolve(response.data.response);
});
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
//@ts-ignore
iframe.contentWindow.postMessage(message, "*");
}
}
);
if (!encKeyHash) {
state.commit("style/hideInfo", true, { root: true });
return;
}
// change entry encryption to key and remove old hash
const oldKeys: string[] = [];
for (const entry of state.state.entries) {
await entry.changeEncryption(
new Encryption(wordArray.toString())
);
oldKeys.push(entry.hash);
entry.genUUID();
}
// store key
await BrowserStorage.set({
key: { enc: encKey, hash: encKeyHash },
});
await EntryStorage.set(state.state.entries);
await new Promise((resolve) => {
BrowserStorage.remove(oldKeys, () => {
resolve();
});
});
state.state.encryption.updateEncryptionPassword(
wordArray.toString()
);
await state.dispatch("updateEntries");
} else {
// --- decrypt using key
const key = CryptoJS.AES.decrypt(encKey.enc, password).toString();
const isCorrectPassword = await new Promise(
(resolve: (value: string) => void) => {
const iframe = document.getElementById("argon-sandbox");
const message = {
action: "verify",
value: key,
hash: encKey.hash,
};
if (iframe) {
window.addEventListener("message", (response) => {
resolve(response.data.response);
});
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
//@ts-ignore
iframe.contentWindow.postMessage(message, "*");
}
}
);
if (!isCorrectPassword) {
state.commit("wrongPassword");
state.commit("currentView/changeView", "EnterPasswordPage", {
root: true,
});
return;
}
state.state.encryption.updateEncryptionPassword(key);
await state.dispatch("updateEntries");
// Encrypt any unencrypted entries.
// Browser sync can cause unencrypted entries to show up.
let needUpdateStorage = false;
for (const entry of state.state.entries) {
if (!entry.encSecret) {
await entry.changeEncryption(state.state.encryption);
needUpdateStorage = true;
}
}
if (needUpdateStorage) {
await EntryStorage.set(state.state.entries);
await state.dispatch("updateEntries");
}
if (!state.getters.currentlyEncrypted) {
chrome.runtime.sendMessage({
action: "cachePassphrase",
value: key,
});
}
}
state.commit("style/hideInfo", true, { root: true });
return;
},
changePassphrase: async (
state: ActionContext<AccountsState, {}>,
password: string
) => {
if (password) {
const wordArray = CryptoJS.lib.WordArray.random(120);
const encKey = CryptoJS.AES.encrypt(wordArray, password).toString();
const encKeyHash = await new Promise(
(resolve: (value: string) => void) => {
const iframe = document.getElementById("argon-sandbox");
const message = {
action: "hash",
value: wordArray.toString(),
};
if (iframe) {
window.addEventListener("message", (response) => {
resolve(response.data.response);
});
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
//@ts-ignore
iframe.contentWindow.postMessage(message, "*");
}
}
);
if (!encKeyHash) {
return;
}
// change entry encryption and regen hash
const removeHashes: string[] = [];
for (const entry of state.state.entries) {
await entry.changeEncryption(
new Encryption(wordArray.toString())
);
// if not uuidv4 regen
if (
/[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}/i.test(
entry.hash
)
) {
removeHashes.push(entry.hash);
entry.genUUID();
}
}
// store key
await BrowserStorage.set({
key: { enc: encKey, hash: encKeyHash },
});
await EntryStorage.set(state.state.entries);
if (removeHashes.length) {
await new Promise((resolve) => {
BrowserStorage.remove(removeHashes, () => {
resolve();
});
});
}
state.state.encryption.updateEncryptionPassword(
wordArray.toString()
);
await state.dispatch("updateEntries");
// https://github.com/Authenticator-Extension/Authenticator/issues/412
if (navigator.userAgent.indexOf("Chrome") !== -1) {
await BrowserStorage.clearLogs();
}
chrome.runtime.sendMessage({
action: "cachePassphrase",
value: wordArray.toString(),
});
} else {
for (const entry of state.state.entries) {
await entry.changeEncryption(new Encryption(""));
}
await EntryStorage.set(state.state.entries);
state.state.encryption.updateEncryptionPassword("");
BrowserStorage.remove("key");
await state.dispatch("updateEntries");
chrome.runtime.sendMessage({
action: "lock",
});
}
// remove cached passphrase in old version
localStorage.removeItem("encodedPhrase");
},
updateEntries: async (state: ActionContext<AccountsState, {}>) => {
const entries = await this.getEntries();
if (state.state.encryption.getEncryptionStatus()) {
for (const entry of entries) {
await entry.applyEncryption(state.state.encryption as Encryption);
}
}
state.commit("loadCodes", entries);
state.commit("updateCodes");
state.commit(
"updateExport",
await EntryStorage.getExport(state.state.entries)
);
state.commit(
"updateEncExport",
await EntryStorage.getExport(state.state.entries, true)
);
state.commit("updateKeyExport", await BrowserStorage.getKey());
state.commit("initComplete");
return;
},
clearFilter: (state: ActionContext<AccountsState, {}>) => {
state.commit("stopFilter");
if (state.state.entries.length >= 10) {
state.commit("showSearch");
}
},
migrateStorage: async (
state: ActionContext<AccountsState, {}>,
newStorageLocation: string
) => {
// sync => local
if (
localStorage.storageLocation === "sync" &&
newStorageLocation === "local"
) {
return new Promise((resolve, reject) => {
chrome.storage.sync.get((syncData) => {
chrome.storage.local.set(syncData, () => {
chrome.storage.local.get((localData) => {
// Double check if data was set
if (
Object.keys(syncData).every(
(value) => Object.keys(localData).indexOf(value) >= 0
)
) {
localStorage.storageLocation = "local";
chrome.storage.sync.clear();
resolve("updateSuccess");
return;
} else {
reject(" All data not transferred successfully.");
return;
}
});
});
});
});
// local => sync
} else if (
localStorage.storageLocation === "local" &&
newStorageLocation === "sync"
) {
return new Promise((resolve, reject) => {
chrome.storage.local.get((localData) => {
chrome.storage.sync.set(localData, () => {
chrome.storage.sync.get((syncData) => {
// Double check if data was set
if (
Object.keys(localData).every(
(value) => Object.keys(syncData).indexOf(value) >= 0
)
) {
localStorage.storageLocation = "sync";
chrome.storage.local.clear();
resolve("updateSuccess");
return;
} else {
reject(" All data not transferred successfully.");
return;
}
});
});
});
});
}
},
},
namespaced: true,
};
}
private async getSiteName() {
return new Promise((resolve: (value: Array<string | null>) => void) => {
chrome.tabs.query({ active: true, lastFocusedWindow: true }, (tabs) => {
const tab = tabs[0];
const query = new URLSearchParams(
document.location.search.substring(1)
);
let title: string | null;
let url: string | null;
const titleFromQuery = query.get("title");
const urlFromQuery = query.get("url");
if (titleFromQuery && urlFromQuery) {
title = decodeURIComponent(titleFromQuery);
url = decodeURIComponent(urlFromQuery);
} else {
if (!tab) {
return resolve([null, null]);
}
title = tab.title?.replace(/[^a-z0-9]/gi, "").toLowerCase() ?? null;
url = tab.url ?? null;
}
if (!url) {
return resolve([title, null]);
}
const urlParser = new URL(url);
const hostname = urlParser.hostname; // it's always lower case
// try to parse name from hostname
// i.e. hostname is www.example.com
// name should be example
let nameFromDomain = "";
// ip address
if (/^\d+\.\d+\.\d+\.\d+$/.test(hostname)) {
nameFromDomain = hostname;
}
// local network
if (hostname.indexOf(".") === -1) {
nameFromDomain = hostname;
}
const hostLevelUnits = hostname.split(".");
if (hostLevelUnits.length === 2) {
nameFromDomain = hostLevelUnits[0];
}
// www.example.com
// example.com.cn
if (hostLevelUnits.length > 2) {
// example.com.cn
if (
["com", "net", "org", "edu", "gov", "co"].indexOf(
hostLevelUnits[hostLevelUnits.length - 2]
) !== -1
) {
nameFromDomain = hostLevelUnits[hostLevelUnits.length - 3];
} else {
// www.example.com
nameFromDomain = hostLevelUnits[hostLevelUnits.length - 2];
}
}
nameFromDomain = nameFromDomain.replace(/-/g, "").toLowerCase();
return resolve([title, nameFromDomain, hostname]);
});
});
}
private getCachedPassphrase() {
return new Promise((resolve: (value: string) => void) => {
chrome.runtime.sendMessage(
{ action: "passphrase" },
(passphrase: string) => {
return resolve(passphrase);
}
);
});
}
private async getEntries() {
const otpEntries = await EntryStorage.get();
return otpEntries;
}
private matchedEntries(
siteName: Array<string | null>,
entries: OTPEntryInterface[]
) {
if (siteName.length < 2) {
return false;
}
const matched = [];
for (const entry of entries) {
if (this.isMatchedEntry(siteName, entry)) {
matched.push(entry.hash);
}
}
return matched;
}
private isMatchedEntry(
siteName: Array<string | null>,
entry: OTPEntryInterface
) {
if (!entry.issuer) {
return false;
}
const issuerHostMatches = entry.issuer.split("::");
const issuer = issuerHostMatches[0]
.replace(/[^0-9a-z]/gi, "")
.toLowerCase();
if (!issuer) {
return false;
}
const siteTitle = siteName[0] || "";
const siteNameFromHost = siteName[1] || "";
const siteHost = siteName[2] || "";
if (issuerHostMatches.length > 1) {
if (siteHost && siteHost.indexOf(issuerHostMatches[1]) !== -1) {
return true;
}
}
// site title should be more detailed
// so we use siteTitle.indexOf(issuer)
if (siteTitle && siteTitle.indexOf(issuer) !== -1) {
return true;
}
if (siteNameFromHost && issuer.indexOf(siteNameFromHost) !== -1) {
return true;
}
return false;
}
} | the_stack |
import * as maptalks from 'maptalks';
import * as THREE from 'three';
import BaseObject from './BaseObject';
import Bar from './Bar';
import Line from './Line';
import ExtrudeLine from './ExtrudeLine';
import ExtrudePolygon from './ExtrudePolygon';
import Model from './Model';
import ExtrudeLineTrail from './ExtrudeLineTrail';
import ExtrudePolygons from './ExtrudePolygons';
import Point from './Point';
import Points from './Points';
import Bars from './Bars';
import ExtrudeLines from './ExtrudeLines';
import Lines from './Lines';
import ThreeVectorTileLayer from './ThreeVectorTileLayer';
import Terrain from './Terrain';
import TerrainVectorTileLayer from './TerrainVectorTileLayer';
import HeatMap from './HeatMap';
import { setRaycasterLinePrecision } from './util/ThreeAdaptUtil';
import GPUPick from './GPUPick';
import FatLine from './FatLine';
import FatLines from './FatLines';
import Box from './Box';
import Boxs from './Boxs';
import MergedMixin from './MergedMixin';
import * as GeoJSONUtil from './util/GeoJSONUtil';
import * as GeoUtil from './util/GeoUtil';
import * as MergeGeometryUtil from './util/MergeGeometryUtil';
import * as ExtrudeUtil from './util/ExtrudeUtil';
import * as LineUtil from './util/LineUtil';
import * as IdentifyUtil from './util/IdentifyUtil';
import * as geometryExtrude from 'deyihu-geometry-extrude';
import LineMaterial from './util/fatline/LineMaterial';
import { BarOptionType, BaseLayerOptionType, BaseObjectOptionType, ExtrudeLineOptionType, ExtrudeLineTrailOptionType, ExtrudePolygonOptionType, FatLineMaterialType, getBaseObjectMaterialType, HeatMapDataType, HeatMapOptionType, LineMaterialType, LineOptionType, LineStringType, PointOptionType, PolygonType, SingleLineStringType, TerrainOptionType } from './type/index';
import { getWorkerCode, getWorkerName } from './worker/getworker';
const options: BaseLayerOptionType = {
'renderer': 'gl',
'doubleBuffer': false,
'glOptions': null,
'geometryEvents': true,
'identifyCountOnEvent': 0,
'forceRenderOnZooming': true,
'loopRenderCount': 50
};
const RADIAN = Math.PI / 180;
const LINEPRECISIONS = [
[4000, 220],
[2000, 100],
[1000, 30],
[500, 15],
[100, 5],
[50, 2],
[10, 1],
[5, 0.7],
[2, 0.1],
[1, 0.05],
[0.5, 0.02]
];
const EVENTS = [
'mousemove',
'click',
'mousedown',
'mouseup',
'dblclick',
'contextmenu',
'touchstart',
'touchmove',
'touchend'
];
const TEMP_COORD = new maptalks.Coordinate(0, 0);
const TEMP_POINT = new maptalks.Point(0, 0);
// const MATRIX4 = new THREE.Matrix4();
/**
* A Layer to render with THREE.JS (http://threejs.org), the most popular library for WebGL. <br>
*
* @classdesc
* A layer to render with THREE.JS
* @example
* var layer = new maptalks.ThreeLayer('three');
*
* layer.prepareToDraw = function (gl, scene, camera) {
* var size = map.getSize();
* return [size.width, size.height]
* };
*
* layer.draw = function (gl, view, scene, camera, width,height) {
* //...
* };
* layer.addTo(map);
* @class
* @category layer
* @extends {maptalks.CanvasLayer}
* @param {String|Number} id - layer's id
* @param {Object} options - options defined in [options]{@link maptalks.ThreeLayer#options}
*/
class ThreeLayer extends maptalks.CanvasLayer {
options: BaseLayerOptionType;
map: maptalks.Map;
type: string;
_animationBaseObjectMap: { [key: string]: BaseObject } = {};
_needsUpdate: boolean = true;
_raycaster: THREE.Raycaster;
_mouse: THREE.Vector2;
_containerPoint: maptalks.Point;
_mousemoveTimeOut: number = 0;
_baseObjects: Array<BaseObject> = [];
_delayMeshes: Array<BaseObject> = [];
constructor(id: string, options: BaseLayerOptionType) {
super(id, options);
this.type = 'ThreeLayer';
}
isRendering(): boolean {
const map = this.getMap();
if (!map) {
return false;
}
return map.isInteracting() || map.isAnimating();
}
prepareToDraw(...args) {
}
/**
* Draw method of ThreeLayer
* In default, it calls renderScene, refresh the camera and the scene
*/
draw() {
this.renderScene();
}
/**
* Draw method of ThreeLayer when map is interacting
* In default, it calls renderScene, refresh the camera and the scene
*/
drawOnInteracting() {
this.renderScene();
}
/**
* Convert a geographic coordinate to THREE Vector3
* @param {maptalks.Coordinate} coordinate - coordinate
* @param {Number} [z=0] z value
* @return {THREE.Vector3}
*/
coordinateToVector3(coordinate: maptalks.Coordinate | Array<number>, z: number = 0): THREE.Vector3 {
const map = this.getMap();
if (!map) {
return null;
}
const isArray = Array.isArray(coordinate);
if (isArray) {
TEMP_COORD.x = coordinate[0];
TEMP_COORD.y = coordinate[1];
}
if (!isArray) {
if (!(coordinate instanceof maptalks.Coordinate)) {
coordinate = new maptalks.Coordinate(coordinate);
}
}
const res = getGLRes(map);
const p = coordinateToPoint(map, isArray ? TEMP_COORD : coordinate, res, TEMP_POINT);
return new THREE.Vector3(p.x, p.y, z);
}
/**
* Convert geographic distance to THREE Vector3
* @param {Number} w - width
* @param {Number} h - height
* @return {THREE.Vector3}
*/
distanceToVector3(w: number, h: number, coord?: maptalks.Coordinate | Array<number>): THREE.Vector3 {
if ((w === 0 && h === 0) || (!maptalks.Util.isNumber(w) || !maptalks.Util.isNumber(h))) {
return new THREE.Vector3(0, 0, 0);
}
const map = this.getMap();
const res = getGLRes(map);
let center = coord || map.getCenter();
if (!(center instanceof maptalks.Coordinate)) {
center = new maptalks.Coordinate(center);
}
const target = map.locate(center, w, h);
const p0 = coordinateToPoint(map, center, res),
p1 = coordinateToPoint(map, target, res);
const x = Math.abs(p1.x - p0.x) * maptalks.Util.sign(w);
const y = Math.abs(p1.y - p0.y) * maptalks.Util.sign(h);
return new THREE.Vector3(x, y, 0);
}
/**
* Convert a Polygon or a MultiPolygon to THREE shape
* @param {maptalks.Polygon|maptalks.MultiPolygon} polygon - polygon or multipolygon
* @return {THREE.Shape}
*/
toShape(polygon: maptalks.Polygon | maptalks.MultiPolygon): THREE.Shape | Array<THREE.Shape> {
if (!polygon) {
return null;
}
if (polygon instanceof maptalks.MultiPolygon) {
return polygon.getGeometries().map(c => this.toShape(c) as any);
}
const center = polygon.getCenter();
const centerPt = this.coordinateToVector3(center);
const shell = polygon.getShell();
const outer = shell.map(c => {
const vector = this.coordinateToVector3(c).sub(centerPt);
return new THREE.Vector2(vector.x, vector.y);
});
const shape = new THREE.Shape(outer);
const holes = polygon.getHoles();
if (holes && holes.length > 0) {
shape.holes = holes.map(item => {
const pts = item.map(c => {
const vector = this.coordinateToVector3(c).sub(centerPt);
return new THREE.Vector2(vector.x, vector.y);
});
return new THREE.Shape(pts);
});
}
return shape;
}
/**
* todo This should also be extracted as a component
* @param {*} polygon
* @param {*} altitude
* @param {*} material
* @param {*} height
*/
toExtrudeMesh(polygon: maptalks.Polygon | maptalks.MultiPolygon, altitude: number, material: THREE.Material, height: number): THREE.Mesh | Array<THREE.Mesh> {
if (!polygon) {
return null;
}
if (polygon instanceof maptalks.MultiPolygon) {
return polygon.getGeometries().map(c => this.toExtrudeMesh(c, altitude, material, height) as any);
}
const rings = polygon.getCoordinates();
rings.forEach(ring => {
const length = ring.length;
for (let i = length - 1; i >= 1; i--) {
if (ring[i].equals(ring[i - 1])) {
ring.splice(i, 1);
}
}
});
polygon.setCoordinates(rings);
const shape = this.toShape(polygon);
const center = this.coordinateToVector3(polygon.getCenter());
height = maptalks.Util.isNumber(height) ? height : altitude;
height = this.distanceToVector3(height, height).x;
const amount = this.distanceToVector3(altitude, altitude).x;
//{ amount: extrudeH, bevelEnabled: true, bevelSegments: 2, steps: 2, bevelSize: 1, bevelThickness: 1 };
const config: { [key: string]: any } = { 'bevelEnabled': false, 'bevelSize': 1 };
const name = parseInt(THREE.REVISION) >= 93 ? 'depth' : 'amount';
config[name] = height;
const geom = new THREE.ExtrudeGeometry(shape, config);
let buffGeom = geom as any;
if ((THREE.BufferGeometry.prototype as any).fromGeometry) {
buffGeom = new THREE.BufferGeometry();
buffGeom.fromGeometry(geom);
}
const mesh = new THREE.Mesh(buffGeom, material);
mesh.position.set(center.x, center.y, amount - height);
return mesh;
}
/**
*
* @param {maptalks.Polygon|maptalks.MultiPolygon} polygon
* @param {Object} options
* @param {THREE.Material} material
*/
toExtrudePolygon(polygon: PolygonType, options: ExtrudePolygonOptionType, material: THREE.Material): ExtrudePolygon {
return new ExtrudePolygon(polygon, options, material, this);
}
/**
*
* @param {maptalks.Coordinate} coordinate
* @param {Object} options
* @param {THREE.Material} material
*/
toBar(coordinate: maptalks.Coordinate, options: BarOptionType, material: THREE.Material): Bar {
return new Bar(coordinate, options, material, this);
}
/**
*
* @param {maptalks.LineString} lineString
* @param {Object} options
* @param {THREE.LineMaterial} material
*/
toLine(lineString: LineStringType, options: LineOptionType, material: LineMaterialType): Line {
return new Line(lineString, options, material, this);
}
/**
*
* @param {maptalks.LineString} lineString
* @param {Object} options
* @param {THREE.Material} material
*/
toExtrudeLine(lineString: LineStringType, options: ExtrudeLineOptionType, material: THREE.Material): ExtrudeLine {
return new ExtrudeLine(lineString, options, material, this);
}
/**
*
* @param {THREE.Mesh|THREE.Group} model
* @param {Object} options
*/
toModel(model: THREE.Object3D, options: BaseObjectOptionType): Model {
return new Model(model, options, this);
}
/**
*
* @param {maptalks.LineString} lineString
* @param {*} options
* @param {THREE.Material} material
*/
toExtrudeLineTrail(lineString: SingleLineStringType, options: ExtrudeLineTrailOptionType, material: THREE.Material): ExtrudeLineTrail {
return new ExtrudeLineTrail(lineString, options, material, this);
}
/**
*
* @param {*} polygons
* @param {*} options
* @param {*} material
*/
toExtrudePolygons(polygons: Array<PolygonType>, options: ExtrudePolygonOptionType, material: THREE.Material): ExtrudePolygons {
return new ExtrudePolygons(polygons, options, material, this);
}
/**
*
* @param {maptalks.Coordinate} coordinate
* @param {*} options
* @param {*} material
*/
toPoint(coordinate: maptalks.Coordinate, options: PointOptionType, material: THREE.PointsMaterial): Point {
return new Point(coordinate, options, material, this);
}
/**
*
* @param {Array} points
* @param {*} options
* @param {*} material
*/
toPoints(points: Array<PointOptionType>, options: PointOptionType, material: THREE.PointsMaterial): Points {
return new Points(points, options, material, this);
}
/**
*
* @param {Array} points
* @param {*} options
* @param {*} material
*/
toBars(points: Array<BarOptionType>, options: BarOptionType, material: THREE.Material): Bars {
return new Bars(points, options, material, this);
}
/**
*
* @param {Array[maptalks.LineString]} lineStrings
* @param {*} options
* @param {*} material
*/
toExtrudeLines(lineStrings: Array<LineStringType>, options: ExtrudeLineOptionType, material: THREE.Material): ExtrudeLines {
return new ExtrudeLines(lineStrings, options, material, this);
}
/**
*
* @param {Array[maptalks.LineString]} lineStrings
* @param {*} options
* @param {*} material
*/
toLines(lineStrings: Array<LineStringType>, options: LineOptionType, material: LineMaterialType): Lines {
return new Lines(lineStrings, options, material, this);
}
/**
*
* @param {*} url
* @param {*} options
* @param {*} getMaterial
* @param {*} worker
*/
toThreeVectorTileLayer(url: string, options: any, getMaterial: getBaseObjectMaterialType): ThreeVectorTileLayer {
return new ThreeVectorTileLayer(url, options, getMaterial, this);
}
/**
*
* @param {*} extent
* @param {*} options
* @param {*} material
*/
toTerrain(extent: maptalks.Extent, options: TerrainOptionType, material: THREE.Material): Terrain {
return new Terrain(extent, options, material, this);
}
/**
*
* @param {*} url
* @param {*} options
* @param {*} material
*/
toTerrainVectorTileLayer(url: string, options: any, material: THREE.Material): TerrainVectorTileLayer {
return new TerrainVectorTileLayer(url, options, material, this);
}
/**
*
* @param {*} data
* @param {*} options
* @param {*} material
*/
toHeatMap(data: Array<HeatMapDataType>, options: HeatMapOptionType, material: THREE.Material): HeatMap {
return new HeatMap(data, options, material, this);
}
/**
*
* @param {*} lineString
* @param {*} options
* @param {*} material
*/
toFatLine(lineString: LineStringType, options: LineOptionType, material: FatLineMaterialType): FatLine {
return new FatLine(lineString, options, material, this);
}
/**
*
* @param {*} lineStrings
* @param {*} options
* @param {*} material
*/
toFatLines(lineStrings: Array<LineStringType>, options, material: FatLineMaterialType): FatLines {
return new FatLines(lineStrings, options, material, this);
}
/**
*
* @param {*} coorindate
* @param {*} options
* @param {*} material
*/
toBox(coorindate: maptalks.Coordinate, options: BarOptionType, material: THREE.Material): Box {
return new Box(coorindate, options, material, this);
}
/**
*
* @param {*} points
* @param {*} options
* @param {*} material
*/
toBoxs(points: Array<BarOptionType>, options: BarOptionType, material: THREE.Material): Boxs {
return new Boxs(points, options, material, this);
}
getBaseObjects(): Array<BaseObject> {
return this.getMeshes().filter((mesh => {
return mesh instanceof BaseObject;
})) as any;
}
getMeshes(): Array<THREE.Object3D | BaseObject> {
const scene = this.getScene();
if (!scene) {
return [];
}
const meshes = [];
for (let i = 0, len = scene.children.length; i < len; i++) {
const child = scene.children[i];
if (child instanceof THREE.Object3D && !(child instanceof THREE.Camera)) {
meshes.push(child['__parent'] || child);
}
}
return meshes;
}
clear() {
return this.clearMesh();
}
clearMesh() {
const scene = this.getScene();
if (!scene) {
return this;
}
for (let i = scene.children.length - 1; i >= 0; i--) {
const child = scene.children[i];
if (child instanceof THREE.Object3D && !(child instanceof THREE.Camera)) {
scene.remove(child);
const parent = child['__parent'];
if (parent && parent instanceof BaseObject) {
parent.isAdd = false;
parent._fire('remove', { target: parent });
delete this._animationBaseObjectMap[child.uuid];
}
}
}
return this;
}
lookAt(vector: THREE.Vector3) {
const renderer = this._getRenderer();
if (renderer) {
renderer.context.lookAt(vector);
}
return this;
}
getCamera(): THREE.Camera {
const renderer = this._getRenderer();
if (renderer) {
return renderer.camera;
}
return null;
}
getScene(): THREE.Scene {
const renderer = this._getRenderer();
if (renderer) {
return renderer.scene;
}
return null;
}
renderScene() {
const renderer = this._getRenderer();
if (renderer) {
renderer.clearCanvas();
renderer.renderScene();
}
return this;
}
loop(render: boolean = false) {
const delayMeshes = this._delayMeshes;
if (!delayMeshes.length) {
return;
}
const map = this.getMap();
if (!map || map.isAnimating() || map.isInteracting()) {
return;
}
const loopRenderCount = this.options.loopRenderCount || 50;
const meshes = delayMeshes.slice(0, loopRenderCount);
if (meshes) {
this.addMesh(meshes, render);
}
delayMeshes.splice(0, loopRenderCount);
}
renderPickScene() {
const renderer = this._getRenderer();
if (renderer) {
const pick = renderer.pick;
if (pick) {
pick.pick(this._containerPoint);
}
}
return this;
}
getThreeRenderer(): THREE.WebGLRenderer {
const renderer = this._getRenderer();
if (renderer) {
return renderer.context;
}
return null;
}
getPick(): GPUPick {
const renderer = this._getRenderer();
if (renderer) {
return renderer.pick;
}
return null;
}
delayAddMesh(meshes: Array<BaseObject>) {
if (!meshes) return this;
if (!Array.isArray(meshes)) {
meshes = [meshes];
}
for (let i = 0, len = meshes.length; i < len; i++) {
this._delayMeshes.push(meshes[i]);
}
return this;
}
/**
* add object3ds
* @param {BaseObject} meshes
*/
addMesh(meshes: Array<BaseObject | THREE.Object3D>, render: boolean = true) {
if (!meshes) return this;
if (!Array.isArray(meshes)) {
meshes = [meshes];
}
const scene = this.getScene();
meshes.forEach(mesh => {
if (mesh instanceof BaseObject) {
scene.add(mesh.getObject3d());
if (!mesh.isAdd) {
mesh.isAdd = true;
mesh._fire('add', { target: mesh });
}
if (mesh._animation && maptalks.Util.isFunction(mesh._animation)) {
this._animationBaseObjectMap[mesh.getObject3d().uuid] = mesh;
}
} else if (mesh instanceof THREE.Object3D) {
scene.add(mesh);
}
});
this._zoomend();
if (render) {
this.renderScene();
}
return this;
}
/**
* remove object3ds
* @param {BaseObject} meshes
*/
removeMesh(meshes: Array<BaseObject | THREE.Object3D>, render: boolean = true) {
if (!meshes) return this;
if (!Array.isArray(meshes)) {
meshes = [meshes];
}
const scene = this.getScene();
meshes.forEach(mesh => {
if (mesh instanceof BaseObject) {
scene.remove(mesh.getObject3d());
if (mesh.isAdd) {
mesh.isAdd = false;
mesh._fire('remove', { target: mesh });
}
if (mesh._animation && maptalks.Util.isFunction(mesh._animation)) {
delete this._animationBaseObjectMap[mesh.getObject3d().uuid];
}
const delayMeshes = this._delayMeshes;
if (delayMeshes.length) {
for (let i = 0, len = delayMeshes.length; i < len; i++) {
if (delayMeshes[i] === mesh) {
delayMeshes.splice(i, 1);
break;
}
}
}
} else if (mesh instanceof THREE.Object3D) {
scene.remove(mesh);
}
});
if (render) {
this.renderScene();
}
return this;
}
_initRaycaster() {
if (!this._raycaster) {
this._raycaster = new THREE.Raycaster();
this._mouse = new THREE.Vector2();
}
return this;
}
/**
*
* @param {Coordinate} coordinate
* @param {Object} options
* @return {Array}
*/
identify(coordinate: maptalks.Coordinate, options: object): Array<BaseObject | THREE.Object3D> {
if (!coordinate) {
console.error('coordinate is null,it should be Coordinate');
return [];
}
if (Array.isArray(coordinate)) {
coordinate = new maptalks.Coordinate(coordinate);
}
if (!(coordinate instanceof maptalks.Coordinate)) {
console.error('coordinate type is error,it should be Coordinate');
return [];
}
const p = this.getMap().coordToContainerPoint(coordinate);
this._containerPoint = p;
const { x, y } = p;
this._initRaycaster();
const raycaster = this._raycaster,
mouse = this._mouse,
camera = this.getCamera(),
scene = this.getScene(),
size = this.getMap().getSize();
//fix Errors will be reported when the layer is not initialized
if (!scene) {
return [];
}
const width = size.width,
height = size.height;
mouse.x = (x / width) * 2 - 1;
mouse.y = -(y / height) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
//set linePrecision for THREE.Line
setRaycasterLinePrecision(raycaster, this._getLinePrecision(this.getMap().getResolution()));
const children: Array<THREE.Object3D> = [], hasidentifyChildren: Array<BaseObject> = [];
scene.children.forEach(mesh => {
const parent = mesh['__parent'];
if (parent && parent.getOptions) {
const baseObject = parent as BaseObject;
const interactive = baseObject.getOptions().interactive;
if (interactive && baseObject.isVisible()) {
//If baseobject has its own hit detection
if (baseObject.identify && maptalks.Util.isFunction(baseObject.identify)) {
hasidentifyChildren.push(baseObject);
} else {
children.push(mesh);
}
}
} else if (mesh instanceof THREE.Mesh || mesh instanceof THREE.Group) {
children.push(mesh);
}
});
let baseObjects: Array<THREE.Object3D | BaseObject> = [];
const intersects = raycaster.intersectObjects(children, true);
if (intersects && Array.isArray(intersects) && intersects.length) {
baseObjects = intersects.map(intersect => {
let object: any = intersect.object;
object = this._recursionMesh(object) || {};
const baseObject = object['__parent'] || object;
baseObject.faceIndex = intersect.faceIndex;
baseObject.index = intersect.index;
return baseObject;
});
}
this.renderPickScene();
if (hasidentifyChildren.length) {
hasidentifyChildren.forEach(baseObject => {
// baseObject identify
if (baseObject.identify(coordinate)) {
baseObjects.push(baseObject);
}
});
}
const len = baseObjects.length;
for (let i = 0; i < len; i++) {
if (baseObjects[i]) {
for (let j = i + 1; j < len; j++) {
if (baseObjects[i] === baseObjects[j]) {
baseObjects.splice(j, 1);
}
}
}
}
options = maptalks.Util.extend({}, options);
const count = options['count'];
return (maptalks.Util.isNumber(count) && count > 0 ? baseObjects.slice(0, count) : baseObjects);
}
/**
* Recursively finding the root node of mesh,Until it is scene node
* @param {*} mesh
*/
_recursionMesh(mesh: THREE.Object3D): THREE.Object3D {
while (mesh && ((mesh.parent !== this.getScene()))) {
mesh = mesh.parent;
}
return mesh;
}
//get Line Precision by Resolution
_getLinePrecision(res = 10): number {
for (let i = 0, len = LINEPRECISIONS.length; i < len; i++) {
const [resLevel, precision] = LINEPRECISIONS[i];
if (res > resLevel) {
return precision;
}
}
return 0.01;
}
/**
* fire baseObject events
* @param {*} e
*/
_identifyBaseObjectEvents(e: any) {
if (!this.options.geometryEvents) {
return this;
}
const map = this.map || this.getMap();
//When map interaction, do not carry out mouse movement detection, which can have better performance
if (map.isInteracting() || !map.options.geometryEvents) {
return this;
}
const { type, coordinate } = e;
const now = maptalks.Util.now();
if (this._mousemoveTimeOut && type === 'mousemove') {
if (now - this._mousemoveTimeOut < 64) {
return this;
}
}
this._mousemoveTimeOut = now;
map.resetCursor('default');
const identifyCountOnEvent = this.options['identifyCountOnEvent'];
let count = Math.max(0, maptalks.Util.isNumber(identifyCountOnEvent) ? identifyCountOnEvent : 0);
if (count === 0) {
count = Infinity;
}
const baseObjects = this.identify(coordinate, { count });
const scene = this.getScene();
if (baseObjects.length === 0 && scene) {
for (let i = 0, len = scene.children.length; i < len; i++) {
const child = scene.children[i] || {};
const parent = child['__parent'];
if (parent) {
(parent as BaseObject).fire('empty', Object.assign({}, e, { target: parent }));
}
}
}
if (type === 'mousemove') {
if (baseObjects.length) {
map.setCursor('pointer');
}
// mouseout objects
const outBaseObjects: Array<THREE.Object3D | BaseObject> = [];
if (this._baseObjects) {
this._baseObjects.forEach(baseObject => {
let isOut = true;
baseObjects.forEach(baseO => {
if (baseObject === baseO) {
isOut = false;
}
});
if (isOut) {
outBaseObjects.push(baseObject);
}
});
}
outBaseObjects.forEach(baseObject => {
if (baseObject && baseObject instanceof BaseObject) {
// reset _mouseover status
// Deal with the mergedmesh
if (baseObject.getSelectMesh) {
if (!baseObject.isHide) {
baseObject._mouseover = false;
baseObject.fire('mouseout', Object.assign({}, e, { target: baseObject, type: 'mouseout', selectMesh: null }));
baseObject.closeToolTip();
}
} else {
baseObject._mouseover = false;
baseObject.fire('mouseout', Object.assign({}, e, { target: baseObject, type: 'mouseout' }));
baseObject.closeToolTip();
}
}
});
baseObjects.forEach(baseObject => {
if (baseObject instanceof BaseObject) {
if (!baseObject._mouseover) {
baseObject.fire('mouseover', Object.assign({}, e, { target: baseObject, type: 'mouseover', selectMesh: (baseObject.getSelectMesh ? baseObject.getSelectMesh() : null) }));
baseObject._mouseover = true;
}
baseObject.fire(type, Object.assign({}, e, { target: baseObject, selectMesh: (baseObject.getSelectMesh ? baseObject.getSelectMesh() : null) }));
// tooltip
const tooltip = baseObject.getToolTip();
if (tooltip && (!tooltip._owner)) {
tooltip.addTo(baseObject);
}
baseObject.openToolTip(coordinate);
}
});
this._baseObjects = baseObjects as any;
} else {
baseObjects.forEach(baseObject => {
if (baseObject instanceof BaseObject) {
baseObject.fire(type, Object.assign({}, e, { target: baseObject, selectMesh: (baseObject.getSelectMesh ? baseObject.getSelectMesh() : null) }));
if (type === 'click') {
const infoWindow = baseObject.getInfoWindow();
if (infoWindow && (!infoWindow._owner)) {
infoWindow.addTo(baseObject);
}
baseObject.openInfoWindow(coordinate);
}
}
});
}
return this;
}
/**
*map zoom event
*/
_zoomend() {
const scene = this.getScene();
if (!scene) {
return;
}
const zoom = this.getMap().getZoom();
scene.children.forEach(mesh => {
const parent = mesh['__parent'];
if (parent && parent.getOptions) {
const baseObject = parent as BaseObject;
if (baseObject.zoomChange && maptalks.Util.isFunction(baseObject.zoomChange)) {
baseObject.zoomChange(zoom);
}
const minZoom = baseObject.getMinZoom(), maxZoom = baseObject.getMaxZoom();
if (zoom < minZoom || zoom > maxZoom) {
if (baseObject.isVisible()) {
baseObject.getObject3d().visible = false;
}
baseObject._zoomVisible = false;
} else if (minZoom <= zoom && zoom <= maxZoom) {
if (baseObject._visible) {
baseObject.getObject3d().visible = true;
}
baseObject._zoomVisible = true;
}
}
});
}
onAdd() {
super.onAdd();
const map = this.map || this.getMap();
if (!map) return this;
EVENTS.forEach(event => {
map.on(event, this._identifyBaseObjectEvents, this);
});
this._needsUpdate = true;
if (!this._animationBaseObjectMap) {
this._animationBaseObjectMap = {};
}
map.on('zooming zoomend', this._zoomend, this);
return this;
}
onRemove() {
super.onRemove();
const map = this.map || this.getMap();
if (!map) return this;
EVENTS.forEach(event => {
map.off(event, this._identifyBaseObjectEvents, this);
});
map.off('zooming zoomend', this._zoomend, this);
return this;
}
_callbackBaseObjectAnimation() {
const layer = this;
if (layer._animationBaseObjectMap) {
for (const uuid in layer._animationBaseObjectMap) {
const baseObject = layer._animationBaseObjectMap[uuid];
baseObject._animation();
}
}
return this;
}
/**
* To make map's 2d point's 1 pixel euqal with 1 pixel on XY plane in THREE's scene:
* 1. fov is 90 and camera's z is height / 2 * scale,
* 2. if fov is not 90, a ratio is caculated to transfer z to the equivalent when fov is 90
* @return {Number} fov ratio on z axis
*/
_getFovRatio(): number {
const map = this.getMap();
const fov = map.getFov();
return Math.tan(fov / 2 * RADIAN);
}
}
ThreeLayer.mergeOptions(options);
class ThreeRenderer extends maptalks.renderer.CanvasLayerRenderer {
scene: THREE.Scene;
camera: THREE.Camera;
canvas: any
layer: ThreeLayer;
gl: any
context: THREE.WebGLRenderer;
matrix4: THREE.Matrix4;
pick: GPUPick;
_renderTime: number = 0;
getPrepareParams(): Array<any> {
return [this.scene, this.camera];
}
getDrawParams(): Array<any> {
return [this.scene, this.camera];
}
_drawLayer() {
super._drawLayer.apply(this, arguments);
// this.renderScene();
}
hitDetect(): boolean {
return false;
}
createCanvas() {
super.createCanvas();
this.createContext();
}
createContext() {
if (this.canvas.gl && this.canvas.gl.wrap) {
this.gl = this.canvas.gl.wrap();
} else {
const layer = this.layer;
const attributes = layer.options.glOptions || {
alpha: true,
depth: true,
antialias: true,
stencil: true,
preserveDrawingBuffer: false
};
attributes.preserveDrawingBuffer = true;
this.gl = this.gl || this._createGLContext(this.canvas, attributes);
}
this._initThreeRenderer();
this.layer.onCanvasCreate(this.context, this.scene, this.camera);
}
_initThreeRenderer() {
this.matrix4 = new THREE.Matrix4();
const renderer = new THREE.WebGLRenderer({ 'context': this.gl, alpha: true });
renderer.autoClear = false;
renderer.setClearColor(new THREE.Color(1, 1, 1), 0);
renderer.setSize(this.canvas.width, this.canvas.height);
renderer.clear();
// renderer.canvas = this.canvas;
this.context = renderer;
const scene = this.scene = new THREE.Scene();
const map = this.layer.getMap();
const fov = map.getFov() * Math.PI / 180;
const camera = this.camera = new THREE.PerspectiveCamera(fov, map.width / map.height, map.cameraNear, map.cameraFar);
camera.matrixAutoUpdate = false;
this._syncCamera();
scene.add(camera);
this.pick = new GPUPick(this.layer);
}
onCanvasCreate() {
super.onCanvasCreate();
}
resizeCanvas(canvasSize: maptalks.Size) {
if (!this.canvas) {
return;
}
let size, map = this.getMap();
if (!canvasSize) {
size = map.getSize();
} else {
size = canvasSize;
}
// const r = maptalks.Browser.retina ? 2 : 1;
const r = map.getDevicePixelRatio ? map.getDevicePixelRatio() : (maptalks.Browser.retina ? 2 : 1);
const canvas = this.canvas;
//retina support
canvas.height = r * size['height'];
canvas.width = r * size['width'];
if (this.layer._canvas && canvas.style) {
canvas.style.width = size.width + 'px';
canvas.style.height = size.height + 'px';
}
this.context.setSize(canvas.width, canvas.height);
}
clearCanvas() {
if (!this.canvas) {
return;
}
this.context.clear();
}
prepareCanvas(): any {
if (!this.canvas) {
this.createCanvas();
} else {
this.clearCanvas();
}
this.layer.fire('renderstart', { 'context': this.context });
return null;
}
renderScene() {
const time = maptalks.Util.now();
// Make sure to execute only once in a frame
if (time - this._renderTime >= 16) {
this.layer._callbackBaseObjectAnimation();
this._renderTime = time;
}
this._syncCamera();
this.context.render(this.scene, this.camera);
this.completeRender();
}
remove() {
delete this._drawContext;
super.remove();
}
_syncCamera() {
const map = this.getMap();
const camera = this.camera;
camera.matrix.elements = map.cameraWorldMatrix;
camera.projectionMatrix.elements = map.projMatrix;
//https://github.com/mrdoob/three.js/commit/d52afdd2ceafd690ac9e20917d0c968ff2fa7661
if (this.matrix4.invert) {
camera.projectionMatrixInverse.elements = this.matrix4.copy(camera.projectionMatrix).invert().elements;
} else {
camera.projectionMatrixInverse.elements = this.matrix4.getInverse(camera.projectionMatrix).elements;
}
}
_createGLContext(canvas: HTMLCanvasElement, options: object) {
const names = ['webgl2', 'webgl', 'experimental-webgl'];
let context = null;
/* eslint-disable no-empty */
for (let i = 0; i < names.length; ++i) {
try {
context = canvas.getContext(names[i], options);
} catch (e) { }
if (context) {
break;
}
}
return context;
/* eslint-enable no-empty */
}
}
ThreeLayer.registerRenderer('gl', ThreeRenderer);
function getGLRes(map: maptalks.Map) {
return map.getGLRes ? map.getGLRes() : map.getGLZoom();
}
function coordinateToPoint(map, coordinate, res, out?: any) {
if (map.coordToPointAtRes) {
return map.coordToPointAtRes(coordinate, res, out);
}
return map.coordinateToPoint(coordinate, res, out);
}
export {
ThreeLayer, ThreeRenderer, BaseObject,
MergedMixin,
GeoJSONUtil, MergeGeometryUtil, GeoUtil, ExtrudeUtil, LineUtil,
IdentifyUtil, geometryExtrude,
LineMaterial
};
if (maptalks.registerWorkerAdapter) {
maptalks.registerWorkerAdapter(getWorkerName(), getWorkerCode());
} | the_stack |
'use strict';
// // These must be in the files to translate
// // This cannot be placed in a library.
// import * as nls from 'vscode-nls';
// const config = JSON.parse(process.env.VSCODE_NLS_CONFIG as string);
// const localize = nls.config(config as nls.Options)();
import * as path from 'path';
import * as vscode from 'vscode';
import { IExternalAPI } from 'vscode-wpilibapi';
import { BuildTestAPI } from './buildtestapi';
import { BuiltinTools } from './builtintools';
import { CommandAPI } from './commandapi';
import { activateCpp } from './cpp/cpp';
import { ApiProvider } from './cppprovider/apiprovider';
import { DeployDebugAPI } from './deploydebugapi';
import { ExecuteAPI } from './executor';
import { activateJava } from './java/java';
import { findJdkPath } from './jdkdetector';
import { localize as i18n } from './locale';
import { closeLogger, getMainLogFile, logger, setLoggerDirectory } from './logger';
import { PersistentFolderState } from './persistentState';
import { Preferences } from './preferences';
import { PreferencesAPI } from './preferencesapi';
import { ProjectInfoGatherer } from './projectinfo';
import { ExampleTemplateAPI } from './shared/exampletemplateapi';
import { UtilitiesAPI } from './shared/utilitiesapi';
import { addVendorExamples } from './shared/vendorexamples';
import { ToolAPI } from './toolapi';
import { existsAsync, mkdirpAsync, setExtensionContext, setJavaHome } from './utilities';
import { fireVendorDepsChanged, VendorLibraries } from './vendorlibraries';
import { createVsCommands } from './vscommands';
import { AlphaError } from './webviews/alphaerror';
import { Gradle2020Import } from './webviews/gradle2020import';
import { Help } from './webviews/help';
import { ProjectCreator } from './webviews/projectcreator';
import { WPILibUpdates } from './wpilibupdates';
// External API class to implement the IExternalAPI interface
class ExternalAPI implements IExternalAPI {
// Create method is used because constructors cannot be async.
public static async Create(resourceFolder: string): Promise<ExternalAPI> {
const preferencesApi = await PreferencesAPI.Create();
const deployDebugApi = await DeployDebugAPI.Create(resourceFolder, preferencesApi);
const buildTestApi = new BuildTestAPI(preferencesApi);
const externalApi = new ExternalAPI(preferencesApi, deployDebugApi, buildTestApi);
return externalApi;
}
private readonly toolApi: ToolAPI;
private readonly deployDebugApi: DeployDebugAPI;
private readonly buildTestApi: BuildTestAPI;
private readonly preferencesApi: PreferencesAPI;
private readonly exampleTemplateApi: ExampleTemplateAPI;
private readonly commandApi: CommandAPI;
private readonly executeApi: ExecuteAPI;
private readonly utilitiesApi: UtilitiesAPI;
private constructor(preferencesApi: PreferencesAPI, deployDebugApi: DeployDebugAPI, buildTestApi: BuildTestAPI) {
this.exampleTemplateApi = new ExampleTemplateAPI();
this.commandApi = new CommandAPI();
this.executeApi = new ExecuteAPI();
this.preferencesApi = preferencesApi;
this.deployDebugApi = deployDebugApi;
this.buildTestApi = buildTestApi;
this.utilitiesApi = new UtilitiesAPI();
this.toolApi = new ToolAPI(this);
}
public getToolAPI(): ToolAPI {
return this.toolApi;
}
public getExampleTemplateAPI(): ExampleTemplateAPI {
return this.exampleTemplateApi;
}
public getDeployDebugAPI(): DeployDebugAPI {
return this.deployDebugApi;
}
public getPreferencesAPI(): PreferencesAPI {
return this.preferencesApi;
}
public getCommandAPI(): CommandAPI {
return this.commandApi;
}
public getBuildTestAPI(): BuildTestAPI {
return this.buildTestApi;
}
public getExecuteAPI(): ExecuteAPI {
return this.executeApi;
}
public getUtilitiesAPI(): UtilitiesAPI {
return this.utilitiesApi;
}
}
let updatePromptCount = 0;
async function handleAfterTrusted(externalApi: ExternalAPI, context: vscode.ExtensionContext,
creationError: boolean, extensionResourceLocation: string,
gradle2020import: Gradle2020Import | undefined,
help: Help | undefined) {
// Only trusted workspace code can occur below here
let jdkLoc = await findJdkPath(externalApi);
if (jdkLoc !== undefined) {
if (jdkLoc.endsWith('\\') || jdkLoc.endsWith('/')) {
jdkLoc = jdkLoc.substring(0, jdkLoc.length - 1);
}
setJavaHome(jdkLoc);
} else {
vscode.window.showErrorMessage(i18n('message', 'Java 11 required, but not found. Might have compilation errors.'));
}
// Activate the C++ parts of the extension
await activateCpp(context, externalApi);
// Active the java parts of the extension
await activateJava(context, externalApi);
try {
// Add built in tools
context.subscriptions.push(await BuiltinTools.Create(externalApi));
} catch (err) {
logger.error('error creating built in tool handler', err);
creationError = true;
}
let vendorLibs: VendorLibraries | undefined;
try {
vendorLibs = new VendorLibraries(externalApi);
context.subscriptions.push(vendorLibs);
await addVendorExamples(extensionResourceLocation, externalApi.getExampleTemplateAPI(), externalApi.getUtilitiesAPI(), vendorLibs);
} catch (err) {
logger.error('error creating vendor lib utilities', err);
creationError = true;
}
let wpilibUpdate: WPILibUpdates | undefined;
try {
wpilibUpdate = new WPILibUpdates(externalApi);
context.subscriptions.push(wpilibUpdate);
} catch (err) {
logger.error('error creating wpilib updater', err);
creationError = true;
}
let projectInfo: ProjectInfoGatherer | undefined;
try {
if (wpilibUpdate !== undefined && vendorLibs !== undefined) {
projectInfo = new ProjectInfoGatherer(vendorLibs, wpilibUpdate, externalApi);
context.subscriptions.push(projectInfo);
}
} catch (err) {
logger.error('error creating project info gatherer', err);
creationError = true;
}
// Create all of our commands that the extension runs
createVsCommands(context, externalApi);
// Detect if we are a new WPILib project, and if so display the WPILib help window.
// Also check for local GradleRIO update
const wp = vscode.workspace.workspaceFolders;
if (wp) {
for (const w of wp) {
const prefs = externalApi.getPreferencesAPI().getPreferences(w);
if (prefs.getIsWPILibProject()) {
const vendorDepsPattern = new vscode.RelativePattern(path.join(w.uri.fsPath, 'vendordeps'), '**/*.json');
const vendorDepsWatcher = vscode.workspace.createFileSystemWatcher(vendorDepsPattern);
context.subscriptions.push(vendorDepsWatcher);
const localW = w;
const fireEvent = () => {
fireVendorDepsChanged(localW);
};
vendorDepsWatcher.onDidChange(fireEvent, null, context.subscriptions);
vendorDepsWatcher.onDidCreate(fireEvent, null, context.subscriptions);
vendorDepsWatcher.onDidDelete(fireEvent, null, context.subscriptions);
if (prefs.getProjectYear() === 'intellisense') {
logger.log('Intellisense only build project found');
continue;
}
if (prefs.getProjectYear() !== '2022beta') {
const importPersistantState = new PersistentFolderState('wpilib.2022betapersist', false, w.uri.fsPath);
if (importPersistantState.Value === false) {
const upgradeResult = await vscode.window.showInformationMessage(i18n('message',
'This project is not compatible with this version of the extension. Would you like to import this project into 2022beta?.'), {
modal: true,
}, 'Yes', 'No', 'No, Don\'t ask again');
if (upgradeResult === 'Yes') {
if (gradle2020import) {
await gradle2020import.startWithProject(w.uri);
}
} else if (upgradeResult === 'No, Don\'t ask again') {
importPersistantState.Value = true;
}
}
continue;
}
if (prefs.getCurrentLanguage() === 'cpp' || prefs.getCurrentLanguage() === 'java') {
let didUpdate: boolean = false;
if (wpilibUpdate) {
didUpdate = await wpilibUpdate.checkForInitialUpdate(w);
}
let runBuild: boolean = !await existsAsync(path.join(w.uri.fsPath, 'build'));
if (didUpdate) {
const result = await vscode.window.showInformationMessage(i18n('message',
'It is recommended to run a "Build" after a WPILib update to ensure dependencies are installed correctly. ' +
'Would you like to do this now?'), {
modal: true,
}, i18n('ui', 'Yes'), i18n('ui', 'No'));
if (result !== i18n('ui', 'Yes')) {
runBuild = false;
}
}
if (runBuild) {
updatePromptCount++;
externalApi.getBuildTestAPI().buildCode(w, undefined).then(() => {
updatePromptCount--;
if (updatePromptCount === 0) {
ApiProvider.promptForUpdates = true;
}
}).catch(() => {
updatePromptCount--;
if (updatePromptCount === 0) {
ApiProvider.promptForUpdates = true;
}
});
}
}
const persistentState = new PersistentFolderState('wpilib.newProjectHelp', false, w.uri.fsPath);
if (persistentState.Value === false) {
persistentState.Value = true;
if (help) {
help.displayHelp();
}
break;
}
} else {
const persistentState = new PersistentFolderState('wpilib.invalidFolder', false, w.uri.fsPath);
if (persistentState.Value === false) {
// Check if wpilib project might be in a subfolder
// Only go 1 subfolder deep
const pattern = new vscode.RelativePattern(w, '*/' + Preferences.wpilibPreferencesFolder + '/' + Preferences.preferenceFileName);
const wpilibFiles = await vscode.workspace.findFiles(pattern);
if (wpilibFiles.length === 1) {
// Only 1 subfolder found, likely it
const openResult = await vscode.window.showInformationMessage(i18n('message', 'Incorrect folder opened for WPILib project. ' +
'The correct folder was found in a subfolder, ' +
'Would you like to open it? Selecting no will cause many tasks to not work.'), {
modal: true,
}, i18n('ui', 'Yes'), i18n('ui', 'No'), i18n('ui', 'No, Don\'t ask again for this folder'));
if (openResult === i18n('ui', 'Yes')) {
const wpRoot = vscode.Uri.file(path.dirname(path.dirname(wpilibFiles[0].fsPath)));
await vscode.commands.executeCommand('vscode.openFolder', wpRoot, false);
} else if (openResult === i18n('ui', 'No, Don\'t ask again for this folder')) {
persistentState.Value = true;
}
} else if (wpilibFiles.length > 1) {
// Multiple subfolders found
const openResult = await vscode.window.showInformationMessage('Incorrect folder opened for WPILib project. ' +
'Multiple possible subfolders found, ' +
'Would you like to open one? Selecting no will cause many tasks to not work.', {
modal: true,
}, i18n('ui', 'Yes'), i18n('ui', 'No'), i18n('ui', 'No, Don\'t ask again for this folder'));
if (openResult === i18n('ui', 'Yes')) {
const list = wpilibFiles.map((value) => {
const fullRoot = path.dirname(path.dirname(value.fsPath));
const baseFolder = path.basename(fullRoot);
return {
fullFolder: vscode.Uri.file(fullRoot),
label: baseFolder,
};
});
const picked = await vscode.window.showQuickPick(list, {
canPickMany: false,
});
if (picked !== undefined) {
await vscode.commands.executeCommand('vscode.openFolder', picked.fullFolder, false);
}
} else if (openResult === i18n('ui', 'No, Don\'t ask again for this folder')) {
persistentState.Value = true;
}
}
}
}
}
}
if (creationError) {
vscode.window.showErrorMessage('A portion of WPILib failed to initialize. See log for details');
}
// Log our extension is active
logger.log('Congratulations, your extension "vscode-wpilib" is now active!');
if (updatePromptCount === 0) {
ApiProvider.promptForUpdates = true;
}
return externalApi;
}
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export async function activate(context: vscode.ExtensionContext) {
setExtensionContext(context);
// Resources folder is used for gradle template along with HTML files
const extensionResourceLocation = path.join(context.extensionPath, 'resources');
if (vscode.extensions.getExtension('wpifirst.vscode-wpilib') !== undefined) {
const alphaError = await AlphaError.Create(extensionResourceLocation);
alphaError.displayPage();
context.subscriptions.push(alphaError);
return;
}
// The external API can be used by other extensions that want to use our
// functionality. Its definition is provided in shared/externalapi.ts.
// That file can be copied to another project.
const externalApi = await ExternalAPI.Create(extensionResourceLocation);
const frcHomeDir = externalApi.getUtilitiesAPI().getWPILibHomeDir();
const logPath = path.join(frcHomeDir, 'logs');
try {
await mkdirpAsync(logPath);
setLoggerDirectory(logPath);
} catch (err) {
logger.error('Error creating logger', err);
}
let creationError: boolean = false;
let help: Help | undefined;
try {
// Create the help window provider
help = await Help.Create(externalApi.getPreferencesAPI(), extensionResourceLocation);
context.subscriptions.push(help);
} catch (err) {
logger.error('error creating help window provider', err);
creationError = true;
}
let gradle2020import: Gradle2020Import | undefined;
try {
// Create the gradle 2020 import provider
gradle2020import = await Gradle2020Import.Create(extensionResourceLocation);
context.subscriptions.push(gradle2020import);
} catch (err) {
logger.error('error creating gradle 2020 importer', err);
creationError = true;
}
try {
// Create the new project creator provider
const projectcreator = await ProjectCreator.Create(externalApi.getExampleTemplateAPI(), extensionResourceLocation);
context.subscriptions.push(projectcreator);
} catch (err) {
logger.error('error creating project creator', err);
creationError = true;
}
context.subscriptions.push(vscode.commands.registerCommand('wpilibcore.showLogFolder', async () => {
let mainLog = getMainLogFile();
if (!await existsAsync(mainLog)) {
mainLog = path.dirname(mainLog);
}
await vscode.commands.executeCommand('revealFileInOS', vscode.Uri.file(mainLog));
}));
context.subscriptions.push(vscode.commands.registerCommand('wpilibcore.openCommandPalette', async () => {
await vscode.commands.executeCommand('workbench.action.quickOpen', '>WPILib ');
}));
if (!vscode.workspace.isTrusted) {
if (creationError) {
vscode.window.showErrorMessage('A portion of WPILib failed to initialize. See log for details');
}
vscode.workspace.onDidGrantWorkspaceTrust(async () => {
await handleAfterTrusted(externalApi, context, creationError, extensionResourceLocation, gradle2020import, help);
});
return externalApi;
}
await handleAfterTrusted(externalApi, context, creationError, extensionResourceLocation, gradle2020import, help);
return externalApi;
}
// this method is called when your extension is deactivated
export function deactivate() {
closeLogger();
} | the_stack |
import BigNumber from 'bignumber.js';
import Decoder from './decoder';
import ParamType from '../spec/paramType';
import Token from '../token';
import { padU32 } from '../util/pad';
describe('decoder/Decoder', () => {
const stringToBytes = function (str: string) {
const matches = str.match(/.{1,2}/g);
if (!matches) {
throw new Error('stringToBytes: mo matches');
}
return matches.map(code => parseInt(code, 16));
};
const address1 =
'0000000000000000000000001111111111111111111111111111111111111111';
const address2 =
'0000000000000000000000002222222222222222222222222222222222222222';
const address3 =
'0000000000000000000000003333333333333333333333333333333333333333';
const address4 =
'0000000000000000000000004444444444444444444444444444444444444444';
const bool1 =
'0000000000000000000000000000000000000000000000000000000000000001';
const bytes1 =
'1234000000000000000000000000000000000000000000000000000000000000';
const bytes2 =
'1000000000000000000000000000000000000000000000000000000000000000';
const bytes3 =
'10000000000000000000000000000000000000000000000000000000000002';
const bytes4 =
'0010000000000000000000000000000000000000000000000000000000000002';
const int1 =
'0111111111111111111111111111111111111111111111111111111111111111';
const intn =
'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff85';
const string1 =
'6761766f66796f726b0000000000000000000000000000000000000000000000';
const string2 =
'4665726ee16e64657a0000000000000000000000000000000000000000000000';
const tokenAddress1 = new Token('address', `0x${address1.slice(-40)}`);
const tokenAddress2 = new Token('address', `0x${address2.slice(-40)}`);
const tokenAddress3 = new Token('address', `0x${address3.slice(-40)}`);
const tokenAddress4 = new Token('address', `0x${address4.slice(-40)}`);
const tokenBool1 = new Token('bool', true);
const tokenFixedBytes1 = new Token('fixedBytes', [0x12, 0x34]);
const tokenBytes1 = new Token('bytes', [0x12, 0x34]);
const tokenBytes2 = new Token(
'bytes',
stringToBytes(bytes2).concat(stringToBytes(bytes2))
);
const tokenBytes3 = new Token('bytes', stringToBytes(bytes3));
const tokenBytes4 = new Token('bytes', stringToBytes(bytes4));
const tokenInt1 = new Token('int', new BigNumber(int1, 16));
const tokenIntn = new Token('int', new BigNumber(-123));
const tokenUint1 = new Token('uint', new BigNumber(int1, 16));
const tokenUintn = new Token('uint', new BigNumber(intn, 16));
const tokenString1 = new Token('string', 'gavofyork');
const tokenString2 = new Token('string', 'Fernández');
const slices = [address1, address2, address3, address4];
describe('peek', () => {
it('returns the slice at the correct position', () => {
expect(Decoder.peek(slices, 1)).toEqual(slices[1]);
});
it('returns empty on invalid slices', () => {
expect(Decoder.peek(null, 4)).toEqual(
'0000000000000000000000000000000000000000000000000000000000000000'
);
});
});
describe('takeBytes', () => {
it('returns a single slice', () => {
expect(Decoder.takeBytes(slices, 0, 32).bytes).toEqual(
stringToBytes(slices[0])
);
});
it('returns a single partial slice', () => {
expect(Decoder.takeBytes(slices, 0, 20).bytes).toEqual(
stringToBytes(slices[0].substr(0, 40))
);
});
it('returns multiple slices', () => {
expect(Decoder.takeBytes(slices, 0, 64).bytes).toEqual(
stringToBytes(`${slices[0]}${slices[1]}`)
);
});
it('returns a single offset slice', () => {
expect(Decoder.takeBytes(slices, 1, 32).bytes).toEqual(
stringToBytes(slices[1])
);
});
it('returns multiple offset slices', () => {
expect(Decoder.takeBytes(slices, 1, 64).bytes).toEqual(
stringToBytes(`${slices[1]}${slices[2]}`)
);
});
it('returns the requires length from slices', () => {
expect(Decoder.takeBytes(slices, 1, 75).bytes).toEqual(
stringToBytes(`${slices[1]}${slices[2]}${slices[3]}`.substr(0, 150))
);
});
it('returns with empty inputs', () => {
expect(Decoder.takeBytes([], 0, 0).bytes).toEqual([]);
});
});
describe('decodeParam', () => {
it('throws an error on non ParamType param', () => {
expect(() =>
Decoder.decodeParam({} as ParamType, undefined, undefined)
).toThrow(/ParamType/);
});
it('throws an error on invalid param type', () => {
const pt = new ParamType('address');
// @ts-ignore We uglily set the type here.
pt._type = 'noMatch';
expect(() => Decoder.decodeParam(pt, undefined, undefined)).toThrow(
/noMatch/
);
});
it('decodes an address', () => {
expect(
Decoder.decodeParam(new ParamType('address'), [address1], 0).token
).toEqual(tokenAddress1);
});
it('decodes a bool', () => {
expect(
Decoder.decodeParam(new ParamType('bool'), [bool1], 0).token
).toEqual(tokenBool1);
});
it('decodes an int', () => {
expect(
Decoder.decodeParam(new ParamType('int'), [int1], 0).token
).toEqual(tokenInt1);
});
it('decodes a negative int', () => {
expect(
Decoder.decodeParam(new ParamType('int'), [intn], 0).token
).toEqual(tokenIntn);
});
it('decodes an uint', () => {
expect(
Decoder.decodeParam(new ParamType('uint'), [int1], 0).token
).toEqual(tokenUint1);
});
it('decodes an uint (negative as int)', () => {
expect(
Decoder.decodeParam(new ParamType('uint'), [intn], 0).token
).toEqual(tokenUintn);
});
it('decodes fixedBytes', () => {
expect(
Decoder.decodeParam(
new ParamType('fixedBytes', undefined, 2),
[bytes1],
0
).token
).toEqual(tokenFixedBytes1);
});
it('decodes bytes', () => {
expect(
Decoder.decodeParam(
new ParamType('bytes'),
[padU32(0x20), padU32(2), bytes1],
0
).token
).toEqual(tokenBytes1);
});
it('decodes string', () => {
expect(
Decoder.decodeParam(
new ParamType('string'),
[padU32(0x20), padU32(9), string1],
0
).token
).toEqual(tokenString1);
});
it('decodes utf8-invalid string', () => {
expect(
Decoder.decodeParam(
new ParamType('string'),
[padU32(0x20), padU32(9), string2],
0
).token
).toEqual(tokenString2);
});
it('decodes string (indexed)', () => {
expect(
Decoder.decodeParam(
new ParamType('string', undefined, 0, true),
[bytes1],
0
)
).toEqual(
Decoder.decodeParam(
new ParamType('fixedBytes', undefined, 32, true),
[bytes1],
0
)
);
});
});
describe('decode', () => {
it('throws an error on invalid params', () => {
expect(() => Decoder.decode(undefined, '123')).toThrow(/array/);
});
describe('address', () => {
it('decodes an address', () => {
expect(
Decoder.decode([new ParamType('address')], `${address1}`)
).toEqual([tokenAddress1]);
});
it('decodes 2 addresses', () => {
expect(
Decoder.decode(
[new ParamType('address'), new ParamType('address')],
`${address1}${address2}`
)
).toEqual([tokenAddress1, tokenAddress2]);
});
it('decodes a fixedArray of addresses', () => {
expect(
Decoder.decode(
[new ParamType('fixedArray', new ParamType('address'), 2)],
`${address1}${address2}`
)
).toEqual([new Token('fixedArray', [tokenAddress1, tokenAddress2])]);
});
it('decodes a dynamic array of addresses', () => {
expect(
Decoder.decode(
[new ParamType('array', new ParamType('address'))],
`${padU32(0x20)}${padU32(2)}${address1}${address2}`
)
).toEqual([new Token('array', [tokenAddress1, tokenAddress2])]);
});
it('decodes a dynamic array of fixed arrays', () => {
expect(
Decoder.decode(
[
new ParamType(
'array',
new ParamType('fixedArray', new ParamType('address'), 2)
)
],
`${padU32(0x20)}${padU32(
2
)}${address1}${address2}${address3}${address4}`
)
).toEqual([
new Token('array', [
new Token('fixedArray', [tokenAddress1, tokenAddress2]),
new Token('fixedArray', [tokenAddress3, tokenAddress4])
])
]);
});
});
describe('int', () => {
it('decodes an int', () => {
expect(Decoder.decode([new ParamType('int')], `${int1}`)).toEqual([
tokenInt1
]);
});
});
describe('uint', () => {
it('decodes an uint', () => {
expect(Decoder.decode([new ParamType('uint')], `${int1}`)).toEqual([
tokenUint1
]);
});
});
describe('fixedBytes', () => {
it('decodes fixedBytes', () => {
expect(
Decoder.decode(
[new ParamType('fixedBytes', undefined, 2)],
`${bytes1}`
)
).toEqual([tokenFixedBytes1]);
});
});
describe('bytes', () => {
it('decodes bytes', () => {
expect(
Decoder.decode(
[new ParamType('bytes')],
`${padU32(0x20)}${padU32(2)}${bytes1}`
)
).toEqual([tokenBytes1]);
});
it('decodes bytes sequence', () => {
expect(
Decoder.decode(
[new ParamType('bytes')],
`${padU32(0x20)}${padU32(0x40)}${bytes2}${bytes2}`
)
).toEqual([tokenBytes2]);
});
it('decodes bytes seuence (2)', () => {
expect(
Decoder.decode(
[new ParamType('bytes'), new ParamType('bytes')],
`${padU32(0x40)}${padU32(0x80)}${padU32(0x1f)}${bytes3}00${padU32(
0x20
)}${bytes4}`
)
).toEqual([tokenBytes3, tokenBytes4]);
});
});
describe('bool', () => {
it('decodes a single bool', () => {
expect(Decoder.decode([new ParamType('bool')], bool1)).toEqual([
tokenBool1
]);
});
});
describe('string', () => {
it('decodes a string', () => {
expect(
Decoder.decode(
[new ParamType('string')],
`${padU32(0x20)}${padU32(9)}${string1}`
)
).toEqual([tokenString1]);
});
});
});
}); | the_stack |
import * as d3 from 'd3';
import './PieChart.scss';
import Utils from "../../Utils";
import { TooltipMeasureFormat } from "./../../Constants/Enums";
import Legend from './../Legend';
import ContextMenu from './../ContextMenu';
import { PieChartData } from '../../Models/PieChartData';
import Slider from '../Slider';
import Tooltip from '../Tooltip';
import { ChartVisualizationComponent } from '../../Interfaces/ChartVisualizationComponent';
class PieChart extends ChartVisualizationComponent {
private contextMenu: ContextMenu;
chartComponentData = new PieChartData();
constructor(renderTarget: Element){
super(renderTarget);
this.chartMargins = {
top: 20,
bottom: 28,
left: 0,
right: 0
}
}
PieChart() { }
public render(data: any, options: any, aggregateExpressionOptions: any) {
super.render(data, options, aggregateExpressionOptions);
this.chartComponentData.mergeDataToDisplayStateAndTimeArrays(this.data, this.chartOptions.timestamp, this.aggregateExpressionOptions);
var timestamp = (options && options.timestamp != undefined) ? options.timestamp : this.chartComponentData.allTimestampsArray[0];
var targetElement = d3.select(this.renderTarget)
.classed("tsi-pieChart", true);
if (this.svgSelection == null) {
this.svgSelection = targetElement.append("svg")
.attr("class", "tsi-pieChartSVG tsi-chartSVG")
.attr('title', this.getString('Pie chart'));
var g = this.svgSelection.append("g");
var tooltip = new Tooltip(d3.select(this.renderTarget));
d3.select(this.renderTarget).append('div').classed('tsi-sliderWrapper', true);
this.draw = (isFromResize = false) => {
// Determine the number of timestamps present, add margin for slider
if(this.chartComponentData.allTimestampsArray.length > 1)
this.chartMargins.bottom = 68;
if(this.chartOptions.legend == "compact") {
this.chartMargins.top = 68;
} else {
this.chartMargins.top = 20;
}
this.width = this.getWidth();
var height = +targetElement.node().getBoundingClientRect().height;
if (!isFromResize) {
this.chartWidth = this.getChartWidth();
}
var chartHeight = height;
var usableHeight = height - this.chartMargins.bottom - this.chartMargins.top
var outerRadius = (Math.min(usableHeight, this.chartWidth) - 10) / 2;
var innerRadius = this.chartOptions.arcWidthRatio &&
(this.chartOptions.arcWidthRatio < 1 && this.chartOptions.arcWidthRatio > 0) ?
outerRadius - (outerRadius * this.chartOptions.arcWidthRatio) :
0;
this.svgSelection
.attr("width", this.chartWidth)
.attr("height", chartHeight)
this.svgSelection.select("g").attr("transform", "translate(" + (this.chartWidth / 2) + "," + (chartHeight / 2) + ")");
var timestamp = (this.chartOptions.timestamp != undefined) ? this.chartOptions.timestamp : this.chartComponentData.allTimestampsArray[0];
this.chartComponentData.updateFlatValueArray(timestamp);
super.themify(targetElement, this.chartOptions.theme);
if (!this.chartOptions.hideChartControlPanel && this.chartControlsPanel === null) {
this.chartControlsPanel = Utils.createControlPanel(this.renderTarget, this.CONTROLSWIDTH, this.chartMargins.top, this.chartOptions);
} else if (this.chartOptions.hideChartControlPanel && this.chartControlsPanel !== null){
this.removeControlPanel();
}
if (this.ellipsisItemsExist() && !this.chartOptions.hideChartControlPanel) {
this.drawEllipsisMenu();
this.chartControlsPanel.style("top", Math.max((this.chartMargins.top - 24), 0) + 'px');
} else {
this.removeControlPanel();
}
var labelMouseover = (aggKey: string, splitBy: string = null) => {
//filter out the selected timeseries/splitby
var selectedFilter = (d: any, j: number ) => {
return !(d.data.aggKey == aggKey && (splitBy == null || d.data.splitBy == splitBy))
}
this.svgSelection.selectAll(".tsi-pie-path")
.filter(selectedFilter)
.attr("stroke-opacity", .3)
.attr("fill-opacity", .3);
}
var labelMouseout = (aggregateKey: string, splitBy: string) => {
this.svgSelection.selectAll(".tsi-pie-path")
.attr("stroke-opacity", 1)
.attr("fill-opacity", 1);
}
function drawTooltip (d: any, mousePosition) {
var xPos = mousePosition[0];
var yPos = mousePosition[1];
tooltip.render(self.chartOptions.theme);
let color = Utils.colorSplitBy(self.chartComponentData.displayState, d.data.splitByI, d.data.aggKey, self.chartOptions.keepSplitByColor);
tooltip.draw(d, self.chartComponentData, xPos, yPos, {...self.chartMargins, top: 0, bottom: 0}, (text) => {
self.tooltipFormat(self.convertToTimeValueFormat(d.data), text, TooltipMeasureFormat.SingleValue);
}, null, 20, 20, color);
}
this.legendObject.draw(this.chartOptions.legend, this.chartComponentData, labelMouseover,
this.svgSelection, this.chartOptions, labelMouseout);
var pie = d3.pie()
.sort(null)
.value(function(d: any) {
return Math.abs(d.val);
});
var path: any = d3.arc()
.outerRadius(outerRadius)
.innerRadius(innerRadius);
var arc = g.selectAll(".tsi-pie-arc")
.data(pie(this.chartComponentData.flatValueArray));
var arcEntered = arc
.enter().append("g")
.merge(arc)
.attr("class", "tsi-pie-arc");
var self = this;
var drawArc = d3.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius);
function arcTween(a) {
var i = d3.interpolate(this._current, a);
this._current = i(0);
return function(t) {
return drawArc(i(t));
};
}
var self = this;
function pathMouseout (d: any) {
if (self.contextMenu && self.contextMenu.contextMenuVisible)
return;
tooltip.hide();
labelMouseout(d.data.aggKey, d.data.splitBy);
(<any>self.legendObject.legendElement.selectAll('.tsi-splitByLabel')).classed("inFocus", false);
}
function pathMouseInteraction (d: any) {
if (this.contextMenu && this.contextMenu.contextMenuVisible)
return;
pathMouseout(d);
labelMouseover(d.data.aggKey, d.data.splitBy);
(<any>self.legendObject.legendElement.selectAll('.tsi-splitByLabel').filter(function (filteredSplitBy: string) {
return (d3.select(this.parentNode).datum() == d.data.aggKey) && (filteredSplitBy == d.data.splitBy);
})).classed("inFocus", true);
drawTooltip(d, d3.mouse(self.svgSelection.node()));
}
var mouseOutArcOnContextMenuClick = () => {
arcEntered.selectAll("path").each(pathMouseout);
}
arcEntered.each(function () {
var pathElem = d3.select(this).selectAll(".tsi-pie-path").data(d => [d]);
var pathEntered = pathElem.enter()
.append("path")
.attr("class", "tsi-pie-path")
.attr("d", drawArc)
.on("mouseover", pathMouseInteraction)
.on("mousemove" , pathMouseInteraction)
.on("mouseout", pathMouseout)
.on("contextmenu", (d: any, i) => {
if (self.chartComponentData.displayState[d.data.aggKey].contextMenuActions &&
self.chartComponentData.displayState[d.data.aggKey].contextMenuActions.length) {
var mousePosition = d3.mouse(<any>targetElement.node());
d3.event.preventDefault();
self.contextMenu.draw(self.chartComponentData, self.renderTarget, self.chartOptions,
mousePosition, d.data.aggKey, d.data.splitBy, mouseOutArcOnContextMenuClick,
new Date(self.chartComponentData.timestamp));
}
})
.each(function(d) { (<any>this)._current = d; })
.merge(pathElem)
.transition()
.duration(self.TRANSDURATION)
.ease(d3.easeExp)
.attrTween("d", arcTween)
.attr("fill", (d: any) => {
return Utils.colorSplitBy(self.chartComponentData.displayState, d.data.splitByI, d.data.aggKey, self.chartOptions.keepSplitByColor);
})
.attr("class", "tsi-pie-path");
});
arc.exit().remove();
/******************** Temporal Slider ************************/
if(this.chartComponentData.allTimestampsArray.length > 1){
d3.select(this.renderTarget).select('.tsi-sliderWrapper').classed('tsi-hidden', false);
slider.render(this.chartComponentData.allTimestampsArray.map(ts => {
var action = () => {
this.chartOptions.timestamp = ts;
this.render(this.chartComponentData.data, this.chartOptions, this.aggregateExpressionOptions);
}
return {label: Utils.timeFormat(this.chartComponentData.usesSeconds, this.chartComponentData.usesMillis,
this.chartOptions.offset, this.chartOptions.is24HourTime, null, null, this.chartOptions.dateLocale)(new Date(ts)), action: action};
}), this.chartOptions, this.chartWidth, Utils.timeFormat(this.chartComponentData.usesSeconds, this.chartComponentData.usesMillis,
this.chartOptions.offset, this.chartOptions.is24HourTime, null, null, this.chartOptions.dateLocale)(new Date(this.chartComponentData.timestamp)));
}
else{
slider.remove();
d3.select(this.renderTarget).select('.tsi-sliderWrapper').classed('tsi-hidden', true);
}
}
this.legendObject = new Legend(this.draw, this.renderTarget, this.CONTROLSWIDTH);
this.contextMenu = new ContextMenu(this.draw, this.renderTarget);
// temporal slider
var slider = new Slider(<any>d3.select(this.renderTarget).select('.tsi-sliderWrapper').node());
window.addEventListener("resize", () => {
if (!this.chartOptions.suppressResizeListener)
this.draw();
});
}
this.draw();
this.gatedShowGrid();
d3.select("html").on("click." + Utils.guid(), () => {
if (this.ellipsisContainer && d3.event.target != this.ellipsisContainer.select(".tsi-ellipsisButton").node()) {
this.ellipsisMenu.setMenuVisibility(false);
}
});
this.legendPostRenderProcess(this.chartOptions.legend, this.svgSelection, true);
}
}
export default PieChart | the_stack |
require('module-alias/register');
import * as _ from 'lodash';
import * as ABIDecoder from 'abi-decoder';
import * as chai from 'chai';
import { Address, SetProtocolTestUtils as SetTestUtils } from 'set-protocol-utils';
import { BigNumber } from 'bignumber.js';
import ChaiSetup from '@utils/chaiSetup';
import { BigNumberSetup } from '@utils/bigNumberSetup';
import {
ConstantAuctionPriceCurveContract,
CoreMockContract,
RebalanceAuctionModuleMockContract,
RebalancingSetEthBidderContract,
RebalancingSetTokenContract,
RebalancingSetTokenFactoryContract,
SetTokenContract,
SetTokenFactoryContract,
StandardTokenMockContract,
TransferProxyContract,
VaultContract,
WethMockContract,
WhiteListContract,
} from '@utils/contracts';
import { ether } from '@utils/units';
import {
DEFAULT_GAS,
ONE_DAY_IN_SECONDS,
DEFAULT_AUCTION_PRICE_NUMERATOR,
DEFAULT_AUCTION_PRICE_DIVISOR,
DEFAULT_REBALANCING_NATURAL_UNIT,
UNLIMITED_ALLOWANCE_IN_BASE_UNITS,
ZERO,
} from '@utils/constants';
import { expectRevertError } from '@utils/tokenAssertions';
import { Blockchain } from '@utils/blockchain';
import { getWeb3, getGasUsageInEth } from '@utils/web3Helper';
import { BidPlacedWithEth } from '@utils/contract_logs/rebalancingSetEthBidder';
import { CoreHelper } from '@utils/helpers/coreHelper';
import { ERC20Helper } from '@utils/helpers/erc20Helper';
import { RebalancingHelper } from '@utils/helpers/rebalancingHelper';
import { RebalancingSetBidderHelper } from '@utils/helpers/rebalancingSetBidderHelper';
BigNumberSetup.configure();
ChaiSetup.configure();
const web3 = getWeb3();
const blockchain = new Blockchain(web3);
const setTestUtils = new SetTestUtils(web3);
const { expect } = chai;
contract('RebalancingSetEthBidder', accounts => {
const [
deployerAccount,
managerAccount,
] = accounts;
let coreMock: CoreMockContract;
let transferProxy: TransferProxyContract;
let vault: VaultContract;
let rebalanceAuctionModuleMock: RebalanceAuctionModuleMockContract;
let factory: SetTokenFactoryContract;
let rebalancingComponentWhiteList: WhiteListContract;
let rebalancingFactory: RebalancingSetTokenFactoryContract;
let constantAuctionPriceCurve: ConstantAuctionPriceCurveContract;
let rebalancingSetEthBidder: RebalancingSetEthBidderContract;
let weth: WethMockContract;
const coreHelper = new CoreHelper(deployerAccount, deployerAccount);
const erc20Helper = new ERC20Helper(deployerAccount);
const rebalancingHelper = new RebalancingHelper(
deployerAccount,
coreHelper,
erc20Helper,
blockchain
);
const rebalancingSetBidderHelper = new RebalancingSetBidderHelper(deployerAccount);
before(async () => {
ABIDecoder.addABI(CoreMockContract.getAbi());
ABIDecoder.addABI(RebalanceAuctionModuleMockContract.getAbi());
ABIDecoder.addABI(RebalancingSetEthBidderContract.getAbi());
transferProxy = await coreHelper.deployTransferProxyAsync();
vault = await coreHelper.deployVaultAsync();
coreMock = await coreHelper.deployCoreMockAsync(transferProxy, vault);
rebalanceAuctionModuleMock = await coreHelper.deployRebalanceAuctionModuleMockAsync(coreMock, vault);
await coreHelper.addModuleAsync(coreMock, rebalanceAuctionModuleMock.address);
factory = await coreHelper.deploySetTokenFactoryAsync(coreMock.address);
rebalancingComponentWhiteList = await coreHelper.deployWhiteListAsync();
rebalancingFactory = await coreHelper.deployRebalancingSetTokenFactoryAsync(
coreMock.address,
rebalancingComponentWhiteList.address,
);
constantAuctionPriceCurve = await rebalancingHelper.deployConstantAuctionPriceCurveAsync(
DEFAULT_AUCTION_PRICE_NUMERATOR,
DEFAULT_AUCTION_PRICE_DIVISOR,
);
await coreHelper.setDefaultStateAndAuthorizationsAsync(coreMock, vault, transferProxy, factory);
await coreHelper.addFactoryAsync(coreMock, rebalancingFactory);
await rebalancingHelper.addPriceLibraryAsync(coreMock, constantAuctionPriceCurve);
weth = await erc20Helper.deployWrappedEtherAsync(deployerAccount, ZERO);
rebalancingSetEthBidder = await rebalancingSetBidderHelper.deployRebalancingSetEthBidderAsync(
rebalanceAuctionModuleMock.address,
transferProxy.address,
weth.address,
);
});
after(async () => {
ABIDecoder.removeABI(CoreMockContract.getAbi());
ABIDecoder.removeABI(RebalanceAuctionModuleMockContract.getAbi());
ABIDecoder.removeABI(RebalancingSetEthBidderContract.getAbi());
});
beforeEach(async () => {
await blockchain.saveSnapshotAsync();
});
afterEach(async () => {
await blockchain.revertAsync();
});
describe('#constructor', async () => {
it('should contain the correct address of the rebalance auction module', async () => {
const proxyAddress = await rebalancingSetEthBidder.transferProxy.callAsync();
expect(proxyAddress).to.equal(transferProxy.address);
});
it('should contain the correct address of the transfer proxy', async () => {
const proxyAddress = await rebalancingSetEthBidder.transferProxy.callAsync();
expect(proxyAddress).to.equal(transferProxy.address);
});
it('should contain the correct address of Wrapped Ether', async () => {
const wethAddress = await rebalancingSetEthBidder.weth.callAsync();
expect(wethAddress).to.equal(weth.address);
});
it('should have unlimited allowance for weth', async () => {
const wethAllowance = await weth.allowance.callAsync(
rebalancingSetEthBidder.address,
transferProxy.address,
);
const expectedWethAllowance = UNLIMITED_ALLOWANCE_IN_BASE_UNITS;
expect(wethAllowance).to.bignumber.equal(expectedWethAllowance);
});
});
describe('#bidAndWithdrawWithEther', async () => {
let subjectRebalancingSetToken: Address;
let subjectQuantity: BigNumber;
let subjectEthQuantity: BigNumber;
let subjectExecutePartialQuantity: boolean;
let subjectCaller: Address;
let proposalPeriod: BigNumber;
let defaultBaseSetNaturalUnit: BigNumber;
let defaultBaseSetComponent: StandardTokenMockContract | WethMockContract;
let defaultBaseSetComponent2: StandardTokenMockContract | WethMockContract;
let wethBaseSetNaturalUnit: BigNumber;
let wethBaseSetComponent: StandardTokenMockContract | WethMockContract;
let wethBaseSetComponent2: StandardTokenMockContract | WethMockContract;
let wethComponentUnits: BigNumber;
let rebalancingSetToken: RebalancingSetTokenContract;
let rebalancingUnitShares: BigNumber;
let defaultSetToken: SetTokenContract;
let wethSetToken: SetTokenContract;
let rebalancingSetTokenQuantityToIssue: BigNumber;
let minBid: BigNumber;
beforeEach(async () => {
// ----------------------------------------------------------------------
// Create Set with no WETH component
// ----------------------------------------------------------------------
// Create component tokens for default Set
defaultBaseSetComponent = await erc20Helper.deployTokenAsync(deployerAccount);
defaultBaseSetComponent2 = await erc20Helper.deployTokenAsync(deployerAccount);
// Create the Set (default is 2 components)
const defaultComponentAddresses = [
defaultBaseSetComponent.address, defaultBaseSetComponent2.address,
];
const defaultComponentUnits = [
ether(0.01), ether(0.01),
];
defaultBaseSetNaturalUnit = ether(0.001);
defaultSetToken = await coreHelper.createSetTokenAsync(
coreMock,
factory.address,
defaultComponentAddresses,
defaultComponentUnits,
defaultBaseSetNaturalUnit,
);
// ----------------------------------------------------------------------
// Create Set with a WETH component
// ----------------------------------------------------------------------
// Create component tokens for Set containing weth
wethBaseSetComponent = weth;
wethBaseSetComponent2 = await erc20Helper.deployTokenAsync(deployerAccount);
// Create the Set (default is 2 components)
const nextComponentAddresses = [
wethBaseSetComponent.address, wethBaseSetComponent2.address,
];
wethComponentUnits = ether(0.01);
const nextComponentUnits = [
wethComponentUnits, ether(0.01),
];
wethBaseSetNaturalUnit = ether(0.001);
wethSetToken = await coreHelper.createSetTokenAsync(
coreMock,
factory.address,
nextComponentAddresses,
nextComponentUnits,
wethBaseSetNaturalUnit,
);
});
async function subject(): Promise<string> {
return rebalancingSetEthBidder.bidAndWithdrawWithEther.sendTransactionAsync(
subjectRebalancingSetToken,
subjectQuantity,
subjectExecutePartialQuantity,
{ from: subjectCaller, gas: DEFAULT_GAS, value: subjectEthQuantity.toNumber()}
);
}
describe('when WETH is an inflow in a bid', async () => {
beforeEach(async () => {
// Create the Rebalancing Set without WETH component
proposalPeriod = ONE_DAY_IN_SECONDS;
rebalancingUnitShares = ether(1);
rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync(
coreMock,
rebalancingFactory.address,
managerAccount,
defaultSetToken.address,
proposalPeriod,
rebalancingUnitShares
);
// Approve tokens and issue defaultSetToken
const baseSetIssueQuantity = ether(1);
await erc20Helper.approveTransfersAsync([
defaultBaseSetComponent,
defaultBaseSetComponent2,
], transferProxy.address);
await coreMock.issue.sendTransactionAsync(
defaultSetToken.address,
baseSetIssueQuantity,
{from: deployerAccount}
);
// Use issued defaultSetToken to issue rebalancingSetToken
await erc20Helper.approveTransfersAsync([defaultSetToken], transferProxy.address);
rebalancingSetTokenQuantityToIssue = baseSetIssueQuantity
.mul(DEFAULT_REBALANCING_NATURAL_UNIT)
.div(rebalancingUnitShares);
await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, rebalancingSetTokenQuantityToIssue);
// Determine minimum bid
const decOne = await defaultSetToken.naturalUnit.callAsync();
const decTwo = await wethSetToken.naturalUnit.callAsync();
minBid = new BigNumber(Math.max(decOne.toNumber(), decTwo.toNumber()) * 1000);
subjectCaller = deployerAccount;
subjectQuantity = minBid;
subjectRebalancingSetToken = rebalancingSetToken.address;
subjectExecutePartialQuantity = false;
// Transition to rebalance
await rebalancingHelper.defaultTransitionToRebalanceAsync(
coreMock,
rebalancingComponentWhiteList,
rebalancingSetToken,
wethSetToken,
constantAuctionPriceCurve.address,
managerAccount
);
// Approve tokens to rebalancingSetEthBidder contract
await erc20Helper.approveTransfersAsync([
wethBaseSetComponent,
wethBaseSetComponent2,
], rebalancingSetEthBidder.address);
subjectEthQuantity = baseSetIssueQuantity.mul(wethComponentUnits).div(wethBaseSetNaturalUnit);
});
it("transfers the correct amount of tokens to the bidder's wallet", async () => {
const expectedTokenFlows = await rebalancingHelper.constructInflowOutflowArraysAsync(
rebalancingSetToken,
subjectQuantity,
DEFAULT_AUCTION_PRICE_NUMERATOR
);
const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync();
const tokenInstances = await erc20Helper.retrieveTokenInstancesAsync(combinedTokenArray);
const oldEthBalance = new BigNumber(await web3.eth.getBalance(subjectCaller));
const oldReceiverTokenBalances = await erc20Helper.getTokenBalances(
tokenInstances,
subjectCaller
);
// Replace WETH balance with ETH balance
const oldReceiverTokenAndEthBalances = _.map(oldReceiverTokenBalances, (balance, index) =>
combinedTokenArray[index] === weth.address ? new BigNumber(oldEthBalance) : balance
);
const txHash = await subject();
const newEthBalance = await web3.eth.getBalance(subjectCaller);
const newReceiverTokenBalances = await erc20Helper.getTokenBalances(
tokenInstances,
subjectCaller
);
// Replace WETH balance with ETH balance and factor in gas paid
const totalGasInEth = await getGasUsageInEth(txHash);
const newReceiverTokenAndEthBalances = _.map(newReceiverTokenBalances, (balance, index) =>
combinedTokenArray[index] === weth.address ? totalGasInEth.add(newEthBalance) : balance
);
const expectedReceiverBalances = _.map(oldReceiverTokenAndEthBalances, (balance, index) =>
balance.add(expectedTokenFlows['outflowArray'][index]).sub(expectedTokenFlows['inflowArray'][index])
);
expect(JSON.stringify(newReceiverTokenAndEthBalances)).to.equal(JSON.stringify(expectedReceiverBalances));
});
it('transfers the correct amount of tokens from the bidder to the rebalancing token in Vault', async () => {
const expectedTokenFlows = await rebalancingHelper.constructInflowOutflowArraysAsync(
rebalancingSetToken,
subjectQuantity,
DEFAULT_AUCTION_PRICE_NUMERATOR
);
const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync();
const oldSenderBalances = await coreHelper.getVaultBalancesForTokensForOwner(
combinedTokenArray,
vault,
rebalancingSetToken.address
);
await subject();
const newSenderBalances = await coreHelper.getVaultBalancesForTokensForOwner(
combinedTokenArray,
vault,
rebalancingSetToken.address
);
const expectedSenderBalances = _.map(oldSenderBalances, (balance, index) =>
balance.add(expectedTokenFlows['inflowArray'][index]).sub(expectedTokenFlows['outflowArray'][index])
);
expect(JSON.stringify(newSenderBalances)).to.equal(JSON.stringify(expectedSenderBalances));
});
it('subtracts the correct amount from remainingCurrentSets', async () => {
const biddingParameters = await rebalancingSetToken.biddingParameters.callAsync();
const currentRemainingSets = new BigNumber(biddingParameters[1]);
await subject();
const expectedRemainingSets = currentRemainingSets.sub(subjectQuantity);
const newBiddingParameters = await rebalancingSetToken.biddingParameters.callAsync();
const newRemainingSets = new BigNumber(newBiddingParameters[1]);
expect(newRemainingSets).to.be.bignumber.equal(expectedRemainingSets);
});
it('emits a BidPlacedWithEth event', async () => {
const txHash = await subject();
const formattedLogs = await setTestUtils.getLogsFromTxHash(txHash);
const expectedLogs = BidPlacedWithEth(
rebalancingSetToken.address,
subjectCaller,
subjectQuantity,
rebalancingSetEthBidder.address
);
await SetTestUtils.assertLogEquivalence(formattedLogs, expectedLogs);
});
describe('but quantity is zero', async () => {
beforeEach(async () => {
subjectQuantity = ZERO;
});
it('should revert', async () => {
await expectRevertError(subject());
});
});
describe('but quantity is more than remainingCurrentSets', async () => {
beforeEach(async () => {
subjectQuantity = rebalancingSetTokenQuantityToIssue.add(minBid);
});
it('should revert', async () => {
await expectRevertError(subject());
});
});
describe('partial fills is true but amount is less than remainingCurrentSets', async () => {
beforeEach(async () => {
subjectExecutePartialQuantity = true;
});
it('subtracts the correct amount from remainingCurrentSets', async () => {
const biddingParameters = await rebalancingSetToken.biddingParameters.callAsync();
const currentRemainingSets = new BigNumber(biddingParameters[1]);
await subject();
const expectedRemainingSets = currentRemainingSets.sub(subjectQuantity);
const newBiddingParameters = await rebalancingSetToken.biddingParameters.callAsync();
const newRemainingSets = new BigNumber(newBiddingParameters[1]);
expect(newRemainingSets).to.be.bignumber.equal(expectedRemainingSets);
});
describe('but quantity is zero', async () => {
beforeEach(async () => {
subjectQuantity = ZERO;
});
it('should revert', async () => {
await expectRevertError(subject());
});
});
});
describe('and quantity is greater than remainingCurrentSets', async () => {
const roundedQuantity = ether(1);
beforeEach(async () => {
subjectQuantity = ether(2);
subjectExecutePartialQuantity = true;
});
it("transfers the correct amount of tokens to the bidder's wallet", async () => {
const expectedTokenFlows = await rebalancingHelper.constructInflowOutflowArraysAsync(
rebalancingSetToken,
roundedQuantity,
DEFAULT_AUCTION_PRICE_NUMERATOR
);
const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync();
const tokenInstances = await erc20Helper.retrieveTokenInstancesAsync(combinedTokenArray);
const oldEthBalance = new BigNumber(await web3.eth.getBalance(subjectCaller));
const oldReceiverTokenBalances = await erc20Helper.getTokenBalances(
tokenInstances,
subjectCaller
);
// Replace WETH balance with ETH balance
const oldReceiverTokenAndEthBalances = _.map(oldReceiverTokenBalances, (balance, index) =>
combinedTokenArray[index] === weth.address ? new BigNumber(oldEthBalance) : balance
);
const txHash = await subject();
const newEthBalance = await web3.eth.getBalance(subjectCaller);
const newReceiverTokenBalances = await erc20Helper.getTokenBalances(
tokenInstances,
subjectCaller
);
// Replace WETH balance with ETH balance and factor in gas paid
const totalGasInEth = await getGasUsageInEth(txHash);
const newReceiverTokenAndEthBalances = _.map(newReceiverTokenBalances, (balance, index) =>
combinedTokenArray[index] === weth.address ? totalGasInEth.add(newEthBalance) : balance
);
const expectedReceiverBalances = _.map(oldReceiverTokenAndEthBalances, (balance, index) =>
balance.add(expectedTokenFlows['outflowArray'][index]).sub(expectedTokenFlows['inflowArray'][index])
);
expect(JSON.stringify(newReceiverTokenAndEthBalances)).to.equal(JSON.stringify(expectedReceiverBalances));
});
it('transfers the correct amount of tokens from the bidder to the rebalancing token in Vault', async () => {
const expectedTokenFlows = await rebalancingHelper.constructInflowOutflowArraysAsync(
rebalancingSetToken,
roundedQuantity,
DEFAULT_AUCTION_PRICE_NUMERATOR
);
const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync();
const oldSenderBalances = await coreHelper.getVaultBalancesForTokensForOwner(
combinedTokenArray,
vault,
rebalancingSetToken.address
);
await subject();
const newSenderBalances = await coreHelper.getVaultBalancesForTokensForOwner(
combinedTokenArray,
vault,
rebalancingSetToken.address
);
const expectedSenderBalances = _.map(oldSenderBalances, (balance, index) =>
balance.add(expectedTokenFlows['inflowArray'][index]).sub(expectedTokenFlows['outflowArray'][index])
);
expect(JSON.stringify(newSenderBalances)).to.equal(JSON.stringify(expectedSenderBalances));
});
it('subtracts the correct amount from remainingCurrentSets', async () => {
const biddingParameters = await rebalancingSetToken.biddingParameters.callAsync();
const currentRemainingSets = new BigNumber(biddingParameters[1]);
await subject();
const expectedRemainingSets = currentRemainingSets.sub(roundedQuantity);
const newBiddingParameters = await rebalancingSetToken.biddingParameters.callAsync();
const newRemainingSets = new BigNumber(newBiddingParameters[1]);
expect(newRemainingSets).to.be.bignumber.equal(expectedRemainingSets);
});
it('emits a BidPlacedWithEth event', async () => {
const txHash = await subject();
const formattedLogs = await setTestUtils.getLogsFromTxHash(txHash);
const expectedLogs = BidPlacedWithEth(
rebalancingSetToken.address,
subjectCaller,
subjectQuantity,
rebalancingSetEthBidder.address
);
await SetTestUtils.assertLogEquivalence(formattedLogs, expectedLogs);
});
});
describe('when submitted ETH quantity is higher than required inflow', async () => {
beforeEach(async () => {
subjectEthQuantity = ether(10);
});
it("transfers the correct amount of tokens and ETH to the bidder's wallet", async () => {
const expectedTokenFlows = await rebalancingHelper.constructInflowOutflowArraysAsync(
rebalancingSetToken,
subjectQuantity,
DEFAULT_AUCTION_PRICE_NUMERATOR
);
const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync();
const tokenInstances = await erc20Helper.retrieveTokenInstancesAsync(combinedTokenArray);
const oldEthBalance = new BigNumber(await web3.eth.getBalance(subjectCaller));
const oldReceiverTokenBalances = await erc20Helper.getTokenBalances(
tokenInstances,
subjectCaller
);
// Replace WETH balance with ETH balance
const oldReceiverTokenAndEthBalances = _.map(oldReceiverTokenBalances, (balance, index) =>
combinedTokenArray[index] === weth.address ? new BigNumber(oldEthBalance) : balance
);
const txHash = await subject();
const newEthBalance = await web3.eth.getBalance(subjectCaller);
const newReceiverTokenBalances = await erc20Helper.getTokenBalances(
tokenInstances,
subjectCaller
);
// Replace WETH balance with ETH balance and factor in gas paid
const totalGasInEth = await getGasUsageInEth(txHash);
const newReceiverTokenAndEthBalances = _.map(newReceiverTokenBalances, (balance, index) =>
combinedTokenArray[index] === weth.address ? totalGasInEth.add(newEthBalance) : balance
);
const expectedReceiverBalances = _.map(oldReceiverTokenAndEthBalances, (balance, index) =>
balance.add(expectedTokenFlows['outflowArray'][index]).sub(expectedTokenFlows['inflowArray'][index])
);
expect(JSON.stringify(newReceiverTokenAndEthBalances)).to.equal(JSON.stringify(expectedReceiverBalances));
});
});
describe('but ETH input quantity is lower than required inflow', async () => {
beforeEach(async () => {
subjectEthQuantity = ZERO;
});
it('should revert', async () => {
await expectRevertError(subject());
});
});
describe('when the contract does not have enough allowance to transfer weth', async () => {
beforeEach(async () => {
await weth.changeAllowanceProxy.sendTransactionAsync(
rebalancingSetEthBidder.address,
transferProxy.address,
ZERO,
{ gas: DEFAULT_GAS }
);
});
it('resets the transferProxy allowance', async () => {
const wethAllowance = await weth.allowance.callAsync(
rebalancingSetEthBidder.address,
transferProxy.address
);
expect(wethAllowance).to.bignumber.equal(ZERO);
await subject();
const expectedWethAllowance = UNLIMITED_ALLOWANCE_IN_BASE_UNITS;
const newWethAllowance = await weth.allowance.callAsync(
rebalancingSetEthBidder.address,
transferProxy.address
);
expect(newWethAllowance).to.bignumber.equal(expectedWethAllowance);
});
});
});
describe('when WETH is an outflow in a bid', async () => {
beforeEach(async () => {
// Create the Rebalancing Set with the WETH component
proposalPeriod = ONE_DAY_IN_SECONDS;
rebalancingUnitShares = ether(1);
rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync(
coreMock,
rebalancingFactory.address,
managerAccount,
wethSetToken.address,
proposalPeriod,
rebalancingUnitShares
);
// Approve tokens and issue wethSetToken
const baseSetIssueQuantity = ether(1);
const requiredWrappedEther = baseSetIssueQuantity.mul(wethComponentUnits).div(wethBaseSetNaturalUnit);
await weth.deposit.sendTransactionAsync(
{ from: deployerAccount, value: requiredWrappedEther.toString() }
);
await erc20Helper.approveTransfersAsync([wethBaseSetComponent, wethBaseSetComponent2], transferProxy.address);
await coreMock.issue.sendTransactionAsync(wethSetToken.address, baseSetIssueQuantity, {from: deployerAccount});
// Use issued defaultSetToken to issue rebalancingSetToken
await erc20Helper.approveTransfersAsync([wethSetToken], transferProxy.address);
rebalancingSetTokenQuantityToIssue = baseSetIssueQuantity
.mul(DEFAULT_REBALANCING_NATURAL_UNIT)
.div(rebalancingUnitShares);
await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, rebalancingSetTokenQuantityToIssue);
// Determine minimum bid
const decOne = await defaultSetToken.naturalUnit.callAsync();
const decTwo = await wethSetToken.naturalUnit.callAsync();
minBid = new BigNumber(Math.max(decOne.toNumber(), decTwo.toNumber()) * 1000);
subjectCaller = deployerAccount;
subjectQuantity = minBid;
subjectRebalancingSetToken = rebalancingSetToken.address;
subjectExecutePartialQuantity = false;
// Transition to rebalance
await rebalancingHelper.defaultTransitionToRebalanceAsync(
coreMock,
rebalancingComponentWhiteList,
rebalancingSetToken,
defaultSetToken,
constantAuctionPriceCurve.address,
managerAccount
);
// Approve tokens to rebalancingSetEthBidder contract
await erc20Helper.approveTransfersAsync([
defaultBaseSetComponent,
defaultBaseSetComponent2,
], rebalancingSetEthBidder.address);
subjectEthQuantity = ZERO;
});
it("transfers the correct amount of tokens to the bidder's wallet", async () => {
const expectedTokenFlows = await rebalancingHelper.constructInflowOutflowArraysAsync(
rebalancingSetToken,
subjectQuantity,
DEFAULT_AUCTION_PRICE_NUMERATOR
);
const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync();
const tokenInstances = await erc20Helper.retrieveTokenInstancesAsync(combinedTokenArray);
const oldEthBalance = new BigNumber(await web3.eth.getBalance(subjectCaller));
const oldReceiverTokenBalances = await erc20Helper.getTokenBalances(
tokenInstances,
subjectCaller
);
// Replace WETH balance with ETH balance
const oldReceiverTokenAndEthBalances = _.map(oldReceiverTokenBalances, (balance, index) =>
combinedTokenArray[index] === weth.address ? new BigNumber(oldEthBalance) : balance
);
const txHash = await subject();
const newEthBalance = await web3.eth.getBalance(subjectCaller);
const newReceiverTokenBalances = await erc20Helper.getTokenBalances(
tokenInstances,
subjectCaller
);
// Replace WETH balance with ETH balance and factor in gas paid
const totalGasInEth = await getGasUsageInEth(txHash);
const newReceiverTokenAndEthBalances = _.map(newReceiverTokenBalances, (balance, index) =>
combinedTokenArray[index] === weth.address ? totalGasInEth.add(newEthBalance) : balance
);
const expectedReceiverBalances = _.map(oldReceiverTokenAndEthBalances, (balance, index) =>
balance.add(expectedTokenFlows['outflowArray'][index]).sub(expectedTokenFlows['inflowArray'][index])
);
expect(JSON.stringify(newReceiverTokenAndEthBalances)).to.equal(JSON.stringify(expectedReceiverBalances));
});
});
describe('when WETH is neither inflow nor outflow in a bid', async () => {
beforeEach(async () => {
// Create the Rebalancing Set with the default component
proposalPeriod = ONE_DAY_IN_SECONDS;
rebalancingUnitShares = ether(1);
rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync(
coreMock,
rebalancingFactory.address,
managerAccount,
defaultSetToken.address,
proposalPeriod,
rebalancingUnitShares
);
// Approve tokens and issue defaultSetToken
const baseSetIssueQuantity = ether(1);
const requiredWrappedEther = baseSetIssueQuantity.mul(wethComponentUnits).div(wethBaseSetNaturalUnit);
await weth.deposit.sendTransactionAsync(
{ from: deployerAccount, value: requiredWrappedEther.toString() }
);
await erc20Helper.approveTransfersAsync([
defaultBaseSetComponent,
defaultBaseSetComponent2,
], transferProxy.address);
await coreMock.issue.sendTransactionAsync(
defaultSetToken.address,
baseSetIssueQuantity,
{from: deployerAccount}
);
// Use issued defaultSetToken to issue rebalancingSetToken
await erc20Helper.approveTransfersAsync([defaultSetToken], transferProxy.address);
rebalancingSetTokenQuantityToIssue = baseSetIssueQuantity
.mul(DEFAULT_REBALANCING_NATURAL_UNIT)
.div(rebalancingUnitShares);
await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, rebalancingSetTokenQuantityToIssue);
// Determine minimum bid
const decOne = await defaultSetToken.naturalUnit.callAsync();
const decTwo = await wethSetToken.naturalUnit.callAsync();
minBid = new BigNumber(Math.max(decOne.toNumber(), decTwo.toNumber()) * 1000);
subjectCaller = deployerAccount;
subjectQuantity = minBid;
subjectRebalancingSetToken = rebalancingSetToken.address;
subjectExecutePartialQuantity = false;
// Create new next Set with no weth component
const defaultNextBaseSetComponent = await erc20Helper.deployTokenAsync(deployerAccount);
const defaultNextBaseSetComponent2 = await erc20Helper.deployTokenAsync(deployerAccount);
const defaultNextComponentAddresses = [
defaultNextBaseSetComponent.address, defaultNextBaseSetComponent2.address,
];
const defaultNextComponentUnits = [
ether(0.01), ether(0.01),
];
const defaultBaseSetNaturalUnit = ether(0.001);
const defaultNextSetToken = await coreHelper.createSetTokenAsync(
coreMock,
factory.address,
defaultNextComponentAddresses,
defaultNextComponentUnits,
defaultBaseSetNaturalUnit,
);
// Transition to rebalance
await rebalancingHelper.defaultTransitionToRebalanceAsync(
coreMock,
rebalancingComponentWhiteList,
rebalancingSetToken,
defaultNextSetToken,
constantAuctionPriceCurve.address,
managerAccount
);
// Approve tokens to rebalancingSetEthBidder contract
await erc20Helper.approveTransfersAsync([
defaultNextBaseSetComponent,
defaultNextBaseSetComponent2,
], rebalancingSetEthBidder.address);
subjectEthQuantity = ether(10);
});
it('returns the amount of ETH minus gas cost', async () => {
const previousEthBalance: BigNumber = new BigNumber(await web3.eth.getBalance(subjectCaller));
const txHash = await subject();
const currentEthBalance = await web3.eth.getBalance(subjectCaller);
const totalGasInEth = await getGasUsageInEth(txHash);
const expectedEthBalance = previousEthBalance.sub(totalGasInEth);
expect(expectedEthBalance).to.bignumber.equal(currentEthBalance);
});
});
});
}); | the_stack |
import {
expect
} from 'chai';
import {
ListField
} from '@phosphor/datastore';
type ListValue = number;
/**
* Return a shuffled copy of an array
*/
function shuffle<T>(array: ReadonlyArray<T>): T[] {
let ret = array.slice();
for (let i = ret.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1)); // random index from 0 to i
[ret[i], ret[j]] = [ret[j], ret[i]]; // swap elements
}
return ret;
}
describe('@phosphor/datastore', () => {
describe('ListField', () => {
let field: ListField<ListValue>;
beforeEach(() => {
field = new ListField<ListValue>({
description: 'A list field storing numbers'
});
});
describe('constructor()', () => {
it('should create a list field', () => {
expect(field).to.be.instanceof(ListField);
});
});
describe('type', () => {
it('should return the type of the field', () => {
expect(field.type).to.equal('list');
});
});
describe('createValue()', () => {
it('should create an initial value for the field', () => {
let value = field.createValue();
expect(value).to.eql([]);
});
});
describe('createMetadata()', () => {
it('should create initial metadata for the field', () => {
let metadata = field.createMetadata();
expect(metadata.ids).to.eql([]);
expect(metadata.cemetery).to.eql({});
});
});
describe('applyUpdate', () => {
it('should return the result of the update', () => {
let previous = field.createValue();
let metadata = field.createMetadata();
let splice = {
index: 0,
remove: 0,
values: [1, 2, 3]
};
let { value, change, patch } = field.applyUpdate({
previous,
update: splice,
metadata,
version: 1,
storeId: 1
});
expect(value).to.eql([1, 2, 3]);
expect(change[0]).to.eql({ index: 0, removed: [], inserted: [1, 2, 3]});
expect(patch.length).to.equal(1);
expect(patch[0].removedValues.length).to.equal(splice.remove);
expect(patch[0].insertedValues).to.eql(splice.values);
expect(patch[0].removedIds.length).to.equal(splice.remove);
expect(patch[0].insertedIds.length).to.equal(splice.values.length);
});
it('should accept multiple splices', () => {
let previous = field.createValue();
let metadata = field.createMetadata();
let splice1 = {
index: 0,
remove: 0,
values: [1, 2, 3]
};
let splice2 = {
index: 1,
remove: 1,
values: [4, 5]
};
let { value, change, patch } = field.applyUpdate({
previous,
update: [splice1, splice2],
metadata,
version: 1,
storeId: 1
});
expect(value).to.eql([1, 4, 5, 3]);
expect(change.length).to.eql(2);
expect(change[0]).to.eql({ index: 0, removed: [], inserted: [1, 2, 3]});
expect(change[1]).to.eql({ index: 1, removed: [2], inserted: [4, 5]});
expect(patch.length).to.equal(2);
expect(patch[0].removedValues.length).to.equal(splice1.remove);
expect(patch[0].insertedValues).to.eql(splice1.values);
expect(patch[0].removedIds.length).to.equal(splice1.remove);
expect(patch[0].insertedIds.length).to.equal(splice1.values.length);
expect(patch[1].removedValues.length).to.equal(splice2.remove);
expect(patch[1].insertedValues).to.eql(splice2.values);
expect(patch[1].removedIds.length).to.equal(splice2.remove);
expect(patch[1].insertedIds.length).to.equal(splice2.values.length);
});
it('should accept long splices', () => {
let previous = field.createValue();
let values: number[] = [];
values.fill(0, 0, 1000000);
let metadata = field.createMetadata();
let splice = {
index: 0,
remove: 0,
values
};
let { value } = field.applyUpdate({
previous,
update: [splice],
metadata,
version: 1,
storeId: 1
});
expect(value).to.eql(values);
});
});
describe('applyPatch', () => {
it('should return the result of the patch', () => {
let previous = field.createValue();
let metadata = field.createMetadata();
// Create a patch
let { patch } = field.applyUpdate({
previous,
update: { index: 0, remove: 0, values: [1, 2, 3] },
metadata,
version: 1,
storeId: 1
});
// Reset the metadata
metadata = field.createMetadata();
// Apply the patch
let patched = field.applyPatch({
previous,
metadata,
patch
});
expect(patched.value).to.eql([1, 2, 3]);
expect(patched.change[0]).to.eql({
index: 0,
removed: [],
inserted: [1, 2, 3]
});
});
it('should allow for out-of-order patches', () => {
let previous = field.createValue();
let metadata = field.createMetadata();
let firstUpdate = field.applyUpdate({
previous,
update: { index: 0, remove: 0, values: [1, 8, 9, 4] },
metadata,
version: 1,
storeId: 1
});
let secondUpdate = field.applyUpdate({
previous: firstUpdate.value,
update: { index: 1, remove: 2, values: [2, 3] },
metadata,
version: 2,
storeId: 1
});
let thirdUpdate = field.applyUpdate({
previous: secondUpdate.value,
update: { index: 4, remove: 0, values: [5, 6, 7] },
metadata,
version: 3,
storeId: 1
});
expect(thirdUpdate.value).to.eql([1, 2, 3, 4, 5, 6, 7]);
// Now if we apply these patches on another client in
// a different order, they should give the same result.
metadata = field.createMetadata();
let firstPatch = field.applyPatch({
previous,
metadata,
patch: thirdUpdate.patch
});
expect(firstPatch.change[0]).to.eql({
index: 0,
removed: [],
inserted: [5, 6, 7]
});
let secondPatch = field.applyPatch({
previous: firstPatch.value,
metadata,
patch: secondUpdate.patch
});
expect(secondPatch.change[0]).to.eql({
index: 0,
removed: [],
inserted: [2, 3]
});
let thirdPatch = field.applyPatch({
previous: secondPatch.value,
metadata,
patch: firstUpdate.patch
});
expect(thirdPatch.change[0]).to.eql({
index: 2,
removed: [],
inserted: [4]
});
expect(thirdPatch.change[1]).to.eql({
index: 0,
removed: [],
inserted: [1]
});
expect(thirdPatch.value).to.eql([1, 2, 3, 4, 5, 6, 7]);
});
it('should allow for racing patches', () => {
let current = field.createValue();
let metadata = field.createMetadata();
let values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let patches: ListField.Patch<ListValue>[] = [];
// Recreate the values array one update at a time,
// capturing the patches.
for (let i = 0, version = 0; i < values.length; i++) {
let u1 = field.applyUpdate({
previous: current,
metadata,
update: {
index: i,
remove: 0,
values: [values[i], values[i], values[i]]
},
version: version,
storeId: 1
});
version++;
current = u1.value;
patches.push(u1.patch);
let u2 = field.applyUpdate({
previous: current,
metadata,
update: {
index: i+1,
remove: 2,
values: []
},
version: version,
storeId: 1
});
version++;
current = u2.value;
patches.push(u2.patch);
};
expect(current).to.eql(values);
// Shuffle the patches and apply them in a random order to
// a new ListField. We try this multiple times to ensure we
// don't accidentally get it right.
for (let i = 0; i < 10; ++i) {
let shuffled = shuffle(patches);
current = field.createValue();
metadata = field.createMetadata();
shuffled.forEach(patch => {
let { value } = field.applyPatch({
previous: current,
metadata,
patch
});
current = value;
});
expect(current).to.eql(values);
}
});
it('should handle concurrently deleted values', () => {
let initial = field.createValue();
let metadata = field.createMetadata();
// First insert some values.
let commonUpdate = field.applyUpdate({
previous: initial,
metadata,
update: { index: 0, remove: 0, values: [1, 2, 3, 4] },
version: 1,
storeId: 1
});
// Two collaborators concurrently remove the same value.
let metadataA = field.createMetadata();
let patchA = field.applyPatch({
previous: initial,
metadata: metadataA,
patch: commonUpdate.patch
});
let updateA = field.applyUpdate({
previous: patchA.value,
metadata: metadataA,
update: { index: 1, remove: 2, values: [] },
version: 2,
storeId: 2
});
expect(updateA.value).to.eql([1, 4]);
let metadataB = field.createMetadata();
let patchB = field.applyPatch({
previous: initial,
metadata: metadataB,
patch: commonUpdate.patch
});
let updateB = field.applyUpdate({
previous: patchB.value,
metadata: metadataB,
update: { index: 0, remove: 2, values: [] },
version: 2,
storeId: 3
});
expect(updateB.value).to.eql([3, 4]);
// Apply the A patch to the B collaborator
let patchB2 = field.applyPatch({
previous: updateB.value,
metadata: metadataB,
patch: updateA.patch
});
expect(patchB2.value).to.eql([4]);
// Apply the B patch to the A collaborator
let patchA2 = field.applyPatch({
previous: updateA.value,
metadata: metadataA,
patch: updateB.patch
});
expect(patchA2.value).to.eql([4]);
// Apply the patches to a third collaborator out-of-order.
let metadataC = field.createMetadata();
let patchC1 = field.applyPatch({
previous: initial,
metadata: metadataC,
patch: updateB.patch
});
let patchC2 = field.applyPatch({
previous: patchC1.value,
metadata: metadataC,
patch: updateA.patch
});
let patchC3 = field.applyPatch({
previous: patchC2.value,
metadata: metadataC,
patch: commonUpdate.patch
});
// Check the final value.
expect(patchC3.value).to.eql([4]);
});
});
describe('unapplyPatch', () => {
it('should remove a patch from the history', () => {
let previous = field.createValue();
let metadata = field.createMetadata();
// Create a patch
let updated1 = field.applyUpdate({
previous,
update: { index: 0, remove: 0, values: [1, 2, 3, 9] },
metadata,
version: 1,
storeId: 1
});
let updated2 = field.applyUpdate({
previous: updated1.value,
update: { index: 3, remove: 1, values: [4, 5, 6] },
metadata,
version: 1,
storeId: 1
});
expect(updated2.value).to.eql([1, 2, 3, 4, 5, 6]);
// Reset the metadata and apply the patches
metadata = field.createMetadata();
let patched1 = field.applyPatch({
previous,
metadata,
patch: updated1.patch
});
let patched2 = field.applyPatch({
previous: patched1.value,
metadata,
patch: updated2.patch
});
expect(patched2.value).to.eql([1, 2, 3, 4, 5, 6]);
// Unapply the patches out of order.
let unpatched1 = field.unapplyPatch({
previous: patched2.value,
metadata,
patch: updated1.patch
});
expect(unpatched1.value).to.eql([4, 5, 6]);
expect(unpatched1.change[0]).to.eql({
index: 0,
removed: [1, 2, 3],
inserted: []
});
let unpatched2 = field.unapplyPatch({
previous: unpatched1.value,
metadata,
patch: updated2.patch
});
expect(unpatched2.value).to.eql([]);
expect(unpatched2.change[0]).to.eql({
index: 0,
removed: [4, 5, 6],
inserted: []
});
});
it('should handle concurrently deleted text', () => {
let previous = field.createValue();
let metadata = field.createMetadata();
// Create a patch
let { patch } = field.applyUpdate({
previous,
update: { index: 0, remove: 0, values: [1, 2, 3] },
metadata,
version: 1,
storeId: 1
});
// Reset the metadata and unnaply the patch before applying it.
metadata = field.createMetadata();
let unpatched = field.unapplyPatch({
previous,
metadata,
patch
});
expect(unpatched.value).to.eql([]);
expect(unpatched.change.length).to.equal(0);
let patched = field.applyPatch({
previous: unpatched.value,
metadata,
patch
});
expect(patched.value).to.eql([]);
expect(patched.change.length).to.equal(0);
});
});
describe('mergeChange', () => {
it('should merge two successive changes', () => {
let change1 = [
{
index: 0,
removed: [],
inserted: [0, 1]
}
];
let change2 = [
{
index: 1,
removed: [1],
inserted: [2, 3]
}
];
let result = field.mergeChange(change1, change2);
expect(result).to.eql([...change1, ...change2]);
});
});
describe('mergePatch', () => {
it('should merge two successive patches', () => {
let patch1 = [
{
removedIds: [],
removedValues: [],
insertedIds: ['id-1', 'id-2'],
insertedValues: [0, 1]
}
];
let patch2 = [
{
removedIds: ['id-1'],
removedValues: [0],
insertedIds: ['id-3', 'id-4'],
insertedValues: [2, 3]
}
];
let result = field.mergePatch(patch1, patch2);
expect(result).to.eql([...patch1, ...patch2]);
});
});
});
}); | the_stack |
// The MIT License (MIT)
//
// vs-deploy (https://github.com/mkloubert/vs-deploy)
// Copyright (c) Marcel Joachim Kloubert <marcel.kloubert@gmx.net>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
import * as Crypto from 'crypto';
import * as deploy_contracts from '../contracts';
import * as deploy_helpers from '../helpers';
import * as deploy_objects from '../objects';
import * as FS from 'fs';
import * as i18 from '../i18';
import * as Moment from 'moment';
import * as Net from 'net';
import * as UUID from 'uuid';
import * as ZLib from 'zlib';
interface DeployTargetRemote extends deploy_contracts.TransformableDeployTarget {
hosts?: string | string[];
messageTransformer?: string;
messageTransformerOptions?: any;
tag?: any;
password?: string;
passwordAlgorithm?: string;
}
/**
* A file to send (JSON message).
*/
export interface RemoteFile {
/**
* The data.
*/
data?: string;
/**
* Indicates if 'data' is compressed or not.
*/
isCompressed?: boolean;
/**
* Indicates if entry is the first one or not.
*/
isFirst: boolean;
/**
* Indicates if entry is the last one or not.
*/
isLast: boolean;
/**
* The name / path of the file.
*/
name: string;
/**
* The index / number of the file (beginning at 1).
*/
nr: number;
/**
* The session ID.
*/
session: string;
/**
* An addtional value send by remote client.
*/
tag?: any;
/**
* The total number of files that will be send.
*/
totalCount: number;
}
interface RemoteContext {
counter: number;
hasCancelled: boolean;
hosts: string[];
session: string;
totalCount: number;
}
/**
* A file data transformer sub context.
*/
export interface FileDataTransformerContext extends TransformerContext {
compress?: boolean;
}
/**
* A message transformer sub context.
*/
export interface MessageTransformerContext extends TransformerContext {
}
/**
* A transformer sub context.
*/
export interface TransformerContext {
/**
* The path of the local file.
*/
file: string;
/**
* Gets the list of global variables defined in settings.
*/
globals: deploy_contracts.GlobalVariables;
/**
* The file to send.
*/
remoteFile: RemoteFile;
}
class RemotePlugin extends deploy_objects.DeployPluginWithContextBase<RemoteContext> {
protected createContext(target: DeployTargetRemote,
files: string[],
opts): Promise<deploy_objects.DeployPluginContextWrapper<RemoteContext>> {
let me = this;
return new Promise<deploy_objects.DeployPluginContextWrapper<RemoteContext>>((resolve, reject) => {
try {
let now = Moment().utc();
let hosts = deploy_helpers.asArray(target.hosts)
.map(x => deploy_helpers.toStringSafe(x))
.filter(x => x);
let id = deploy_helpers.toStringSafe(UUID.v4());
id = deploy_helpers.replaceAllStrings(id, '-', '');
let ctx: RemoteContext = {
counter: 0,
hasCancelled: false,
hosts: hosts,
session: `${now.format('YYYYMMDDHHmmss')}-${id}`,
totalCount: files.length,
};
me.onCancelling(() => ctx.hasCancelled = true, opts);
let wrapper: deploy_objects.DeployPluginContextWrapper<RemoteContext> = {
context: ctx,
};
resolve(wrapper);
}
catch (e) {
reject(e);
}
});
}
protected deployFileWithContext(ctx: RemoteContext,
file: string, target: DeployTargetRemote, opts?: deploy_contracts.DeployFileOptions): void {
if (!opts) {
opts = {};
}
let me = this;
++ctx.counter;
let allErrors: any[] = [];
let completed = (err?: any) => {
if (err) {
allErrors.push(err);
}
if (allErrors.length > 1) {
err = new Error(allErrors.map((x, i) => i18.t('errors.countable', i + 1, x))
.join('\n\n'));
}
else if (1 === allErrors.length) {
err = allErrors[0];
}
if (opts.onCompleted) {
opts.onCompleted(me, {
canceled: ctx.hasCancelled,
error: err,
file: file,
target: target,
});
}
};
if (ctx.hasCancelled) {
completed(); // cancellation requested
}
else {
// data transformer
let transformer = me.loadDataTransformer(target, deploy_contracts.DataTransformerMode.Transform);
// whole JSON transformer
let jsonTransformer = me.loadDataTransformer(target, deploy_contracts.DataTransformerMode.Transform,
(t) => t.messageTransformer);
let pwd = deploy_helpers.toStringSafe(target.password);
if ('' !== pwd) {
// add password wrapper
let baseJsonTransformer = jsonTransformer;
let pwdAlgo = deploy_helpers.normalizeString(target.passwordAlgorithm);
if ('' === pwdAlgo) {
pwdAlgo = deploy_contracts.DEFAULT_PASSWORD_ALGORITHM;
}
jsonTransformer = (ctx) => {
return new Promise<Buffer>((resolve, reject) => {
try {
let btResult = Promise.resolve(baseJsonTransformer(ctx));
btResult.then((uncryptedData) => {
try {
let cipher = Crypto.createCipher(pwdAlgo, pwd);
let a = cipher.update(uncryptedData);
let b = cipher.final();
// return crypted data
resolve(Buffer.concat([a, b]));
}
catch (e) {
reject(e);
}
}).catch((err) => {
reject(err);
});
}
catch (e) {
reject(e);
}
});
};
}
try {
let relativePath = deploy_helpers.toRelativeTargetPathWithValues(file, target, me.context.values(), opts.baseDirectory);
if (false === relativePath) {
completed(new Error(i18.t('relativePaths.couldNotResolve', file)));
return;
}
while (0 === relativePath.indexOf('/')) {
relativePath = relativePath.substr(1);
}
if (!relativePath) {
completed(new Error(i18.t('relativePaths.isEmpty', file)));
return;
}
if (opts.onBeforeDeploy) {
opts.onBeforeDeploy(me, {
destination: relativePath,
file: file,
target: target,
});
}
FS.readFile(file, (err, data) => {
if (err) {
completed(err);
return;
}
try {
let remoteFile: RemoteFile = {
isFirst: 1 === ctx.counter,
isLast: ctx.counter === ctx.totalCount,
name: <string>relativePath,
nr: ctx.counter,
session: ctx.session,
tag: target.tag,
totalCount: ctx.totalCount,
};
let transformCtx: FileDataTransformerContext = {
file: file,
globals: me.context.globals(),
remoteFile: remoteFile,
};
let tCtx = me.createDataTransformerContext(target, deploy_contracts.DataTransformerMode.Transform,
transformCtx);
tCtx.data = data;
let tResult = Promise.resolve(transformer(tCtx));
tResult.then((transformedFileData) => {
ZLib.gzip(transformedFileData, (err, compressedData) => {
if (err) {
completed(err);
return;
}
if (deploy_helpers.isNullOrUndefined(transformCtx.compress)) {
// auto compression
remoteFile.isCompressed = compressedData.length < transformedFileData.length;
}
else {
remoteFile.isCompressed = deploy_helpers.toBooleanSafe(transformCtx.compress);
}
let dataToSend = remoteFile.isCompressed ? compressedData : transformedFileData;
try {
remoteFile.data = dataToSend.toString('base64');
}
catch (e) {
completed(e);
return;
}
let json: Buffer;
try {
json = new Buffer(JSON.stringify(remoteFile), 'utf8');
}
catch (e) {
completed(e);
return;
}
try {
let jsonTransformerCtx: MessageTransformerContext = {
file: file,
globals: me.context.globals(),
remoteFile: remoteFile,
};
let tCtx = me.createDataTransformerContext(target, deploy_contracts.DataTransformerMode.Transform,
jsonTransformerCtx);
tCtx.data = json;
tCtx.options = deploy_helpers.cloneObject(target.messageTransformerOptions);
let tResult = jsonTransformer(tCtx);
Promise.resolve(tResult).then((transformedJsonData) => {
let hostsTodo = ctx.hosts.map(x => x);
let deployNext: () => void;
deployNext = () => {
if (hostsTodo.length < 1) {
completed();
return;
}
let h = hostsTodo.pop();
if (!h) {
completed();
return;
}
let hostCompleted = (err?: any) => {
if (err) {
allErrors.push(err);
}
deployNext();
};
try {
let addr = h;
let port = deploy_contracts.DEFAULT_PORT;
let separator = h.indexOf(':');
if (separator > -1) {
addr = deploy_helpers.toStringSafe(h.substr(0, separator).toLowerCase().trim(),
deploy_contracts.DEFAULT_HOST);
port = parseInt(deploy_helpers.toStringSafe(h.substr(separator + 1).trim(),
'' + deploy_contracts.DEFAULT_PORT));
}
let client = new Net.Socket();
client.on('error', (err) => {
hostCompleted(err);
});
client.connect(port, addr, (err) => {
if (err) {
hostCompleted(err);
return;
}
try {
let dataLength = Buffer.alloc(4);
dataLength.writeUInt32LE(transformedJsonData.length, 0);
client.write(dataLength);
client.write(transformedJsonData);
try {
client.destroy();
}
catch (e) {
me.context.log(i18.t('errors.withCategory',
'RemotePlugin.deployFile().client.connect()', e));
}
hostCompleted();
}
catch (e) {
hostCompleted(e);
}
});
}
catch (e) {
hostCompleted(e);
}
};
deployNext();
}).catch((err) => {
completed(err); // JSON data transformation failed
});
}
catch (e) {
completed(e);
}
});
}).catch((err) => {
completed(err); // file data transformation failed
});
}
catch (e) { // tResult
completed(e);
}
});
}
catch (e) {
completed(e);
}
}
}
public info(): deploy_contracts.DeployPluginInfo {
return {
description: i18.t('plugins.remote.description'),
};
}
}
/**
* Creates a new Plugin.
*
* @param {deploy_contracts.DeployContext} ctx The deploy context.
*
* @returns {deploy_contracts.DeployPlugin} The new instance.
*/
export function createPlugin(ctx: deploy_contracts.DeployContext): deploy_contracts.DeployPlugin {
return new RemotePlugin(ctx);
} | the_stack |
import * as test from 'tape';
import {NoteSequence} from '../protobuf/index';
import * as sequences from './sequences';
const STEPS_PER_QUARTER = 4;
function createTestNS() {
const ns = NoteSequence.create();
ns.tempos.push(NoteSequence.Tempo.create({qpm: 60, time: 0}));
ns.timeSignatures.push(NoteSequence.TimeSignature.create({
time: 0,
numerator: 4,
denominator: 4,
}));
return ns;
}
function addTrackToSequence(
ns: NoteSequence, instrument: number, notes: number[][]) {
for (const noteParams of notes) {
const note = new NoteSequence.Note({
pitch: noteParams[0],
instrument,
velocity: noteParams[1],
startTime: noteParams[2],
endTime: noteParams[3]
});
ns.notes.push(note);
if (ns.totalTime < note.endTime) {
ns.totalTime = note.endTime;
}
}
}
function addQuantizedTrackToSequence(
ns: NoteSequence, instrument: number, notes: number[][]) {
for (const noteParams of notes) {
const note = new NoteSequence.Note({
pitch: noteParams[0],
instrument,
velocity: noteParams[1],
quantizedStartStep: noteParams[2],
quantizedEndStep: noteParams[3]
});
ns.notes.push(note);
if (ns.totalQuantizedSteps < note.quantizedEndStep) {
ns.totalQuantizedSteps = note.quantizedEndStep;
}
}
}
function addChordsToSequence(
ns: NoteSequence, chords: Array<Array<number|string>>) {
for (const chordParams of chords) {
const ta = NoteSequence.TextAnnotation.create({
text: chordParams[0] as string,
time: chordParams[1] as number,
annotationType:
NoteSequence.TextAnnotation.TextAnnotationType.CHORD_SYMBOL
});
ns.textAnnotations.push(ta);
}
}
function addControlChangesToSequence(
ns: NoteSequence, instrument: number, controlChanges: number[][]) {
for (const ccParams of controlChanges) {
const cc = NoteSequence.ControlChange.create({
time: ccParams[0],
controlNumber: ccParams[1],
controlValue: ccParams[2],
instrument
});
ns.controlChanges.push(cc);
}
}
function addQuantizedStepsToSequence(
ns: NoteSequence, quantizedSteps: number[][]) {
quantizedSteps.forEach((qstep, i) => {
const note = ns.notes[i];
note.quantizedStartStep = qstep[0];
note.quantizedEndStep = qstep[1];
if (note.quantizedEndStep > ns.totalQuantizedSteps) {
ns.totalQuantizedSteps = note.quantizedEndStep;
}
});
}
function addQuantizedChordStepsToSequence(
ns: NoteSequence, quantizedSteps: number[]) {
const chordAnnotations = ns.textAnnotations.filter(
ta => ta.annotationType ===
NoteSequence.TextAnnotation.TextAnnotationType.CHORD_SYMBOL);
quantizedSteps.forEach((qstep, i) => {
const ta = chordAnnotations[i];
ta.quantizedStep = qstep;
});
}
function addQuantizedControlStepsToSequence(
ns: NoteSequence, quantizedSteps: number[]) {
quantizedSteps.forEach((qstep, i) => {
const cc = ns.controlChanges[i];
cc.quantizedStep = qstep;
});
}
function compareNotes(note1: NoteSequence.INote, note2: NoteSequence.INote) {
return note1.pitch === note2.pitch && note1.velocity === note2.velocity &&
note1.quantizedStartStep === note2.quantizedStartStep &&
note1.quantizedEndStep === note2.quantizedEndStep;
}
function compareNotesArray(a: NoteSequence.INote[], b: NoteSequence.INote[]) {
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; i++) {
if (!compareNotes(a[i], b[i])) {
return false;
}
}
return true;
}
test('Quantize NoteSequence', (t: test.Test) => {
const ns = createTestNS();
addTrackToSequence(ns, 0, [
[12, 100, 0.01, 10.0], [11, 55, 0.22, 0.50], [40, 45, 2.50, 3.50],
[55, 120, 4.0, 4.01], [52, 99, 4.75, 5.0]
]);
addChordsToSequence(ns, [['B7', 0.22], ['Em9', 4.0]]);
addControlChangesToSequence(ns, 0, [[2.0, 64, 127], [4.0, 64, 0]]);
// Make a copy.
const expectedQuantizedSequence = sequences.clone(ns);
expectedQuantizedSequence.quantizationInfo =
NoteSequence.QuantizationInfo.create(
{stepsPerQuarter: STEPS_PER_QUARTER});
expectedQuantizedSequence.quantizationInfo.stepsPerQuarter =
STEPS_PER_QUARTER;
addQuantizedStepsToSequence(
expectedQuantizedSequence,
[[0, 40], [1, 2], [10, 14], [16, 17], [19, 20]]);
addQuantizedChordStepsToSequence(expectedQuantizedSequence, [1, 16]);
addQuantizedControlStepsToSequence(expectedQuantizedSequence, [8, 16]);
const qns = sequences.quantizeNoteSequence(ns, STEPS_PER_QUARTER);
t.deepEqual(
NoteSequence.toObject(qns),
NoteSequence.toObject(expectedQuantizedSequence));
t.end();
});
test('Quantize NoteSequence, Time Signature Change', (t: test.Test) => {
const ns = createTestNS();
addTrackToSequence(ns, 0, [
[12, 100, 0.01, 10.0], [11, 55, 0.22, 0.50], [40, 45, 2.50, 3.50],
[55, 120, 4.0, 4.01], [52, 99, 4.75, 5.0]
]);
ns.timeSignatures.length = 0;
sequences.quantizeNoteSequence(ns, STEPS_PER_QUARTER);
// Single time signature.
ns.timeSignatures.push(NoteSequence.TimeSignature.create(
{numerator: 4, denominator: 4, time: 0}));
sequences.quantizeNoteSequence(ns, STEPS_PER_QUARTER);
// Multiple time signatures with no change.
ns.timeSignatures.push(NoteSequence.TimeSignature.create(
{numerator: 4, denominator: 4, time: 1}));
sequences.quantizeNoteSequence(ns, STEPS_PER_QUARTER);
// Time signature change.
ns.timeSignatures.push(NoteSequence.TimeSignature.create(
{numerator: 2, denominator: 4, time: 2}));
t.throws(
() => sequences.quantizeNoteSequence(ns, STEPS_PER_QUARTER),
sequences.MultipleTimeSignatureException);
t.end();
});
test(
'Quantize NoteSequence, Implicit Time Signature Change', (t: test.Test) => {
const ns = createTestNS();
addTrackToSequence(ns, 0, [
[12, 100, 0.01, 10.0], [11, 55, 0.22, 0.50], [40, 45, 2.50, 3.50],
[55, 120, 4.0, 4.01], [52, 99, 4.75, 5.0]
]);
ns.timeSignatures.length = 0;
// No time signature.
sequences.quantizeNoteSequence(ns, STEPS_PER_QUARTER);
// Implicit time signature change.
ns.timeSignatures.push(NoteSequence.TimeSignature.create(
{numerator: 2, denominator: 4, time: 2}));
t.throws(
() => sequences.quantizeNoteSequence(ns, STEPS_PER_QUARTER),
sequences.MultipleTimeSignatureException);
t.end();
});
test(
'Quantize NoteSequence, No Implicit Time Signature Change, Out Of Order',
(t: test.Test) => {
const ns = createTestNS();
addTrackToSequence(ns, 0, [
[12, 100, 0.01, 10.0], [11, 55, 0.22, 0.50], [40, 45, 2.50, 3.50],
[55, 120, 4.0, 4.01], [52, 99, 4.75, 5.0]
]);
ns.timeSignatures.length = 0;
// No time signature.
sequences.quantizeNoteSequence(ns, STEPS_PER_QUARTER);
// No implicit time signature change, but time signatures are added out of
// order.
ns.timeSignatures.push(NoteSequence.TimeSignature.create(
{numerator: 2, denominator: 4, time: 2}));
ns.timeSignatures.push(NoteSequence.TimeSignature.create(
{numerator: 2, denominator: 4, time: 0}));
sequences.quantizeNoteSequence(ns, STEPS_PER_QUARTER);
t.pass();
t.end();
});
test('StepsPerQuarterToStepsPerSecond', (t: test.Test) => {
t.equal(sequences.stepsPerQuarterToStepsPerSecond(4, 60.0), 4.0);
t.end();
});
test('QuantizeToStep', (t: test.Test) => {
t.equal(sequences.quantizeToStep(8.0001, 4), 32);
t.equal(sequences.quantizeToStep(8.4999, 4), 34);
t.equal(sequences.quantizeToStep(8.4999, 4, 1.0), 33);
t.end();
});
test('Quantize NoteSequence, Tempo Change', (t: test.Test) => {
const ns = createTestNS();
addTrackToSequence(ns, 0, [
[12, 100, 0.01, 10.0], [11, 55, 0.22, 0.50], [40, 45, 2.50, 3.50],
[55, 120, 4.0, 4.01], [52, 99, 4.75, 5.0]
]);
ns.tempos.length = 0;
// No tempos.
sequences.quantizeNoteSequence(ns, STEPS_PER_QUARTER);
// Single tempo.
ns.tempos.push(NoteSequence.Tempo.create({qpm: 60, time: 0}));
sequences.quantizeNoteSequence(ns, STEPS_PER_QUARTER);
// Multiple tempos with no change.
ns.tempos.push(NoteSequence.Tempo.create({qpm: 60, time: 1}));
sequences.quantizeNoteSequence(ns, STEPS_PER_QUARTER);
// Tempo change.
ns.tempos.push(NoteSequence.Tempo.create({qpm: 120, time: 2}));
t.throws(
() => sequences.quantizeNoteSequence(ns, STEPS_PER_QUARTER),
sequences.MultipleTempoException);
t.end();
});
test('Quantize NoteSequence, Implicit Tempo Change', (t: test.Test) => {
const ns = createTestNS();
addTrackToSequence(ns, 0, [
[12, 100, 0.01, 10.0], [11, 55, 0.22, 0.50], [40, 45, 2.50, 3.50],
[55, 120, 4.0, 4.01], [52, 99, 4.75, 5.0]
]);
ns.tempos.length = 0;
// No tempos.
sequences.quantizeNoteSequence(ns, STEPS_PER_QUARTER);
// Implicit tempo change.
ns.tempos.push(NoteSequence.Tempo.create({qpm: 60, time: 2}));
t.throws(
() => sequences.quantizeNoteSequence(ns, STEPS_PER_QUARTER),
sequences.MultipleTempoException);
t.end();
});
test(
'Quantize NoteSequence, No Implicit Tempo Change, Out of Order',
(t: test.Test) => {
const ns = createTestNS();
addTrackToSequence(ns, 0, [
[12, 100, 0.01, 10.0], [11, 55, 0.22, 0.50], [40, 45, 2.50, 3.50],
[55, 120, 4.0, 4.01], [52, 99, 4.75, 5.0]
]);
ns.tempos.length = 0;
// No tempos.
sequences.quantizeNoteSequence(ns, STEPS_PER_QUARTER);
// No implicit tempo change, but tempos are added out of order.
ns.tempos.push(NoteSequence.Tempo.create({qpm: 60, time: 2}));
ns.tempos.push(NoteSequence.Tempo.create({qpm: 60, time: 0}));
sequences.quantizeNoteSequence(ns, STEPS_PER_QUARTER);
t.pass();
t.end();
});
test('Quantize NoteSequence, Rounding', (t: test.Test) => {
const ns = createTestNS();
addTrackToSequence(ns, 1, [
[12, 100, 0.01, 0.24], [11, 100, 0.22, 0.55], [40, 100, 0.50, 0.75],
[41, 100, 0.689, 1.18], [44, 100, 1.19, 1.69], [55, 100, 4.0, 4.01]
]);
// Make a copy.
const expectedQuantizedSequence = sequences.clone(ns);
expectedQuantizedSequence.quantizationInfo =
NoteSequence.QuantizationInfo.create(
{stepsPerQuarter: STEPS_PER_QUARTER});
addQuantizedStepsToSequence(
expectedQuantizedSequence,
[[0, 1], [1, 2], [2, 3], [3, 5], [5, 7], [16, 17]]);
const quantizedSequence =
sequences.quantizeNoteSequence(ns, STEPS_PER_QUARTER);
t.deepEqual(
NoteSequence.toObject(quantizedSequence),
NoteSequence.toObject(expectedQuantizedSequence));
t.end();
});
test('Quantize NoteSequence, MultiTrack', (t: test.Test) => {
const ns = createTestNS();
addTrackToSequence(ns, 0, [[12, 100, 1.0, 4.0], [19, 100, 0.95, 3.0]]);
addTrackToSequence(ns, 3, [[12, 100, 1.0, 4.0], [19, 100, 2.0, 5.0]]);
addTrackToSequence(
ns, 7, [[12, 100, 1.0, 5.0], [19, 100, 2.0, 4.0], [24, 100, 3.0, 3.5]]);
// Make a copy.
const expectedQuantizedSequence = sequences.clone(ns);
expectedQuantizedSequence.quantizationInfo =
NoteSequence.QuantizationInfo.create(
{stepsPerQuarter: STEPS_PER_QUARTER});
addQuantizedStepsToSequence(
expectedQuantizedSequence,
[[4, 16], [4, 12], [4, 16], [8, 20], [4, 20], [8, 16], [12, 14]]);
const quantizedSequence =
sequences.quantizeNoteSequence(ns, STEPS_PER_QUARTER);
t.deepEqual(
NoteSequence.toObject(quantizedSequence),
NoteSequence.toObject(expectedQuantizedSequence));
t.end();
});
test('Assert isQuantizedNoteSequence', (t: test.Test) => {
const ns = createTestNS();
addTrackToSequence(ns, 0, [
[12, 100, 0.01, 10.0], [11, 55, 0.22, 0.50], [40, 45, 2.50, 3.50],
[55, 120, 4.0, 4.01], [52, 99, 4.75, 5.0]
]);
t.throws(
() => sequences.assertIsQuantizedSequence(ns),
sequences.QuantizationStatusException);
const qns = sequences.quantizeNoteSequence(ns, STEPS_PER_QUARTER);
sequences.assertIsQuantizedSequence(qns);
t.end();
});
test('Assert isRelativeQuantizedNoteSequence', (t: test.Test) => {
const ns = createTestNS();
addTrackToSequence(ns, 0, [
[12, 100, 0.01, 10.0], [11, 55, 0.22, 0.50], [40, 45, 2.50, 3.50],
[55, 120, 4.0, 4.01], [52, 99, 4.75, 5.0]
]);
t.throws(
() => sequences.assertIsRelativeQuantizedSequence(ns),
sequences.QuantizationStatusException);
const qns = sequences.quantizeNoteSequence(ns, STEPS_PER_QUARTER);
sequences.assertIsRelativeQuantizedSequence(qns);
t.end();
});
function testUnQuantize(
t: test.Test, expectedTimes: Array<[number, number]>,
expectedTotalTime: number, originalQpm?: number, finalQpm?: number,
originalTotalSteps?: number) {
let qns = createTestNS();
const notes = [
[12, 100, 0.01, 0.24], [11, 100, 0.22, 0.55], [40, 100, 0.50, 0.75],
[41, 100, 0.689, 1.18], [44, 100, 1.19, 1.69]
];
addTrackToSequence(qns, 1, notes);
qns = sequences.quantizeNoteSequence(qns, STEPS_PER_QUARTER);
if (!originalQpm) {
qns.tempos = [];
} else {
qns.tempos[0].qpm = originalQpm;
}
if (originalTotalSteps) {
qns.totalQuantizedSteps = originalTotalSteps;
}
const ns = sequences.unquantizeSequence(qns, finalQpm);
const expectedSequence = NoteSequence.create();
expectedSequence.timeSignatures = ns.timeSignatures;
qns.notes.forEach((n, i) => {
expectedSequence.notes.push({
pitch: n.pitch,
instrument: n.instrument,
velocity: n.velocity,
startTime: expectedTimes[i][0],
endTime: expectedTimes[i][1]
});
});
expectedSequence.totalTime = expectedTotalTime;
if (!finalQpm && !originalQpm) {
expectedSequence.tempos = [];
} else {
expectedSequence.tempos =
[{time: 0, qpm: finalQpm ? finalQpm : originalQpm}];
}
t.deepEqual(
NoteSequence.toObject(ns), NoteSequence.toObject(expectedSequence));
t.end();
}
test('Un-Quantize NoteSequence, ns qpm', (t: test.Test) => {
testUnQuantize(
t, [[0.0, 0.25], [0.25, 0.50], [0.50, 0.75], [0.75, 1.25], [1.25, 1.75]],
1.75, 60);
});
test('Un-Quantize NoteSequence, no qpm', (t: test.Test) => {
testUnQuantize(
t,
[
[0.0, 0.125], [0.125, 0.25], [0.25, 0.375], [0.375, 0.625],
[0.625, 0.875]
],
0.875);
});
test('Un-Quantize NoteSequence, arg qpm', (t: test.Test) => {
testUnQuantize(
t, [[0.0, 0.5], [0.5, 1.00], [1.00, 1.5], [1.5, 2.5], [2.5, 3.5]], 3.5,
undefined, 30);
});
test('Un-Quantize NoteSequence, orig and arg qpm', (t: test.Test) => {
testUnQuantize(
t, [[0.0, 0.5], [0.5, 1.00], [1.00, 1.5], [1.5, 2.5], [2.5, 3.5]], 3.5,
60, 30);
});
test('Un-Quantize NoteSequence, existing total steps lower', (t: test.Test) => {
testUnQuantize(
t, [[0.0, 0.5], [0.5, 1.00], [1.00, 1.5], [1.5, 2.5], [2.5, 3.5]], 3.5,
undefined, 30, 1);
});
test(
'Un-Quantize NoteSequence, existing total steps higher', (t: test.Test) => {
testUnQuantize(
t, [[0.0, 0.5], [0.5, 1.00], [1.00, 1.5], [1.5, 2.5], [2.5, 3.5]], 10,
undefined, 30, 20);
});
test('Merge Instruments', (t: test.Test) => {
const ns = createTestNS();
ns.notes.push({pitch: 60, program: 0, isDrum: false});
ns.notes.push({pitch: 64, program: 0, isDrum: false});
ns.notes.push({pitch: 36, program: 0, isDrum: true});
ns.notes.push({pitch: 48, program: 32, isDrum: false});
ns.notes.push({pitch: 42, program: 1, isDrum: true});
const expected = sequences.clone(ns);
expected.notes[0].instrument = 0;
expected.notes[1].instrument = 0;
expected.notes[2].instrument = 2;
expected.notes[3].instrument = 1;
expected.notes[4].instrument = 2;
expected.notes[4].program = 0;
t.deepEqual(
NoteSequence.toObject(sequences.mergeInstruments(ns)),
NoteSequence.toObject(expected));
t.end();
});
test('Replace Instruments', (t: test.Test) => {
const ns1 = createTestNS();
// This should be kept.
ns1.notes.push({pitch: 72, instrument: 2});
// These should be replaced.
ns1.notes.push({pitch: 60, instrument: 0});
ns1.notes.push({pitch: 70, instrument: 1});
ns1.notes.push({pitch: 62, instrument: 0});
// This should be kept.
ns1.notes.push({pitch: 70, instrument: 2});
const ns2 = createTestNS();
// These should be replaced.
ns2.notes.push({pitch: 40, instrument: 0});
ns2.notes.push({pitch: 41, instrument: 0});
ns2.notes.push({pitch: 42, instrument: 0});
ns2.notes.push({pitch: 50, instrument: 1});
ns2.notes.push({pitch: 51, instrument: 1});
// This should not be replaced.
ns2.notes.push({pitch: 60, instrument: 3});
const expected = createTestNS();
// These are sorted by instrument, then time.
expected.notes.push({pitch: 40, instrument: 0});
expected.notes.push({pitch: 41, instrument: 0});
expected.notes.push({pitch: 42, instrument: 0});
expected.notes.push({pitch: 50, instrument: 1});
expected.notes.push({pitch: 51, instrument: 1});
// We are not sorting by pitch.
expected.notes.push({pitch: 72, instrument: 2});
expected.notes.push({pitch: 70, instrument: 2});
t.deepEqual(
NoteSequence.toObject(sequences.replaceInstruments(ns1, ns2)),
NoteSequence.toObject(expected));
t.end();
});
test('Concatenate 1 NoteSequence (unquantized)', (t: test.Test) => {
const ns1 = createTestNS();
const expected = createTestNS();
addTrackToSequence(ns1, 0, [[60, 100, 0.0, 1.0], [72, 100, 0.5, 1.5]]);
addTrackToSequence(expected, 0, [[60, 100, 0.0, 1.0], [72, 100, 0.5, 1.5]]);
t.deepEqual(
NoteSequence.toObject(sequences.concatenate([ns1])),
NoteSequence.toObject(expected));
t.end();
});
test('Concatenate 2 NoteSequences (unquantized)', (t: test.Test) => {
const ns1 = createTestNS();
const ns2 = createTestNS();
const expected = createTestNS();
addTrackToSequence(ns1, 0, [[60, 100, 0.0, 1.0], [72, 100, 0.5, 1.5]]);
addTrackToSequence(ns2, 0, [[59, 100, 0.0, 1.0], [71, 100, 0.5, 1.5]]);
addTrackToSequence(expected, 0, [
[60, 100, 0.0, 1.0], [72, 100, 0.5, 1.5], [59, 100, 1.5, 2.5],
[71, 100, 2.0, 3.0]
]);
t.deepEqual(
NoteSequence.toObject(sequences.concatenate([ns1, ns2])),
NoteSequence.toObject(expected));
t.end();
});
test(
'Concatenate 2 NoteSequences with individual durations (unquantized)',
(t: test.Test) => {
const ns1 = createTestNS();
const ns2 = createTestNS();
const expected = createTestNS();
addTrackToSequence(ns1, 0, [[60, 100, 0.0, 1.0], [72, 100, 0.5, 1.5]]);
addTrackToSequence(ns2, 0, [[59, 100, 0.0, 1.0], [71, 100, 0.5, 1.5]]);
addTrackToSequence(expected, 0, [
[60, 100, 0.0, 1.0], [72, 100, 0.5, 1.5], [59, 100, 3.0, 4.0],
[71, 100, 3.5, 4.5]
]);
expected.totalTime = 6;
t.deepEqual(
NoteSequence.toObject(sequences.concatenate([ns1, ns2], [3, 3])),
NoteSequence.toObject(expected));
t.end();
});
test('Concatenate 3 NoteSequences (unquantized)', (t: test.Test) => {
const ns1 = createTestNS();
const ns2 = createTestNS();
const ns3 = createTestNS();
const expected = createTestNS();
addTrackToSequence(ns1, 0, [[60, 100, 0.0, 1.0], [72, 100, 0.5, 1.5]]);
addTrackToSequence(ns2, 0, [[59, 100, 0.0, 1.0], [71, 100, 0.5, 1.5]]);
addTrackToSequence(ns3, 0, [[58, 100, 1.0, 1.5], [70, 100, 2.0, 2.5]]);
addTrackToSequence(expected, 0, [
[60, 100, 0.0, 1.0], [72, 100, 0.5, 1.5], [59, 100, 1.5, 2.5],
[71, 100, 2.0, 3.0], [58, 100, 4.0, 4.5], [70, 100, 5.0, 5.5]
]);
t.deepEqual(
NoteSequence.toObject(sequences.concatenate([ns1, ns2, ns3])),
NoteSequence.toObject(expected));
t.end();
});
test('Concatenate 1 NoteSequence (quantized)', (t: test.Test) => {
const ns1 = createTestNS();
const expected = createTestNS();
addQuantizedTrackToSequence(ns1, 0, [[60, 100, 0, 2], [72, 100, 2, 3]]);
addQuantizedTrackToSequence(expected, 0, [[60, 100, 0, 2], [72, 100, 2, 3]]);
ns1.quantizationInfo = NoteSequence.QuantizationInfo.create(
{stepsPerQuarter: STEPS_PER_QUARTER});
expected.quantizationInfo = NoteSequence.QuantizationInfo.create(
{stepsPerQuarter: STEPS_PER_QUARTER});
t.deepEqual(
NoteSequence.toObject(sequences.concatenate([ns1])),
NoteSequence.toObject(expected));
t.end();
});
test('Concatenate 2 NoteSequences (quantized)', (t: test.Test) => {
const ns1 = createTestNS();
const ns2 = createTestNS();
const expected = createTestNS();
addQuantizedTrackToSequence(ns1, 0, [[60, 100, 0, 4], [72, 100, 2, 6]]);
addQuantizedTrackToSequence(ns2, 0, [[59, 100, 0, 4], [71, 100, 1, 6]]);
ns1.quantizationInfo = NoteSequence.QuantizationInfo.create(
{stepsPerQuarter: STEPS_PER_QUARTER});
ns2.quantizationInfo = NoteSequence.QuantizationInfo.create(
{stepsPerQuarter: STEPS_PER_QUARTER});
addQuantizedTrackToSequence(
expected, 0,
[[60, 100, 0, 4], [72, 100, 2, 6], [59, 100, 6, 10], [71, 100, 7, 12]]);
expected.quantizationInfo = NoteSequence.QuantizationInfo.create(
{stepsPerQuarter: STEPS_PER_QUARTER});
t.deepEqual(
NoteSequence.toObject(sequences.concatenate([ns1, ns2])),
NoteSequence.toObject(expected));
t.end();
});
test(
'Concatenate 2 NoteSequences with individual durations (quantized)',
(t: test.Test) => {
const ns1 = createTestNS();
const ns2 = createTestNS();
const expected = createTestNS();
addQuantizedTrackToSequence(ns1, 0, [[60, 100, 0, 4], [72, 100, 2, 6]]);
addQuantizedTrackToSequence(ns2, 0, [[59, 100, 0, 4], [71, 100, 1, 6]]);
ns1.quantizationInfo = NoteSequence.QuantizationInfo.create(
{stepsPerQuarter: STEPS_PER_QUARTER});
ns2.quantizationInfo = NoteSequence.QuantizationInfo.create(
{stepsPerQuarter: STEPS_PER_QUARTER});
addQuantizedTrackToSequence(expected, 0, [
[60, 100, 0, 4], [72, 100, 2, 6], [59, 100, 10, 14], [71, 100, 11, 16]
]);
expected.quantizationInfo = NoteSequence.QuantizationInfo.create(
{stepsPerQuarter: STEPS_PER_QUARTER});
expected.totalQuantizedSteps = 20;
t.deepEqual(
NoteSequence.toObject(sequences.concatenate([ns1, ns2], [10, 10])),
NoteSequence.toObject(expected));
t.end();
});
test('Concatenate 3 NoteSequences (quantized)', (t: test.Test) => {
const ns1 = createTestNS();
const ns2 = createTestNS();
const ns3 = createTestNS();
const expected = createTestNS();
addQuantizedTrackToSequence(ns1, 0, [[60, 100, 0, 2], [72, 100, 1, 3]]);
addQuantizedTrackToSequence(ns2, 0, [[59, 100, 0, 2], [71, 100, 1, 3]]);
addQuantizedTrackToSequence(ns3, 0, [[58, 100, 2, 3], [70, 100, 4, 6]]);
ns1.quantizationInfo = NoteSequence.QuantizationInfo.create(
{stepsPerQuarter: STEPS_PER_QUARTER});
ns2.quantizationInfo = NoteSequence.QuantizationInfo.create(
{stepsPerQuarter: STEPS_PER_QUARTER});
ns3.quantizationInfo = NoteSequence.QuantizationInfo.create(
{stepsPerQuarter: STEPS_PER_QUARTER});
addQuantizedTrackToSequence(expected, 0, [
[60, 100, 0, 2], [72, 100, 1, 3], [59, 100, 3, 5], [71, 100, 4, 6],
[58, 100, 8, 9], [70, 100, 10, 12]
]);
expected.quantizationInfo = NoteSequence.QuantizationInfo.create(
{stepsPerQuarter: STEPS_PER_QUARTER});
t.deepEqual(
NoteSequence.toObject(sequences.concatenate([ns1, ns2, ns3])),
NoteSequence.toObject(expected));
t.end();
});
test('Concatenate error case: mismatched quantizationInfo', (t: test.Test) => {
const ns1 = createTestNS();
const ns2 = createTestNS();
addQuantizedTrackToSequence(ns1, 0, [[60, 100, 0, 4], [72, 100, 2, 6]]);
addQuantizedTrackToSequence(ns2, 0, [[59, 100, 0, 4], [71, 100, 1, 6]]);
ns1.quantizationInfo = NoteSequence.QuantizationInfo.create(
{stepsPerQuarter: STEPS_PER_QUARTER});
ns2.quantizationInfo =
NoteSequence.QuantizationInfo.create({stepsPerQuarter: 1});
t.throws(() => sequences.concatenate([ns1, ns2]), Error);
t.end();
});
test(
'Concatenate error case: mismatched quantized and unquantized sequences',
(t: test.Test) => {
const ns1 = createTestNS();
const ns2 = createTestNS();
addQuantizedTrackToSequence(ns1, 0, [[60, 100, 0, 4], [72, 100, 2, 6]]);
addTrackToSequence(ns2, 0, [[59, 100, 0, 4], [71, 100, 1, 6]]);
ns1.quantizationInfo = NoteSequence.QuantizationInfo.create(
{stepsPerQuarter: STEPS_PER_QUARTER});
t.throws(() => sequences.concatenate([ns1, ns2]), Error);
t.end();
});
test('Trim NoteSequence (unquantized)', (t: test.Test) => {
const ns1 = createTestNS();
const expected = createTestNS();
addTrackToSequence(ns1, 0, [
[60, 100, 0.0, 1.0], [72, 100, 0.5, 1.5], [59, 100, 1.5, 2.5],
[71, 100, 2.0, 3.0], [58, 100, 3.0, 4.5], [70, 100, 5.0, 5.5]
]);
addTrackToSequence(expected, 0, [[59, 100, 0, 1], [71, 100, 0.5, 1.5]]);
expected.totalTime = 2.5;
t.deepEqual(
NoteSequence.toObject(sequences.trim(ns1, 1.5, 4.0)),
NoteSequence.toObject(expected));
t.end();
});
test('Trim and truncate NoteSequence (unquantized)', (t: test.Test) => {
const ns1 = createTestNS();
const expected = createTestNS();
addTrackToSequence(ns1, 0, [
[60, 100, 0.0, 1.0], [72, 100, 0.5, 1.5], [59, 100, 1.5, 2.5],
[71, 100, 2.0, 3.0], [58, 100, 3.0, 4.5], [70, 100, 5.0, 5.5]
]);
addTrackToSequence(
expected, 0, [[59, 100, 0, 1], [71, 100, 0.5, 1.5], [58, 100, 1.5, 2.5]]);
expected.totalTime = 2.5;
t.deepEqual(
NoteSequence.toObject(sequences.trim(ns1, 1.5, 4.0, true)),
NoteSequence.toObject(expected));
t.end();
});
test('Trim NoteSequence (quantized)', (t: test.Test) => {
const ns1 = createTestNS();
ns1.quantizationInfo = NoteSequence.QuantizationInfo.create(
{stepsPerQuarter: STEPS_PER_QUARTER});
addQuantizedTrackToSequence(
ns1, 0,
[[60, 100, 0, 4], [60, 100, 2, 3], [60, 100, 3, 4], [60, 100, 3, 6]]);
const expected = createTestNS();
expected.quantizationInfo = NoteSequence.QuantizationInfo.create(
{stepsPerQuarter: STEPS_PER_QUARTER});
addQuantizedTrackToSequence(expected, 0, [[60, 100, 1, 2], [60, 100, 2, 3]]);
expected.totalQuantizedSteps = 4;
t.deepEqual(
NoteSequence.toObject(sequences.trim(ns1, 1, 5)),
NoteSequence.toObject(expected));
t.end();
});
test('Trim and truncate NoteSequence (quantized)', (t: test.Test) => {
const ns1 = createTestNS();
ns1.quantizationInfo = NoteSequence.QuantizationInfo.create(
{stepsPerQuarter: STEPS_PER_QUARTER});
addQuantizedTrackToSequence(
ns1, 0,
[[60, 100, 0, 4], [60, 100, 2, 3], [60, 100, 3, 4], [60, 100, 3, 6]]);
const expected = createTestNS();
expected.quantizationInfo = NoteSequence.QuantizationInfo.create(
{stepsPerQuarter: STEPS_PER_QUARTER});
addQuantizedTrackToSequence(
expected, 0, [[60, 100, 1, 2], [60, 100, 2, 3], [60, 100, 2, 4]]);
t.deepEqual(
NoteSequence.toObject(sequences.trim(ns1, 1, 5, true)),
NoteSequence.toObject(expected));
t.end();
});
test('Split sequence in 2 steps', (t: test.Test) => {
let ns1 = createTestNS();
addTrackToSequence(
ns1, 0,
[[60, 100, 0, 3], [72, 100, 2, 4], [80, 100, 6, 9], [20, 100, 40, 42]]);
ns1 = sequences.quantizeNoteSequence(ns1, 1);
// The first [60, 100, 0, 3] is split in 2 sequences.
const expected1 = [new NoteSequence.Note(
{pitch: 60, velocity: 100, quantizedStartStep: 0, quantizedEndStep: 2})];
// This contains the leftover from the first note, and [72, 100, 2, 4].
const expected2 = [
new NoteSequence.Note(
{pitch: 60, velocity: 100, quantizedStartStep: 0, quantizedEndStep: 1}),
new NoteSequence.Note(
{pitch: 72, velocity: 100, quantizedStartStep: 0, quantizedEndStep: 2})
];
// [80, 100, 6, 9] is basically [80, 100, 0, 3], so it's split in 2 sequences
const expected3 = [new NoteSequence.Note(
{pitch: 80, velocity: 100, quantizedStartStep: 0, quantizedEndStep: 2})];
const expected4 = [new NoteSequence.Note(
{pitch: 80, velocity: 100, quantizedStartStep: 0, quantizedEndStep: 1})];
const expected5 = [new NoteSequence.Note(
{pitch: 20, velocity: 100, quantizedStartStep: 0, quantizedEndStep: 2})];
const split = sequences.split(ns1, 2);
t.equal(5, split.length);
// The objects aren't exactly equal since the returned sequences' notes
// have more fields (instruments, drums), so loosely compare notes.
t.is(true, compareNotesArray(split[0].notes, expected1), 'split 1 ok');
t.is(true, compareNotesArray(split[1].notes, expected2), 'split 2 ok');
t.is(true, compareNotesArray(split[2].notes, expected3), 'split 3 ok');
t.is(true, compareNotesArray(split[3].notes, expected4), 'split 4 ok');
t.is(true, compareNotesArray(split[4].notes, expected5), 'split 5 ok');
t.end();
});
test('Split sequence in 64 steps', (t: test.Test) => {
let ns1 = createTestNS();
addTrackToSequence(ns1, 0, [
[60, 100, 0, 3], [70, 100, 2, 4], [80, 100, 6, 9], [90, 100, 40, 42],
[10, 100, 63, 68], [20, 100, 70, 74]
]);
ns1 = sequences.quantizeNoteSequence(ns1, 1);
// There are basically just 2 sequences, before or after the 64 step mark.
const expected1 = [
new NoteSequence.Note(
{pitch: 60, velocity: 100, quantizedStartStep: 0, quantizedEndStep: 3}),
new NoteSequence.Note(
{pitch: 70, velocity: 100, quantizedStartStep: 2, quantizedEndStep: 4}),
new NoteSequence.Note(
{pitch: 80, velocity: 100, quantizedStartStep: 6, quantizedEndStep: 9}),
new NoteSequence.Note({
pitch: 90,
velocity: 100,
quantizedStartStep: 40,
quantizedEndStep: 42
}),
new NoteSequence.Note({
pitch: 10,
velocity: 100,
quantizedStartStep: 63,
quantizedEndStep: 64
})
];
// This contains the leftover from the first note, and [72, 100, 2, 4].
const expected2 = [
new NoteSequence.Note(
{pitch: 10, velocity: 100, quantizedStartStep: 0, quantizedEndStep: 4}),
new NoteSequence.Note(
{pitch: 20, velocity: 100, quantizedStartStep: 6, quantizedEndStep: 10})
];
const split = sequences.split(ns1, 64);
t.equal(2, split.length);
// The objects aren't exactly equal since the returned sequences' notes
// have more fields (instruments, drums), so loosely compare notes.
t.is(true, compareNotesArray(split[0].notes, expected1), 'split 1 ok');
t.is(true, compareNotesArray(split[1].notes, expected2), 'split 2 ok');
t.end();
});
test('Merge Consecutive Notes', (t: test.Test) => {
const ns1 = createTestNS();
ns1.quantizationInfo = NoteSequence.QuantizationInfo.create(
{stepsPerQuarter: STEPS_PER_QUARTER});
// These should be merged.
ns1.notes.push({pitch: 60, quantizedStartStep: 1, quantizedEndStep: 2});
ns1.notes.push({pitch: 60, quantizedStartStep: 2, quantizedEndStep: 3});
ns1.notes.push({pitch: 60, quantizedStartStep: 3, quantizedEndStep: 4});
ns1.notes.push({pitch: 60, quantizedStartStep: 4, quantizedEndStep: 5});
// This shouldn't be merged because it's not consecutive.
ns1.notes.push({pitch: 60, quantizedStartStep: 6, quantizedEndStep: 10});
// This shouldn't be merged because it's a different pitch.
ns1.notes.push({pitch: 70, quantizedStartStep: 10, quantizedEndStep: 11});
// These should be merged.
ns1.notes.push({pitch: 70, quantizedStartStep: 11, quantizedEndStep: 13});
ns1.notes.push({pitch: 70, quantizedStartStep: 13, quantizedEndStep: 16});
// This shouldn't be merged because it starts on the measure boundary.
ns1.notes.push({pitch: 70, quantizedStartStep: 16, quantizedEndStep: 17});
const expected = createTestNS();
expected.quantizationInfo = NoteSequence.QuantizationInfo.create(
{stepsPerQuarter: STEPS_PER_QUARTER});
// These are sorted by instrument, then time.
expected.notes.push({pitch: 60, quantizedStartStep: 1, quantizedEndStep: 5});
expected.notes.push({pitch: 60, quantizedStartStep: 6, quantizedEndStep: 10});
expected.notes.push(
{pitch: 70, quantizedStartStep: 10, quantizedEndStep: 16});
expected.notes.push(
{pitch: 70, quantizedStartStep: 16, quantizedEndStep: 17});
t.deepEqual(
NoteSequence.toObject(sequences.mergeConsecutiveNotes(ns1)),
NoteSequence.toObject(expected));
t.end();
});
test('applySustain error case: quantized sequence', (t: test.Test) => {
const ns1 = createTestNS();
addQuantizedTrackToSequence(ns1, 0, [[60, 100, 0, 4], [72, 100, 2, 6]]);
ns1.quantizationInfo = NoteSequence.QuantizationInfo.create(
{stepsPerQuarter: STEPS_PER_QUARTER});
t.throws(() => sequences.applySustainControlChanges(ns1), Error);
t.end();
});
test('applySustain to sequence without sustain', (t: test.Test) => {
const ns = createTestNS();
addTrackToSequence(ns, 0, [
[12, 100, 0.01, 10.0], [11, 55, 0.22, 0.50], [40, 45, 2.50, 3.50],
[55, 120, 4.0, 4.01], [52, 99, 4.75, 5.0]
]);
const sustainedNS = sequences.applySustainControlChanges(ns);
t.deepEqual(
NoteSequence.toObject(ns),
NoteSequence.toObject(sustainedNS));
t.end();
});
test('applySustain to sequence with sustain', (t: test.Test) => {
const ns = createTestNS();
addTrackToSequence(ns, 0, [
[60, 100, 1.0, 2.0],
[61, 100, 2.0, 3.0],
[62, 100, 3.0, 4.0],
[64, 100, 5.0, 6.0],
[65, 100, 6.0, 7.0]
]);
addControlChangesToSequence(ns, 0, [
[0.0, 64, 127],
[5.0, 64, 0]
]);
const expectedNS = createTestNS();
addTrackToSequence(expectedNS, 0, [
[60, 100, 1.0, 5.0],
[61, 100, 2.0, 5.0],
[62, 100, 3.0, 5.0],
[64, 100, 5.0, 6.0],
[65, 100, 6.0, 7.0]
]);
addControlChangesToSequence(expectedNS, 0, [
[0.0, 64, 127],
[5.0, 64, 0]
]);
const sustainedNS = sequences.applySustainControlChanges(ns);
t.deepEqual(
NoteSequence.toObject(sustainedNS),
NoteSequence.toObject(expectedNS));
t.end();
}); | the_stack |
import fs, { copyFileSync, createReadStream, existsSync, unlinkSync, writeFileSync, statSync } from 'fs';
import * as path from 'path';
import os, { homedir } from 'os';
import { promisify } from 'util';
import crypto from 'crypto';
import globby from 'globby';
import mkdirp from 'mkdirp';
import rimRaf from 'rimraf';
import appModule from 'app-module-path';
import { confirm } from './inquirer';
const flexUI = '@twilio/flex-ui';
const react = 'react';
const reactDOM = 'react-dom';
export interface PackageJson {
name: string;
version: string;
dependencies: Record<string, string>;
devDependencies: Record<string, string>;
peerDependencies?: Record<string, string>;
}
export interface AppPackageJson extends PackageJson {
dependencies: {
'flex-plugin': string;
'flex-plugin-scripts': string;
};
}
export interface FlexConfigurationPlugin {
name: string;
dir: string;
}
export interface CLIFlexConfiguration {
plugins: FlexConfigurationPlugin[];
}
export type JsonObject<T> = { [K in keyof T]: T[K] };
export default fs;
const packageJsonStr = 'package.json';
/**
* This is an alias for require. Useful for mocking out in tests
* @param filePath the file to require
* @private
*/
/* istanbul ignore next */
// eslint-disable-next-line global-require, @typescript-eslint/no-require-imports, @typescript-eslint/explicit-module-boundary-types
export const _require = (filePath: string) => require(filePath);
// Set working directory
export const _setRequirePaths = (requirePath: string): void => {
appModule.addPath(requirePath);
// Now try to specifically set the node_modules path
const requirePaths: string[] = (require.main && require.main.paths) || [];
if (!requirePaths.includes(requirePath)) {
requirePaths.push(requirePath);
}
};
/**
* Reads a JSON file
*
* @param filePath the file path to read
*/
export const readPackageJson = (filePath: string): PackageJson => {
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
};
/**
* Returns the file size in bytes
* @param filePaths the path to the file
*/
export const getSileSizeInBytes = (...filePaths: string[]): number => statSync(path.join(...filePaths)).size;
/**
* Returns the file size in MB
* @param filePaths the path to file
*/
export const getFileSizeInMB = (...filePaths: string[]): number => getSileSizeInBytes(...filePaths) / (1024 * 1024);
/**
* Builds path relative to the given dir
* @param dir the dir
* @param paths the paths
*/
export const resolveRelative = (dir: string, ...paths: string[]): string => {
if (paths.length === 0) {
return dir;
}
const lastElement = paths[paths.length - 1];
// Check if last element is an extension
if (lastElement.charAt(0) !== '.') {
return path.join(dir, ...paths);
}
// Only one entry as extension
if (paths.length === 1) {
return path.join(`${dir}${lastElement}`);
}
const secondLastElement = paths[paths.length - 2];
const remainder = paths.slice(0, paths.length - 2);
return path.join(dir, ...[...remainder, `${secondLastElement}${lastElement}`]);
};
// Working directory
let internalCwd = fs.realpathSync(process.cwd());
let internalCoreCwd = fs.realpathSync(process.cwd());
/**
* Sets the working directory
* @param p the path to set
*/
export const setCwd = (p: string): void => {
internalCwd = p;
_setRequirePaths(path.join(internalCwd, 'node_modules'));
};
/**
* Returns the working directory
*/
export const getCwd = (): string => internalCwd;
/**
* Sets the core working directory
* @param p the path to set
*/
export const setCoreCwd = (p: string): void => {
internalCoreCwd = p;
_setRequirePaths(path.join(internalCoreCwd, 'node_modules'));
};
/**
* The core cwd is the working directory of core packages such as flex-plugin-scripts and flex-plugin
*/
export const getCoreCwd = (): string => internalCoreCwd;
/**
* Reads the file
* @param filePaths the file paths
*/
export const readFileSync = (...filePaths: string[]): string => fs.readFileSync(path.join(...filePaths), 'utf8');
/**
* Reads a JSON file (Templated)
*
* @param filePaths the file paths to read
*/
export const readJsonFile = <T>(...filePaths: string[]): T => {
return JSON.parse(readFileSync(...filePaths));
};
/**
* Gets the CLI paths. This is separated out from getPaths because create-flex-plugin also needs to read it,
* but that script will not have flex-plugin-scripts installed which would cause an exception to be thrown.
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export const getCliPaths = () => {
const coreCwd = getCoreCwd();
const coreNodeModulesDir = resolveRelative(coreCwd, 'node_modules');
const homeDir = homedir();
const cliDir = resolveRelative(homeDir, '/.twilio-cli');
const flexDir = resolveRelative(cliDir, 'flex');
return {
dir: cliDir,
nodeModulesDir: coreNodeModulesDir,
flexDir,
pluginsJsonPath: resolveRelative(flexDir, 'plugins.json'),
};
};
// Read plugins.json from Twilio CLI
export const readPluginsJson = (): CLIFlexConfiguration =>
readJsonFile<CLIFlexConfiguration>(getCliPaths().pluginsJsonPath);
/**
* Writes string to file
*/
export const writeFile = (str: string, ...paths: string[]): void => writeFileSync(path.join(...paths), str);
/**
* Writes an object as a JSON string to the file
* @param obj the object to write
* @param paths the path to write to
*/
export const writeJSONFile = <T>(obj: JsonObject<T>, ...paths: string[]): void =>
writeFile(JSON.stringify(obj, null, 2), ...paths);
// The OS root directory
const rootDir = os.platform() === 'win32' ? getCwd().split(path.sep)[0] : '/';
/*
* Promise version of {@link copyTempDir}
*/
const promiseCopyTempDir = promisify(_require('copy-template-dir'));
/**
* Checks the provided array of files exist
*
* @param files the files to check that they exist
*/
export const checkFilesExist = (...files: string[]): boolean => {
return files.map(fs.existsSync).every((resp) => resp);
};
/**
* Calculates the sha of a file
* @param paths
*/
/* istanbul ignore next */
export const calculateSha256 = async (...paths: string[]): Promise<string> => {
return new Promise((resolve, reject) => {
const shasum = crypto.createHash('sha256');
const stream = createReadStream(path.join(...paths));
stream.on('data', (data) => shasum.update(data));
stream.on('error', (err) => reject(err));
stream.on('end', () => resolve(shasum.digest('hex')));
});
};
/**
* Removes a file
* @param paths
*/
export const removeFile = (...paths: string[]): void => unlinkSync(path.join(...paths));
/**
* Copies from from src to dest
* @param srcPaths
* @param destPaths
*/
export const copyFile = (srcPaths: string[], destPaths: string[]): void =>
copyFileSync(path.join(...srcPaths), path.join(...destPaths));
/**
* Checks the provided file exists
*
* @param paths the paths to the file
*/
export const checkAFileExists = (...paths: string[]): boolean => existsSync(path.join(...paths));
/**
* Gets package.json path
*/
export const getPackageJsonPath = (): string => path.join(getCwd(), packageJsonStr);
/**
* Reads app package.json from the rootDir.
*/
export const readAppPackageJson = (): AppPackageJson => {
return readPackageJson(getPackageJsonPath()) as AppPackageJson;
};
/**
* Updates the package.json version field
*
* @param version the new version
*/
export const updateAppVersion = (version: string): void => {
const packageJson = readAppPackageJson();
packageJson.version = version;
fs.writeFileSync(getPackageJsonPath(), JSON.stringify(packageJson, null, 2));
};
/**
* Finds the closest up file relative to dir
*
* @param dir the directory
* @param file the file to look for
*/
export const findUp = (dir: string, file: string): string => {
const resolved = path.resolve(dir);
if (resolved === rootDir) {
throw new Error(`Reached OS root directory without finding ${file}`);
}
const filePath = path.join(resolved, file);
if (fs.existsSync(filePath)) {
return filePath;
}
return findUp(path.resolve(resolved, '..'), file);
};
/**
* mkdir -p wrapper
*/
export const mkdirpSync = mkdirp.sync;
/**
* Copies a template by applying the variables
*
* @param source the source
* @param target the target
* @param variables the variables
*/
/* istanbul ignore next */
// eslint-disable-next-line @typescript-eslint/ban-types
export const copyTemplateDir = async (source: string, target: string, variables: object): Promise<unknown> => {
return promiseCopyTempDir(source, target, variables);
};
/**
* rm -rf sync script
*/
export const rmRfSync = rimRaf.sync;
/**
* Builds path relative to cwd
* @param paths the paths
*/
export const resolveCwd = (...paths: string[]): string => resolveRelative(getCwd(), ...paths);
/**
* Finds globs in any cwd directory
* @param dir the cwd to check for patterns
* @param patterns the patterns
*/
export const findGlobsIn = (dir: string, ...patterns: string[]): string[] => {
return globby.sync(patterns, { cwd: dir });
};
/**
* Finds globs in the src directory
* @param patterns the patterns
*/
export const findGlobs = (...patterns: string[]): string[] => {
return findGlobsIn(path.join(getCwd(), 'src'), ...patterns);
};
/**
* Touch ~/.twilio-cli/flex/plugins.json if it does not exist
* Check if this plugin is in this config file. If not, add it.
* @param name the plugin name
* @param dir the plugin directory
* @param promptForOverwrite whether to prompt for overwrite
* @return whether the plugin-directory was overwritten
*/
export const checkPluginConfigurationExists = async (
name: string,
dir: string,
promptForOverwrite = false,
): Promise<boolean> => {
const cliPaths = getCliPaths();
if (!checkFilesExist(cliPaths.pluginsJsonPath)) {
mkdirpSync(cliPaths.flexDir);
writeJSONFile({ plugins: [] }, cliPaths.pluginsJsonPath);
}
const config = readPluginsJson();
const plugin = config.plugins.find((p) => p.name === name);
if (!plugin) {
config.plugins.push({ name, dir });
writeJSONFile(config, cliPaths.pluginsJsonPath);
return true;
}
if (plugin.dir === dir) {
return false;
}
const answer = promptForOverwrite
? await confirm(
`You already have a plugin called ${plugin.name} located at ${plugin.dir}. Do you want to update it to ${dir}?`,
'N',
)
: true;
if (answer) {
plugin.dir = dir;
writeJSONFile(config, cliPaths.pluginsJsonPath);
return true;
}
return false;
};
/**
* Adds the node_modules to the app module.
* This is needed because we spawn different scripts when running start/build/test and so we lose
* the original cwd directory
*/
export const addCWDNodeModule = (...args: string[]): void => {
const indexCoreCwd = args.indexOf('--core-cwd');
if (indexCoreCwd !== -1) {
const coreCwd = args[indexCoreCwd + 1];
if (coreCwd) {
setCoreCwd(coreCwd);
}
}
const indexCwd = args.indexOf('--cwd');
if (indexCwd === -1) {
// This is to setup the app environment
setCwd(getCwd());
} else {
const cwd = args[indexCwd + 1];
if (cwd) {
setCwd(cwd);
}
}
};
/**
* Returns the absolute path to the pkg if found
* @param pkg the package to lookup
*/
/* istanbul ignore next */
export const resolveModulePath = (pkg: string, ...paths: string[]): string | false => {
try {
return require.resolve(pkg);
} catch {
// Now try to specifically set the node_modules path
const requirePaths: string[] = (require.main && require.main.paths) || [];
requirePaths.push(...paths);
try {
return require.resolve(pkg, { paths: requirePaths });
} catch {
return false;
}
}
};
/**
* Returns the path to flex-plugin-scripts
*/
export const _getFlexPluginScripts = (): string => {
const flexPluginScriptPath = resolveModulePath('flex-plugin-scripts');
if (flexPluginScriptPath === false) {
throw new Error('Could not resolve flex-plugin-scripts');
}
return path.join(path.dirname(flexPluginScriptPath), '..');
};
/**
* Returns the path to flex-plugin-webpack
*/
export const _getFlexPluginWebpackPath = (scriptsNodeModulesDir: string): string => {
const flexPluginWebpackPath = resolveModulePath('flex-plugin-webpack', scriptsNodeModulesDir);
if (flexPluginWebpackPath === false) {
throw new Error(`Could not resolve flex-plugin-webpack`);
}
return path.join(path.dirname(flexPluginWebpackPath), '..');
};
/**
* Returns the paths to all modules and directories used in the plugin-builder
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export const getPaths = () => {
const cwd = getCwd();
const nodeModulesDir = resolveCwd('node_modules');
const scriptsDir = _getFlexPluginScripts();
const scriptsNodeModulesDir = resolveRelative(scriptsDir, 'node_modules');
const devAssetsDir = resolveRelative(scriptsDir, 'dev_assets');
const publicDir = resolveCwd('public');
const buildDir = resolveCwd('build');
const srcDir = resolveCwd('src');
const flexUIDir = resolveRelative(nodeModulesDir, flexUI);
const tsConfigPath = resolveCwd('tsconfig.json');
const webpackDir = _getFlexPluginWebpackPath(scriptsNodeModulesDir);
// package.json information
let pkgName = '';
let pkgVersion = '';
// This file can be required in locations that don't have package.json
try {
const pkg: PackageJson = readAppPackageJson();
pkgName = pkg.name;
pkgVersion = pkg.version;
} catch (e) {
// no-op
}
return {
cwd,
// flex-plugin-webpack paths
webpack: {
dir: webpackDir,
nodeModulesDir: resolveRelative(webpackDir, 'node_modules'),
},
// flex-plugin-scripts paths
scripts: {
dir: scriptsDir,
nodeModulesDir: scriptsNodeModulesDir,
devAssetsDir,
indexHTMLPath: resolveRelative(devAssetsDir, 'index.html'),
tsConfigPath: resolveRelative(devAssetsDir, 'tsconfig.json'),
},
// twilio-cli/flex/plugins.json paths
cli: getCliPaths(),
// plugin-app (the customer app)
app: {
dir: cwd,
name: pkgName,
version: pkgVersion,
pkgPath: resolveCwd(packageJsonStr),
jestConfigPath: resolveCwd('jest.config.js'),
webpackConfigPath: resolveCwd('webpack.config.js'),
devServerConfigPath: resolveCwd('webpack.dev.js'),
tsConfigPath,
isTSProject: () => checkFilesExist(tsConfigPath),
setupTestsPaths: [resolveCwd('setupTests.js'), resolveRelative(srcDir, 'setupTests.js')],
// .env file support
envPath: resolveCwd('/.env'),
hasEnvFile: () => checkFilesExist(resolveCwd('/.env')),
envExamplePath: resolveCwd('/.env.example'),
hasEnvExampleFile: () => checkFilesExist(resolveCwd('/.env.example')),
envDefaultsPath: resolveCwd('/.env.defaults'),
hasEnvDefaultsPath: () => checkFilesExist(resolveCwd('/.env.defaults')),
// build/*
buildDir,
bundlePath: resolveRelative(buildDir, pkgName, '.js'),
sourceMapPath: resolveRelative(buildDir, pkgName, '.js.map'),
// src/*
srcDir,
entryPath: resolveRelative(srcDir, 'index'),
// node_modules/*,
nodeModulesDir,
flexUIDir,
flexUIPkgPath: resolveRelative(flexUIDir, packageJsonStr),
// public/*
publicDir,
appConfig: resolveRelative(publicDir, 'appConfig.js'),
// dependencies
dependencies: {
react: {
version: readPackageJson(resolveRelative(nodeModulesDir, react, packageJsonStr)).version,
},
reactDom: {
version: readPackageJson(resolveRelative(nodeModulesDir, reactDOM, packageJsonStr)).version,
},
flexUI: {
version: readPackageJson(resolveRelative(nodeModulesDir, flexUI, packageJsonStr)).version,
},
},
},
// others
assetBaseUrlTemplate: `/plugins/${pkgName}/%PLUGIN_VERSION%`,
extensions: ['js', 'mjs', 'jsx', 'ts', 'tsx'],
};
};
/**
* Returns the version of the dependency that is installed in node_modules
* @param pkgName the package name
* @return the version of the package installed
*/
/* istanbul ignore next */
// eslint-disable-next-line import/no-unused-modules
export const getDependencyVersion = (pkgName: string): string => {
try {
return _require(`${pkgName}/package.json`).version;
} catch {
try {
return _require(resolveRelative(getPaths().app.nodeModulesDir, pkgName, packageJsonStr)).version;
} catch {
return _require(resolveRelative(getPaths().scripts.nodeModulesDir, pkgName, packageJsonStr)).version;
}
}
};
/**
* Returns the package.json version field of the package
* @param name the package
*/
/* istanbul ignore next */
export const getPackageVersion = (name: string): string => {
const installedPath = resolveRelative(getPaths().app.nodeModulesDir, name, packageJsonStr);
return readPackageJson(installedPath).version;
};
/**
* Determines whether the directory is plugin based on the package.json
* @param packageJson the package json
*/
export const isPluginDir = (packageJson: PackageJson): boolean => {
return Boolean(packageJson.dependencies[flexUI] || packageJson.devDependencies[flexUI]);
};
/**
* Fetches the version corresponding to the dependency inside the given package
* @param pkg the package.json to check
* @param name the package to look for
*/
export const packageDependencyVersion = (pkg: PackageJson, name: string): string | null => {
if (pkg.dependencies && name in pkg.dependencies) {
return pkg.dependencies[name];
}
if (pkg.devDependencies && name in pkg.devDependencies) {
return pkg.devDependencies[name];
}
if (pkg.peerDependencies && name in pkg.peerDependencies) {
return pkg.peerDependencies[name];
}
return null;
};
/**
* Fetches the version corresponding to the dependency inside the flex-ui package.json
* @param name the package to check
*/
export const flexUIPackageDependencyVersion = (name: string): string | null => {
return packageDependencyVersion(_require(getPaths().app.flexUIPkgPath) as PackageJson, name);
}; | the_stack |
import { useEffect, useState } from 'react';
import { useCookies } from 'react-cookie';
import { useRouter } from 'next/router'
import Link from "next/link";
// helpers
import {
currentPlayback,
CurrentSongWithAnalysis,
fetchAccessToken,
fetchPlaylists,
fetchProfile,
fetchTopData,
keyCodeToKey,
modeKeyToMode,
TopData,
fetchingTopData
} from '../utils/spotify';
import { Loading } from '../components/loading';
// telemetry
import * as ga from '../utils/ga';
import {
Error,
Header,
SEO
} from '../components/layout'
import { AuthData } from '..';
import { ErrorObject } from '../components/layout/Error';
const Auth = () => {
// create router object
const router = useRouter()
// access cookies
const [cookies, setCookie, ] = useCookies(['spottydata-credentials']);
// check for error code
const params = router.query
if (params.error === "access_denied") {
if(process.browser) {
// log cancelation
ga.event({
category: 'auth',
action: 'click',
label: 'cancel_authentication',
})
// send user home
router.push("/")
}
}
// extract authorization code
let authCode: string | undefined
if(Array.isArray(params.code)) {
authCode = params.code[0]
} else {
authCode = params.code
}
// state management
const [authData, setAuthData] = useState<AuthData>(cookies['authData'] || undefined)
const [profile, setProfile] = useState<SpotifyApi.UserObjectPublic | undefined>(undefined)
const [playlists, setPlaylists] = useState<SpotifyApi.PlaylistObjectFull[] | undefined>(undefined)
const [playback, setPlayback] = useState<CurrentSongWithAnalysis | undefined>(undefined)
const [top, setTop] = useState<TopData | undefined>(undefined)
const [artistTimeFrame, setArtistTimeFrame] = useState<string>('short_term')
const [trackTimeFrame, setTrackTimeFrame] = useState<string>('short_term')
const [loadingMessage, setLoadingMessage] = useState<string>("")
const [error, setError] = useState<ErrorObject | undefined>(undefined)
/**
* Drive access token fetching
*/
useEffect(() => {
if(authCode !== undefined && authData === undefined) {
setLoadingMessage("Authenting...")
fetchAccessToken(
authCode || "",
process.env.NEXT_PUBLIC_CLIENT_ID || "",
process.env.NEXT_PUBLIC_CLIENT_SECRET || "",
process.env.NEXT_PUBLIC_REDIRECT_URI || "",
setAuthData,
setError,
setCookie
)
}
}, [authCode, authData])
/**
* Drive user data fetching
*/
useEffect(() => {
if(authData !== undefined) {
setLoadingMessage("Fetching profile...")
fetchProfile(
authData,
setProfile,
setError,
setCookie
)
fetchPlaylists(
authData,
setPlaylists,
setError
)
fetchTopData(
authData,
setTop,
setError
)
}
}, [authData])
/**
* Playback watcher
*/
useEffect(() => {
if(authData !== undefined) {
currentPlayback(authData, setPlayback, setError)
}
let playbackCycle = setInterval(() => {
if(authData !== undefined) {
currentPlayback(authData, setPlayback, setError)
}
}, 3000) // run every five seconds
// cleanup
return () => clearInterval(playbackCycle)
}, [authData])
if(error) {
// render the error
return (
<div>
<SEO title="Error!"/>
<Error error={error} />
</div>
)
} else if (authData === undefined || profile === undefined || playlists === undefined || fetchingTopData(top) || top === undefined) {
// render a spinner
// console.log(fetchingTopData(top))
return (
<div className="min-h-screen flex flex-col justify-center items-center">
<SEO title="Loading..."/>
<Loading message={loadingMessage} />
</div>
)
} else {
// render profile page
//console.log(fetchingTopData(top))
return (
<div className="flex flex-col items-center justify-start bg-white min-h-screen">
<SEO title={`${profile.display_name} | Profile`} />
<div className="h-40 md:h-64 w-full bg-gradient border-b border-black">
<div className="p-1 md:p-4 flex flex-row items-center justify-between">
<Link href="/">
<span className="cursor-pointer font-bold">← Home</span>
</Link>
<Header />
</div>
<p className="md:mt-4 md:ml-4 ml-1 mt-1 text-6xl md:text-9xl font-extrabold opacity-10 truncate overflow-clip">{profile.display_name}</p>
</div>
<div className="mx-4 p-4 rounded-lg shadow-xl border-2 border-black -translate-y-20 md:-translate-y-1/4 bg-white w-11/12 md:max-w-screen-lg">
<div className="flex flex-row items-start justify-between mb-4 border-b border-gray-200 pb-4">
<div className="flex flex-row items-center">
<img
className="rounded-lg border-2 border-black shadow-md mr-4"
height={75}
width={75}
src={profile.images ? profile.images[0].url : ""}
/>
<p className="font-extrabold text-2xl md:text-4xl">
Welcome,{' '}
<span className="text-green-500">{profile.display_name}</span>
</p>
</div>
{
playback?.is_playing ?
<div className="text-center animate-pulse text-xs px-2 py-1 text-green-600 bg-green-200 border-2 border-green-600 rounded-full">
Listening
</div> :
<span className="text-center text-xs px-2 py-1 bg-gray-200 border-2 border-black rounded-full">
Paused
</span>
}
</div>
<div className="flex flex-row flex-wrap items-start justify-start mb-4 border-b border-gray-200 pb-4 font-bold text-lg md:text-xl">
<p className="mr-4">Followers:{' '}<span className="text-purple-500">{profile.followers ? profile.followers.total : '0'}</span></p>
<p className="mr-4">Playlists:{' '}<span className="text-red-500">{playlists.length}</span></p>
<p className="mr-4">Total tracks:{' '}
<span className="text-yellow-500">
{playlists.map(p => p.tracks.total).reduce((a,b) => a + b, 0)}
</span>
</p>
</div>
<div className="flex flex-col justify-start">
<p className="text-2xl font-bold md:text-3xl">Currently listening to: </p>
{
playback ?
<>
<div className="flex flex-row items-center my-2">
<img
className="rounded-lg border-2 border-black shadow-md"
height={75}
width={75}
src={playback.item.album.images[0].url}
/>
<div className="ml-2">
<p className="text-xl md:text-2xl font-semibold">{playback.item.name}</p>
<p className="text-base italic">{playback.item.artists[0].name}</p>
</div>
</div>
<div className="my-2 flex flex-col md:flex-row text-lg md:text-2xl">
<p>Song Key: <span className="mr-4 font-bold text-blue-500">{keyCodeToKey(playback.analysis.key)}</span></p>
<p>Tempo: <span className="mr-4 font-bold text-green-500">{Math.round(playback.analysis.tempo)} bpm</span></p>
<p>Mode: <span className="mr-4 font-bold text-red-500">{modeKeyToMode(playback.analysis.mode)}</span></p>
</div>
</>
:
<div className="flex flex-col items-center justify-center p-4 my-2 text-center">
<p className="text-2xl text-gray-300 font-semibold">
No music playing{' '}<span className="opacity-50">💤</span>
</p>
<p className="text-2xl text-gray-300 font-semibold">
...play something to see some analysis!
</p>
</div>
}
</div>
</div>
<div className="-translate-y-20 md:-translate-y-24 w-11/12 md:max-w-screen-lg">
<div
onClick={() => router.push("/analysis")}
className="w-full cursor-pointer my-4 p-3 rounded-lg shadow-xl border-2 border-black bg-black text-white hover:bg-white hover:text-black transition-all"
>
<p className="font-bold text-2xl md:text-3xl text-center">Run full analysis →</p>
</div>
</div>
<div className="-translate-y-20 md:-translate-y-24 w-11/12 md:max-w-screen-lg">
<div className="flex flex-col md:flex-row flex-wrap justify-start md:justify-between items-center md:items-stretch">
<div className="w-full p-4 md:flex-1 md:mr-2 my-2 md:my-0 rounded-lg border-2 border-black shadow-xl bg-white">
<div className="flex flex-row justify-between items-center border-b pb-2">
<p className="font-bold text-2xl md:text-3xl">Top artists</p>
<select
className="text-xl p-1 border-2 border-black rounded-lg cursor-pointer shadow-sm"
onChange={e => {
setArtistTimeFrame(e.target.value)
}}
>
<option value="short_term">4 weeks</option>
<option value="medium_term">6 months</option>
<option value="long_term">All time</option>
</select>
</div>
<table>
<tbody>
{
top.artists[artistTimeFrame]?.items.map((a, i) => {
return (
<tr className="md:text-lg my-2" key={i}>
<td className="font-bold text-2xl p-1">
{i+1}.
</td>
<td className="m-2 p-1">
<img
className="rounded-md border border-black"
src={a.images[0].url}
style={{
objectFit: 'cover',
height: '50px',
width: '50px'
}}
/>
</td>
<td className="p-1">
<p>
{a.name}
</p>
</td>
</tr>
)
})
}
</tbody>
</table>
</div>
<div className="w-full p-4 md:flex-1 md:ml-2 my-2 md:my-0 rounded-lg border-2 border-black shadow-xl bg-white">
<div className="flex flex-row justify-between items-center border-b pb-2">
<p className="font-bold text-2xl md:text-3xl">Top Songs</p>
<select
className="text-xl p-1 border-2 border-black rounded-lg cursor-pointer shadow-sm"
onChange={e => {
setTrackTimeFrame(e.target.value)
}}
>
<option value="short_term">4 weeks</option>
<option value="medium_term">6 months</option>
<option value="long_term">All time</option>
</select>
</div>
<table>
<tbody>
{
top.tracks[trackTimeFrame]?.items.map((t, i) => {
return (
<tr className="text-base md:text-lg" key={i}>
<td className="font-bold text-2xl p-1">
{i+1}.
</td>
<td className="m-2 p-1" style={{
minWidth: '50px'
}}>
<img
className="rounded-md border border-black"
src={t.album.images[0].url}
style={{
objectFit: 'cover',
height: '50px',
width: '50px'
}}
/>
</td>
<td className="max-w-min p-1">
<p className="mb-0 text-base">
{t.name}
</p>
<p className="text-gray-500 italic text-xs md:text-base">
{t.artists[0].name}
</p>
</td>
</tr>
)
})
}
</tbody>
</table>
</div>
</div>
</div>
</div>
)
}
}
export default Auth | the_stack |
import { computed, makeObservable, obx } from '@alilc/lowcode-editor-core';
import {
Designer,
ISensor,
LocateEvent,
isDragNodeObject,
isDragAnyObject,
DragObject,
Scroller,
ScrollTarget,
IScrollable,
DropLocation,
isLocationChildrenDetail,
LocationChildrenDetail,
LocationDetailType,
ParentalNode,
contains,
Node,
} from '@alilc/lowcode-designer';
import { uniqueId } from '@alilc/lowcode-utils';
import { IEditor } from '@alilc/lowcode-types';
import TreeNode from './tree-node';
import { IndentTrack } from './helper/indent-track';
import DwellTimer from './helper/dwell-timer';
import { Backup } from './views/backup-pane';
import { ITreeBoard, TreeMaster, getTreeMaster } from './tree-master';
export class OutlineMain implements ISensor, ITreeBoard, IScrollable {
private _designer?: Designer;
@obx.ref private _master?: TreeMaster;
get master() {
return this._master;
}
@computed get currentTree() {
return this._master?.currentTree;
}
readonly id = uniqueId('outline');
@obx.ref _visible = false;
get visible() {
return this._visible;
}
readonly editor: IEditor;
readonly at: string | symbol;
constructor(editor: IEditor, at: string | symbol) {
makeObservable(this);
this.editor = editor;
this.at = at;
let inited = false;
const setup = async () => {
if (inited) {
return false;
}
inited = true;
const designer = await editor.onceGot('designer');
this.setupDesigner(designer);
};
if (at === Backup) {
setup();
} else {
editor.on('skeleton.panel.show', (key: string) => {
if (key === at) {
setup();
this._visible = true;
}
});
editor.on('skeleton.panel.hide', (key: string) => {
if (key === at) {
this._visible = false;
}
});
}
}
/**
* @see ISensor
*/
fixEvent(e: LocateEvent): LocateEvent {
if (e.fixed) {
return e;
}
const notMyEvent = e.originalEvent.view?.document !== document;
if (!e.target || notMyEvent) {
e.target = document.elementFromPoint(e.canvasX!, e.canvasY!);
}
// documentModel : 目标文档
e.documentModel = this._designer?.currentDocument;
// 事件已订正
e.fixed = true;
return e;
}
private indentTrack = new IndentTrack();
private dwell = new DwellTimer((target, event) => {
const { document } = target;
const { designer } = document;
let index: any;
let focus: any;
let valid = true;
if (target.hasSlots()) {
index = null;
focus = { type: 'slots' };
} else {
index = 0;
valid = document.checkNesting(target, event.dragObject as any);
}
designer.createLocation({
target,
source: this.id,
event,
detail: {
type: LocationDetailType.Children,
index,
focus,
valid,
},
});
});
/**
* @see ISensor
*/
locate(e: LocateEvent): DropLocation | undefined | null {
this.sensing = true;
this.scroller?.scrolling(e);
const { globalY, dragObject } = e;
const { nodes } = dragObject;
const tree = this._master?.currentTree;
if (!tree || !tree.root || !this._shell) {
return null;
}
const operationalNodes = nodes?.filter((node: any) => {
const onMoveHook = node.componentMeta?.getMetadata().configure?.advanced?.callbacks?.onMoveHook;
const canMove = onMoveHook && typeof onMoveHook === 'function' ? onMoveHook(node) : true;
return canMove;
});
if (!operationalNodes || operationalNodes.length === 0) {
return;
}
const { document } = tree;
const { designer } = document;
const pos = getPosFromEvent(e, this._shell);
const irect = this.getInsertionRect();
const originLoc = document.dropLocation;
const componentMeta = e.dragObject.nodes ? e.dragObject.nodes[0].componentMeta : null;
if (e.dragObject.type === 'node' && componentMeta && componentMeta.isModal) {
return designer.createLocation({
target: document.focusNode,
detail: {
type: LocationDetailType.Children,
index: 0,
valid: true,
},
source: this.id,
event: e,
});
}
if (originLoc && ((pos && pos === 'unchanged') || (irect && globalY >= irect.top && globalY <= irect.bottom))) {
const loc = originLoc.clone(e);
const indented = this.indentTrack.getIndentParent(originLoc, loc);
if (indented) {
const [parent, index] = indented;
if (checkRecursion(parent, dragObject)) {
if (tree.getTreeNode(parent).expanded) {
this.dwell.reset();
return designer.createLocation({
target: parent,
source: this.id,
event: e,
detail: {
type: LocationDetailType.Children,
index,
valid: document.checkNesting(parent, e.dragObject as any),
},
});
}
(originLoc.detail as LocationChildrenDetail).focus = {
type: 'node',
node: parent,
};
// focus try expand go on
this.dwell.focus(parent, e);
} else {
this.dwell.reset();
}
// FIXME: recreate new location
} else if ((originLoc.detail as LocationChildrenDetail).near) {
(originLoc.detail as LocationChildrenDetail).near = undefined;
this.dwell.reset();
}
return;
}
this.indentTrack.reset();
if (pos && pos !== 'unchanged') {
let treeNode = tree.getTreeNodeById(pos.nodeId);
if (treeNode) {
let { focusSlots } = pos;
let { node } = treeNode;
if (isDragNodeObject(dragObject)) {
const newNodes = operationalNodes;
let i = newNodes.length;
let p: any = node;
while (i-- > 0) {
if (contains(newNodes[i], p)) {
p = newNodes[i].parent;
}
}
if (p !== node) {
node = p || document.focusNode;
treeNode = tree.getTreeNode(node);
focusSlots = false;
}
}
if (focusSlots) {
this.dwell.reset();
return designer.createLocation({
target: node as ParentalNode,
source: this.id,
event: e,
detail: {
type: LocationDetailType.Children,
index: null,
valid: false,
focus: { type: 'slots' },
},
});
}
if (!treeNode.isRoot()) {
const loc = this.getNear(treeNode, e);
this.dwell.tryFocus(loc);
return loc;
}
}
}
const loc = this.drillLocate(tree.root, e);
this.dwell.tryFocus(loc);
return loc;
}
private getNear(treeNode: TreeNode, e: LocateEvent, index?: number, rect?: DOMRect) {
const { document } = treeNode.tree;
const { designer } = document;
const { globalY, dragObject } = e;
// TODO: check dragObject is anyData
const { node, expanded } = treeNode;
if (!rect) {
rect = this.getTreeNodeRect(treeNode);
if (!rect) {
return null;
}
}
if (index == null) {
index = node.index;
}
if (node.isSlot()) {
// 是个插槽根节点
if (!treeNode.isContainer() && !treeNode.hasSlots()) {
return designer.createLocation({
target: node.parent!,
source: this.id,
event: e,
detail: {
type: LocationDetailType.Children,
index: null,
near: { node, pos: 'replace' },
valid: true, // TODO: future validation the slot limit
},
});
}
const loc1 = this.drillLocate(treeNode, e);
if (loc1) {
return loc1;
}
return designer.createLocation({
target: node.parent!,
source: this.id,
event: e,
detail: {
type: LocationDetailType.Children,
index: null,
valid: false,
focus: { type: 'slots' },
},
});
}
let focusNode: Node | undefined;
// focus
if (!expanded && (treeNode.isContainer() || treeNode.hasSlots())) {
focusNode = node;
}
// before
const titleRect = this.getTreeTitleRect(treeNode) || rect;
if (globalY < titleRect.top + titleRect.height / 2) {
return designer.createLocation({
target: node.parent!,
source: this.id,
event: e,
detail: {
type: LocationDetailType.Children,
index,
valid: document.checkNesting(node.parent!, dragObject as any),
near: { node, pos: 'before' },
focus: checkRecursion(focusNode, dragObject) ? { type: 'node', node: focusNode } : undefined,
},
});
}
if (globalY > titleRect.bottom) {
focusNode = undefined;
}
if (expanded) {
// drill
const loc = this.drillLocate(treeNode, e);
if (loc) {
return loc;
}
}
// after
return designer.createLocation({
target: node.parent!,
source: this.id,
event: e,
detail: {
type: LocationDetailType.Children,
index: index + 1,
valid: document.checkNesting(node.parent!, dragObject as any),
near: { node, pos: 'after' },
focus: checkRecursion(focusNode, dragObject) ? { type: 'node', node: focusNode } : undefined,
},
});
}
private drillLocate(treeNode: TreeNode, e: LocateEvent): DropLocation | null {
const { document } = treeNode.tree;
const { designer } = document;
const { dragObject, globalY } = e;
if (!checkRecursion(treeNode.node, dragObject)) {
return null;
}
if (isDragAnyObject(dragObject)) {
// TODO: future
return null;
}
const container = treeNode.node as ParentalNode;
const detail: LocationChildrenDetail = {
type: LocationDetailType.Children,
};
const locationData: any = {
target: container,
detail,
source: this.id,
event: e,
};
const isSlotContainer = treeNode.hasSlots();
const isContainer = treeNode.isContainer();
if (container.isSlot() && !treeNode.expanded) {
// 未展开,直接定位到内部第一个节点
if (isSlotContainer) {
detail.index = null;
detail.focus = { type: 'slots' };
detail.valid = false;
} else {
detail.index = 0;
detail.valid = document.checkNesting(container, dragObject);
}
}
let items: TreeNode[] | null = null;
let slotsRect: DOMRect | undefined;
let focusSlots = false;
// isSlotContainer
if (isSlotContainer) {
slotsRect = this.getTreeSlotsRect(treeNode);
if (slotsRect) {
if (globalY <= slotsRect.bottom) {
focusSlots = true;
items = treeNode.slots;
} else if (!isContainer) {
// 不在 slots 范围,又不是 container 的情况,高亮 slots 区
detail.index = null;
detail.focus = { type: 'slots' };
detail.valid = false;
return designer.createLocation(locationData);
}
}
}
if (!items && isContainer) {
items = treeNode.children;
}
if (!items) {
return null;
}
const l = items.length;
let index = 0;
let before = l < 1;
let current: TreeNode | undefined;
let currentIndex = index;
for (; index < l; index++) {
current = items[index];
currentIndex = index;
const rect = this.getTreeNodeRect(current);
if (!rect) {
continue;
}
// rect
if (globalY < rect.top) {
before = true;
break;
}
if (globalY > rect.bottom) {
continue;
}
const loc = this.getNear(current, e, index, rect);
if (loc) {
return loc;
}
}
if (focusSlots) {
detail.focus = { type: 'slots' };
detail.valid = false;
detail.index = null;
} else {
if (current) {
detail.index = before ? currentIndex : currentIndex + 1;
detail.near = { node: current.node, pos: before ? 'before' : 'after' };
} else {
detail.index = l;
}
detail.valid = document.checkNesting(container, dragObject);
}
return designer.createLocation(locationData);
}
/**
* @see ISensor
*/
isEnter(e: LocateEvent): boolean {
if (!this._shell) {
return false;
}
const rect = this._shell.getBoundingClientRect();
return e.globalY >= rect.top && e.globalY <= rect.bottom && e.globalX >= rect.left && e.globalX <= rect.right;
}
private tryScrollAgain: number | null = null;
/**
* @see IScrollBoard
*/
scrollToNode(treeNode: TreeNode, detail?: any, tryTimes = 0) {
if (tryTimes < 1 && this.tryScrollAgain) {
(window as any).cancelIdleCallback(this.tryScrollAgain);
this.tryScrollAgain = null;
}
if (this.sensing || !this.bounds || !this.scroller || !this.scrollTarget) {
// is a active sensor
return;
}
let rect: ClientRect | undefined;
if (detail && isLocationChildrenDetail(detail)) {
rect = this.getInsertionRect();
} else {
rect = this.getTreeNodeRect(treeNode);
}
if (!rect) {
if (tryTimes < 3) {
this.tryScrollAgain = (window as any).requestIdleCallback(() => this.scrollToNode(treeNode, detail, tryTimes + 1));
}
return;
}
const { scrollHeight, top: scrollTop } = this.scrollTarget;
const { height, top, bottom } = this.bounds;
if (rect.top < top || rect.bottom > bottom) {
const opt: any = {};
opt.top = Math.min(rect.top + rect.height / 2 + scrollTop - top - height / 2, scrollHeight - height);
if (rect.height >= height) {
opt.top = Math.min(scrollTop + rect.top - top, opt.top);
}
this.scroller.scrollTo(opt);
}
// make tail scroll be sure
if (tryTimes < 4) {
this.tryScrollAgain = (window as any).requestIdleCallback(() => this.scrollToNode(treeNode, detail, 4));
}
}
private sensing = false;
/**
* @see ISensor
*/
deactiveSensor() {
this.sensing = false;
this.scroller?.cancel();
this.dwell.reset();
this.indentTrack.reset();
}
/**
* @see IScrollable
*/
get bounds(): DOMRect | null {
if (!this._shell) {
return null;
}
return this._shell.getBoundingClientRect();
}
private _scrollTarget?: ScrollTarget;
/**
* @see IScrollable
*/
get scrollTarget() {
return this._scrollTarget;
}
private scroller?: Scroller;
private setupDesigner(designer: Designer) {
this._designer = designer;
this._master = getTreeMaster(designer);
this._master.addBoard(this);
designer.dragon.addSensor(this);
this.scroller = designer.createScroller(this);
}
purge() {
this._designer?.dragon.removeSensor(this);
this._master?.removeBoard(this);
// todo purge treeMaster if needed
}
private _sensorAvailable = false;
/**
* @see ISensor
*/
get sensorAvailable() {
return this._sensorAvailable;
}
private _shell: HTMLDivElement | null = null;
mount(shell: HTMLDivElement | null) {
if (this._shell === shell) {
return;
}
this._shell = shell;
if (shell) {
this._scrollTarget = new ScrollTarget(shell);
this._sensorAvailable = true;
} else {
this._scrollTarget = undefined;
this._sensorAvailable = false;
}
}
private getInsertionRect(): DOMRect | undefined {
if (!this._shell) {
return undefined;
}
return this._shell.querySelector('.insertion')?.getBoundingClientRect();
}
private getTreeNodeRect(treeNode: TreeNode): DOMRect | undefined {
if (!this._shell) {
return undefined;
}
return this._shell.querySelector(`.tree-node[data-id="${treeNode.id}"]`)?.getBoundingClientRect();
}
private getTreeTitleRect(treeNode: TreeNode): DOMRect | undefined {
if (!this._shell) {
return undefined;
}
return this._shell.querySelector(`.tree-node-title[data-id="${treeNode.id}"]`)?.getBoundingClientRect();
}
private getTreeSlotsRect(treeNode: TreeNode): DOMRect | undefined {
if (!this._shell) {
return undefined;
}
return this._shell.querySelector(`.tree-node-slots[data-id="${treeNode.id}"]`)?.getBoundingClientRect();
}
}
function checkRecursion(parent: Node | undefined | null, dragObject: DragObject): parent is ParentalNode {
if (!parent) {
return false;
}
if (isDragNodeObject(dragObject)) {
const { nodes } = dragObject;
if (nodes.some((node) => node.contains(parent))) {
return false;
}
}
return true;
}
function getPosFromEvent(
{ target }: LocateEvent,
stop: Element,
): null | 'unchanged' | { nodeId: string; focusSlots: boolean } {
if (!target || !stop.contains(target)) {
return null;
}
if (target.matches('.insertion')) {
return 'unchanged';
}
target = target.closest('[data-id]');
if (!target || !stop.contains(target)) {
return null;
}
const nodeId = (target as HTMLDivElement).dataset.id!;
return {
focusSlots: target.matches('.tree-node-slots'),
nodeId,
};
} | the_stack |
import { Dialog } from '@syncfusion/ej2-popups';
import { CheckBox } from '@syncfusion/ej2-buttons';
import { NumericTextBox } from '@syncfusion/ej2-inputs';
import { WTableFormat } from '../index';
import { isNullOrUndefined, L10n, createElement } from '@syncfusion/ej2-base';
import { SelectionTableFormat } from '../index';
import { TableWidget } from '../viewer/page';
import { CellOptionsDialog } from './index';
import { DocumentHelper } from '../viewer';
/**
* The Table options dialog is used to modify default cell margins and cell spacing of selected table.
*/
export class TableOptionsDialog {
/**
* @private
*/
public documentHelper: DocumentHelper;
/**
* @private
*/
public dialog: Dialog;
/**
* @private
*/
public target: HTMLElement;
private cellspacingTextBox: HTMLElement;
private allowSpaceCheckBox: CheckBox;
private cellSpaceTextBox: NumericTextBox;
/**
* @private
*/
public leftMarginBox: NumericTextBox;
/**
* @private
*/
public topMarginBox: NumericTextBox;
/**
* @private
*/
public rightMarginBox: NumericTextBox;
/**
* @private
*/
public bottomMarginBox: NumericTextBox;
/**
* @private
*/
public tableFormatIn: WTableFormat;
/**
* @param {DocumentHelper} documentHelper - Specifies the document helper.
* @private
*/
public constructor(documentHelper: DocumentHelper) {
this.documentHelper = documentHelper;
}
/**
* @private
* @returns {WTableFormat} - Returns table format.
*/
public get tableFormat(): WTableFormat {
if (isNullOrUndefined(this.tableFormatIn)) {
return this.tableFormatIn = new WTableFormat();
}
return this.tableFormatIn;
}
private getModuleName(): string {
return 'TableOptionsDialog';
}
/**
* @private
* @param {L10n} localValue - Specifies the locale value
* @param {boolean} isRtl - Specifies the is rtl
* @returns {void}
*/
public initTableOptionsDialog(localValue: L10n, isRtl?: boolean): void {
this.target = createElement('div', {
id: this.documentHelper.owner.containerId + '_insertCellMarginsDialog', className: 'e-de-table-options-dlg'
});
const innerDiv: HTMLDivElement = <HTMLDivElement>createElement('div', {
className: 'e-de-table-options-dlg-div'
});
const innerDivLabel: HTMLElement = createElement('Label', {
id: this.target.id + '_innerDivLabel', className: 'e-de-cell-dia-options-label',
innerHTML: localValue.getConstant('Default cell margins')
});
innerDiv.appendChild(innerDivLabel);
CellOptionsDialog.getCellMarginDialogElements(this, innerDiv, localValue);
const div: HTMLDivElement = <HTMLDivElement>createElement('div', { styles: 'width: 475px; position: relative;' });
const cellSpaceLabel: HTMLElement = createElement('Label', {
className: 'e-de-cell-dia-options-label',
id: this.target.id + '_cellSpaceLabel'
});
cellSpaceLabel.innerHTML = localValue.getConstant('Default cell spacing');
div.appendChild(cellSpaceLabel);
const table2: HTMLTableElement = <HTMLTableElement>createElement('TABLE', {
styles: 'height: 30px;'
});
const tr3: HTMLTableRowElement = <HTMLTableRowElement>createElement('tr');
const td5: HTMLTableCellElement = <HTMLTableCellElement>createElement('td');
const allowSpaceCheckBox: HTMLInputElement = <HTMLInputElement>createElement('input', {
attrs: { 'type': 'checkbox' }, id: this.target.id + '_cellcheck'
});
let td6Padding: string;
if (isRtl) {
td6Padding = 'padding-right:25px;';
} else {
td6Padding = 'padding-left:25px;';
}
const td6: HTMLTableCellElement = <HTMLTableCellElement>createElement('td', { styles: td6Padding });
this.cellspacingTextBox = <HTMLInputElement>createElement('input', {
attrs: { 'type': 'text' }, id: this.target.id + '_cellspacing'
});
td5.appendChild(allowSpaceCheckBox);
td6.appendChild(this.cellspacingTextBox); tr3.appendChild(td5); tr3.appendChild(td6);
table2.appendChild(tr3);
div.appendChild(table2);
const divBtn: HTMLDivElement = document.createElement('div');
this.target.appendChild(div);
this.target.appendChild(divBtn);
this.cellSpaceTextBox = new NumericTextBox({
value: 0, min: 0, max: 264.5, width: 174,
decimals: 2, enablePersistence: false
});
this.cellSpaceTextBox.appendTo(this.cellspacingTextBox);
this.allowSpaceCheckBox = new CheckBox({
label: localValue.getConstant('Allow spacing between cells'),
change: this.changeAllowSpaceCheckBox,
enableRtl: isRtl,
cssClass: 'e-de-tbl-margin-sub-header'
});
this.allowSpaceCheckBox.appendTo(allowSpaceCheckBox);
}
/**
* @private
* @returns {void}
*/
public loadCellMarginsDialog(): void {
const tableFormat: SelectionTableFormat = this.documentHelper.selection.tableFormat;
this.cellSpaceTextBox.value = tableFormat.cellSpacing;
this.bottomMarginBox.value = tableFormat.bottomMargin;
this.topMarginBox.value = tableFormat.topMargin;
this.rightMarginBox.value = tableFormat.rightMargin;
this.leftMarginBox.value = tableFormat.leftMargin;
if (tableFormat.cellSpacing > 0) {
this.allowSpaceCheckBox.checked = true;
this.cellSpaceTextBox.enabled = true;
} else {
this.allowSpaceCheckBox.checked = false;
this.cellSpaceTextBox.enabled = false;
}
}
/**
* @private
* @returns {void}
*/
public applyTableCellProperties = (): void => {
const tableFormat: SelectionTableFormat = this.documentHelper.selection.tableFormat;
if (!isNullOrUndefined(this.bottomMarginBox.value || this.leftMarginBox.value
|| this.rightMarginBox.value || this.topMarginBox.value || this.cellSpaceTextBox.value)
&& (tableFormat.bottomMargin !== this.bottomMarginBox.value
|| tableFormat.leftMargin !== this.leftMarginBox.value
|| tableFormat.rightMargin !== this.rightMarginBox.value
|| tableFormat.topMargin !== this.topMarginBox.value
|| tableFormat.cellSpacing !== this.cellSpaceTextBox.value)) {
this.documentHelper.owner.tablePropertiesDialogModule.isTableOptionsUpdated = true;
this.applyTableOptions(this.tableFormat);
this.documentHelper.owner.tablePropertiesDialogModule.applyTableSubProperties();
}
this.closeCellMarginsDialog();
};
/**
* @private
* @param {WTableFormat} tableFormat Specifies table format.
* @returns {void}
*/
public applySubTableOptions(tableFormat: WTableFormat): void {
this.documentHelper.owner.editorHistory.initComplexHistory(this.documentHelper.selection, 'TableMarginsSelection');
this.applyTableOptionsHistory(tableFormat);
if (!isNullOrUndefined(this.documentHelper.owner.editorHistory.currentHistoryInfo)) {
this.documentHelper.owner.editorHistory.updateComplexHistory();
}
}
/**
* @private
* @param {WTableFormat} tableFormat Specifies table format.
* @returns {void}
*/
public applyTableOptionsHelper(tableFormat: WTableFormat): void {
this.applySubTableOptionsHelper(tableFormat);
}
private applyTableOptionsHistory(tableFormat: WTableFormat): void {
this.documentHelper.owner.editorModule.initHistory('TableOptions');
this.applySubTableOptionsHelper(tableFormat);
}
private applySubTableOptionsHelper(tableFormat: WTableFormat): void {
let ownerTable: TableWidget = this.documentHelper.selection.start.currentWidget.paragraph.associatedCell.ownerTable;
ownerTable = ownerTable.combineWidget(this.documentHelper.owner.viewer) as TableWidget;
const currentTableFormat: WTableFormat = ownerTable.tableFormat;
if (!isNullOrUndefined(this.documentHelper.owner.editorHistory.currentBaseHistoryInfo)) {
this.documentHelper.owner.editorHistory.currentBaseHistoryInfo.addModifiedTableOptions(currentTableFormat);
}
currentTableFormat.cellSpacing = tableFormat.cellSpacing;
currentTableFormat.leftMargin = tableFormat.leftMargin;
currentTableFormat.topMargin = tableFormat.topMargin;
currentTableFormat.rightMargin = tableFormat.rightMargin;
currentTableFormat.bottomMargin = tableFormat.bottomMargin;
this.documentHelper.owner.tablePropertiesDialogModule.calculateGridValue(ownerTable);
}
/**
* @private
* @param {WTableFormat} tableFormat Specifies the table format
*/
public applyTableOptions(tableFormat: WTableFormat): void {
tableFormat.leftMargin = this.leftMarginBox.value;
tableFormat.topMargin = this.topMarginBox.value;
tableFormat.bottomMargin = this.bottomMarginBox.value;
tableFormat.rightMargin = this.rightMarginBox.value;
if (this.allowSpaceCheckBox.checked) {
tableFormat.cellSpacing = this.cellSpaceTextBox.value;
}
}
/**
* @private
* @returns {void}
*/
public closeCellMarginsDialog = (): void => {
this.documentHelper.dialog.hide();
this.documentHelper.dialog.element.style.pointerEvents = '';
this.documentHelper.updateFocus();
};
/**
* @private
* @returns {void}
*/
public show(): void {
const documentLocale: L10n = new L10n('documenteditor', this.documentHelper.owner.defaultLocale);
documentLocale.setLocale(this.documentHelper.owner.locale);
if (!this.target) {
this.initTableOptionsDialog(documentLocale, this.documentHelper.owner.enableRtl);
}
this.loadCellMarginsDialog();
this.documentHelper.dialog.header = documentLocale.getConstant('Table Options');
this.documentHelper.dialog.content = this.target;
this.documentHelper.dialog.beforeOpen = undefined;
this.documentHelper.dialog.position = { X: 'center', Y: 'center' };
// this.documentHelper.dialog.cssClass = 'e-de-table-margin-size';
this.documentHelper.dialog.height = 'auto';
this.documentHelper.dialog.width = 'auto';
this.documentHelper.dialog.open = undefined;
this.documentHelper.dialog.beforeOpen = this.documentHelper.updateFocus;
this.documentHelper.dialog.close = this.removeEvents;
this.documentHelper.dialog.buttons = [{
click: this.applyTableCellProperties,
buttonModel: { content: documentLocale.getConstant('Ok'), cssClass: 'e-flat e-table-cell-okay', isPrimary: true }
},
{
click: this.closeCellMarginsDialog,
buttonModel: { content: documentLocale.getConstant('Cancel'), cssClass: 'e-flat e-table-cell-cancel' }
}];
this.documentHelper.dialog.dataBind();
this.documentHelper.dialog.show();
}
/**
* @private
* @returns {void}
*/
public changeAllowSpaceCheckBox = (): void => {
if (this.allowSpaceCheckBox.checked) {
this.cellSpaceTextBox.enabled = true;
} else {
this.cellSpaceTextBox.enabled = false;
}
};
/**
* @private
* @returns {void}
*/
public removeEvents = (): void => {
this.documentHelper.dialog2.element.style.pointerEvents = '';
this.documentHelper.updateFocus();
};
/**
* @private
* @returns {void}
*/
public destroy(): void {
if (!isNullOrUndefined(this.target)) {
if (this.target.parentElement) {
this.target.parentElement.removeChild(this.target);
}
for (let p: number = 0; p < this.target.childNodes.length; p++) {
this.target.removeChild(this.target.childNodes[p]);
p--;
}
this.target = undefined;
}
this.dialog = undefined;
this.target = undefined;
this.documentHelper = undefined;
this.cellspacingTextBox = undefined;
this.allowSpaceCheckBox = undefined;
}
} | the_stack |
import JiraClient from 'jira-connector'
import {BotConfig} from './bot-config'
import * as Configs from './configs'
import logger from './logger'
import * as Errors from './errors'
import {Context} from './context'
import mem from 'mem'
import moment from 'moment'
type JiraIssue = any
// import {Issue as JiraIssue} from 'jira-connector/api/issue'
export const looksLikeIssueKey = (str: string) =>
!!str.match(/[A-Za-z0-9]+-[0-9]+/)
export const findIssueKeys = (str: string) =>
str.match(/([A-Za-z0-9]+-[0-9]+)/g) || []
export type Issue = {
key: string
summary: string
status: string
url: string
issueType: string
assigneeJira: string
reporterJira: string
project: string
createdTimeHumanized: string
}
export enum JiraSubscriptionEvents {
Unknown = 'unknown',
IssueCreated = 'jira:issue_created',
IssueUpdated = 'jira:issue_updated',
// disabled events:
//
// IssueDeleted = 'jira:issue_deleted',
// CommentCreated = 'comment_created',
// CommentUpdated = 'comment_updated',
// CommentDeleted = 'comment_deleted',
// IssuePropertySet = 'issue_property_set',
// IssuePropertyDeleted = 'issue_property_deleted',
}
export class JiraClientWrapper {
private jiraClient: JiraClient
private jiraHost: string
constructor(jiraClient: JiraClient, jiraHost: string) {
this.jiraClient = jiraClient
this.jiraHost = jiraHost
}
jiraRespMapper = (issue: JiraIssue): Issue => ({
assigneeJira: issue.fields.assignee?.displayName,
createdTimeHumanized: moment(issue.fields.created).fromNow(),
issueType: issue.fields.issuetype.name,
key: issue.key,
project: issue.fields.project.name,
reporterJira: issue.fields.reporter?.displayName,
status: issue.fields.status.statusCategory.name,
summary: issue.fields.summary,
url: `https://${this.jiraHost}/browse/${issue.key}`,
})
get({issueKey}: {issueKey: string}): Promise<any> {
return this.jiraClient.issue.getIssue({issueKey}).then(this.jiraRespMapper)
}
getOrSearch({
query,
project,
status,
assigneeJira,
}: {
query: string
project: string
status: string
assigneeJira: string
}): Promise<any> {
const jql =
(project ? `project = "${project}" AND ` : '') +
(status ? `status = "${status}" AND ` : '') +
(assigneeJira ? `assignee = "${assigneeJira}" AND ` : '') +
`text ~ "${query}"`
logger.debug({msg: 'getOrSearch', jql})
return Promise.all([
looksLikeIssueKey(query)
? this.jiraClient.issue.getIssue({
issueKey: query,
//fields: ['key', 'summary', 'status'],
})
: new Promise(r => r()),
this.jiraClient.search.search({
jql,
fields: ['key', 'summary', 'status', 'project', 'issuetype'],
method: 'GET',
maxResults: 11,
}),
]).then(([fromGet, fromSearch]) => ({
jql,
issues: [
...(fromGet ? [fromGet] : []),
...(fromSearch ? fromSearch.issues : []),
].map(this.jiraRespMapper),
}))
}
addComment(issueKey: string, comment: string): Promise<any> {
return this.jiraClient.issue
.addComment({
issueKey,
body: comment,
})
.then(
({id}: {id: string}) =>
`https://${this.jiraHost}/browse/${issueKey}?focusedCommentId=${id}`
)
}
createIssue({
assigneeJira,
description,
issueType,
name,
project,
}: {
assigneeJira: string
description: string
issueType: string
name: string
project: string
}): Promise<any> {
logger.debug({
msg: 'createIssue',
assigneeJira,
issueType,
project,
name,
description,
})
return this.jiraClient.issue
.createIssue({
fields: {
assignee: assigneeJira ? {name: assigneeJira} : undefined,
project: {key: project.toUpperCase()},
issuetype: {name: issueType},
summary: name,
description,
},
})
.then(({key}: {key: string}) => `https://${this.jiraHost}/browse/${key}`)
}
getIssueTypes(): Promise<Array<string>> {
logger.debug({
msg: 'getIssueTypes',
})
return this.jiraClient.issueType
.getAllIssueTypes()
.then((resp: Array<{name: string}>) => resp.map(({name}) => name))
}
getProjects(): Promise<Array<string>> {
logger.debug({
msg: 'getProjects',
})
return this.jiraClient.project
.getAllProjects()
.then((resp: Array<{key: string}>) => resp.map(({key}) => key))
}
getStatuses(): Promise<Array<string>> {
logger.debug({
msg: 'getStatuses',
})
return this.jiraClient.status
.getAllStatuses()
.then((resp: Array<{name: string}>) => resp.map(({name}) => name))
}
subscribe(
jqlFilter: string,
events: Array<JiraSubscriptionEvents>,
url: string
): Promise<string> {
logger.debug({
msg: 'subscribe',
})
return this.jiraClient.webhook
.createWebhook({
name: `jirabot-webhook-${new Date().toJSON()}`,
url,
filters: {'issue-related-events-section': jqlFilter},
events,
})
.then((res?: {self?: string}) => {
return res && res.self
})
}
unsubscribe(webhookURI: string): Promise<any> {
return this.jiraClient.webhook.deleteWebhook({webhookURI})
}
}
export const projectToJqlFilter = (project: string) => `project = ${project}`
const jiraClientCacheTimeout = 60 * 1000 // 1min
const getJiraClient = mem(
(
jiraHost: string,
accessToken: string,
tokenSecret: string,
consumerKey: string,
privateKey: string
): JiraClient =>
new JiraClient({
host: jiraHost,
oauth: {
token: accessToken,
token_secret: tokenSecret,
consumer_key: consumerKey,
private_key: privateKey,
},
}),
{maxAge: jiraClientCacheTimeout, cacheKey: JSON.stringify}
)
export const getAccountId = async (
teamJiraConfig: Configs.TeamJiraConfig,
accessToken: string,
tokenSecret: string
): Promise<Errors.ResultOrError<string, Errors.UnknownError>> => {
const tempJiraClient = getJiraClient(
teamJiraConfig.jiraHost,
accessToken,
tokenSecret,
teamJiraConfig.jiraAuth.consumerKey,
teamJiraConfig.jiraAuth.privateKey
)
try {
const accountDetail = await tempJiraClient.myself.getMyself()
return Errors.makeResult(accountDetail.accountId)
} catch (err) {
return Errors.makeUnknownError(err)
}
}
export const getJiraFromTeamnameAndUsername = async (
context: Context,
teamname: string,
username: string
): Promise<Errors.ResultOrError<
JiraClientWrapper,
Errors.JirabotNotEnabledError | Errors.UnknownError
>> => {
const teamJiraConfigRet = await context.configs.getTeamJiraConfig(teamname)
if (teamJiraConfigRet.type === Errors.ReturnType.Error) {
switch (teamJiraConfigRet.error.type) {
case Errors.ErrorType.Unknown:
return Errors.makeError(teamJiraConfigRet.error)
case Errors.ErrorType.KVStoreNotFound:
return Errors.makeError(Errors.JirabotNotEnabledForTeamError)
default:
let _: never = teamJiraConfigRet.error
return Errors.makeError(undefined)
}
}
const teamJiraConfig = teamJiraConfigRet.result.config
const teamUserConfigRet = await context.configs.getTeamUserConfig(
teamname,
username
)
if (teamUserConfigRet.type === Errors.ReturnType.Error) {
switch (teamUserConfigRet.error.type) {
case Errors.ErrorType.Unknown:
return Errors.makeError(teamUserConfigRet.error)
case Errors.ErrorType.KVStoreNotFound:
return Errors.makeError(Errors.JirabotNotEnabledForUserError)
default:
let _: never = teamUserConfigRet.error
return Errors.makeError(undefined)
}
}
const teamUserConfig = teamUserConfigRet.result.config
const jiraClient = getJiraClient(
teamJiraConfig.jiraHost,
teamUserConfig.accessToken,
teamUserConfig.tokenSecret,
teamJiraConfig.jiraAuth.consumerKey,
teamJiraConfig.jiraAuth.privateKey
)
return Errors.makeResult(
new JiraClientWrapper(jiraClient, teamJiraConfig.jiraHost)
)
}
class JiraMetadata {
private issueTypesArray: Array<string>
private projectsArray: Array<string>
private statusesArray: Array<string>
// lowercased => original
private issueTypesMap: Map<string, string>
private projectsMap: Map<string, string>
private statusesMap: Map<string, string>
constructor(data: {
issueTypes: Array<string>
projects: Array<string>
statuses: Array<string>
}) {
this.issueTypesArray = [...data.issueTypes]
this.projectsArray = [...data.projects]
this.statusesArray = [...data.statuses]
this.issueTypesMap = new Map(data.issueTypes.map(s => [s.toLowerCase(), s]))
this.projectsMap = new Map(data.projects.map(s => [s.toLowerCase(), s]))
this.statusesMap = new Map(data.statuses.map(s => [s.toLowerCase(), s]))
}
normalizeIssueType(issueType: string): undefined | string {
return this.issueTypesMap.get(issueType.toLowerCase())
}
normalizeProject(projectKey: string): undefined | string {
return this.projectsMap.get(projectKey.toLowerCase())
}
normalizeStatus(status: string): undefined | string {
return this.statusesMap.get(status.toLowerCase())
}
issueTypes(): Array<string> {
return [...this.issueTypesArray]
}
projects(): Array<string> {
return [...this.projectsArray]
}
statuses(): Array<string> {
return [...this.statusesArray]
}
defaultIssueType(): string {
return (
this.issueTypesMap.get('story') ||
this.issueTypesMap.get('bug') ||
this.issueTypesArray?.[0] ||
''
)
}
}
const jiraMetadataCacheTimeout = 10 * 1000 // 10s
const jiraMetadataCache = new Map<
string,
{fetchTime: number; jiraMetadata: JiraMetadata}
>() // teamname -> JiraMetadata
const getFromJiraMetadataCache = (
teamname: string
): undefined | JiraMetadata => {
const cached = jiraMetadataCache.get(teamname)
return (
cached &&
(Date.now() - cached.fetchTime < jiraMetadataCacheTimeout
? cached.jiraMetadata
: undefined)
)
}
const putInJiraMetadataCache = (
teamname: string,
jiraMetadata: JiraMetadata
) => {
jiraMetadataCache.set(teamname, {fetchTime: Date.now(), jiraMetadata})
}
export const getJiraMetadata = async (
context: Context,
teamname: string,
username: string
): Promise<Errors.ResultOrError<
JiraMetadata,
Errors.UnknownError | Errors.JirabotNotEnabledError
>> => {
const cached = getFromJiraMetadataCache(teamname)
if (cached) {
return Errors.makeResult(cached)
}
const jiraRet = await getJiraFromTeamnameAndUsername(
context,
teamname,
username
)
if (jiraRet.type === Errors.ReturnType.Error) {
switch (jiraRet.error.type) {
case Errors.ErrorType.JirabotNotEnabled:
break
case Errors.ErrorType.Unknown:
logger.warn({msg: 'getJiraMetadata', error: jiraRet.error})
break
default:
let _: never = jiraRet.error
}
return jiraRet
}
const jira = jiraRet.result
try {
const jiraMetadata = new JiraMetadata({
issueTypes: await jira.getIssueTypes(),
projects: await jira.getProjects(),
statuses: await jira.getStatuses(),
})
putInJiraMetadataCache(teamname, jiraMetadata)
return Errors.makeResult(jiraMetadata)
} catch (error) {
return Errors.makeUnknownError(error)
}
} | the_stack |
import { makeTest, TestBedConfig, ItFuncConfig } from './scaffolding/runner';
import { Misc } from './miscellaneous/misc';
const configList: TestBedConfig[] = [{
datasourceSettings: { startIndex: 1, padding: 0.5, itemSize: 20, minIndex: -49, maxIndex: 100 },
templateSettings: { viewportHeight: 200, itemHeight: 20 }
}, {
datasourceSettings: { startIndex: 600, padding: 1.2, itemSize: 40, minIndex: -69, maxIndex: 1300 },
templateSettings: { viewportHeight: 100, itemHeight: 40 }
}, {
datasourceSettings: { startIndex: 174, padding: 0.7, itemSize: 25, minIndex: 169, maxIndex: 230 },
templateSettings: { viewportHeight: 50, itemHeight: 25 }
}, {
datasourceSettings: { startIndex: 33, padding: 0.62, itemSize: 100, minIndex: 20, maxIndex: 230, horizontal: true },
templateSettings: { viewportWidth: 450, itemWidth: 100, horizontal: true }
}, {
datasourceSettings: {
startIndex: 1,
padding: 0.25,
itemSize: 20,
minIndex: -40,
maxIndex: 159,
windowViewport: true
},
templateSettings: { noViewportClass: true, viewportHeight: 0, itemHeight: 20 }
}];
const noItemSizeConfigList = configList.map(
({ datasourceSettings: { itemSize: _, ...restDatasourceSettings }, ...config }) => ({
...config, datasourceSettings: { ...restDatasourceSettings }
})
);
const commonConfig = configList[0]; // [-49, ..., 100]
const startIndexAroundMinIndexConfigList: TestBedConfig[] = [{
...commonConfig, datasourceSettings: { ...commonConfig.datasourceSettings, startIndex: -9999 }
}, {
...commonConfig, datasourceSettings: { ...commonConfig.datasourceSettings, startIndex: -50 }
}, {
...commonConfig, datasourceSettings: { ...commonConfig.datasourceSettings, startIndex: -49 }
}, {
...commonConfig, datasourceSettings: { ...commonConfig.datasourceSettings, startIndex: -48 }
}];
const startIndexAroundMaxIndexConfigList: TestBedConfig[] = [{
...commonConfig, datasourceSettings: { ...commonConfig.datasourceSettings, startIndex: 99 }
}, {
...commonConfig, datasourceSettings: { ...commonConfig.datasourceSettings, startIndex: 100 }
}, {
...commonConfig, datasourceSettings: { ...commonConfig.datasourceSettings, startIndex: 101 }
}, {
...commonConfig, datasourceSettings: { ...commonConfig.datasourceSettings, startIndex: 999 }
}];
const noMaxIndexConfigList: TestBedConfig[] = configList.map(
({ datasourceSettings: { maxIndex: _, ...datasourceSettings }, ...config }) => ({ ...config, datasourceSettings })
);
const noMinIndexConfigList: TestBedConfig[] = configList.map(
({ datasourceSettings: { minIndex: _, ...datasourceSettings }, ...config }) => ({ ...config, datasourceSettings })
);
const forwardGapConfigList: TestBedConfig[] = startIndexAroundMaxIndexConfigList.map(
({ datasourceSettings: { minIndex: _, ...datasourceSettings }, ...config }) => ({ ...config, datasourceSettings })
);
const checkMinMaxIndexes = (misc: Misc) => {
const elements = misc.getElements();
const { firstIndex, lastIndex, minIndex, maxIndex } = misc.scroller.adapter.bufferInfo;
expect(firstIndex).toEqual(minIndex);
expect(lastIndex).toEqual(maxIndex);
expect(minIndex).toEqual(misc.getElementIndex(elements[0]));
expect(maxIndex).toEqual(misc.getElementIndex(elements[elements.length - 1]));
};
const getParams = (
{ datasourceSettings: settings }: TestBedConfig
): { maxIndex: number, minIndex: number, itemSize: number, startIndex: number, padding: number } => ({
maxIndex: settings.maxIndex as number,
minIndex: settings.minIndex as number,
itemSize: settings.itemSize as number,
startIndex: settings.startIndex as number,
padding: settings.padding as number,
});
const _testCommonCase: ItFuncConfig = settings => misc => async done => {
await misc.relaxNext();
const { settings: { bufferSize }, adapter } = misc.scroller;
const { maxIndex, minIndex, itemSize: _itemSize, startIndex, padding } = getParams(settings);
const viewportSize = misc.getViewportSize();
const viewportSizeDelta = viewportSize * padding;
const itemSize = _itemSize || misc.scroller.buffer.defaultSize;
const hasMinIndex = minIndex !== void 0;
const hasMaxIndex = maxIndex !== void 0;
let innerLoopCount = 3;
const _negativeItemsAmount = Math.ceil(viewportSizeDelta / itemSize);
const negativeItemsAmount = Math.max(_negativeItemsAmount, bufferSize);
const _positiveItemsAmount = Math.ceil((viewportSize + viewportSizeDelta) / itemSize);
let positiveItemsAmount = Math.max(_positiveItemsAmount, bufferSize);
if (!_itemSize) { // if Settings.itemSize is not set, then there could be 1 more fetch
const positiveDiff = _positiveItemsAmount - bufferSize;
if (positiveDiff > 0) {
innerLoopCount = 4;
// if the additional fetch size is less than bufferSize
if (positiveDiff < bufferSize) {
positiveItemsAmount = 2 * bufferSize;
}
}
}
if (hasMinIndex) {
const negativeSize = (startIndex - minIndex) * itemSize;
const negativeItemsSize = negativeItemsAmount * itemSize;
const bwdPaddingSize = negativeSize - negativeItemsSize;
expect(misc.padding.backward.getSize()).toEqual(bwdPaddingSize);
expect(adapter.bufferInfo.absMinIndex).toEqual(minIndex);
} else {
expect(adapter.bufferInfo.absMinIndex).toEqual(-Infinity);
}
if (hasMaxIndex) {
const positiveSize = (maxIndex - startIndex + 1) * itemSize;
const positiveItemsSize = positiveItemsAmount * itemSize;
const fwdPaddingSize = positiveSize - positiveItemsSize;
expect(misc.padding.forward.getSize()).toEqual(fwdPaddingSize);
expect(adapter.bufferInfo.absMaxIndex).toEqual(maxIndex);
} else {
expect(adapter.bufferInfo.absMaxIndex).toEqual(Infinity);
}
let totalSize;
if (hasMinIndex && hasMaxIndex) {
totalSize = (maxIndex - minIndex + 1) * itemSize;
} else if (hasMinIndex) {
const knownSize = (startIndex - minIndex) * itemSize;
totalSize = knownSize + positiveItemsAmount * itemSize;
} else if (hasMaxIndex) {
const knownSize = (maxIndex - startIndex + 1) * itemSize;
totalSize = knownSize + negativeItemsAmount * itemSize;
}
expect(misc.getScrollableSize()).toEqual(totalSize);
expect(misc.innerLoopCount).toEqual(innerLoopCount);
checkMinMaxIndexes(misc);
done();
};
const _testStartIndexEdgeCase: ItFuncConfig = (settings) => misc => async done => {
await misc.relaxNext();
const { maxIndex, minIndex, itemSize, startIndex, padding } = getParams(settings);
const { adapter } = misc.scroller;
const viewportSize = misc.getViewportSize();
const totalSize = (maxIndex - minIndex + 1) * itemSize;
const viewportSizeDelta = viewportSize * padding;
let _startIndex = Math.max(minIndex, startIndex); // startIndex < minIndex
_startIndex = Math.min(maxIndex, _startIndex); // startIndex > maxIndex
// visible part of the viewport must be filled
const viewportItemsAmount = Math.ceil(viewportSize / itemSize);
const diff = _startIndex + viewportItemsAmount - maxIndex - 1;
if (diff > 0) {
_startIndex -= diff;
}
const negativeSize = (_startIndex - minIndex) * itemSize;
const negativeItemsAmount = Math.ceil(viewportSizeDelta / itemSize);
const negativeItemsSize = negativeItemsAmount * itemSize;
const bwdPaddingSize = Math.max(0, negativeSize - negativeItemsSize);
const positiveSize = (maxIndex - _startIndex + 1) * itemSize;
const positiveItemsAmount = Math.ceil((viewportSize + viewportSizeDelta) / itemSize);
const positiveItemsSize = positiveItemsAmount * itemSize;
const fwdPaddingSize = Math.max(0, positiveSize - positiveItemsSize);
expect(misc.getScrollableSize()).toEqual(totalSize);
expect(misc.padding.backward.getSize()).toEqual(bwdPaddingSize);
expect(misc.padding.forward.getSize()).toEqual(fwdPaddingSize);
expect(adapter.bufferInfo.absMinIndex).toEqual(minIndex);
expect(adapter.bufferInfo.absMaxIndex).toEqual(maxIndex);
checkMinMaxIndexes(misc);
done();
};
const _testForwardGapCase: ItFuncConfig = () => misc => async done => {
await misc.relaxNext();
const viewportSize = misc.getViewportSize();
const viewportChildren = misc.scroller.viewport.element.children;
const lastChild = viewportChildren[viewportChildren.length - 2];
const lastChildBottom = lastChild.getBoundingClientRect().bottom;
let gapSize = viewportSize - lastChildBottom;
gapSize = Math.max(0, gapSize);
expect(gapSize).toEqual(0);
expect(misc.padding.forward.getSize()).toEqual(0);
done();
};
describe('Min/max Indexes Spec', () => {
describe('Common cases', () =>
configList.forEach(config =>
makeTest({
config,
title: 'should fill the viewport and the paddings',
it: _testCommonCase(config)
})
)
);
describe('No maxIndex cases', () =>
noMaxIndexConfigList.forEach(config =>
makeTest({
config,
title: 'should fill the viewport and backward padding',
it: _testCommonCase(config)
})
)
);
describe('No minIndex cases', () =>
noMinIndexConfigList.forEach(config =>
makeTest({
config,
title: 'should fill the viewport and forward padding',
it: _testCommonCase(config)
})
)
);
describe('No itemSize cases', () =>
noItemSizeConfigList.forEach(config =>
makeTest({
config,
title: 'should fill the viewport and the paddings',
it: _testCommonCase(config)
})
)
);
describe('startIndex\'s around minIndex', () =>
startIndexAroundMinIndexConfigList.forEach(config =>
makeTest({
config,
title: 'should reset backward padding',
it: _testStartIndexEdgeCase(config)
})
)
);
describe('startIndex\'s around maxIndex', () =>
startIndexAroundMaxIndexConfigList.forEach(config =>
makeTest({
config,
title: 'should reset forward padding',
it: _testStartIndexEdgeCase(config)
})
)
);
describe('startIndex\'s around maxIndex and no minIndex', () =>
forwardGapConfigList.forEach(config =>
makeTest({
config,
title: 'should fill forward padding gap',
it: _testForwardGapCase(config)
})
)
);
}); | the_stack |
import * as ng1 from 'angular';
import {
NgTableDefaultGetDataProvider, DefaultGetData, NgTableParams,
ngTableCoreModule
} from '../../src/core';
describe('ngTableDefaultGetData', () => {
interface IPerson {
age: number;
}
beforeAll(() => expect(ngTableCoreModule).toBeDefined());
describe('provider', () => {
let ngTableDefaultGetDataProvider: NgTableDefaultGetDataProvider;
beforeEach(ng1.mock.module("ngTable-core"));
beforeEach(() => {
ng1.mock.module((_ngTableDefaultGetDataProvider_: NgTableDefaultGetDataProvider) => {
ngTableDefaultGetDataProvider = _ngTableDefaultGetDataProvider_;
});
});
beforeEach(inject());
it('should be configured to use built-in angular filters', () => {
expect(ngTableDefaultGetDataProvider.filterFilterName).toBe('filter');
expect(ngTableDefaultGetDataProvider.sortingFilterName).toBe('orderBy');
});
});
describe('service', () => {
let ngTableDefaultGetData: DefaultGetData<any>,
tableParams: NgTableParams<any>;
beforeEach(ng1.mock.module('ngTable-core'));
beforeEach(inject((
_ngTableDefaultGetData_: DefaultGetData<any>) => {
ngTableDefaultGetData = _ngTableDefaultGetData_;
tableParams = new NgTableParams({ count: 10 }, { counts: [10] });
}));
describe('sorting', () => {
it('empty sorting', () => {
// given
tableParams.sorting();
// when
var actualResults = ngTableDefaultGetData([{ age: 1 }, { age: 2 }, { age: 3 }], tableParams);
// then
expect(actualResults).toEqual([{ age: 1 }, { age: 2 }, { age: 3 }]);
});
it('single property sort ascending', () => {
// given
tableParams.sorting({ age: 'asc' });
// when
var actualResults = ngTableDefaultGetData([{ age: 1 }, { age: 3 }, { age: 2 }], tableParams);
// then
expect(actualResults).toEqual([{ age: 1 }, { age: 2 }, { age: 3 }]);
});
it('single property sort descending', () => {
// given
tableParams.sorting({ age: 'desc' });
// when
var actualResults = ngTableDefaultGetData([{ age: 1 }, { age: 3 }, { age: 2 }], tableParams);
// then
expect(actualResults).toEqual([{ age: 3 }, { age: 2 }, { age: 1 }]);
});
it('multiple property sort ascending', () => {
// given
tableParams.sorting({ age: 'asc', name: 'asc' });
// when
var data = [
{ age: 1, name: 'b' }, { age: 3, name: 'a' }, { age: 2, name: 'a' }, { age: 1, name: 'a' }
];
var actualResults = ngTableDefaultGetData(data, tableParams);
// then
var expectedData = [
{ age: 1, name: 'a' }, { age: 1, name: 'b' }, { age: 2, name: 'a' }, { age: 3, name: 'a' }
];
expect(actualResults).toEqual(expectedData);
});
});
describe('filters', () => {
it('empty filter', () => {
// given
tableParams.filter({});
// when
var actualResults = ngTableDefaultGetData([{ age: 1 }, { age: 2 }, { age: 3 }], tableParams);
// then
expect(actualResults).toEqual([{ age: 1 }, { age: 2 }, { age: 3 }]);
});
it('empty filter - simple values', () => {
// given
tableParams.filter({});
// when
var actualResults = ngTableDefaultGetData([1, 2, 3], tableParams);
// then
expect(actualResults).toEqual([1, 2, 3]);
});
it('single property filter', () => {
// given
tableParams.filter({ age: 1 });
// when
var actualResults = ngTableDefaultGetData([{ age: 1 }, { age: 2 }, { age: 3 }], tableParams);
// then
expect(actualResults).toEqual([{ age: 1 }]);
});
it('multiple property filter', () => {
// given
var data = [{ age: 1, name: 'A' }, { age: 2, name: 'B' }, { age: 3, name: 'B' }];
tableParams.filter({ age: 2, name: 'B' });
// when
var actualResults = ngTableDefaultGetData(data, tableParams);
// then
expect(actualResults).toEqual([{ age: 2, name: 'B' }]);
});
it('should remove null and undefined values before applying', () => {
// given
var data = [{ age: 1, name: 'A' }, { age: 2, name: 'B' }, { age: 3, name: 'B' }];
tableParams.filter({ age: null, name: 'B' });
// when
var actualResults = ngTableDefaultGetData(data, tableParams);
// then
expect(actualResults).toEqual([{ age: 2, name: 'B' }, { age: 3, name: 'B' }]);
});
it('should remove empty string value before applying', () => {
// given
var data = [{ age: 1, name: 'A' }, { age: 2, name: 'B' }, { age: 3, name: 'B' }];
tableParams.filter({ age: 2, name: '' });
// when
var actualResults = ngTableDefaultGetData(data, tableParams);
// then
expect(actualResults).toEqual([{ age: 2, name: 'B' }]);
});
it('single nested property, one level deep', () => {
// given
tableParams.filter({ 'details.age': 1 });
// when
var data = [{
details: { age: 1 }
}, {
details: { age: 2 }
}, {
details: { age: 3 }
}, {
age: 1
}];
var actualResults = ngTableDefaultGetData(data, tableParams);
// then
expect(actualResults).toEqual([{ details: { age: 1 } }]);
});
it('single nested property, two levels deep', () => {
// given
tableParams.filter({ 'details.personal.age': 1 });
// when
var data = [{
details: { personal: { age: 1 } }
}, {
details: { personal: { age: 2 } }
}, {
details: { personal: { age: 3 } }
}, {
age: 1
}];
var actualResults = ngTableDefaultGetData(data, tableParams);
// then
expect(actualResults).toEqual([{ details: { personal: { age: 1 } } }]);
});
it('multiple nested property, two levels deep', () => {
// given
tableParams.filter({ 'details.personal.age': 1, 'job.money': 100 });
// when
var data = [{
details: { personal: { age: 1 } },
job: { money: 200 }
}, {
details: { personal: { age: 1 } },
job: { money: 100 }
}, {
details: { personal: { age: 3 } },
job: { money: 100 }
}];
var actualResults = ngTableDefaultGetData(data, tableParams);
// then
var expected = [{
details: { personal: { age: 1 } },
job: { money: 100 }
}];
expect(actualResults).toEqual(expected);
});
describe('filterComparator', () => {
it('function', () => {
// given
var comparer = (actual: any, expected: any) => ng1.equals(actual, expected);
tableParams.settings({ filterOptions: { filterComparator: comparer } });
tableParams.filter({ age: 1 });
// when
var actualResults = ngTableDefaultGetData([{ age: 10 }, { age: 1 }, { age: 101 }, { age: 2 }], tableParams);
// then
expect(actualResults).toEqual([{ age: 1 }]);
});
it('"true"', () => {
// given
tableParams.settings({ filterOptions: { filterComparator: true } });
tableParams.filter({ age: 1 });
// when
var actualResults = ngTableDefaultGetData([{ age: 10 }, { age: 1 }, { age: 101 }, { age: 2 }], tableParams);
// then
expect(actualResults).toEqual([{ age: 1 }]);
});
it('"false"', () => {
// given
tableParams.settings({ filterOptions: { filterComparator: false } });
tableParams.filter({ age: 1 });
// when
var actualResults = ngTableDefaultGetData([{ age: 10 }, { age: 1 }, { age: 101 }, { age: 2 }], tableParams);
// then
expect(actualResults).toEqual([{ age: 10 }, { age: 1 }, { age: 101 }]);
});
it('"undefined" (the default)', () => {
// given
tableParams.settings({ filterOptions: { filterComparator: undefined } });
tableParams.filter({ age: 1 });
// when
var actualResults = ngTableDefaultGetData([{ age: 10 }, { age: 1 }, { age: 101 }, { age: 2 }], tableParams);
// then
expect(actualResults).toEqual([{ age: 10 }, { age: 1 }, { age: 101 }]);
});
})
});
});
describe('service, custom filters', () => {
var ngTableDefaultGetData: DefaultGetData<IPerson>,
tableParams: NgTableParams<IPerson>;
type PersonCriteria = { ages: number[] };
beforeEach(() => {
// add a custom filter available to our tests
ng1.mock.module('ngTable-core', ($provide: ng1.auto.IProvideService) => {
$provide.factory('myCustomFilterFilter', myCustomFilter)
});
myCustomFilter.$inject = [];
function myCustomFilter() {
return jasmine.createSpy('myCustomFilterSpy', filter).and.callThrough();
function filter(people: IPerson[], criteriaObj: PersonCriteria/*, comparator*/) {
return people.filter(p => criteriaObj.ages.indexOf(p.age) !== -1);
}
}
});
beforeEach(inject((
_ngTableDefaultGetData_: DefaultGetData<IPerson>) => {
ngTableDefaultGetData = _ngTableDefaultGetData_;
tableParams = new NgTableParams<IPerson>({ count: 10 }, { counts: [10] });
}));
it('filterFilterName override', () => {
// given
tableParams.settings({ filterOptions: { filterFilterName: 'myCustomFilter' } });
tableParams.filter({ ages: [1, 2] });
// when
var actualResults = ngTableDefaultGetData([{ age: 1 }, { age: 2 }, { age: 3 }], tableParams);
// then
expect(actualResults).toEqual([{ age: 1 }, { age: 2 }]);
});
it('`this` context of custom filter should be set to the NgTableParams instance', inject((myCustomFilterFilter: jasmine.Spy) => {
// given
tableParams.settings({ filterOptions: { filterFilterName: 'myCustomFilter' } });
tableParams.filter({ ages: [1, 2] });
// when
ngTableDefaultGetData([{ age: 1 }, { age: 2 }, { age: 3 }], tableParams);
// then
expect(myCustomFilterFilter.calls.mostRecent().object).toBe(tableParams);
}));
it('custom filter function', () => {
// given
var filterFn = (data: IPerson[], criteriaObj: PersonCriteria/*, comparator*/) => {
return data.filter(p => criteriaObj.ages.indexOf(p.age) !== -1);
};
tableParams.settings({ filterOptions: { filterFn: filterFn } });
tableParams.filter({ ages: [1, 2] });
// when
var actualResults = ngTableDefaultGetData([{ age: 1 }, { age: 2 }, { age: 3 }], tableParams);
// then
expect(actualResults).toEqual([{ age: 1 }, { age: 2 }]);
});
it('`this` context of custom filter function should be set to the NgTableParams instance', () => {
// given
var filterFnSpy = jasmine.createSpy('filterFn', ng1.identity).and.callThrough();
tableParams.settings({ filterOptions: { filterFn: filterFnSpy } });
tableParams.filter({ age: 1 });
// when
var actualResults = ngTableDefaultGetData([{ age: 1 }], tableParams);
// then
expect(filterFnSpy.calls.mostRecent().object).toBe(tableParams);
});
});
}); | the_stack |
import { member } from "babyioc";
import { Section } from "eightbittr";
import { MenuDialogRaw } from "menugraphr";
import { FullScreenPokemon } from "../FullScreenPokemon";
import { Following } from "./actions/Following";
import { Grass } from "./actions/Grass";
import { Ledges } from "./actions/Ledges";
import { Roaming } from "./actions/Roaming";
import { Walking } from "./actions/Walking";
import { Pokemon } from "./Battles";
import { Direction } from "./Constants";
import { HMMoveSchema } from "./constants/Moves";
import { Area, Map } from "./Maps";
import { Dialog, DialogOptions } from "./Menus";
import {
Actor,
AreaGate,
AreaSpawner,
Character,
Detector,
Enemy,
GymDetector,
HMCharacter,
MenuTriggerer,
Player,
Pokeball,
RoamingCharacter,
SightDetector,
ThemeDetector,
Transporter,
TransportSchema,
} from "./Actors";
/**
* Actions characters may perform walking around.
*/
export class Actions extends Section<FullScreenPokemon> {
/**
* Sets characters following each other.
*/
@member(Following)
public readonly following: Following;
/**
* Visual and battle updates for walking in tall grass.
*/
@member(Grass)
public readonly grass: Grass;
/**
* Hops characters down ledges.
*/
@member(Ledges)
public readonly ledges: Ledges;
/**
* Idle characters turning and walking in random directions.
*/
@member(Roaming)
public readonly roaming: Roaming;
/**
* Starts, continues, and stops characters walking.
*/
@member(Walking)
public readonly walking: Walking;
/**
* Spawning callback for Characters. Sight and roaming are accounted for.
*
* @param actor A newly placed Character.
*/
public spawnCharacter = (actor: Character): void => {
if (actor.sight) {
actor.sightDetector = this.game.actors.add<SightDetector>([
this.game.actors.names.sightDetector,
{
direction: actor.direction,
width: actor.sight * 8,
},
]);
actor.sightDetector.viewer = actor;
this.animatePositionSightDetector(actor);
}
if (actor.roaming) {
this.game.timeHandler.addEvent(
(): void => this.roaming.startRoaming(actor as RoamingCharacter),
this.game.numberMaker.randomInt(70)
);
}
};
/**
* Collision callback for a Player and a Pokeball it's interacting with.
*
* @param actor A Player interacting with other.
* @param other A Pokeball being interacted with by actor.
*/
public activatePokeball = (actor: Player, other: Pokeball): void => {
switch (other.action) {
case "item":
if (!other.item) {
throw new Error("Pokeball must have an item for the item action.");
}
this.game.menuGrapher.createMenu("GeneralText");
this.game.menuGrapher.addMenuDialog(
"GeneralText",
["%%%%%%%PLAYER%%%%%%% found " + other.item + "!"],
(): void => {
this.game.menuGrapher.deleteActiveMenu();
this.game.death.kill(other);
this.game.stateHolder.addChange(other.id, "alive", false);
}
);
this.game.menuGrapher.setActiveMenu("GeneralText");
this.game.saves.addItemToBag(other.item, other.amount);
break;
case "cutscene":
if (!other.cutscene) {
throw new Error("Pokeball must have a cutscene for the cutscene action.");
}
this.game.scenePlayer.startCutscene(other.cutscene, {
player: actor,
triggerer: other,
});
if (other.routine) {
this.game.scenePlayer.playRoutine(other.routine);
}
break;
case "pokedex":
if (!other.pokemon) {
throw new Error("Pokeball must have a Pokemon for the cutscene action.");
}
this.game.menus.pokedex.openPokedexListing(other.pokemon);
break;
case "dialog":
if (!other.dialog) {
throw new Error("Pokeball must have a dialog for the cutscene action.");
}
this.game.menuGrapher.createMenu("GeneralText");
this.game.menuGrapher.addMenuDialog("GeneralText", other.dialog);
this.game.menuGrapher.setActiveMenu("GeneralText");
break;
case "yes/no":
this.game.menuGrapher.createMenu("Yes/No", {
killOnB: ["GeneralText"],
});
this.game.menuGrapher.addMenuList("Yes/No", {
options: [
{
text: "YES",
callback: (): void => console.log("What do, yes?"),
},
{
text: "NO",
callback: (): void => console.log("What do, no?"),
},
],
});
this.game.menuGrapher.setActiveMenu("Yes/No");
break;
default:
throw new Error("Unknown Pokeball action: " + other.action + ".");
}
};
/**
* Activates a WindowDetector by immediately starting its cycle of
* checking whether it's in-frame to activate.
*
* @param actor A newly placed WindowDetector.
*/
public spawnWindowDetector = (actor: Detector): void => {
if (!this.checkWindowDetector(actor)) {
this.game.timeHandler.addEventInterval(
(): boolean => this.checkWindowDetector(actor),
7,
Infinity
);
}
};
/**
* Freezes a Character to start a dialog.
*
* @param actor A Player to freeze.
*/
public animatePlayerDialogFreeze(actor: Player): void {
this.walking.animateCharacterPreventWalking(actor);
this.game.classCycler.cancelClassCycle(actor, "walking");
if (actor.walkingFlipping) {
this.game.timeHandler.cancelEvent(actor.walkingFlipping);
actor.walkingFlipping = undefined;
}
}
/**
* Freezes a Character and starts a battle with an enemy.
*
* @param _ A Character about to start a battle with other.
* @param other An enemy about to battle actor.
*/
public animateTrainerBattleStart(actor: Character, other: Enemy): void {
console.log("should start battle", actor, other);
// const battleName: string = other.battleName || other.title;
// const battleSprite: string = other.battleSprite || battleName;
// this.game.battles.startBattle({
// battlers: {
// opponent: {
// name: battleName.split(""),
// sprite: battleSprite + "Front",
// category: "Trainer",
// hasActors: true,
// reward: other.reward,
// actors: other.actors.map(
// (schema: WildPokemonSchema): Pokemon => {
// return this.game.equations.createPokemon(schema);
// })
// }
// },
// textStart: ["", " wants to fight!"],
// textDefeat: other.textDefeat,
// textAfterBattle: other.textAfterBattle,
// giftAfterBattle: other.giftAfterBattle,
// badge: other.badge,
// textVictory: other.textVictory,
// nextCutscene: other.nextCutscene
// });
}
/**
* Creates and positions a set of four Actors around a point.
*
* @param x The horizontal value of the point.
* @param y The vertical value of the point.
* @param title A title for each Actor to create.
* @param settings Additional settings for each Actor.
* @param groupType Which group to move the Actors into, if any.
* @returns The four created Actors.
*/
public animateActorCorners(
x: number,
y: number,
title: string,
settings: any,
groupType?: string
): [Actor, Actor, Actor, Actor] {
const actors: Actor[] = [];
for (let i = 0; i < 4; i += 1) {
actors.push(this.game.actors.add([title, settings]));
}
if (groupType) {
for (const actor of actors) {
this.game.groupHolder.switchGroup(actor, actor.groupType, groupType);
}
}
this.game.physics.setLeft(actors[0], x);
this.game.physics.setLeft(actors[1], x);
this.game.physics.setRight(actors[2], x);
this.game.physics.setRight(actors[3], x);
this.game.physics.setBottom(actors[0], y);
this.game.physics.setBottom(actors[3], y);
this.game.physics.setTop(actors[1], y);
this.game.physics.setTop(actors[2], y);
this.game.graphics.flipping.flipHoriz(actors[0]);
this.game.graphics.flipping.flipHoriz(actors[1]);
this.game.graphics.flipping.flipVert(actors[1]);
this.game.graphics.flipping.flipVert(actors[2]);
return actors as [Actor, Actor, Actor, Actor];
}
/**
* Moves a set of four Actors away from a point.
*
* @param actors The four Actors to move.
* @param amount How far to move each Actor horizontally and vertically.
*/
public animateExpandCorners(actors: [Actor, Actor, Actor, Actor], amount: number): void {
this.game.physics.shiftHoriz(actors[0], amount);
this.game.physics.shiftHoriz(actors[1], amount);
this.game.physics.shiftHoriz(actors[2], -amount);
this.game.physics.shiftHoriz(actors[3], -amount);
this.game.physics.shiftVert(actors[0], -amount);
this.game.physics.shiftVert(actors[1], amount);
this.game.physics.shiftVert(actors[2], amount);
this.game.physics.shiftVert(actors[3], -amount);
}
/**
* Creates a small smoke animation from a point.
*
* @param x The horizontal location of the point.
* @param y The vertical location of the point.
* @param callback A callback for when the animation is done.
*/
public animateSmokeSmall(x: number, y: number, callback: (actor: Actor) => void): void {
const actors: Actor[] = this.animateActorCorners(x, y, "SmokeSmall", undefined, "Text");
this.game.timeHandler.addEvent((): void => {
for (const actor of actors) {
this.game.death.kill(actor);
}
}, 7);
this.game.timeHandler.addEvent((): void => this.animateSmokeMedium(x, y, callback), 7);
}
/**
* Creates a medium-sized smoke animation from a point.
*
* @param x The horizontal location of the point.
* @param y The vertical location of the point.
* @param callback A callback for when the animation is done.
*/
public animateSmokeMedium(x: number, y: number, callback: (actor: Actor) => void): void {
const actors: [Actor, Actor, Actor, Actor] = this.animateActorCorners(
x,
y,
"SmokeMedium",
undefined,
"Text"
);
this.game.timeHandler.addEvent((): void => this.animateExpandCorners(actors, 4), 7);
this.game.timeHandler.addEvent((): void => {
for (const actor of actors) {
this.game.death.kill(actor);
}
}, 14);
this.game.timeHandler.addEvent((): void => this.animateSmokeLarge(x, y, callback), 14);
}
/**
* Creates a large smoke animation from a point.
*
* @param x The horizontal location of the point.
* @param y The vertical location of the point.
* @param callback A callback for when the animation is done.
*/
public animateSmokeLarge(x: number, y: number, callback: (actor: Actor) => void): void {
const actors: [Actor, Actor, Actor, Actor] = this.animateActorCorners(
x,
y,
"SmokeLarge",
undefined,
"Text"
);
this.animateExpandCorners(actors, 10);
this.game.timeHandler.addEvent((): void => this.animateExpandCorners(actors, 8), 7);
this.game.timeHandler.addEvent((): void => {
for (const actor of actors) {
this.game.death.kill(actor);
}
}, 21);
if (callback) {
this.game.timeHandler.addEvent(callback, 21);
}
}
/**
* Animates an exclamation mark above An Actor.
*
* @param actor An Actor to show the exclamation over.
* @param timeout How long to keep the exclamation (by default, 140).
* @param callback A callback for when the exclamation is removed.
* @returns The exclamation Actor.
*/
public animateExclamation(actor: Actor, timeout = 140, callback?: () => void): Actor {
const exclamation: Actor = this.game.actors.add(this.game.actors.names.exclamation);
this.game.physics.setMidXObj(exclamation, actor);
this.game.physics.setBottom(exclamation, actor.top);
this.game.timeHandler.addEvent((): void => this.game.death.kill(exclamation), timeout);
if (callback) {
this.game.timeHandler.addEvent(callback, timeout);
}
return exclamation;
}
/**
* Sets An Actor facing a particular direction.
*
* @param actor An in-game Actor.
* @param direction A direction for actor to face.
* @todo Add more logic here for better performance.
*/
public animateCharacterSetDirection(actor: Actor, direction: Direction): void {
actor.direction = direction;
if (direction % 2 === 1) {
this.game.graphics.flipping.unflipHoriz(actor);
}
this.game.graphics.classes.removeClasses(
actor,
this.game.constants.directionClasses[Direction.Top],
this.game.constants.directionClasses[Direction.Right],
this.game.constants.directionClasses[Direction.Bottom],
this.game.constants.directionClasses[Direction.Left]
);
this.game.graphics.classes.addClass(
actor,
this.game.constants.directionClasses[direction]
);
if (direction === Direction.Right) {
this.game.graphics.flipping.flipHoriz(actor);
this.game.graphics.classes.addClass(
actor,
this.game.constants.directionClasses[Direction.Left]
);
}
}
/**
* Sets An Actor facing a random direction.
*
* @param actor An in-game Actor.
*/
public animateCharacterSetDirectionRandom(actor: Actor): void {
this.animateCharacterSetDirection(actor, this.game.numberMaker.randomIntWithin(0, 3));
}
/**
* Positions a Character's detector in front of it as its sight.
*
* @param actor A Character that should be able to see.
*/
public animatePositionSightDetector(actor: Character): void {
const detector: SightDetector = actor.sightDetector!;
const direction: Direction = actor.direction;
if (detector.direction !== direction) {
if (actor.direction % 2 === 0) {
this.game.physics.setWidth(detector, actor.width);
this.game.physics.setHeight(detector, actor.sight! * 8);
} else {
this.game.physics.setWidth(detector, actor.sight! * 8);
this.game.physics.setHeight(detector, actor.height);
}
detector.direction = direction;
}
switch (direction) {
case 0:
this.game.physics.setBottom(detector, actor.top);
this.game.physics.setMidXObj(detector, actor);
break;
case 1:
this.game.physics.setLeft(detector, actor.right);
this.game.physics.setMidYObj(detector, actor);
break;
case 2:
this.game.physics.setTop(detector, actor.bottom);
this.game.physics.setMidXObj(detector, actor);
break;
case 3:
this.game.physics.setRight(detector, actor.left);
this.game.physics.setMidYObj(detector, actor);
break;
default:
throw new Error("Unknown direction: " + direction + ".");
}
}
/**
* Animates the various logic pieces for finishing a dialog, such as pushes,
* gifts, options, and battle starting or disabling.
*
* @param actor A Player that's finished talking to other.
* @param other A Character that actor has finished talking to.
*/
public animateCharacterDialogFinish(actor: Player, other: Character): void {
this.game.modAttacher.fireEvent(this.game.mods.eventNames.onDialogFinish, other);
actor.talking = false;
other.talking = false;
if (other.directionPreferred) {
this.animateCharacterSetDirection(other, other.directionPreferred);
}
if (other.transport) {
other.active = true;
this.activateTransporter(actor, other as any);
return;
}
if (other.pushSteps) {
this.walking.startWalkingOnPath(actor, other.pushSteps);
}
if (other.gift) {
this.game.menuGrapher.createMenu("GeneralText", {
deleteOnFinish: true,
});
this.game.menuGrapher.addMenuDialog(
"GeneralText",
"%%%%%%%PLAYER%%%%%%% got " + other.gift.toUpperCase() + "!",
(): void => this.animateCharacterDialogFinish(actor, other)
);
this.game.menuGrapher.setActiveMenu("GeneralText");
this.game.saves.addItemToBag(other.gift);
other.gift = undefined;
this.game.stateHolder.addChange(other.id, "gift", undefined);
return;
}
if (other.dialogNext) {
other.dialog = other.dialogNext;
other.dialogNext = undefined;
this.game.stateHolder.addChange(other.id, "dialog", other.dialog);
this.game.stateHolder.addChange(other.id, "dialogNext", undefined);
}
if (other.dialogOptions) {
this.animateCharacterDialogOptions(actor, other, other.dialogOptions);
} else if (other.trainer && !(other as Enemy).alreadyBattled) {
this.animateTrainerBattleStart(actor, other as Enemy);
(other as Enemy).alreadyBattled = true;
this.game.stateHolder.addChange(other.id, "alreadyBattled", true);
}
if (other.trainer) {
other.trainer = false;
this.game.stateHolder.addChange(other.id, "trainer", false);
if (other.sight) {
other.sight = undefined;
this.game.stateHolder.addChange(other.id, "sight", undefined);
}
}
if (!other.dialogOptions) {
this.game.saves.autoSaveIfEnabled();
}
}
/**
* Displays a yes/no options menu for after a dialog has completed.
*
*
* @param actor A Player that's finished talking to other.
* @param other A Character that actor has finished talking to.
* @param dialog The dialog settings that just finished.
*/
public animateCharacterDialogOptions(actor: Player, other: Character, dialog: Dialog): void {
if (!dialog.options) {
throw new Error("Dialog should have .options.");
}
const options: DialogOptions = dialog.options;
const generateCallback = (callbackDialog: string | Dialog): (() => void) | undefined => {
if (!callbackDialog) {
return undefined;
}
let callback: (...args: any[]) => void;
let words: MenuDialogRaw;
if (callbackDialog.constructor === Object && (callbackDialog as Dialog).options) {
words = (callbackDialog as Dialog).words;
callback = (): void => {
this.animateCharacterDialogOptions(actor, other, callbackDialog as Dialog);
};
} else {
words = (callbackDialog as Dialog).words || (callbackDialog as string);
if ((callbackDialog as Dialog).cutscene) {
callback = this.game.scenePlayer.bindCutscene(
(callbackDialog as Dialog).cutscene!,
{
player: actor,
tirggerer: other,
}
);
}
}
return (): void => {
this.game.menuGrapher.deleteMenu("Yes/No");
this.game.menuGrapher.createMenu("GeneralText", {
deleteOnFinish: true,
});
this.game.menuGrapher.addMenuDialog("GeneralText", words, callback);
this.game.menuGrapher.setActiveMenu("GeneralText");
};
};
console.warn("DialogOptions assumes type = Yes/No for now...");
this.game.menuGrapher.createMenu("Yes/No", {
position: {
offset: {
left: 28,
},
},
});
this.game.menuGrapher.addMenuList("Yes/No", {
options: [
{
text: "YES",
callback: generateCallback(options.Yes),
},
{
text: "NO",
callback: generateCallback(options.No),
},
],
});
this.game.menuGrapher.setActiveMenu("Yes/No");
}
/**
* Activates a Detector to trigger a cutscene and/or routine.
*
* @param actor A Player triggering other.
* @param other A Detector triggered by actor.
*/
public activateCutsceneTriggerer = (actor: Player, other: Detector): void => {
if (other.removed || actor.collidedTrigger === other) {
return;
}
actor.collidedTrigger = other;
this.animatePlayerDialogFreeze(actor);
if (!other.keepAlive) {
if (other.id.indexOf("Anonymous") !== -1) {
console.warn("Deleting anonymous CutsceneTriggerer:", other.id);
}
this.game.stateHolder.addChange(other.id, "alive", false);
this.game.death.kill(other);
}
if (other.cutscene) {
this.game.scenePlayer.startCutscene(other.cutscene, {
player: actor,
triggerer: other,
});
}
if (other.routine) {
this.game.scenePlayer.playRoutine(other.routine);
}
};
/**
* Activates a Detector to play an audio theme.
*
* @param actor A Player triggering other.
* @param other A Detector triggered by actor.
*/
public activateThemePlayer = async (actor: Player, other: ThemeDetector): Promise<void> => {
if (
!actor.player ||
this.game.audioPlayer.hasSound(this.game.audio.aliases.theme, other.theme)
) {
return;
}
await this.game.audioPlayer.play(other.theme, {
alias: this.game.audio.aliases.theme,
loop: true,
});
};
/**
* Activates a Detector to play a cutscene, and potentially a dialog.
*
* @param actor A Player triggering other.
* @param other A Detector triggered by actor.
*/
public activateCutsceneResponder(actor: Character, other: Detector): void {
if (!actor.player || other.removed) {
return;
}
if (other.dialog) {
this.activateMenuTriggerer(actor, other);
return;
}
this.game.scenePlayer.startCutscene(other.cutscene!, {
player: actor,
triggerer: other,
});
}
/**
* Activates a Detector to open a menu, and potentially a dialog.
*
* @param actor A Character triggering other.
* @param other A Detector triggered by actor.
*/
public activateMenuTriggerer = (actor: Character, other: MenuTriggerer): void => {
if (other.removed || actor.collidedTrigger === other) {
return;
}
if (!other.dialog) {
throw new Error("MenuTriggerer should have .dialog.");
}
const name: string = other.menu || "GeneralText";
const dialog: MenuDialogRaw | MenuDialogRaw[] = other.dialog;
actor.collidedTrigger = other;
this.walking.animateCharacterPreventWalking(actor);
if (!other.keepAlive) {
this.game.death.kill(other);
}
if (!this.game.menuGrapher.getMenu(name)) {
this.game.menuGrapher.createMenu(name, other.menuAttributes);
}
if (dialog) {
this.game.menuGrapher.addMenuDialog(name, dialog, (): void => {
const complete: () => void = (): void => {
this.game.mapScreener.blockInputs = false;
delete actor.collidedTrigger;
};
this.game.menuGrapher.deleteMenu("GeneralText");
if (other.pushSteps) {
this.walking.startWalkingOnPath(actor, [...other.pushSteps, complete]);
} else {
complete();
}
});
}
this.game.menuGrapher.setActiveMenu(name);
};
/**
* Activates a Character's sight detector for when another Character walks
* into it.
*
* @param actor A Character triggering other.
* @param other A sight detector being triggered by actor.
*/
public activateSightDetector = (actor: Character, other: SightDetector): void => {
if (other.viewer.talking) {
return;
}
other.viewer.talking = true;
other.active = false;
this.game.mapScreener.blockInputs = true;
this.game.scenePlayer.startCutscene("TrainerSpotted", {
player: actor,
sightDetector: other,
triggerer: other.viewer,
});
};
/**
* Activation callback for level transports (any Actor with a .transport
* attribute). Depending on the transport, either the map or location are
* shifted to it.
*
* @param actor A Character attempting to enter other.
* @param other A transporter being entered by actor.
*/
public activateTransporter = (actor: Character, other: Transporter): void => {
if (!actor.player || !other.active) {
return;
}
if (!other.transport) {
throw new Error("No transport given to activateTransporter");
}
const transport: TransportSchema = other.transport as TransportSchema;
let callback: () => void;
if (typeof transport === "string") {
callback = (): void => {
this.game.maps.setLocation(transport);
};
} else if (typeof transport.map !== "undefined") {
callback = (): void => {
this.game.maps.setMap(transport.map, transport.location);
};
} else if (typeof transport.location !== "undefined") {
callback = (): void => {
this.game.maps.setLocation(transport.location);
};
} else {
throw new Error(`Unknown transport type: '${transport}'`);
}
other.active = false;
this.game.animations.fading.animateFadeToColor({
callback,
color: "Black",
});
};
/**
* Activation trigger for a gym statue. If the Player is looking up at it,
* it speaks the status of the gym leader.
*
* @param actor A Player activating other.
* @param other A gym statue being activated by actor.
*/
public activateGymStatue = (actor: Character, other: GymDetector): void => {
if (actor.direction !== 0) {
return;
}
const gym: string = other.gym;
const leader: string = other.leader;
const dialog: string[] = [
`${gym.toUpperCase()}\n %%%%%%%POKEMON%%%%%%% GYM \n LEADER: ${leader.toUpperCase()}`,
"WINNING TRAINERS: %%%%%%%RIVAL%%%%%%%",
];
if (this.game.itemsHolder.getItem(this.game.storage.names.badges)[leader]) {
dialog[1] += " \n %%%%%%%PLAYER%%%%%%%";
}
this.game.menuGrapher.createMenu("GeneralText");
this.game.menuGrapher.addMenuDialog("GeneralText", dialog);
this.game.menuGrapher.setActiveMenu("GeneralText");
};
/**
* Calls an HMCharacter's partyActivate Function when the Player activates the HMCharacter.
*
* @param player The Player.
* @param actor The Solid to be affected.
*/
public activateHMCharacter = (player: Player, actor: HMCharacter): void => {
if (
actor.requiredBadge &&
!this.game.itemsHolder.getItem(this.game.storage.names.badges)[actor.requiredBadge]
) {
return;
}
for (const pokemon of this.game.itemsHolder.getItem(
this.game.storage.names.pokemonInParty
)) {
for (const move of pokemon.moves) {
if (move.title === actor.moveName) {
actor.moveCallback(player, pokemon);
return;
}
}
}
};
/**
* Activates a Spawner by calling its .activate.
*
* @param actor A newly placed Spawner.
*/
public activateSpawner = (actor: Detector): void => {
if (!actor.activate) {
throw new Error("Spawner should have .activate.");
}
actor.activate.call(this, actor);
};
/**
* Checks if a WindowDetector is within frame, and activates it if so.
*
* @param actor An in-game WindowDetector.
*/
public checkWindowDetector(actor: Detector): boolean {
if (
actor.bottom < 0 ||
actor.left > this.game.mapScreener.width ||
actor.top > this.game.mapScreener.height ||
actor.right < 0
) {
return false;
}
if (!actor.activate) {
throw new Error("WindowDetector should have .activate.");
}
actor.activate.call(this, actor);
this.game.death.kill(actor);
return true;
}
/**
* Activates an AreaSpawner. If it's for a different Area than the current,
* that area is spawned in the appropriate direction.
*
* @param actor An AreaSpawner to activate.
*/
public spawnAreaSpawner = (actor: AreaSpawner): void => {
const map: Map = this.game.areaSpawner.getMap(actor.map) as Map;
const area: Area = map.areas[actor.area];
if (area === this.game.areaSpawner.getArea()) {
this.game.death.kill(actor);
return;
}
if (
area.spawnedBy &&
area.spawnedBy === (this.game.areaSpawner.getArea() as Area).spawnedBy
) {
this.game.death.kill(actor);
return;
}
area.spawnedBy = (this.game.areaSpawner.getArea() as Area).spawnedBy;
this.game.maps.activateAreaSpawner(actor, area);
};
/**
* Activation callback for an AreaGate. The Player is marked to now spawn
* in the new Map and Area.
*
* @param actor A Character walking to other.
* @param other An AreaGate potentially being triggered.
*/
public activateAreaGate = (actor: Character, other: AreaGate): void => {
if (!actor.player || !actor.walking || actor.direction !== other.direction) {
return;
}
const area: Area = this.game.areaSpawner.getMap(other.map).areas[other.area] as Area;
let areaOffsetX: number;
let areaOffsetY: number;
switch (actor.direction) {
case Direction.Top:
areaOffsetX = actor.left - other.left;
areaOffsetY = area.height! - actor.height;
break;
case Direction.Right:
areaOffsetX = 0;
areaOffsetY = actor.top - other.top;
break;
case Direction.Bottom:
areaOffsetX = actor.left - other.left;
areaOffsetY = 0;
break;
case Direction.Left:
areaOffsetX = area.width! - actor.width;
areaOffsetY = actor.top - other.top;
break;
default:
throw new Error(`Unknown direction: '${actor.direction}'.`);
}
const screenOffsetX: number = areaOffsetX - actor.left;
const screenOffsetY: number = areaOffsetY - actor.top;
this.game.mapScreener.top = screenOffsetY;
this.game.mapScreener.right = screenOffsetX + this.game.mapScreener.width;
this.game.mapScreener.bottom = screenOffsetY + this.game.mapScreener.height;
this.game.mapScreener.left = screenOffsetX;
this.game.mapScreener.activeArea = this.game.areaSpawner.getMap().areas[
other.area
] as Area;
this.game.itemsHolder.setItem(this.game.storage.names.map, other.map);
this.game.itemsHolder.setItem(this.game.storage.names.area, other.area);
this.game.itemsHolder.setItem(this.game.storage.names.location, undefined);
this.game.maps.setStateCollection(area);
other.active = false;
this.game.timeHandler.addEvent((): void => {
other.active = true;
}, 2);
};
/**
* Makes sure that Player is facing the correct HMCharacter
*
* @param player The Player.
* @param pokemon The Pokemon using the move.
* @param move The move being used.
* @todo Add context for what happens if player is not bordering the correct HMCharacter.
* @todo Refactor to give borderedActor a .hmActivate property.
*/
public partyActivateCheckActor(player: Player, pokemon: Pokemon, move: HMMoveSchema): void {
const borderedActor: Actor | undefined = player.bordering[player.direction];
if (borderedActor && borderedActor.title.indexOf(move.characterName!) !== -1) {
move.partyActivate!(player, pokemon);
}
}
/**
* Cuts a CuttableTree.
*
* @param player The Player.
* @todo Add an animation for what happens when the CuttableTree is cut.
*/
public partyActivateCut = (player: Player): void => {
this.game.menuGrapher.deleteAllMenus();
this.game.menus.pause.close();
this.game.death.kill(player.bordering[player.direction]!);
};
/**
* Makes a StrengthBoulder move.
*
* @param player The Player.
* @todo Verify the exact speed, sound, and distance.
*/
public partyActivateStrength = (player: Player): void => {
const boulder: HMCharacter = player.bordering[player.direction] as HMCharacter;
this.game.menuGrapher.deleteAllMenus();
this.game.menus.pause.close();
if (
!this.game.actorHitter.checkHitForActors(player as any, boulder as any) ||
boulder.bordering[player.direction] !== undefined
) {
return;
}
let xvel = 0;
let yvel = 0;
switch (player.direction) {
case 0:
yvel = -4;
break;
case 1:
xvel = 4;
break;
case 2:
yvel = 4;
break;
case 3:
xvel = -4;
break;
default:
throw new Error(`Unknown direction: '${player.direction}'.`);
}
this.game.timeHandler.addEventInterval(
(): void => this.game.physics.shiftBoth(boulder, xvel, yvel),
1,
8
);
for (let i = 0; i < boulder.bordering.length; i += 1) {
boulder.bordering[i] = undefined;
}
};
/**
* Starts the Player surfing.
*
* @param player The Player.
* @todo Add the dialogue for when the Player starts surfing.
*/
public partyActivateSurf = (player: Player): void => {
this.game.menuGrapher.deleteAllMenus();
this.game.menus.pause.close();
if (player.cycling) {
return;
}
player.bordering[player.direction] = undefined;
this.game.graphics.classes.addClass(player, "surfing");
console.log("Should start walking");
// this.animateCharacterStartWalking(player, player.direction, [1]);
player.surfing = true;
};
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/profilesMappers";
import * as Parameters from "../models/parameters";
import { TrafficManagerManagementClientContext } from "../trafficManagerManagementClientContext";
/** Class representing a Profiles. */
export class Profiles {
private readonly client: TrafficManagerManagementClientContext;
/**
* Create a Profiles.
* @param {TrafficManagerManagementClientContext} client Reference to the service client.
*/
constructor(client: TrafficManagerManagementClientContext) {
this.client = client;
}
/**
* Checks the availability of a Traffic Manager Relative DNS name.
* @param parameters The Traffic Manager name parameters supplied to the
* CheckTrafficManagerNameAvailability operation.
* @param [options] The optional parameters
* @returns Promise<Models.ProfilesCheckTrafficManagerRelativeDnsNameAvailabilityResponse>
*/
checkTrafficManagerRelativeDnsNameAvailability(parameters: Models.CheckTrafficManagerRelativeDnsNameAvailabilityParameters, options?: msRest.RequestOptionsBase): Promise<Models.ProfilesCheckTrafficManagerRelativeDnsNameAvailabilityResponse>;
/**
* @param parameters The Traffic Manager name parameters supplied to the
* CheckTrafficManagerNameAvailability operation.
* @param callback The callback
*/
checkTrafficManagerRelativeDnsNameAvailability(parameters: Models.CheckTrafficManagerRelativeDnsNameAvailabilityParameters, callback: msRest.ServiceCallback<Models.TrafficManagerNameAvailability>): void;
/**
* @param parameters The Traffic Manager name parameters supplied to the
* CheckTrafficManagerNameAvailability operation.
* @param options The optional parameters
* @param callback The callback
*/
checkTrafficManagerRelativeDnsNameAvailability(parameters: Models.CheckTrafficManagerRelativeDnsNameAvailabilityParameters, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.TrafficManagerNameAvailability>): void;
checkTrafficManagerRelativeDnsNameAvailability(parameters: Models.CheckTrafficManagerRelativeDnsNameAvailabilityParameters, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.TrafficManagerNameAvailability>, callback?: msRest.ServiceCallback<Models.TrafficManagerNameAvailability>): Promise<Models.ProfilesCheckTrafficManagerRelativeDnsNameAvailabilityResponse> {
return this.client.sendOperationRequest(
{
parameters,
options
},
checkTrafficManagerRelativeDnsNameAvailabilityOperationSpec,
callback) as Promise<Models.ProfilesCheckTrafficManagerRelativeDnsNameAvailabilityResponse>;
}
/**
* Lists all Traffic Manager profiles within a resource group.
* @param resourceGroupName The name of the resource group containing the Traffic Manager profiles
* to be listed.
* @param [options] The optional parameters
* @returns Promise<Models.ProfilesListByResourceGroupResponse>
*/
listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.ProfilesListByResourceGroupResponse>;
/**
* @param resourceGroupName The name of the resource group containing the Traffic Manager profiles
* to be listed.
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.ProfileListResult>): void;
/**
* @param resourceGroupName The name of the resource group containing the Traffic Manager profiles
* to be listed.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProfileListResult>): void;
listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProfileListResult>, callback?: msRest.ServiceCallback<Models.ProfileListResult>): Promise<Models.ProfilesListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
options
},
listByResourceGroupOperationSpec,
callback) as Promise<Models.ProfilesListByResourceGroupResponse>;
}
/**
* Lists all Traffic Manager profiles within a subscription.
* @param [options] The optional parameters
* @returns Promise<Models.ProfilesListBySubscriptionResponse>
*/
listBySubscription(options?: msRest.RequestOptionsBase): Promise<Models.ProfilesListBySubscriptionResponse>;
/**
* @param callback The callback
*/
listBySubscription(callback: msRest.ServiceCallback<Models.ProfileListResult>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
listBySubscription(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProfileListResult>): void;
listBySubscription(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProfileListResult>, callback?: msRest.ServiceCallback<Models.ProfileListResult>): Promise<Models.ProfilesListBySubscriptionResponse> {
return this.client.sendOperationRequest(
{
options
},
listBySubscriptionOperationSpec,
callback) as Promise<Models.ProfilesListBySubscriptionResponse>;
}
/**
* Gets a Traffic Manager profile.
* @param resourceGroupName The name of the resource group containing the Traffic Manager profile.
* @param profileName The name of the Traffic Manager profile.
* @param [options] The optional parameters
* @returns Promise<Models.ProfilesGetResponse>
*/
get(resourceGroupName: string, profileName: string, options?: msRest.RequestOptionsBase): Promise<Models.ProfilesGetResponse>;
/**
* @param resourceGroupName The name of the resource group containing the Traffic Manager profile.
* @param profileName The name of the Traffic Manager profile.
* @param callback The callback
*/
get(resourceGroupName: string, profileName: string, callback: msRest.ServiceCallback<Models.Profile>): void;
/**
* @param resourceGroupName The name of the resource group containing the Traffic Manager profile.
* @param profileName The name of the Traffic Manager profile.
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, profileName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Profile>): void;
get(resourceGroupName: string, profileName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Profile>, callback?: msRest.ServiceCallback<Models.Profile>): Promise<Models.ProfilesGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
profileName,
options
},
getOperationSpec,
callback) as Promise<Models.ProfilesGetResponse>;
}
/**
* Create or update a Traffic Manager profile.
* @param resourceGroupName The name of the resource group containing the Traffic Manager profile.
* @param profileName The name of the Traffic Manager profile.
* @param parameters The Traffic Manager profile parameters supplied to the CreateOrUpdate
* operation.
* @param [options] The optional parameters
* @returns Promise<Models.ProfilesCreateOrUpdateResponse>
*/
createOrUpdate(resourceGroupName: string, profileName: string, parameters: Models.Profile, options?: msRest.RequestOptionsBase): Promise<Models.ProfilesCreateOrUpdateResponse>;
/**
* @param resourceGroupName The name of the resource group containing the Traffic Manager profile.
* @param profileName The name of the Traffic Manager profile.
* @param parameters The Traffic Manager profile parameters supplied to the CreateOrUpdate
* operation.
* @param callback The callback
*/
createOrUpdate(resourceGroupName: string, profileName: string, parameters: Models.Profile, callback: msRest.ServiceCallback<Models.Profile>): void;
/**
* @param resourceGroupName The name of the resource group containing the Traffic Manager profile.
* @param profileName The name of the Traffic Manager profile.
* @param parameters The Traffic Manager profile parameters supplied to the CreateOrUpdate
* operation.
* @param options The optional parameters
* @param callback The callback
*/
createOrUpdate(resourceGroupName: string, profileName: string, parameters: Models.Profile, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Profile>): void;
createOrUpdate(resourceGroupName: string, profileName: string, parameters: Models.Profile, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Profile>, callback?: msRest.ServiceCallback<Models.Profile>): Promise<Models.ProfilesCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
profileName,
parameters,
options
},
createOrUpdateOperationSpec,
callback) as Promise<Models.ProfilesCreateOrUpdateResponse>;
}
/**
* Deletes a Traffic Manager profile.
* @param resourceGroupName The name of the resource group containing the Traffic Manager profile
* to be deleted.
* @param profileName The name of the Traffic Manager profile to be deleted.
* @param [options] The optional parameters
* @returns Promise<Models.ProfilesDeleteMethodResponse>
*/
deleteMethod(resourceGroupName: string, profileName: string, options?: msRest.RequestOptionsBase): Promise<Models.ProfilesDeleteMethodResponse>;
/**
* @param resourceGroupName The name of the resource group containing the Traffic Manager profile
* to be deleted.
* @param profileName The name of the Traffic Manager profile to be deleted.
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, profileName: string, callback: msRest.ServiceCallback<Models.DeleteOperationResult>): void;
/**
* @param resourceGroupName The name of the resource group containing the Traffic Manager profile
* to be deleted.
* @param profileName The name of the Traffic Manager profile to be deleted.
* @param options The optional parameters
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, profileName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DeleteOperationResult>): void;
deleteMethod(resourceGroupName: string, profileName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DeleteOperationResult>, callback?: msRest.ServiceCallback<Models.DeleteOperationResult>): Promise<Models.ProfilesDeleteMethodResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
profileName,
options
},
deleteMethodOperationSpec,
callback) as Promise<Models.ProfilesDeleteMethodResponse>;
}
/**
* Update a Traffic Manager profile.
* @param resourceGroupName The name of the resource group containing the Traffic Manager profile.
* @param profileName The name of the Traffic Manager profile.
* @param parameters The Traffic Manager profile parameters supplied to the Update operation.
* @param [options] The optional parameters
* @returns Promise<Models.ProfilesUpdateResponse>
*/
update(resourceGroupName: string, profileName: string, parameters: Models.Profile, options?: msRest.RequestOptionsBase): Promise<Models.ProfilesUpdateResponse>;
/**
* @param resourceGroupName The name of the resource group containing the Traffic Manager profile.
* @param profileName The name of the Traffic Manager profile.
* @param parameters The Traffic Manager profile parameters supplied to the Update operation.
* @param callback The callback
*/
update(resourceGroupName: string, profileName: string, parameters: Models.Profile, callback: msRest.ServiceCallback<Models.Profile>): void;
/**
* @param resourceGroupName The name of the resource group containing the Traffic Manager profile.
* @param profileName The name of the Traffic Manager profile.
* @param parameters The Traffic Manager profile parameters supplied to the Update operation.
* @param options The optional parameters
* @param callback The callback
*/
update(resourceGroupName: string, profileName: string, parameters: Models.Profile, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Profile>): void;
update(resourceGroupName: string, profileName: string, parameters: Models.Profile, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Profile>, callback?: msRest.ServiceCallback<Models.Profile>): Promise<Models.ProfilesUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
profileName,
parameters,
options
},
updateOperationSpec,
callback) as Promise<Models.ProfilesUpdateResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const checkTrafficManagerRelativeDnsNameAvailabilityOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "providers/Microsoft.Network/checkTrafficManagerNameAvailability",
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.CheckTrafficManagerRelativeDnsNameAvailabilityParameters,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.TrafficManagerNameAvailability
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listByResourceGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles",
urlParameters: [
Parameters.resourceGroupName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ProfileListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listBySubscriptionOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Network/trafficmanagerprofiles",
urlParameters: [
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ProfileListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.profileName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.Profile
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const createOrUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.profileName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.Profile,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.Profile
},
201: {
bodyMapper: Mappers.Profile
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const deleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.profileName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.DeleteOperationResult
},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const updateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.profileName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.Profile,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.Profile
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
}; | the_stack |
import {SpriteBase} from "../SpriteBase";
import {LocationKey, TileEvent} from "../tile_events/TileEvent";
import * as numbers from "../magic_numbers";
import {
directions,
get_centered_pos_in_px,
get_directions,
get_opposite_direction,
get_px_position,
get_surroundings,
mount_collision_polygon,
reverse_directions,
} from "../utils";
import {JumpEvent} from "../tile_events/JumpEvent";
import {ClimbEvent} from "../tile_events/ClimbEvent";
import {GoldenSun} from "../GoldenSun";
import {Map} from "../Map";
import {RopeEvent} from "../tile_events/RopeEvent";
import {GameEvent} from "../game_events/GameEvent";
export enum interactable_object_interaction_types {
ONCE = "once",
INFINITE = "infinite",
}
export enum interactable_object_event_types {
JUMP = "jump",
JUMP_AROUND = "jump_around",
CLIMB = "climb",
ROPE = "rope",
}
export class InteractableObjects {
private static readonly BUSH_KEY = "bush";
private static readonly BUSH_FRAME = "leaves/bush/00";
protected game: Phaser.Game;
protected data: GoldenSun;
private allowed_tiles: {x: number; y: number; collision_layer: number}[];
private not_allowed_tiles: {x: number; y: number}[];
private events_id: Set<TileEvent["id"]>;
private collision_change_functions: Function[];
private anchor_x: number;
private anchor_y: number;
private scale_x: number;
private scale_y: number;
private storage_keys: {
position?: string;
base_collision_layer?: string;
enable?: string;
entangled_by_bush?: string;
};
private tile_events_info: {
[event_id: number]: {
collision_layer_shift?: number;
intermediate_collision_layer_shift?: number;
};
};
private block_climb_collision_layer_shift: number;
private _key_name: string;
private _sprite_info: SpriteBase;
private _base_collision_layer: number;
private _tile_x_pos: number;
private _tile_y_pos: number;
private _collision_tiles_bodies: Phaser.Physics.P2.Body[];
private _color_filter: any;
private _enable: boolean;
private _entangled_by_bush: boolean;
private _sprite: Phaser.Sprite;
private _psynergy_casted: {[field_psynergy_key: string]: boolean};
private _blocking_stair_block: Phaser.Physics.P2.Body;
private _active: boolean;
private _label: string;
private _object_drop_tiles: {
x: number;
y: number;
dest_x: number;
dest_y: number;
destination_collision_layer: number;
animation_duration: number;
dust_animation: boolean;
}[];
private _bush_sprite: Phaser.Sprite;
protected _pushable: boolean;
protected _is_rope_dock: boolean;
protected _rollable: boolean;
protected _breakable: boolean;
protected _extra_sprites: (Phaser.Sprite | Phaser.Graphics | Phaser.Group)[];
public allow_jumping_over_it: boolean;
public allow_jumping_through_it: boolean;
private toggle_enable_events: {
event: GameEvent;
on_enable: boolean;
}[];
constructor(
game,
data,
key_name,
x,
y,
storage_keys,
allowed_tiles,
base_collision_layer,
not_allowed_tiles,
object_drop_tiles,
anchor_x,
anchor_y,
scale_x,
scale_y,
block_climb_collision_layer_shift,
events_info,
enable,
entangled_by_bush,
toggle_enable_events,
label,
allow_jumping_over_it,
allow_jumping_through_it
) {
this.game = game;
this.data = data;
this._key_name = key_name;
this.storage_keys = storage_keys ?? {};
if (this.storage_keys.position !== undefined) {
const position = this.data.storage.get(this.storage_keys.position);
x = position.x;
y = position.y;
}
this._tile_x_pos = x;
this._tile_y_pos = y;
this._sprite_info = null;
this.allowed_tiles = allowed_tiles ?? [];
if (this.storage_keys.base_collision_layer !== undefined) {
base_collision_layer = this.data.storage.get(this.storage_keys.base_collision_layer);
}
this._base_collision_layer = base_collision_layer ?? 0;
if (this.storage_keys.enable !== undefined) {
enable = this.data.storage.get(this.storage_keys.enable);
}
this._enable = enable ?? true;
if (this.storage_keys.entangled_by_bush !== undefined) {
entangled_by_bush = this.data.storage.get(this.storage_keys.entangled_by_bush);
}
this._entangled_by_bush = entangled_by_bush ?? false;
this.not_allowed_tiles = not_allowed_tiles ?? [];
this._object_drop_tiles = object_drop_tiles ?? [];
this.events_id = new Set();
this._collision_tiles_bodies = [];
this.collision_change_functions = [];
this._color_filter = this.game.add.filter("ColorFilters");
this.anchor_x = anchor_x;
this.anchor_y = anchor_y;
this.scale_x = scale_x;
this.scale_y = scale_y;
this._psynergy_casted = {};
this.block_climb_collision_layer_shift = block_climb_collision_layer_shift;
this._active = true;
this._pushable = false;
this._is_rope_dock = false;
this._rollable = false;
this._breakable = false;
this.tile_events_info = {};
for (let index in events_info) {
this.tile_events_info[+index] = events_info[index];
}
this._extra_sprites = [];
if (toggle_enable_events !== undefined) {
this.toggle_enable_events = toggle_enable_events.map(event_info => {
const event = this.data.game_event_manager.get_event_instance(event_info.event);
return {
event: event,
on_enable: event_info.on_enable,
};
});
} else {
this.toggle_enable_events = [];
}
this._label = label;
this.allow_jumping_over_it = allow_jumping_over_it ?? false;
this.allow_jumping_through_it = allow_jumping_through_it ?? false;
}
get key_name() {
return this._key_name;
}
/** Gets the current x tile position of this interactable object. */
get tile_x_pos() {
return this._tile_x_pos;
}
/** Gets the current y tile position of this interactable object. */
get tile_y_pos() {
return this._tile_y_pos;
}
/** Gets the x position in px. */
get x(): number {
return this.sprite.body ? this.sprite.body.x : this.sprite.x;
}
/** Gets the y position in px. */
get y(): number {
return this.sprite.body ? this.sprite.body.y : this.sprite.y;
}
/** The unique label that identifies this Interactable Object. */
get label() {
return this._label;
}
/** This IO body if available. */
get body() {
return this.sprite?.body ?? null;
}
get base_collision_layer() {
return this._base_collision_layer;
}
get sprite() {
return this._sprite;
}
get sprite_info() {
return this._sprite_info;
}
get object_drop_tiles() {
return this._object_drop_tiles;
}
get blocking_stair_block() {
return this._blocking_stair_block;
}
get psynergy_casted() {
return this._psynergy_casted;
}
get color_filter() {
return this._color_filter;
}
get collision_tiles_bodies() {
return this._collision_tiles_bodies;
}
/** When active is false, the io is removed from the map. */
get active() {
return this._active;
}
get pushable() {
return this._pushable;
}
get is_rope_dock() {
return this._is_rope_dock;
}
get rollable() {
return this._rollable;
}
get breakable() {
return this._breakable;
}
/** When enable is false, the io is on the map, but a char can't interact with it. */
get enable() {
return this._enable;
}
get entangled_by_bush() {
return this._entangled_by_bush;
}
get bush_sprite() {
return this._bush_sprite;
}
get width() {
return this.sprite.width;
}
get height() {
return this.sprite.height;
}
get is_interactable_object() {
return true;
}
position_allowed(x: number, y: number) {
if (
this.data.map.interactable_objects.filter(io => {
return (
io.tile_x_pos === x && io.tile_y_pos === y && io.base_collision_layer === this.base_collision_layer
);
}).length
) {
return false;
}
for (let i = 0; i < this.allowed_tiles.length; ++i) {
const tile = this.allowed_tiles[i];
if (tile.x === x && tile.y === y && tile.collision_layer === this.data.map.collision_layer) {
return true;
}
}
return false;
}
get_current_position(map: Map) {
if (this._sprite) {
const x = (this.sprite.x / map.tile_width) | 0;
const y = (this.sprite.y / map.tile_height) | 0;
return {x: x, y: y};
} else {
return {
x: this.tile_x_pos,
y: this.tile_y_pos,
};
}
}
set_tile_position(pos: {x?: number; y?: number}, update_on_map: boolean = true) {
const new_x_pos = pos.x ?? this.tile_x_pos;
const new_y_pos = pos.y ?? this.tile_y_pos;
if (update_on_map) {
this.data.map.update_body_tile(
this.tile_x_pos,
this.tile_y_pos,
new_x_pos,
new_y_pos,
this.base_collision_layer,
this.base_collision_layer,
this
);
}
this._tile_x_pos = new_x_pos;
this._tile_y_pos = new_y_pos;
}
set_enable(enable: boolean) {
this._enable = enable;
if (this.storage_keys.enable !== undefined) {
this.data.storage.set(this.storage_keys.enable, enable);
}
this.toggle_enable_events.forEach(event_info => {
if (enable === event_info.on_enable) {
event_info.event.fire();
}
});
}
set_entangled_by_bush(entangled_by_bush: boolean) {
this._entangled_by_bush = entangled_by_bush;
if (this.storage_keys.entangled_by_bush !== undefined) {
this.data.storage.set(this.storage_keys.entangled_by_bush, entangled_by_bush);
}
}
destroy_bush() {
if (this._bush_sprite) {
this._bush_sprite.destroy();
this._bush_sprite = null;
}
}
change_collision_layer(destination_collision_layer: number, update_on_map: boolean = true) {
this.sprite.body.removeCollisionGroup(
this.data.collision.interactable_objs_collision_groups[this.base_collision_layer]
);
this.sprite.body.setCollisionGroup(
this.data.collision.interactable_objs_collision_groups[destination_collision_layer]
);
if (update_on_map) {
this.data.map.update_body_tile(
this.tile_x_pos,
this.tile_y_pos,
this.tile_x_pos,
this.tile_y_pos,
this.base_collision_layer,
destination_collision_layer,
this
);
}
this._base_collision_layer = destination_collision_layer;
this.sprite.base_collision_layer = destination_collision_layer;
//the below statement may change the events activation layers too
this.collision_change_functions.forEach(f => f());
}
insert_event(id: number) {
this.events_id.add(id);
}
get_events() {
return [...this.events_id].map(id => TileEvent.get_event(id));
}
remove_event(id: number) {
this.events_id.delete(id);
}
destroy_collision_tiles_bodies() {
this._collision_tiles_bodies.forEach(body => {
body.destroy();
});
this._collision_tiles_bodies = [];
}
private creating_blocking_stair_block() {
const target_layer = this.base_collision_layer + this.block_climb_collision_layer_shift;
const x_pos = (this.tile_x_pos + 0.5) * this.data.map.tile_width;
const y_pos = (this.tile_y_pos + 1.5) * this.data.map.tile_height - 4;
const body = this.game.physics.p2.createBody(x_pos, y_pos, 0, true);
body.clearShapes();
const width = this.data.dbs.interactable_objects_db[this.key_name].body_radius * 2;
body.setRectangle(width, width, 0, 0);
if (!(target_layer in this.data.collision.interactable_objs_collision_groups)) {
this.data.collision.interactable_objs_collision_groups[
target_layer
] = this.game.physics.p2.createCollisionGroup();
}
body.setCollisionGroup(this.data.collision.interactable_objs_collision_groups[target_layer]);
body.damping = numbers.MAP_DAMPING;
body.angularDamping = numbers.MAP_DAMPING;
body.setZeroRotation();
body.fixedRotation = true;
body.dynamic = false;
body.static = true;
body.debug = this.data.hero.sprite.body.debug;
body.collides(this.data.collision.hero_collision_group);
this._blocking_stair_block = body;
}
initial_config(map: Map) {
this._sprite_info = this.data.info.iter_objs_sprite_base_list[this.key_name];
const interactable_object_db = this.data.dbs.interactable_objects_db[this.key_name];
if (interactable_object_db.psynergy_keys) {
for (let psynergy_key in interactable_object_db.psynergy_keys) {
const psynergy_properties = interactable_object_db.psynergy_keys[psynergy_key];
if (psynergy_properties.interaction_type === interactable_object_interaction_types.ONCE) {
this.psynergy_casted[psynergy_key] = false;
}
}
}
if (this.sprite_info) {
const interactable_object_key = this.sprite_info.getSpriteKey(this.key_name);
const interactable_object_sprite = this.data.middlelayer_group.create(0, 0, interactable_object_key);
this._sprite = interactable_object_sprite;
this.sprite.is_interactable_object = true;
this.sprite.roundPx = true;
this.sprite.base_collision_layer = this.base_collision_layer;
if (interactable_object_db.send_to_back !== undefined) {
this.sprite.send_to_back = interactable_object_db.send_to_back;
}
this.sprite.anchor.setTo(this.anchor_x ?? 0.0, this.anchor_y ?? 0.0);
this.sprite.scale.setTo(this.scale_x ?? 1.0, this.scale_y ?? 1.0);
this.sprite.x = get_centered_pos_in_px(this.tile_x_pos, map.tile_width);
this.sprite.y = get_centered_pos_in_px(this.tile_y_pos, map.tile_height);
this.sprite_info.setAnimation(this.sprite, this.key_name);
const initial_animation = interactable_object_db.initial_animation;
const anim_key = this.sprite_info.getAnimationKey(this.key_name, initial_animation);
this.sprite.animations.play(anim_key);
if (interactable_object_db.stop_animation_on_start) {
//yes, it's necessary to play before stopping it.
this.sprite.animations.stop();
}
}
if (this.entangled_by_bush) {
this.init_bush(map);
}
}
init_bush(map: Map) {
this._bush_sprite = this.data.middlelayer_group.create(0, 0, InteractableObjects.BUSH_KEY);
this._bush_sprite.roundPx = true;
this._bush_sprite.base_collision_layer = this.base_collision_layer;
this._bush_sprite.anchor.setTo(0.5, 0.75);
this._bush_sprite.frameName = InteractableObjects.BUSH_FRAME;
if (this.sprite) {
this._bush_sprite.x = this.sprite.x;
this._bush_sprite.y = this.sprite.y;
this._bush_sprite.sort_function = () => {
this.data.middlelayer_group.setChildIndex(
this._bush_sprite,
this.data.middlelayer_group.getChildIndex(this.sprite) + 1
);
};
} else {
this._bush_sprite.x = get_px_position(this.tile_x_pos, map.tile_width) + (map.tile_width >> 1);
this._bush_sprite.y = get_px_position(this.tile_y_pos, map.tile_height) + map.tile_height;
}
this._extra_sprites.push(this._bush_sprite);
}
set_color_filter() {
this.sprite.filters = [this.color_filter];
}
unset_color_filter() {
this.sprite.filters = undefined;
}
toggle_collision(enable: boolean) {
this.sprite.body.data.shapes.forEach(shape => (shape.sensor = !enable));
}
initialize_related_events(map: Map) {
if (!this.data.dbs.interactable_objects_db[this.key_name].events) {
return;
}
const position = this.get_current_position(map);
for (let i = 0; i < this.data.dbs.interactable_objects_db[this.key_name].events.length; ++i) {
let x_pos = position.x;
let y_pos = position.y;
const event_info = Object.assign(
{},
this.data.dbs.interactable_objects_db[this.key_name].events[i],
this.tile_events_info[i] ?? {}
);
x_pos += event_info.x_shift ?? 0;
y_pos += event_info.y_shift ?? 0;
const collision_layer_shift = this.tile_events_info[i]?.collision_layer_shift ?? 0;
const active_event = event_info.active ?? true;
const target_layer = this.base_collision_layer + collision_layer_shift;
switch (event_info.type) {
case interactable_object_event_types.JUMP:
this.set_jump_type_event(i, x_pos, y_pos, active_event, target_layer, map);
break;
case interactable_object_event_types.JUMP_AROUND:
this.set_jump_around_event(x_pos, y_pos, active_event, target_layer, map);
break;
case interactable_object_event_types.CLIMB:
this.set_stair_event(i, event_info, x_pos, y_pos, active_event, target_layer, map);
break;
case interactable_object_event_types.ROPE:
this.set_rope_event(event_info, x_pos, y_pos, active_event, target_layer, map);
break;
}
}
}
play(action: string, animation: string, frame_rate?: number, loop?: boolean) {
const anim_key = this.sprite_info.getAnimationKey(action, animation);
return this.sprite.animations.play(anim_key, frame_rate, loop);
}
private not_allowed_tile_test(x: number, y: number) {
for (let i = 0; i < this.not_allowed_tiles.length; ++i) {
const not_allowed_tile = this.not_allowed_tiles[i];
if (not_allowed_tile.x === x && not_allowed_tile.y === y) {
return true;
}
}
return false;
}
private set_jump_type_event(
event_index: number,
x_pos: number,
y_pos: number,
active_event: boolean,
target_layer: number,
map: Map
) {
if (this.not_allowed_tile_test(x_pos, y_pos)) return;
const this_event_location_key = LocationKey.get_key(x_pos, y_pos);
if (!(this_event_location_key in map.events)) {
map.events[this_event_location_key] = [];
}
const new_event = new JumpEvent(
this.game,
this.data,
x_pos,
y_pos,
[
reverse_directions[directions.right],
reverse_directions[directions.left],
reverse_directions[directions.down],
reverse_directions[directions.up],
],
[target_layer],
active_event,
undefined,
this,
false,
undefined
);
map.events[this_event_location_key].push(new_event);
this.insert_event(new_event.id);
const collision_layer_shift = this.tile_events_info[event_index]?.collision_layer_shift ?? 0;
new_event.collision_layer_shift_from_source = collision_layer_shift;
this.collision_change_functions.push(() => {
new_event.set_activation_collision_layers(this.base_collision_layer + collision_layer_shift);
});
if (new_event.is_active() >= 0) {
new_event.activation_collision_layers.forEach(collision_layer => {
if (collision_layer !== this.base_collision_layer) {
map.set_collision_in_tile(new_event.x, new_event.y, false, collision_layer);
}
});
}
}
private set_rope_event(
event_info: any,
x_pos: number,
y_pos: number,
active_event: boolean,
target_layer: number,
map: Map
) {
const activation_directions =
event_info.activation_directions ?? get_directions(false).map(dir => reverse_directions[dir]);
[null, ...activation_directions].forEach((direction_label: string) => {
let activation_collision_layer = target_layer;
let activation_direction = direction_label;
const direction = direction_label === null ? direction_label : directions[direction_label];
let x = x_pos;
let y = y_pos;
switch (direction) {
case directions.up:
++y;
break;
case directions.down:
--y;
break;
case directions.right:
--x;
break;
case directions.left:
++x;
break;
case null:
activation_direction = activation_directions.map(
dir => reverse_directions[get_opposite_direction(directions[dir as string])]
);
activation_collision_layer = event_info.rope_collision_layer;
break;
default:
return;
}
if (this.not_allowed_tile_test(x, y)) return;
const this_event_location_key = LocationKey.get_key(x, y);
if (!(this_event_location_key in map.events)) {
map.events[this_event_location_key] = [];
}
const new_event = new RopeEvent(
this.game,
this.data,
x,
y,
activation_direction,
activation_collision_layer,
active_event,
undefined,
false,
event_info.key_name,
this,
event_info.walk_over_rope,
event_info.dock_exit_collision_layer ?? map.collision_layer,
event_info.rope_collision_layer
);
map.events[this_event_location_key].push(new_event);
this.insert_event(new_event.id);
});
}
private set_jump_around_event(x_pos: number, y_pos: number, active_event: boolean, target_layer: number, map: Map) {
get_surroundings(x_pos, y_pos).forEach((pos, index) => {
if (this.not_allowed_tile_test(pos.x, pos.y)) return;
const this_event_location_key = LocationKey.get_key(pos.x, pos.y);
if (!(this_event_location_key in map.events)) {
map.events[this_event_location_key] = [];
}
const new_event = new JumpEvent(
this.game,
this.data,
pos.x,
pos.y,
[
reverse_directions[directions.right],
reverse_directions[directions.left],
reverse_directions[directions.down],
reverse_directions[directions.up],
][index],
[target_layer],
active_event,
undefined,
this,
false,
undefined
) as JumpEvent;
map.events[this_event_location_key].push(new_event);
this.insert_event(new_event.id);
this.collision_change_functions.push(() => {
new_event.set_activation_collision_layers(this.base_collision_layer);
});
});
}
private set_stair_event(
event_index: number,
event_info: any,
x_pos: number,
y_pos: number,
active_event: boolean,
target_layer: number,
map: Map
) {
const collision_layer_shift = this.tile_events_info[event_index]?.collision_layer_shift ?? 0;
const intermediate_collision_layer_shift =
this.tile_events_info[event_index]?.intermediate_collision_layer_shift ?? 0;
const events_data = [
{
x: x_pos,
y: y_pos + 1,
activation_directions: [reverse_directions[directions.up]],
activation_collision_layers: [this.base_collision_layer],
change_to_collision_layer: this.base_collision_layer + intermediate_collision_layer_shift,
climbing_only: false,
collision_change_function: (event: ClimbEvent) => {
event.set_activation_collision_layers(this.base_collision_layer);
event.change_collision_layer_destination(
this.base_collision_layer + intermediate_collision_layer_shift
);
},
collision_layer_shift_from_source: 0,
},
{
x: x_pos,
y: y_pos,
activation_directions: [reverse_directions[directions.down]],
activation_collision_layers: [this.base_collision_layer + intermediate_collision_layer_shift],
change_to_collision_layer: this.base_collision_layer,
climbing_only: true,
collision_change_function: (event: ClimbEvent) => {
event.set_activation_collision_layers(
this.base_collision_layer + intermediate_collision_layer_shift
);
event.change_collision_layer_destination(this.base_collision_layer);
},
collision_layer_shift_from_source: 0,
},
{
x: x_pos,
y: y_pos + event_info.top_event_y_shift + 1,
activation_directions: [reverse_directions[directions.up]],
activation_collision_layers: [this.base_collision_layer + intermediate_collision_layer_shift],
change_to_collision_layer: target_layer,
climbing_only: true,
collision_change_function: (event: ClimbEvent) => {
event.set_activation_collision_layers(
this.base_collision_layer + intermediate_collision_layer_shift
);
event.change_collision_layer_destination(this.base_collision_layer + collision_layer_shift);
},
collision_layer_shift_from_source: collision_layer_shift,
},
{
x: x_pos,
y: y_pos + event_info.top_event_y_shift,
activation_directions: [reverse_directions[directions.down]],
activation_collision_layers: [target_layer],
change_to_collision_layer: this.base_collision_layer + intermediate_collision_layer_shift,
climbing_only: false,
collision_change_function: (event: ClimbEvent) => {
event.set_activation_collision_layers(this.base_collision_layer + collision_layer_shift);
event.change_collision_layer_destination(
this.base_collision_layer + intermediate_collision_layer_shift
);
},
collision_layer_shift_from_source: collision_layer_shift,
},
];
events_data.forEach(event_data => {
const this_location_key = LocationKey.get_key(event_data.x, event_data.y);
if (!(this_location_key in map.events)) {
map.events[this_location_key] = [];
}
const new_event = new ClimbEvent(
this.game,
this.data,
event_data.x,
event_data.y,
event_data.activation_directions,
event_data.activation_collision_layers,
active_event,
undefined,
false,
undefined,
event_data.change_to_collision_layer,
this,
event_data.climbing_only,
event_info.dynamic
);
map.events[this_location_key].push(new_event);
this.insert_event(new_event.id);
new_event.collision_layer_shift_from_source = event_data.collision_layer_shift_from_source;
this.collision_change_functions.push(event_data.collision_change_function.bind(null, new_event));
});
}
toggle_active(active: boolean) {
if (active) {
this.sprite.body?.collides(this.data.collision.hero_collision_group);
this._collision_tiles_bodies.forEach(body => {
body.collides(this.data.collision.hero_collision_group);
});
if (this._blocking_stair_block) {
this._blocking_stair_block.collides(this.data.collision.hero_collision_group);
}
this.sprite.visible = true;
this._active = true;
} else {
this.sprite.body?.removeCollisionGroup(this.data.collision.hero_collision_group);
this._collision_tiles_bodies.forEach(body => {
body.removeCollisionGroup(this.data.collision.hero_collision_group);
});
if (this._blocking_stair_block) {
this._blocking_stair_block.removeCollisionGroup(this.data.collision.hero_collision_group);
}
this.sprite.visible = false;
this._active = false;
}
}
config_body() {
const db = this.data.dbs.interactable_objects_db[this.key_name];
if (db.body_radius === 0 || this.base_collision_layer < 0) return;
const collision_groups = this.data.collision.interactable_objs_collision_groups;
this.game.physics.p2.enable(this.sprite, false);
this.sprite.anchor.setTo(this.anchor_x ?? 0.0, this.anchor_y ?? 0.0); //Important to be after enabling physics
this.sprite.body.clearShapes();
let polygon;
if (db.custom_body_polygon) {
polygon = db.custom_body_polygon.map(vertex => {
return vertex.map(point => {
if (point === "sprite_width") {
point = this.sprite.width;
} else if (point === "sprite_height") {
point = this.sprite.height;
}
return point;
});
});
} else {
const width = db.body_radius << 1;
polygon = mount_collision_polygon(width, -(width >> 1), db.collision_body_bevel);
}
const x = this.sprite.body.x;
const y = this.sprite.body.y;
this.sprite.body.addPolygon(
{
optimalDecomp: false,
skipSimpleCheck: true,
removeCollinearPoints: false,
},
polygon
);
this.sprite.body.x = x;
this.sprite.body.y = y;
this.sprite.body.setCollisionGroup(collision_groups[this.base_collision_layer]);
this.sprite.body.damping = 1;
this.sprite.body.angularDamping = 1;
this.sprite.body.setZeroRotation();
this.sprite.body.fixedRotation = true;
this.sprite.body.static = true;
if (this.block_climb_collision_layer_shift !== undefined) {
this.creating_blocking_stair_block();
}
this.sprite.body.collides(this.data.collision.hero_collision_group);
}
/**
* Shifts the related events of this interactable object.
* @param event_shift_x the x shift amount.
* @param event_shift_y the y shift amount.
*/
shift_events(event_shift_x: number, event_shift_y: number) {
const object_events = this.get_events();
for (let i = 0; i < object_events.length; ++i) {
const event = object_events[i];
this.data.map.events[event.location_key] = this.data.map.events[event.location_key].filter(e => {
return e.id !== event.id;
});
if (this.data.map.events[event.location_key].length === 0) {
delete this.data.map.events[event.location_key];
}
let old_x = event.x;
let old_y = event.y;
let new_x = old_x + event_shift_x;
let new_y = old_y + event_shift_y;
event.set_position(new_x, new_y, true);
}
}
destroy_body(update_map: boolean = true) {
if (this.body) {
this.body.destroy();
if (update_map) {
this.data.map.remove_body_tile(this.tile_x_pos, this.tile_y_pos, this.base_collision_layer, this);
}
}
}
/**
* Method to be overriden.
*/
custom_unset() {}
unset(remove_from_middlelayer_group: boolean = true) {
if (this.sprite) {
this.sprite.destroy();
}
this._extra_sprites.forEach(sprite => {
if (sprite) {
sprite.destroy(true);
}
});
if (this.blocking_stair_block) {
this.blocking_stair_block.destroy();
}
this.collision_tiles_bodies.forEach(body => {
body.destroy();
});
this.toggle_enable_events.forEach(event_info => {
event_info.event.destroy();
});
if (remove_from_middlelayer_group) {
this.data.middlelayer_group.removeChild(this.sprite);
}
this.custom_unset();
}
} | the_stack |
import * as AWS from '@aws-sdk/types'
import { AssumeRoleParams, fromIni } from '@aws-sdk/credential-provider-ini'
import { fromProcess } from '@aws-sdk/credential-provider-process'
import { ParsedIniData, SharedConfigFiles } from '@aws-sdk/shared-ini-file-loader'
import { SSO } from '@aws-sdk/client-sso'
import { SSOOIDC } from '@aws-sdk/client-sso-oidc'
import { chain } from '@aws-sdk/property-provider'
import { fromInstanceMetadata, fromContainerMetadata } from '@aws-sdk/credential-provider-imds'
import { fromEnv } from '@aws-sdk/credential-provider-env'
import { Profile } from '../../shared/credentials/credentialsFile'
import { getLogger } from '../../shared/logger'
import { getStringHash } from '../../shared/utilities/textUtilities'
import { getMfaTokenFromUser } from '../credentialsCreator'
import { hasProfileProperty, resolveProviderWithCancel } from '../credentialsUtilities'
import { SSO_PROFILE_PROPERTIES, validateSsoProfile } from '../sso/sso'
import { DiskCache } from '../sso/diskCache'
import { SsoAccessTokenProvider } from '../sso/ssoAccessTokenProvider'
import { CredentialsProvider, CredentialsProviderType, CredentialsId } from './credentials'
import { SsoCredentialProvider } from './ssoCredentialProvider'
import { CredentialType } from '../../shared/telemetry/telemetry.gen'
import { ext } from '../../shared/extensionGlobals'
const SHARED_CREDENTIAL_PROPERTIES = {
AWS_ACCESS_KEY_ID: 'aws_access_key_id',
AWS_SECRET_ACCESS_KEY: 'aws_secret_access_key',
AWS_SESSION_TOKEN: 'aws_session_token',
CREDENTIAL_PROCESS: 'credential_process',
CREDENTIAL_SOURCE: 'credential_source',
REGION: 'region',
ROLE_ARN: 'role_arn',
SOURCE_PROFILE: 'source_profile',
MFA_SERIAL: 'mfa_serial',
SSO_START_URL: 'sso_start_url',
SSO_REGION: 'sso_region',
SSO_ACCOUNT_ID: 'sso_account_id',
SSO_ROLE_NAME: 'sso_role_name',
}
const CREDENTIAL_SOURCES = {
ECS_CONTAINER: 'EcsContainer',
EC2_INSTANCE_METADATA: 'Ec2InstanceMetadata',
ENVIRONMENT: 'Environment',
}
/**
* Represents one profile from the AWS Shared Credentials files.
*/
export class SharedCredentialsProvider implements CredentialsProvider {
private readonly profile: Profile
public constructor(
private readonly profileName: string,
private readonly allSharedCredentialProfiles: Map<string, Profile>
) {
const profile = this.allSharedCredentialProfiles.get(profileName)
if (!profile) {
throw new Error(`Profile not found: ${profileName}`)
}
this.profile = profile
}
public getCredentialsId(): CredentialsId {
return {
credentialSource: this.getProviderType(),
credentialTypeId: this.profileName,
}
}
public static getProviderType(): CredentialsProviderType {
return 'profile'
}
public getProviderType(): CredentialsProviderType {
return SharedCredentialsProvider.getProviderType()
}
public getTelemetryType(): CredentialType {
if (this.isSsoProfile()) {
return 'ssoProfile'
} else if (this.isCredentialSource(CREDENTIAL_SOURCES.EC2_INSTANCE_METADATA)) {
return 'ec2Metadata'
} else if (this.isCredentialSource(CREDENTIAL_SOURCES.ECS_CONTAINER)) {
return 'ecsMetatdata' // TODO: fix telemetry value typo
} else if (this.isCredentialSource(CREDENTIAL_SOURCES.ENVIRONMENT)) {
return 'other'
}
return 'staticProfile'
}
public getHashCode(): string {
return getStringHash(JSON.stringify(this.profile))
}
public getDefaultRegion(): string | undefined {
return this.profile[SHARED_CREDENTIAL_PROPERTIES.REGION]
}
public canAutoConnect(): boolean {
// check if SSO token is still valid
if (this.isSsoProfile()) {
return !!new DiskCache().loadAccessToken(this.profile[SHARED_CREDENTIAL_PROPERTIES.SSO_START_URL]!)
}
return !hasProfileProperty(this.profile, SHARED_CREDENTIAL_PROPERTIES.MFA_SERIAL)
}
public async isAvailable(): Promise<boolean> {
const validationMessage = this.validate()
if (validationMessage) {
getLogger().error(`Profile ${this.profileName} is not a valid Credential Profile: ${validationMessage}`)
return false
}
return true
}
/**
* Returns undefined if the Profile is valid, else a string indicating what is invalid
*/
public validate(): string | undefined {
const expectedProperties: string[] = []
if (hasProfileProperty(this.profile, SHARED_CREDENTIAL_PROPERTIES.CREDENTIAL_SOURCE)) {
return this.validateSourcedCredentials()
} else if (hasProfileProperty(this.profile, SHARED_CREDENTIAL_PROPERTIES.ROLE_ARN)) {
return this.validateSourceProfileChain()
} else if (hasProfileProperty(this.profile, SHARED_CREDENTIAL_PROPERTIES.CREDENTIAL_PROCESS)) {
// No validation. Don't check anything else.
return undefined
} else if (hasProfileProperty(this.profile, SHARED_CREDENTIAL_PROPERTIES.AWS_SESSION_TOKEN)) {
expectedProperties.push(
SHARED_CREDENTIAL_PROPERTIES.AWS_ACCESS_KEY_ID,
SHARED_CREDENTIAL_PROPERTIES.AWS_SECRET_ACCESS_KEY
)
} else if (hasProfileProperty(this.profile, SHARED_CREDENTIAL_PROPERTIES.AWS_ACCESS_KEY_ID)) {
expectedProperties.push(SHARED_CREDENTIAL_PROPERTIES.AWS_SECRET_ACCESS_KEY)
} else if (this.isSsoProfile()) {
return validateSsoProfile(this.profile, this.profileName)
} else {
return `Profile ${this.profileName} is not supported by the Toolkit.`
}
const missingProperties = this.getMissingProperties(expectedProperties)
if (missingProperties.length !== 0) {
return `Profile ${this.profileName} is missing properties: ${missingProperties.join(', ')}`
}
return undefined
}
/**
* Patches 'source_profile' credentials as static representations, which the SDK can handle in all cases.
*
* XXX: Returns undefined if no `source_profile` property exists. Else we would prevent the SDK from re-reading
* the shared credential files if they were to change. #1953
*
* The SDK is unable to resolve `source_profile` fields when the source profile uses SSO/MFA/credential_process.
* We can handle this resolution ourselves, giving the SDK the resolved credentials by 'pre-loading' them.
*/
private async patchSourceCredentials(): Promise<ParsedIniData | undefined> {
if (!hasProfileProperty(this.profile, SHARED_CREDENTIAL_PROPERTIES.SOURCE_PROFILE)) {
return undefined
}
const loadedCreds: ParsedIniData = {}
const source = new SharedCredentialsProvider(
this.profile[SHARED_CREDENTIAL_PROPERTIES.SOURCE_PROFILE]!,
this.allSharedCredentialProfiles
)
const creds = await source.getCredentials()
loadedCreds[this.profile[SHARED_CREDENTIAL_PROPERTIES.SOURCE_PROFILE]!] = {
[SHARED_CREDENTIAL_PROPERTIES.AWS_ACCESS_KEY_ID]: creds.accessKeyId,
[SHARED_CREDENTIAL_PROPERTIES.AWS_SECRET_ACCESS_KEY]: creds.secretAccessKey,
[SHARED_CREDENTIAL_PROPERTIES.AWS_SESSION_TOKEN]: creds.sessionToken,
}
loadedCreds[this.profileName] = {
[SHARED_CREDENTIAL_PROPERTIES.MFA_SERIAL]: source.profile[SHARED_CREDENTIAL_PROPERTIES.MFA_SERIAL],
}
loadedCreds[this.profileName] = {
...loadedCreds[this.profileName],
...this.profile,
}
return loadedCreds
}
public async getCredentials(): Promise<AWS.Credentials> {
const validationMessage = this.validate()
if (validationMessage) {
throw new Error(`Profile ${this.profileName} is not a valid Credential Profile: ${validationMessage}`)
}
const loadedCreds = await this.patchSourceCredentials()
// SSO entry point
if (this.isSsoProfile()) {
const ssoCredentialProvider = this.makeSsoProvider()
return await ssoCredentialProvider.refreshCredentials()
}
const provider = chain(this.makeCredentialsProvider(loadedCreds))
return await resolveProviderWithCancel(this.profileName, provider())
}
private getMissingProperties(propertyNames: string[]): string[] {
return propertyNames.filter(propertyName => !this.profile[propertyName])
}
/**
* Returns undefined if the Profile Chain is valid, else a string indicating what is invalid
*/
private validateSourceProfileChain(): string | undefined {
const profilesTraversed: string[] = [this.profileName]
let profile = this.profile
while (profile[SHARED_CREDENTIAL_PROPERTIES.SOURCE_PROFILE]) {
const profileName = profile[SHARED_CREDENTIAL_PROPERTIES.SOURCE_PROFILE]!
// Cycle
if (profilesTraversed.includes(profileName)) {
profilesTraversed.push(profileName)
return `Cycle detected within Shared Credentials Profiles. Reference chain: ${profilesTraversed.join(
' -> '
)}`
}
profilesTraversed.push(profileName)
// Missing reference
if (!this.allSharedCredentialProfiles.has(profileName)) {
return `Shared Credentials Profile ${profileName} not found. Reference chain: ${profilesTraversed.join(
' -> '
)}`
}
profile = this.allSharedCredentialProfiles.get(profileName)!
}
}
private validateSourcedCredentials(): string | undefined {
if (hasProfileProperty(this.profile, SHARED_CREDENTIAL_PROPERTIES.SOURCE_PROFILE)) {
return `credential_source and source_profile cannot both be set`
}
const source = this.profile[SHARED_CREDENTIAL_PROPERTIES.CREDENTIAL_SOURCE]!
if (!Object.values(CREDENTIAL_SOURCES).includes(source)) {
return `Credential source ${this.profile[SHARED_CREDENTIAL_PROPERTIES.CREDENTIAL_SOURCE]} is not supported`
}
}
private makeCredentialsProvider(loadedCreds?: ParsedIniData): AWS.CredentialProvider {
const logger = getLogger()
if (hasProfileProperty(this.profile, SHARED_CREDENTIAL_PROPERTIES.CREDENTIAL_SOURCE)) {
logger.verbose(
`Profile ${this.profileName} contains ${SHARED_CREDENTIAL_PROPERTIES.CREDENTIAL_SOURCE} - treating as Environment Credentials`
)
return this.makeSourcedCredentialsProvider()
}
if (hasProfileProperty(this.profile, SHARED_CREDENTIAL_PROPERTIES.ROLE_ARN)) {
logger.verbose(
`Profile ${this.profileName} contains ${SHARED_CREDENTIAL_PROPERTIES.ROLE_ARN} - treating as regular Shared Credentials`
)
return this.makeSharedIniFileCredentialsProvider(loadedCreds)
}
if (hasProfileProperty(this.profile, SHARED_CREDENTIAL_PROPERTIES.CREDENTIAL_PROCESS)) {
logger.verbose(
`Profile ${this.profileName} contains ${SHARED_CREDENTIAL_PROPERTIES.CREDENTIAL_PROCESS} - treating as Process Credentials`
)
return fromProcess({ profile: this.profileName })
}
if (hasProfileProperty(this.profile, SHARED_CREDENTIAL_PROPERTIES.AWS_SESSION_TOKEN)) {
logger.verbose(
`Profile ${this.profileName} contains ${SHARED_CREDENTIAL_PROPERTIES.AWS_SESSION_TOKEN} - treating as regular Shared Credentials`
)
return this.makeSharedIniFileCredentialsProvider(loadedCreds)
}
if (hasProfileProperty(this.profile, SHARED_CREDENTIAL_PROPERTIES.AWS_ACCESS_KEY_ID)) {
logger.verbose(
`Profile ${this.profileName} contains ${SHARED_CREDENTIAL_PROPERTIES.AWS_ACCESS_KEY_ID} - treating as regular Shared Credentials`
)
return this.makeSharedIniFileCredentialsProvider(loadedCreds)
}
logger.error(`Profile ${this.profileName} did not contain any supported properties`)
throw new Error(`Shared Credentials profile ${this.profileName} is not supported`)
}
private makeSharedIniFileCredentialsProvider(loadedCreds?: ParsedIniData): AWS.CredentialProvider {
const assumeRole = async (credentials: AWS.Credentials, params: AssumeRoleParams) => {
const region = this.getDefaultRegion() ?? 'us-east-1'
const stsClient = ext.toolkitClientBuilder.createStsClient(region, { credentials })
const response = await stsClient.assumeRole(params)
return {
accessKeyId: response.Credentials!.AccessKeyId!,
secretAccessKey: response.Credentials!.SecretAccessKey!,
sessionToken: response.Credentials?.SessionToken,
expiration: response.Credentials?.Expiration,
}
}
return fromIni({
profile: this.profileName,
mfaCodeProvider: async mfaSerial => await getMfaTokenFromUser(mfaSerial, this.profileName),
roleAssumer: assumeRole,
loadedConfig: loadedCreds
? Promise.resolve({
credentialsFile: loadedCreds,
configFile: {},
} as SharedConfigFiles)
: undefined,
})
}
private makeSourcedCredentialsProvider(): AWS.CredentialProvider {
if (this.isCredentialSource(CREDENTIAL_SOURCES.EC2_INSTANCE_METADATA)) {
return fromInstanceMetadata()
} else if (this.isCredentialSource(CREDENTIAL_SOURCES.ECS_CONTAINER)) {
return fromContainerMetadata()
} else if (this.isCredentialSource(CREDENTIAL_SOURCES.ENVIRONMENT)) {
return fromEnv()
}
throw new Error(
`Credential source ${this.profile[SHARED_CREDENTIAL_PROPERTIES.CREDENTIAL_SOURCE]} is not supported`
)
}
private makeSsoProvider() {
// These properties are validated before reaching this method
const ssoRegion = this.profile[SHARED_CREDENTIAL_PROPERTIES.SSO_REGION]!
const ssoUrl = this.profile[SHARED_CREDENTIAL_PROPERTIES.SSO_START_URL]!
const ssoOidcClient = new SSOOIDC({ region: ssoRegion })
const cache = new DiskCache()
const ssoAccessTokenProvider = new SsoAccessTokenProvider(ssoRegion, ssoUrl, ssoOidcClient, cache)
const ssoClient = new SSO({ region: ssoRegion })
const ssoAccount = this.profile[SHARED_CREDENTIAL_PROPERTIES.SSO_ACCOUNT_ID]!
const ssoRole = this.profile[SHARED_CREDENTIAL_PROPERTIES.SSO_ROLE_NAME]!
return new SsoCredentialProvider(ssoAccount, ssoRole, ssoClient, ssoAccessTokenProvider)
}
public isSsoProfile(): boolean {
for (const propertyName of SSO_PROFILE_PROPERTIES) {
if (hasProfileProperty(this.profile, propertyName)) {
return true
}
}
return false
}
private isCredentialSource(source: string): boolean {
if (hasProfileProperty(this.profile, SHARED_CREDENTIAL_PROPERTIES.CREDENTIAL_SOURCE)) {
return this.profile[SHARED_CREDENTIAL_PROPERTIES.CREDENTIAL_SOURCE] === source
}
return false
}
} | the_stack |
import {
Bounds,
Cursor,
CursorStackSymbol,
ElementBuilder,
ElementOperations,
Environment,
GlimmerTreeChanges,
GlimmerTreeConstruction,
LiveBlock,
Maybe,
Option,
UpdatableBlock,
ModifierInstance,
} from '@glimmer/interfaces';
import { assert, expect, Stack, symbol } from '@glimmer/util';
import {
AttrNamespace,
SimpleComment,
SimpleDocumentFragment,
SimpleElement,
SimpleNode,
SimpleText,
} from '@simple-dom/interface';
import { clear, ConcreteBounds, CursorImpl, SingleNodeBounds } from '../bounds';
import { destroy, registerDestructor } from '@glimmer/destroyable';
import { DynamicAttribute, dynamicAttribute } from './attributes/dynamic';
export interface FirstNode {
firstNode(): SimpleNode;
}
export interface LastNode {
lastNode(): SimpleNode;
}
class First {
constructor(private node: SimpleNode) {}
firstNode(): SimpleNode {
return this.node;
}
}
class Last {
constructor(private node: SimpleNode) {}
lastNode(): SimpleNode {
return this.node;
}
}
export class Fragment implements Bounds {
private bounds: Bounds;
constructor(bounds: Bounds) {
this.bounds = bounds;
}
parentElement(): SimpleElement {
return this.bounds.parentElement();
}
firstNode(): SimpleNode {
return this.bounds.firstNode();
}
lastNode(): SimpleNode {
return this.bounds.lastNode();
}
}
export const CURSOR_STACK: CursorStackSymbol = symbol('CURSOR_STACK');
export class NewElementBuilder implements ElementBuilder {
public dom: GlimmerTreeConstruction;
public updateOperations: GlimmerTreeChanges;
public constructing: Option<SimpleElement> = null;
public operations: Option<ElementOperations> = null;
private env: Environment;
[CURSOR_STACK] = new Stack<Cursor>();
private modifierStack = new Stack<Option<ModifierInstance[]>>();
private blockStack = new Stack<LiveBlock>();
static forInitialRender(env: Environment, cursor: CursorImpl) {
return new this(env, cursor.element, cursor.nextSibling).initialize();
}
static resume(env: Environment, block: UpdatableBlock): NewElementBuilder {
let parentNode = block.parentElement();
let nextSibling = block.reset(env);
let stack = new this(env, parentNode, nextSibling).initialize();
stack.pushLiveBlock(block);
return stack;
}
constructor(env: Environment, parentNode: SimpleElement, nextSibling: Option<SimpleNode>) {
this.pushElement(parentNode, nextSibling);
this.env = env;
this.dom = env.getAppendOperations();
this.updateOperations = env.getDOM();
}
protected initialize(): this {
this.pushSimpleBlock();
return this;
}
debugBlocks(): LiveBlock[] {
return this.blockStack.toArray();
}
get element(): SimpleElement {
return this[CURSOR_STACK].current!.element;
}
get nextSibling(): Option<SimpleNode> {
return this[CURSOR_STACK].current!.nextSibling;
}
get hasBlocks() {
return this.blockStack.size > 0;
}
protected block(): LiveBlock {
return expect(this.blockStack.current, 'Expected a current live block');
}
popElement() {
this[CURSOR_STACK].pop();
expect(this[CURSOR_STACK].current, "can't pop past the last element");
}
pushSimpleBlock(): LiveBlock {
return this.pushLiveBlock(new SimpleLiveBlock(this.element));
}
pushUpdatableBlock(): UpdatableBlockImpl {
return this.pushLiveBlock(new UpdatableBlockImpl(this.element));
}
pushBlockList(list: LiveBlock[]): LiveBlockList {
return this.pushLiveBlock(new LiveBlockList(this.element, list));
}
protected pushLiveBlock<T extends LiveBlock>(block: T, isRemote = false): T {
let current = this.blockStack.current;
if (current !== null) {
if (!isRemote) {
current.didAppendBounds(block);
}
}
this.__openBlock();
this.blockStack.push(block);
return block;
}
popBlock(): LiveBlock {
this.block().finalize(this);
this.__closeBlock();
return expect(this.blockStack.pop(), 'Expected popBlock to return a block');
}
__openBlock(): void {}
__closeBlock(): void {}
// todo return seems unused
openElement(tag: string): SimpleElement {
let element = this.__openElement(tag);
this.constructing = element;
return element;
}
__openElement(tag: string): SimpleElement {
return this.dom.createElement(tag, this.element);
}
flushElement(modifiers: Option<ModifierInstance[]>) {
let parent = this.element;
let element = expect(
this.constructing,
`flushElement should only be called when constructing an element`
);
this.__flushElement(parent, element);
this.constructing = null;
this.operations = null;
this.pushModifiers(modifiers);
this.pushElement(element, null);
this.didOpenElement(element);
}
__flushElement(parent: SimpleElement, constructing: SimpleElement) {
this.dom.insertBefore(parent, constructing, this.nextSibling);
}
closeElement(): Option<ModifierInstance[]> {
this.willCloseElement();
this.popElement();
return this.popModifiers();
}
pushRemoteElement(
element: SimpleElement,
guid: string,
insertBefore: Maybe<SimpleNode>
): Option<RemoteLiveBlock> {
return this.__pushRemoteElement(element, guid, insertBefore);
}
__pushRemoteElement(
element: SimpleElement,
_guid: string,
insertBefore: Maybe<SimpleNode>
): Option<RemoteLiveBlock> {
this.pushElement(element, insertBefore);
if (insertBefore === undefined) {
while (element.lastChild) {
element.removeChild(element.lastChild);
}
}
let block = new RemoteLiveBlock(element);
return this.pushLiveBlock(block, true);
}
popRemoteElement() {
this.popBlock();
this.popElement();
}
protected pushElement(element: SimpleElement, nextSibling: Maybe<SimpleNode> = null) {
this[CURSOR_STACK].push(new CursorImpl(element, nextSibling));
}
private pushModifiers(modifiers: Option<ModifierInstance[]>): void {
this.modifierStack.push(modifiers);
}
private popModifiers(): Option<ModifierInstance[]> {
return this.modifierStack.pop();
}
didAppendBounds(bounds: Bounds): Bounds {
this.block().didAppendBounds(bounds);
return bounds;
}
didAppendNode<T extends SimpleNode>(node: T): T {
this.block().didAppendNode(node);
return node;
}
didOpenElement(element: SimpleElement): SimpleElement {
this.block().openElement(element);
return element;
}
willCloseElement() {
this.block().closeElement();
}
appendText(string: string): SimpleText {
return this.didAppendNode(this.__appendText(string));
}
__appendText(text: string): SimpleText {
let { dom, element, nextSibling } = this;
let node = dom.createTextNode(text);
dom.insertBefore(element, node, nextSibling);
return node;
}
__appendNode(node: SimpleNode): SimpleNode {
this.dom.insertBefore(this.element, node, this.nextSibling);
return node;
}
__appendFragment(fragment: SimpleDocumentFragment): Bounds {
let first = fragment.firstChild;
if (first) {
let ret = new ConcreteBounds(this.element, first, fragment.lastChild!);
this.dom.insertBefore(this.element, fragment, this.nextSibling);
return ret;
} else {
return new SingleNodeBounds(this.element, this.__appendComment(''));
}
}
__appendHTML(html: string): Bounds {
return this.dom.insertHTMLBefore(this.element, this.nextSibling, html);
}
appendDynamicHTML(value: string): void {
let bounds = this.trustedContent(value);
this.didAppendBounds(bounds);
}
appendDynamicText(value: string): SimpleText {
let node = this.untrustedContent(value);
this.didAppendNode(node);
return node;
}
appendDynamicFragment(value: SimpleDocumentFragment): void {
let bounds = this.__appendFragment(value);
this.didAppendBounds(bounds);
}
appendDynamicNode(value: SimpleNode): void {
let node = this.__appendNode(value);
let bounds = new SingleNodeBounds(this.element, node);
this.didAppendBounds(bounds);
}
private trustedContent(value: string): Bounds {
return this.__appendHTML(value);
}
private untrustedContent(value: string): SimpleText {
return this.__appendText(value);
}
appendComment(string: string): SimpleComment {
return this.didAppendNode(this.__appendComment(string));
}
__appendComment(string: string): SimpleComment {
let { dom, element, nextSibling } = this;
let node = dom.createComment(string);
dom.insertBefore(element, node, nextSibling);
return node;
}
__setAttribute(name: string, value: string, namespace: Option<AttrNamespace>): void {
this.dom.setAttribute(this.constructing!, name, value, namespace);
}
__setProperty(name: string, value: unknown): void {
(this.constructing! as any)[name] = value;
}
setStaticAttribute(name: string, value: string, namespace: Option<AttrNamespace>): void {
this.__setAttribute(name, value, namespace);
}
setDynamicAttribute(
name: string,
value: unknown,
trusting: boolean,
namespace: Option<AttrNamespace>
): DynamicAttribute {
let element = this.constructing!;
let attribute = dynamicAttribute(element, name, namespace, trusting);
attribute.set(this, value, this.env);
return attribute;
}
}
export class SimpleLiveBlock implements LiveBlock {
protected first: Option<FirstNode> = null;
protected last: Option<LastNode> = null;
protected nesting = 0;
constructor(private parent: SimpleElement) {}
parentElement() {
return this.parent;
}
firstNode(): SimpleNode {
let first = expect(
this.first,
'cannot call `firstNode()` while `SimpleLiveBlock` is still initializing'
);
return first.firstNode();
}
lastNode(): SimpleNode {
let last = expect(
this.last,
'cannot call `lastNode()` while `SimpleLiveBlock` is still initializing'
);
return last.lastNode();
}
openElement(element: SimpleElement) {
this.didAppendNode(element);
this.nesting++;
}
closeElement() {
this.nesting--;
}
didAppendNode(node: SimpleNode) {
if (this.nesting !== 0) return;
if (!this.first) {
this.first = new First(node);
}
this.last = new Last(node);
}
didAppendBounds(bounds: Bounds) {
if (this.nesting !== 0) return;
if (!this.first) {
this.first = bounds;
}
this.last = bounds;
}
finalize(stack: ElementBuilder) {
if (this.first === null) {
stack.appendComment('');
}
}
}
export class RemoteLiveBlock extends SimpleLiveBlock {
constructor(parent: SimpleElement) {
super(parent);
registerDestructor(this, () => {
// In general, you only need to clear the root of a hierarchy, and should never
// need to clear any child nodes. This is an important constraint that gives us
// a strong guarantee that clearing a subtree is a single DOM operation.
//
// Because remote blocks are not normally physically nested inside of the tree
// that they are logically nested inside, we manually clear remote blocks when
// a logical parent is cleared.
//
// HOWEVER, it is currently possible for a remote block to be physically nested
// inside of the block it is logically contained inside of. This happens when
// the remote block is appended to the end of the application's entire element.
//
// The problem with that scenario is that Glimmer believes that it owns more of
// the DOM than it actually does. The code is attempting to write past the end
// of the Glimmer-managed root, but Glimmer isn't aware of that.
//
// The correct solution to that problem is for Glimmer to be aware of the end
// of the bounds that it owns, and once we make that change, this check could
// be removed.
//
// For now, a more targeted fix is to check whether the node was already removed
// and avoid clearing the node if it was. In most cases this shouldn't happen,
// so this might hide bugs where the code clears nested nodes unnecessarily,
// so we should eventually try to do the correct fix.
if (this.parentElement() === this.firstNode().parentNode) {
clear(this);
}
});
}
}
export class UpdatableBlockImpl extends SimpleLiveBlock implements UpdatableBlock {
reset(): Option<SimpleNode> {
destroy(this);
let nextSibling = clear(this);
this.first = null;
this.last = null;
this.nesting = 0;
return nextSibling;
}
}
// FIXME: All the noops in here indicate a modelling problem
export class LiveBlockList implements LiveBlock {
constructor(private readonly parent: SimpleElement, public boundList: LiveBlock[]) {
this.parent = parent;
this.boundList = boundList;
}
parentElement() {
return this.parent;
}
firstNode(): SimpleNode {
let head = expect(
this.boundList[0],
'cannot call `firstNode()` while `LiveBlockList` is still initializing'
);
return head.firstNode();
}
lastNode(): SimpleNode {
let boundList = this.boundList;
let tail = expect(
boundList[boundList.length - 1],
'cannot call `lastNode()` while `LiveBlockList` is still initializing'
);
return tail.lastNode();
}
openElement(_element: SimpleElement) {
assert(false, 'Cannot openElement directly inside a block list');
}
closeElement() {
assert(false, 'Cannot closeElement directly inside a block list');
}
didAppendNode(_node: SimpleNode) {
assert(false, 'Cannot create a new node directly inside a block list');
}
didAppendBounds(_bounds: Bounds) {}
finalize(_stack: ElementBuilder) {
assert(this.boundList.length > 0, 'boundsList cannot be empty');
}
}
export function clientBuilder(env: Environment, cursor: CursorImpl): ElementBuilder {
return NewElementBuilder.forInitialRender(env, cursor);
} | the_stack |
import {Dictionary} from "../dictionary";
import { GetBuiltinFunction } from "./builtin";
import { resolve } from "dns";
import { isString } from "util";
import { GlobalVariableResolverResults } from "./util";
import { rubyBridge } from "../global";
export type HieraSourceResolveCallback = () => Promise<number>;
export type ResolvedFunction = (args: PuppetASTObject[]) => Promise<any>;
export class EncryptedVariable
{
public raw: string;
public data: string;
public algorithm: string;
constructor(raw: string, data: string, algorithm: string)
{
this.raw = raw;
this.data = data;
this.algorithm = algorithm;
}
}
export interface Resolver
{
resolveClass(className: string, public_: boolean): Promise<PuppetASTClass>;
resolveDefinedType(definedTypeName: string, public_: boolean): Promise<PuppetASTDefinedType>;
resolveFunction(context: PuppetASTContainerContext, resolver: Resolver, name: string): Promise<ResolvedFunction>;
getGlobalVariable(name: string): any;
/*
This method should return:
GlobalVariableResolverResults.MISSING when global cannot be found
GlobalVariableResolverResults.EXISTS when it exists but hierarchy is unknown
0 and above then it exists with hierarchy as value
*/
hasGlobalVariable(name: string): number;
getNodeName(): string;
resolveHieraSource(kind: string, key: string, resolve: HieraSourceResolveCallback): Promise<void>;
registerResource(resource: PuppetASTResource): void;
}
export interface PuppetASTContainerContext
{
setProperty(kind: string, name: string, pp: PuppetASTResolvedProperty): void;
getProperty(name: string): PuppetASTResolvedProperty;
getName(): string;
}
export abstract class PuppetHint
{
public kind: string;
public message: string;
constructor(kind: string, message: string)
{
this.kind = kind;
this.message = message;
}
}
export class PuppetASTObject
{
protected _resolved: any;
private _beingResolved: boolean;
private _hints: PuppetHint[];
public toString(): string
{
return "" + this._resolved;
}
public async resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
if (this._beingResolved)
return this._resolved;
this._beingResolved = true;
try
{
this._resolved = await this._resolve(context, resolver);
}
finally
{
this._beingResolved = false;
}
return this._resolved;
}
protected carryHints(hints: PuppetHint[])
{
if (hints == null)
return;
for (const hint of hints)
{
this.hint(hint);
}
}
public async access(args: Array<PuppetASTObject>, context: PuppetASTContainerContext, resolver: Resolver): Promise<PuppetASTObject>
{
return await this._access(args, context, resolver);
}
protected async _access(args: Array<PuppetASTObject>, context: PuppetASTContainerContext, resolver: Resolver): Promise<PuppetASTObject>
{
const resolved = await this.resolve(context, resolver);
if (resolved == null)
return new PuppetASTValue(null);
const key = await args[0].resolve(context, resolver);
const value = resolved[key];
return new PuppetASTValue(value);
}
protected hint(hint: PuppetHint)
{
if (this._hints == null)
{
this._hints = [];
}
for (const existing of this._hints)
{
if (existing.toString() == hint.toString())
return;
}
this._hints.push(hint);
}
public get hints()
{
return this._hints;
}
public get hasHints()
{
return this._hints != null && this._hints.length > 0;
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
throw "Not implemented";
}
}
export class ResolveError extends Error
{
public readonly obj: PuppetASTObject;
constructor (obj: PuppetASTObject, message: string)
{
super(message);
this.obj = obj;
}
}
type PuppetASTInvokeFunctor = (invoke: PuppetASTInvoke, args: Array<any>,
context: PuppetASTContainerContext, resolver: Resolver) => Promise<any>;
export class PuppetASTReturn extends Error
{
public value: any;
constructor(value: any)
{
super();
this.value = value;
}
}
export class PuppetASTEnvironment extends PuppetASTObject implements PuppetASTContainerContext
{
public readonly name: string;
public readonly resolvedLocals: Dictionary<string, PuppetASTResolvedProperty>;
public readonly nodeDefinitions: Array<PuppetASTNode>;
constructor (name: string)
{
super();
this.name = name;
this.resolvedLocals = new Dictionary();
this.nodeDefinitions = [];
}
public addNodeDefinition(node: PuppetASTNode)
{
this.nodeDefinitions.push(node);
}
public setProperty(kind: string, name: string, pp: PuppetASTResolvedProperty): void
{
switch (kind)
{
case "local":
{
this.resolvedLocals.put(name, pp);
break;
}
}
}
public getProperty(name: string): PuppetASTResolvedProperty
{
return this.resolvedLocals.get(name);
}
public getName(): string
{
return this.name;
}
protected async tryNode(nodeName: string, context: PuppetASTContainerContext, resolver: Resolver): Promise<boolean>
{
for (const def of this.nodeDefinitions)
{
for (const entry of def.matches.entries)
{
if (entry instanceof PuppetASTRegularExpression)
{
const matcher = await entry.matcher(context, resolver);
if (matcher.test(nodeName))
{
await def.body.resolve(context, resolver);
return true;
}
}
else if (entry instanceof PuppetASTPrimitive)
{
const matches = await entry.resolve(context, resolver);
if (matches == nodeName)
{
await def.body.resolve(context, resolver);
return true;
}
}
}
}
return false;
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
const nodeName = resolver.getNodeName();
const split = nodeName.split(".");
while (true)
{
if (await this.tryNode(split.join("."), context, resolver))
{
return;
}
split.pop();
if (split.length == 0)
break;
}
// try default
for (const def of this.nodeDefinitions)
{
for (const entry of def.matches.entries)
{
if (entry instanceof PuppetASTDefault)
{
await def.body.resolve(context, resolver);
return;
}
}
}
}
}
export class PuppetASTInvoke extends PuppetASTObject
{
public readonly functor: PuppetASTQualifiedName;
public readonly args: PuppetASTList;
private static readonly InvokeFunctions: any =
{
};
constructor(args: Array<PuppetASTObject>)
{
super();
const obj: OrderedDictionary = <OrderedDictionary>args[0];
this.functor = obj.get("functor");
this.args = obj.get("args");
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
const functorName: string = await this.functor.resolve(context, resolver);
const builtin = GetBuiltinFunction(functorName);
if (builtin == null)
{
console.log("Warning: Unknown function: " + functorName);
return null;
}
const resolvedArgs: any = [];
for (const arg of this.args.entries)
{
resolvedArgs.push(await arg.resolve(context, resolver))
}
return await builtin(this, context, resolver, resolvedArgs);
}
public static Create(args: Array<PuppetASTObject>)
{
return new PuppetASTInvoke(args);
}
}
export class PuppetASTUnknown extends PuppetASTObject
{
public readonly kind: string;
public readonly args: Array<PuppetASTObject>;
constructor(kind: string, args: Array<PuppetASTObject>)
{
super();
this.kind = kind;
this.args = args;
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
throw new ResolveError(this, "Unknown object of kind " + this.kind);
}
public toString(): string
{
return this.kind;
}
}
export class PuppetASTIgnored extends PuppetASTObject
{
public readonly what: string;
constructor(what: string, args: Array<PuppetASTObject>)
{
super();
this.what = what;
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
console.log("Entry ignored: " + this.what);
}
public static Create(what: string)
{
return function (args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTIgnored(what, args);
}
}
}
export class PuppetASTAccess extends PuppetASTObject
{
public readonly what: PuppetASTObject;
public readonly values: Array<PuppetASTObject>;
private accessOf: PuppetASTObject;
constructor(args: Array<PuppetASTObject>)
{
super();
this.what = args[0];
args.splice(0, 1);
this.values = args;
}
public toString(): string
{
return this.accessOf.toString();
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
this.accessOf = await this.what.access(this.values, context, resolver);
if (this.accessOf == null)
return null;
return await this.accessOf.resolve(context, resolver);
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTAccess(args);
}
}
export class PuppetASTSwitch extends PuppetASTObject
{
public readonly variable: PuppetASTObject;
public readonly over: PuppetASTList;
constructor(args: Array<PuppetASTObject>)
{
super();
this.variable = args[0];
this.over = (<PuppetASTList>args[1]);
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
const resolvedValue = await this.variable.resolve(context, resolver);
let default_ = null;
for (const entry of this.over.entries)
{
if (!(entry instanceof PuppetASTKeyedEntry))
continue;
const keyed = <PuppetASTKeyedEntry>entry;
if (keyed.key instanceof PuppetASTDefault)
{
default_ = await keyed.value.resolve(context, resolver);
}
else if (keyed.key instanceof PuppetASTRegularExpression)
{
if (await keyed.key.matchesValue(context, resolver, resolvedValue))
{
return await keyed.value.resolve(context, resolver);
}
}
else
{
const key = await keyed.key.resolve(context, resolver);
if (key == resolvedValue)
{
return await keyed.value.resolve(context, resolver);
}
}
}
if (default_ == null)
{
throw new ResolveError(this, "Failed to resolve switch: default value was hit and not provided")
}
return default_;
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTSwitch(args);
}
}
export class PuppetASTCase extends PuppetASTObject
{
public readonly variable: PuppetASTObject;
public readonly cases: PuppetASTList;
constructor(args: Array<PuppetASTObject>)
{
super();
this.variable = args[0];
this.cases = (<PuppetASTList>args[1]);
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
const resolvedValue = await this.variable.resolve(context, resolver);
let default_: PuppetASTObject = null;
for (const entry of this.cases.entries)
{
const obj: OrderedDictionary = <OrderedDictionary>entry;
const when: PuppetASTList = obj.get("when");
const then: PuppetASTObject = obj.get("then");
let matches = false;
for (const val of when.entries)
{
if (val instanceof PuppetASTDefault)
{
default_ = then;
continue;
}
else if (val instanceof PuppetASTRegularExpression)
{
matches = await val.matchesValue(context, resolver, resolvedValue);
if (matches)
break;
}
const possibleValue = await val.resolve(context, resolver);
if (possibleValue == resolvedValue)
{
matches = true;
break;
}
}
if (matches)
{
return await then.resolve(context, resolver);
}
}
if (default_ == null)
{
throw new ResolveError(this, "Failed to resolve switch: default value was hit and not provided")
}
return await default_.resolve(context, resolver);
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTCase(args);
}
}
export class PuppetASTParenthesis extends PuppetASTObject
{
public readonly condition: PuppetASTObject;
constructor(args: Array<PuppetASTObject>)
{
super();
this.condition = args[0];
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
return await this.condition.resolve(context, resolver);
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTParenthesis(args);
}
}
export class PuppetASTQualifiedName extends PuppetASTObject
{
public readonly value: PuppetASTObject;
constructor(args: Array<PuppetASTObject>)
{
super();
this.value = args[0];
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
return await this.value.resolve(context, resolver);
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTQualifiedName(args);
}
}
export class PuppetASTHash extends PuppetASTObject
{
public readonly dict: any;
public readonly args: Array<PuppetASTKeyedEntry>;
constructor(args: Array<PuppetASTObject>)
{
super();
this.dict = {};
this.args = <Array<PuppetASTKeyedEntry>>args;
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
for (const arg of this.args)
{
await arg.resolve(context, resolver)
const key = await arg.key.resolve(context, resolver);
const value = await arg.value.resolve(context, resolver);
this.dict[key] = value;
}
return this.dict;
}
protected async _access(args: Array<PuppetASTObject>, context: PuppetASTContainerContext, resolver: Resolver): Promise<PuppetASTObject>
{
const key = await args[0].resolve(context, resolver);
const value = this.dict[key];
return new PuppetASTValue(value);
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTHash(args);
}
}
type PuppetASTConditionTest = (a: any, b: any) => boolean;
export class PuppetASTCondition extends PuppetASTObject
{
public readonly test: PuppetASTConditionTest;
public readonly a: PuppetASTObject;
public readonly b: PuppetASTObject;
constructor(test: PuppetASTConditionTest, args: Array<PuppetASTObject>)
{
super();
this.test = test;
this.a = args[0];
this.b = args[1];
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
const resolvedA = await this.a.resolve(context, resolver);
const resolvedB = await this.b.resolve(context, resolver);
return this.test(resolvedA, resolvedB);
}
public static Less(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTCondition((a: any, b: any) => {
return a < b;
}, args);
}
public static More(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTCondition((a: any, b: any) => {
return a > b;
}, args);
}
public static MoreOrEqual(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTCondition((a: any, b: any) => {
return a >= b;
}, args);
}
public static LessOrEqual(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTCondition((a: any, b: any) => {
return a <= b;
}, args);
}
public static Equal(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTCondition((a: any, b: any) => {
return a == b;
}, args);
}
public static NotEqual(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTCondition((a: any, b: any) => {
return a != b;
}, args);
}
public static In(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTCondition((a: any, b: any) =>
{
if (b == null)
return false;
return a in b;
}, args);
}
}
type PuppetASTMathTest = (a: number, b: number) => number;
export class PuppetASTMath extends PuppetASTObject
{
public readonly test: PuppetASTMathTest;
public readonly a: PuppetASTObject;
public readonly b: PuppetASTObject;
constructor(test: PuppetASTMathTest, args: Array<PuppetASTObject>)
{
super();
this.test = test;
this.a = args[0];
this.b = args[1];
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
const resolvedA = await this.a.resolve(context, resolver);
const resolvedB = await this.b.resolve(context, resolver);
return this.test(resolvedA, resolvedB);
}
public static Plus(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTMath((a: any, b: any) => {
return a + b;
}, args);
}
public static Minus(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTMath((a: any, b: any) => {
return a - b;
}, args);
}
public static Multiply(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTMath((a: any, b: any) => {
return a * b;
}, args);
}
public static Divide(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTMath((a: any, b: any) => {
return a / b;
}, args);
}
}
export class PuppetASTAndCondition extends PuppetASTObject
{
public readonly a: PuppetASTObject;
public readonly b: PuppetASTObject;
constructor(args: Array<PuppetASTObject>)
{
super();
this.a = args[0];
this.b = args[1];
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
if (!await this.a.resolve(context, resolver))
return false;
if (!await this.b.resolve(context, resolver))
return false;
return true;
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTAndCondition(args);
}
}
export class PuppetASTOrCondition extends PuppetASTObject
{
public readonly a: PuppetASTObject;
public readonly b: PuppetASTObject;
constructor(args: Array<PuppetASTObject>)
{
super();
this.a = args[0];
this.b = args[1];
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
if (await this.a.resolve(context, resolver))
return true;
if (await this.b.resolve(context, resolver))
return true;
return false;
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTOrCondition(args);
}
}
export class PuppetASTNot extends PuppetASTObject
{
public readonly value: PuppetASTObject;
constructor(args: Array<PuppetASTObject>)
{
super();
this.value = args[0];
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
const v = await this.value.resolve(context, resolver);
return !v;
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTNot(args);
}
}
export class PuppetASTIf extends PuppetASTObject
{
public readonly test: PuppetASTObject;
public readonly then: PuppetASTObject;
public readonly else: PuppetASTObject;
constructor(args: Array<PuppetASTObject>)
{
super();
const obj: OrderedDictionary = <OrderedDictionary>args[0];
this.test = obj.get("test");
this.then = obj.get("then");
this.else = obj.get("else");
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
const v = await this.test.resolve(context, resolver);
if (v)
{
return await this.then.resolve(context, resolver);
}
if (this.else)
return await this.else.resolve(context, resolver);
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTIf(args);
}
}
export class PuppetASTUnless extends PuppetASTObject
{
public readonly test: PuppetASTObject;
public readonly then: PuppetASTObject;
public readonly else: PuppetASTObject;
constructor(args: Array<PuppetASTObject>)
{
super();
const obj: OrderedDictionary = <OrderedDictionary>args[0];
this.test = obj.get("test");
this.then = obj.get("then");
this.else = obj.get("else");
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
const v = await this.test.resolve(context, resolver);
if (v)
{
return await this.then.resolve(context, resolver);
}
if (this.else)
return await this.else.resolve(context, resolver);
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTUnless(args);
}
}
export class PuppetASTDefault extends PuppetASTObject
{
constructor(args: Array<PuppetASTObject>)
{
super();
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
return "default";
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTDefault(args);
}
}
export class PuppetASTNOP extends PuppetASTObject
{
constructor(args: Array<PuppetASTObject>)
{
super();
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
// do nothing
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTNOP(args);
}
}
export class PuppetASTKeyedEntry extends PuppetASTObject
{
public readonly key: PuppetASTObject;
public readonly value: PuppetASTObject;
constructor(args: Array<PuppetASTObject>)
{
super();
this.key = args[0];
this.value = args[1];
}
public toString(): string
{
return this.key.toString() + "=>" + this.value.toString();
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
return this;
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTKeyedEntry(args);
}
}
export class PuppetASTApplyOrder extends PuppetASTObject
{
public readonly first: PuppetASTObject;
public readonly second: PuppetASTObject;
constructor(args: Array<PuppetASTObject>)
{
super();
this.first = args[0];
this.second = args[1];
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
await this.first.resolve(context, resolver);
await this.second.resolve(context, resolver);
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTApplyOrder(args);
}
}
export class PuppetASTNotifyOrder extends PuppetASTObject
{
public readonly first: PuppetASTObject;
public readonly second: PuppetASTObject;
constructor(args: Array<PuppetASTObject>)
{
super();
this.first = args[0];
this.second = args[1];
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
await this.first.resolve(context, resolver);
await this.second.resolve(context, resolver);
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTNotifyOrder(args);
}
}
export class PuppetASTPrimitive extends PuppetASTObject
{
public readonly value: any;
constructor(value: any)
{
super();
this.value = value;
}
public toString(): string
{
return "" + this.value;
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
return this.value;
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTPrimitive(args);
}
}
export class PuppetASTRegularExpression extends PuppetASTObject
{
public readonly value: PuppetASTObject;
constructor(args: Array<PuppetASTObject>)
{
super();
this.value = args[0];
}
public toString(): string
{
return "" + this.value;
}
public async matcher(context: PuppetASTContainerContext, resolver: Resolver): Promise<RegExp>
{
return new RegExp(await this.resolve(context, resolver));
}
public async matches(context: PuppetASTContainerContext, resolver: Resolver, object: PuppetASTObject): Promise<boolean>
{
const re = new RegExp(await this.resolve(context, resolver));
const value = await object.resolve(context, resolver);
return re.test(value);
}
public async matchesValue(context: PuppetASTContainerContext, resolver: Resolver, value: string): Promise<boolean>
{
const re = new RegExp(await this.resolve(context, resolver));
return re.test(value);
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
return await this.value.resolve(context, resolver);
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTRegularExpression(args);
}
}
export class PuppetASTRegularExpressionCheck extends PuppetASTObject
{
public readonly variable: PuppetASTObject;
public readonly regexp: PuppetASTObject;
constructor(args: Array<PuppetASTObject>)
{
super();
this.variable = args[0];
this.regexp = args[1];
}
public toString(): string
{
return "" + this.regexp.toString();
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
if (this.regexp instanceof PuppetASTRegularExpression)
{
return await this.regexp.matches(context, resolver, this.variable);
}
// wrap
const wrap = new PuppetASTRegularExpression([this.regexp]);
return await wrap.matches(context, resolver, this.variable);
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTRegularExpressionCheck(args);
}
}
export class PuppetASTList extends PuppetASTObject
{
public readonly entries: Array<PuppetASTObject>;
constructor(args: Array<PuppetASTObject>)
{
super();
this.entries = args;
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
for (const entry of this.entries)
{
await entry.resolve(context, resolver);
}
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTList(args);
}
}
export class PuppetASTArray extends PuppetASTObject
{
public readonly entries: Array<PuppetASTObject>;
constructor(args: Array<PuppetASTObject>)
{
super();
this.entries = args;
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
const result: any[] = [];
for (const entry of this.entries)
{
const value = await entry.resolve(context, resolver);
result.push(value);
}
return result;
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTArray(args);
}
}
export class PuppetASTTypeOf extends PuppetASTObject
{
public readonly type: PuppetASTObject;
public readonly args: Array<PuppetASTObject>;
constructor(type: PuppetASTType, args: Array<PuppetASTObject>)
{
super();
this.type = type;
this.args = args;
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
return this;
}
}
export class PuppetASTClassOf extends PuppetASTObject
{
public readonly className: string;
constructor(className: string)
{
super();
this.className = className;
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
try
{
return await resolver.resolveClass(this.className, false) != null;
}
catch (e)
{
return false;
}
}
}
export class PuppetASTType extends PuppetASTObject
{
public readonly type: PuppetASTObject;
constructor(args: Array<PuppetASTObject>)
{
super();
this.type = args[0];
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
return await this.type.resolve(context, resolver)
}
protected async _access(args: Array<PuppetASTObject>, context: PuppetASTContainerContext, resolver: Resolver): Promise<PuppetASTObject>
{
const type = await this.type.resolve(context, resolver);
switch (type)
{
case "Class":
{
const className = await args[0].resolve(context, resolver);
return new PuppetASTClassOf(className);
}
default:
{
return new PuppetASTTypeOf(this, args);
}
}
}
public toString(): string
{
return "Type[" + this.type.toString() + "]";
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTType(args);
}
}
export class PuppetASTToString extends PuppetASTObject
{
public readonly obj: PuppetASTObject;
constructor(args: Array<PuppetASTObject>)
{
super();
this.obj = args[0];
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
const result = "" + await this.obj.resolve(context, resolver)
this.carryHints(this.obj.hints);
return result;
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTToString(args);
}
}
export class PuppetASTConcat extends PuppetASTObject
{
public readonly entries: Array<PuppetASTObject>;
constructor(args: Array<PuppetASTObject>)
{
super();
this.entries = args;
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
const resolved = [];
for (const entry of this.entries)
{
resolved.push(await entry.resolve(context, resolver));
this.carryHints(entry.hints);
}
return resolved.join("");
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTConcat(args);
}
}
export class PuppetASTNode extends PuppetASTObject
{
public matches: PuppetASTList;
public body: PuppetASTObject;
constructor(args: Array<PuppetASTObject>)
{
super();
const arg = <OrderedDictionary>args[0];
this.matches = arg.get("matches");
this.body = arg.get("body");
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
if (context instanceof PuppetASTEnvironment)
{
context.addNodeDefinition(this);
}
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTNode(args);
}
}
export class PuppetASTBlock extends PuppetASTObject
{
public entries: Array<PuppetASTObject>;
constructor(args: Array<PuppetASTObject>)
{
super();
this.entries = args;
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
for (const entry of this.entries)
{
await entry.resolve(context, resolver);
}
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTBlock(args);
}
}
export class PuppetASTFunctionCall implements PuppetASTContainerContext
{
private readonly name: string;
private readonly body: PuppetASTList;
private readonly params: OrderedDictionary;
public readonly args: Array<PuppetASTObject>;
public readonly resolvedLocals: Dictionary<string, PuppetASTResolvedProperty>;
constructor(name: string, body: PuppetASTList, params: OrderedDictionary, args: PuppetASTObject[])
{
this.name = name;
this.body = body;
this.params = params || new OrderedDictionary();
this.args = args;
this.resolvedLocals = new Dictionary();
}
public async apply(caller: PuppetASTObject, resolver: Resolver): Promise<any>
{
const passedArgs = this.args.length;
const haveArgs = this.params.length;
if (passedArgs > haveArgs)
{
throw new ResolveError(caller, "Passed way too many arguments");
}
for (let i = 0; i < passedArgs; i++)
{
const arg = this.args[i];
const name = this.params.keys[i];
const param: OrderedDictionary = this.params.get(name);
const pp = new PuppetASTResolvedProperty();
if (param.get("type") != null)
pp.type = param.get("type");
pp.value = await arg.resolve(this, resolver);
this.setProperty("local", name, pp)
}
for (let i = passedArgs; i < haveArgs; i++)
{
const name = this.params.keys[i];
const param: OrderedDictionary = this.params.get(name);
if (!param.has("value"))
throw new ResolveError(caller, "Param " + name + " is has no default value and was not provided");
const pp = new PuppetASTResolvedProperty();
if (param.get("type") != null)
pp.type = param.get("type");
const value: PuppetASTObject = param.get("value");
pp.value = await value.resolve(this, resolver);
this.setProperty("local", name, pp)
}
try
{
await this.body.resolve(this, resolver);
}
catch (e)
{
if (e instanceof PuppetASTReturn)
{
return e.value;
}
else
{
throw e;
}
}
return null;
}
public setProperty(kind: string, name: string, pp: PuppetASTResolvedProperty): void
{
switch (kind)
{
case "local":
{
this.resolvedLocals.put(name, pp);
break;
}
}
}
public getProperty(name: string): PuppetASTResolvedProperty
{
return this.resolvedLocals.get(name);
}
public getName(): string
{
return this.name;
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTFunction(args);
}
}
export class PuppetASTFunction extends PuppetASTObject
{
private readonly name: PuppetASTObject;
private readonly body: PuppetASTList;
private readonly params: OrderedDictionary;
public readonly args: Array<PuppetASTObject>;
constructor(args: Array<PuppetASTObject>)
{
super();
const _args: OrderedDictionary = <OrderedDictionary>args[0];
this.name = _args.get("name");
this.body = _args.get("body");
this.params = _args.get("params");
}
public async apply(context: PuppetASTContainerContext, resolver: Resolver, args: PuppetASTObject[]): Promise<any>
{
const name = await this.name.resolve(context, resolver);
const call = new PuppetASTFunctionCall(name, this.body, this.params, args);
return await call.apply(this, resolver);
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTFunction(args);
}
}
export class PuppetASTCall extends PuppetASTObject
{
public readonly args: Array<PuppetASTObject>;
public readonly functor: PuppetASTObject;
public readonly functorArgs: PuppetASTList;
constructor(args: Array<PuppetASTObject>)
{
super();
const args_: OrderedDictionary = <OrderedDictionary>args[0];
this.functor = args_.get("functor");
this.functorArgs = args_.get("args");
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
const functorName = await this.functor.resolve(context, resolver);
const builtin = GetBuiltinFunction(functorName);
if (builtin != null)
{
return await builtin(this, context, resolver, this.functorArgs.entries);
}
const function_ = await resolver.resolveFunction(context, resolver, functorName);
if (function_ != null)
{
try
{
return await function_(this.functorArgs.entries);
}
catch (e)
{
if (e.code == 404)
{
this.hint(new PuppetHintFunctionNotFound(functorName));
return null;
}
this.hint(new PuppetHintVariableNotFound(functorName));
return null;
}
}
this.hint(new PuppetHintFunctionNotFound(functorName));
return null;
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTCall(args);
}
}
export class PuppetASTResolvedProperty
{
private _hasType: boolean;
private _type: any;
private _hierarchy: number;
private _hasValue: boolean;
private _value: any;
private _hasError: boolean;
private _error: any;
private _hints: Array<PuppetHint>;
constructor()
{
this._hints = [];
this._hasType = false;
this._hasValue = false;
this._hasError = false;
this._hierarchy = GlobalVariableResolverResults.MISSING;
}
public set type(value: any)
{
this._type = value;
this._hasType = true;
}
public set value(value: any)
{
this._value = value;
this._hasValue = true;
}
public set error(value: any)
{
this._error = value;
this._hasError = true;
}
public hasHint(hint: PuppetHint): boolean
{
for (const existing of this._hints)
{
if (existing.toString() == hint.toString())
return true;
}
return false;
}
public addHints(value: Array<PuppetHint>)
{
if (value == null)
return;
for (const hint of value)
{
if (this.hasHint(hint))
continue;
this._hints.push(hint);
}
}
public get hierarchy(): number
{
return this._hierarchy;
}
public set hierarchy(value: number)
{
this._hierarchy = value;
}
public get type(): any
{
return this._type;
}
public get value(): any
{
return this._value;
}
public get error(): any
{
return this._error;
}
public get hints(): Array<any>
{
return this._hints;
}
public get hasType(): boolean
{
return this._hasType;
}
public get hasValue(): boolean
{
return this._hasValue;
}
public get hasError(): boolean
{
return this._hasError;
}
public get hasHints(): boolean
{
return this._hints != null && this._hints.length > 0;
}
}
export class PuppetASTClass extends PuppetASTObject implements PuppetASTContainerContext
{
public readonly name: string;
public parentName: string;
public readonly params: OrderedDictionary;
public readonly body: PuppetASTObject;
public readonly parent: PuppetASTPrimitive;
private _options: Dictionary<string, any>;
private _public: boolean;
private _resolvedParent: PuppetASTClass;
public readonly resolvedLocals: Dictionary<string, PuppetASTResolvedProperty>;
public readonly resolvedFields: Dictionary<string, PuppetASTResolvedProperty>;
constructor(args: Array<PuppetASTObject>)
{
super();
const metaData: OrderedDictionary = <OrderedDictionary>args[0];
this._public = false;
this.name = metaData.get("name").value;
this.body = metaData.get("body");
this.params = metaData.get("params") || new OrderedDictionary();
this.parent = metaData.get("parent");
this._resolvedParent = null;
this.resolvedLocals = new Dictionary();
this.resolvedFields = new Dictionary();
}
public setOption(key: string, value: any)
{
if (this._options == null)
{
this._options = new Dictionary();
}
this._options.put(key, value);
}
public get options(): Array<string>
{
return this._options != null ? this._options.getKeys() : [];
}
public getOption(key: string)
{
return this._options != null ? this._options.get(key) : null;
}
public markPublic()
{
this._public = true;
}
public isPublic()
{
return this._public;
}
public get resolvedParent(): PuppetASTClass
{
return this._resolvedParent;
}
public getResolvedProperty(name: string): PuppetASTResolvedProperty
{
if (this.resolvedLocals.has(name))
return this.resolvedLocals.get(name);
if (this._resolvedParent)
return this._resolvedParent.getResolvedProperty(name);
return null;
}
public getProperty(name: string): PuppetASTResolvedProperty
{
return this.getResolvedProperty(name);
}
public getName(): string
{
return this.name;
}
public setResolvedProperty(name: string, pp: PuppetASTResolvedProperty)
{
this.resolvedLocals.put(name, pp);
}
public setProperty(kind: string, name: string, pp: PuppetASTResolvedProperty)
{
switch (kind)
{
case "local":
{
this.setResolvedProperty(name, pp);
break;
}
case "field":
{
this.resolvedFields.put(name, pp);
break;
}
}
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
if (this.parent)
{
console.log("Resolving parent for class " + this.name);
this.parentName = await this.parent.resolve(context, resolver);
this._resolvedParent = await resolver.resolveClass(this.parentName, false);
if (this._resolvedParent && this._resolvedParent.hasHints)
{
this.carryHints(this._resolvedParent.hints);
}
}
console.log("Resolving class " + this.name);
{
const pp = new PuppetASTResolvedProperty();
pp.value = this.name;
this.resolvedLocals.put("title", pp);
this.resolvedLocals.put("name", pp);
}
for (const paramName of this.params.keys)
{
const param: OrderedDictionary = this.params.get(paramName);
let type = param.get("type");
if (type instanceof PuppetASTObject)
{
try
{
type = await type.resolve(this, resolver);
}
catch (e)
{
console.log("Failed to resolve type for param " + paramName + " (" + type.constructor.name + "): " + e);
type = null;
}
}
const globalParamName = this.name + "::" + paramName;
const has = resolver.hasGlobalVariable(globalParamName);
if (has != GlobalVariableResolverResults.MISSING)
{
const globalParamValue = resolver.getGlobalVariable(globalParamName);
const pp = new PuppetASTResolvedProperty();
pp.value = globalParamValue;
if (type != null)
pp.type = type;
pp.hierarchy = has;
this.resolvedLocals.put(paramName, pp);
this.resolvedFields.put(paramName, pp);
}
else
{
const value = param.get("value");
const pp = new PuppetASTResolvedProperty();
let result: any;
let hasValue: boolean = false;
if (value instanceof PuppetASTObject)
{
try
{
result = await value.resolve(this, resolver);
hasValue = true;
}
catch (e)
{
console.log("Failed to resolve param " + paramName + " (" + value.constructor.name + "): " + e);
const pp = new PuppetASTResolvedProperty();
if (type != null)
pp.type = type;
pp.error = e;
pp.addHints(value.hints);
this.resolvedLocals.put(paramName, pp);
this.resolvedFields.put(paramName, pp);
continue;
}
}
if (hasValue)
{
pp.addHints(value.hints);
pp.value = result;
}
if (type != null)
pp.type = type;
this.resolvedLocals.put(paramName, pp);
this.resolvedFields.put(paramName, pp);
}
}
if (this.body)
{
try
{
await this.body.resolve(this, resolver);
}
catch (e)
{
if (e instanceof ResolveError)
{
this.hint(new PuppetHintBodyCompilationError("Failed to resolve class body: " + e.message));
console.log("Failed to resolve class body: " + e.message);
}
else
{
throw e;
}
}
}
console.log("Class " + this.name + " has been resolved");
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTClass(args);
}
}
export class PuppetASTResource extends PuppetASTObject implements PuppetASTContainerContext
{
private readonly ops: PuppetASTList;
private readonly title: PuppetASTObject;
private _resolvedTitle: string;
private _definedType: PuppetASTDefinedType;
private _hierarchy: number;
private _options: Dictionary<string, any>;
public readonly resolvedFields: Dictionary<string, PuppetASTResolvedProperty>;
public readonly resolvedLocals: Dictionary<string, PuppetASTResolvedProperty>;
constructor(args: OrderedDictionary, definedType: PuppetASTDefinedType)
{
super();
this._definedType = definedType;
this.ops = args.get("ops");
this.title = args.get("title");
this.resolvedFields = new Dictionary();
this.resolvedLocals = new Dictionary();
this._hierarchy = GlobalVariableResolverResults.MISSING;
}
public set hierarchy(value: number)
{
this._hierarchy = value;
}
public get hierarchy(): number
{
return this._hierarchy;
}
public setOption(key: string, value: any)
{
if (this._options == null)
{
this._options = new Dictionary();
}
this._options.put(key, value);
}
public get definedType(): PuppetASTDefinedType
{
return this._definedType;
}
public get options(): Array<string>
{
return this._options != null ? this._options.getKeys() : [];
}
public getOption(key: string)
{
return this._options != null ? this._options.get(key) : null;
}
public setProperty(kind: string, name: string, pp: PuppetASTResolvedProperty): void
{
switch (kind)
{
case "local":
{
this.resolvedLocals.put(name, pp);
break;
}
case "field":
{
this.resolvedFields.put(name, pp);
break;
}
}
}
public getResolvedProperty(name: string): PuppetASTResolvedProperty
{
if (this.resolvedLocals.has(name))
return this.resolvedLocals.get(name);
return null;
}
public getProperty(name: string): PuppetASTResolvedProperty
{
return this.getResolvedProperty(name);
}
public getName(): string
{
return this._resolvedTitle;
}
public getTitle(): string
{
return this._resolvedTitle;
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
await this.title.resolve(this, resolver);
this._resolvedTitle = this.title.toString();
this.resolvedFields.clear();
this.resolvedLocals.clear();
console.log("Resolving defined type " + this._definedType.name + "/" + this._resolvedTitle);
{
const pp = new PuppetASTResolvedProperty();
pp.value = this._resolvedTitle;
pp.type = "string";
this.setProperty("local", "title", pp);
this.setProperty("local", "name", pp);
}
console.log("Defined type has been resolved");
try
{
const suppliedProperties: any = {};
if (this.ops instanceof PuppetASTList)
{
for (const entry of this.ops.entries)
{
if (!(entry instanceof PuppetASTKeyedEntry))
continue;
const keyed = <PuppetASTKeyedEntry>entry;
const key = await keyed.key.resolve(this, resolver);
const value = await keyed.value.resolve(this, resolver);
suppliedProperties[key] = value;
}
}
for (const paramName of this._definedType.params.keys)
{
const param: OrderedDictionary = this._definedType.params.get(paramName);
let type = param.get("type");
const value = param.get("value");
if (type instanceof PuppetASTObject)
{
try
{
type = await type.resolve(this, resolver);
}
catch (e)
{
console.log("Failed to resolve type for param " + paramName + " (" + type.constructor.name + "): " + e);
type = null;
}
}
const pp = new PuppetASTResolvedProperty();
if (suppliedProperties.hasOwnProperty(paramName))
{
pp.value = suppliedProperties[paramName];
pp.hierarchy = this._hierarchy;
}
else
{
let hasValue: boolean = false;
let result: any = null;
if (value instanceof PuppetASTObject)
{
try
{
result = await value.resolve(this, resolver);
hasValue = true;
}
catch (e)
{
console.log("Failed to resolve param " + paramName + " (" + value.constructor.name + "): " + e);
const pp = new PuppetASTResolvedProperty();
if (type != null)
pp.type = type;
pp.error = e;
pp.addHints(value.hints);
this.setProperty("local", paramName, pp);
this.setProperty("field", paramName, pp);
continue;
}
}
if (hasValue)
{
pp.addHints(value.hints);
pp.value = result;
}
}
if (type != null)
pp.type = type;
this.setProperty("local", paramName, pp);
this.setProperty("field", paramName, pp);
}
/*
if (this._definedType.body)
{
try
{
await this._definedType.body.resolve(context, resolver);
}
catch (e)
{
if (e instanceof ResolveError)
{
this.hint(new PuppetHintBodyCompilationError("Failed to resolve resource body: " + e.message));
console.log("Failed to resolve resource body: " + e.message);
}
else
{
throw e;
}
}
}
*/
}
finally
{
await resolver.registerResource(this);
}
}
}
export class PuppetASTResourcesDeclaration extends PuppetASTObject
{
public readonly bodies: PuppetASTList;
public readonly type: PuppetASTQualifiedName;
public readonly entries: Dictionary<string, PuppetASTResource>;
private _hierarchy: number;
private _public: boolean;
constructor(args: Array<PuppetASTObject>, _public?: boolean)
{
super();
this._hierarchy = GlobalVariableResolverResults.MISSING;
this._public = _public;
const values: OrderedDictionary = <OrderedDictionary>args[0];
this.bodies = values.get("bodies");
this.type = values.get("type");
this.entries = new Dictionary();
}
public set hierarchy(value: number)
{
this._hierarchy = value;
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
const definedTypeName = await this.type.resolve(context, resolver);
switch (definedTypeName)
{
case "class":
{
// https://puppet.com/docs/puppet/5.3/lang_classes.html#using-resource-like-declarations
// TODO
return;
}
case "anchor":
case "file":
case "package":
{
// ignored;
return;
}
}
const definedType = await resolver.resolveDefinedType(definedTypeName, this._public)
if (definedType == null)
return;
for (const body of this.bodies.entries)
{
const resource = new PuppetASTResource(<OrderedDictionary>(body), definedType);
resource.hierarchy = this._hierarchy;
await resource.resolve(context, resolver);
this.entries.put(resource.getTitle(), resource);
}
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTResourcesDeclaration(args);
}
}
export class PuppetASTDefinedType extends PuppetASTObject
{
public readonly name: string;
public readonly params: OrderedDictionary;
public readonly body: PuppetASTObject;
private _public: boolean;
public getName(): string
{
return this.name;
}
public isPublic()
{
return this._public;
}
public markPublic()
{
this._public = true;
}
constructor(args: Array<PuppetASTObject>)
{
super();
const metaData: OrderedDictionary = <OrderedDictionary>args[0];
this.name = metaData.get("name").value;
this.body = metaData.get("body");
this.params = metaData.get("params") || new OrderedDictionary();
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
// resolving defined type itself produces nothing, you need PuppetASTResource for that
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTDefinedType(args);
}
}
export class PuppetASTSetInstruction extends PuppetASTObject
{
public readonly receiver: PuppetASTObject;
public readonly provider: PuppetASTObject;
constructor(args: Array<PuppetASTObject>)
{
super();
this.receiver = args[0];
this.provider = args[1];
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
if (!(this.receiver instanceof PuppetASTVariable))
{
throw new ResolveError(this.receiver, "Cannot assign to a non-variable");
}
if (this.receiver.className != "")
{
throw new ResolveError(this.receiver, "Cannot assign to external variables");
}
const paramName = this.receiver.name;
const pp = new PuppetASTResolvedProperty();
try
{
pp.value = await this.provider.resolve(context, resolver);
}
catch (e)
{
pp.error = e;
}
pp.addHints(this.provider.hints);
context.setProperty("local", paramName, pp);
return pp;
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTSetInstruction(args);
}
}
export class PuppetHintVariableNotFound extends PuppetHint
{
public variable: string;
constructor(variable: string)
{
super("VariableNotFound", "Variable not found: " + variable);
this.variable = variable;
}
}
export class PuppetHintFunctionNotFound extends PuppetHint
{
public function_: string;
constructor(function_: string)
{
super("FunctionNotFound", "Function not found: " + function_);
this.function_ = function_;
}
}
export class PuppetHintBodyCompilationError extends PuppetHint
{
constructor(message: string)
{
super("BodyCompilationError", message);
}
}
export class PuppetASTValue extends PuppetASTObject
{
private value: any;
constructor(value: any)
{
super();
this.value = value;
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
return this.value;
}
}
export class PuppetASTVariable extends PuppetASTObject
{
public readonly fullName: string;
public readonly name: string;
public readonly className: string;
public readonly root: boolean;
constructor(args: Array<PuppetASTObject> | string)
{
super();
if (isString(args))
{
this.fullName = args;
}
else
{
this.fullName = (<PuppetASTPrimitive>args[0]).value;
}
const split = this.fullName.split("::");
// cases like "$::operatingsystem"
this.root = split.length > 1 && split[0] == "";
this.name = split[split.length - 1];
split.splice(split.length - 1, 1);
this.className = split.join("::");
}
protected async _access(args: Array<PuppetASTObject>, context: PuppetASTContainerContext, resolver: Resolver): Promise<PuppetASTObject>
{
const resolved = await this.resolve(context, resolver);
if (resolved == null)
return null;
const key = await args[0].resolve(context, resolver);
const value = resolved[key];
return new PuppetASTValue(value);
}
public isRoot()
{
return this.root || this.className == "";
}
public async defined(context: PuppetASTContainerContext, resolver: Resolver): Promise<number>
{
const isRoot = this.isRoot();
if (isRoot || context.getName() == this.className)
{
// we're asking the current context, no need to resolve
const property = context.getProperty(this.name);
if (property && property.hasValue)
{
return GlobalVariableResolverResults.EXISTS;
}
else if (isRoot)
{
const has = resolver.hasGlobalVariable(this.name)
if (has != GlobalVariableResolverResults.MISSING)
{
return has;
}
}
}
else
{
const class_:PuppetASTClass = await resolver.resolveClass(this.className, false);
const property = class_.getResolvedProperty(this.name);
if (property && property.hasValue)
{
return GlobalVariableResolverResults.EXISTS;
}
}
return GlobalVariableResolverResults.MISSING;
}
protected async _resolve(context: PuppetASTContainerContext, resolver: Resolver): Promise<any>
{
const isRoot = this.isRoot();
if (isRoot || context.getName() == this.className)
{
// we're asking the current context, no need to resolve
const property = context.getProperty(this.name);
if (property)
{
this.carryHints(property.hints);
if (property.value instanceof EncryptedVariable)
{
// encrypted variables cannot be resolved, because decryption of those
// would require a private key, using it posesses a security risk
return "";
}
return property.value;
}
else if (isRoot)
{
// if we've been asking for a variable without classpath mentioned,
// try to find a global variable
if (resolver.hasGlobalVariable(this.name) != GlobalVariableResolverResults.MISSING)
{
return resolver.getGlobalVariable(this.name);
}
}
}
else
{
const class_:PuppetASTClass = await resolver.resolveClass(this.className, false);
const property = class_.getResolvedProperty(this.name);
if (property)
{
this.carryHints(property.hints);
if (property.error)
{
throw property.error;
}
return property.value;
}
}
this.hint(new PuppetHintVariableNotFound(this.fullName));
return "";
}
public static Create(args: Array<PuppetASTObject>): PuppetASTObject
{
return new PuppetASTVariable(args);
}
}
export class OrderedDictionary extends PuppetASTObject
{
private _value: any;
private _keys: string[];
constructor()
{
super();
this._value = {};
this._keys = [];
}
public get length(): number
{
return this._keys.length;
}
public has(key: string): boolean
{
return this._value.hasOwnProperty(key);
}
public get(key: string): any
{
return this._value[key];
}
public delete(key: string)
{
const i = this._keys.indexOf(key);
if (i < 0)
return;
this._keys.splice(i, 1);
delete this._value[key];
}
public put(key: string, value: any)
{
if (this._keys.indexOf(key) < 0)
{
this._keys.push(key);
}
this._value[key] = value;
}
public get keys(): string[]
{
return this._keys;
}
*[Symbol.iterator]()
{
for (const key of this._keys)
{
yield this._value[key];
}
}
}
export class PuppetASTParser
{
private readonly calls: any;
constructor()
{
this.calls = {
"block": PuppetASTBlock.Create,
"class": PuppetASTClass.Create,
"define": PuppetASTDefinedType.Create,
"=": PuppetASTSetInstruction.Create,
"var": PuppetASTVariable.Create,
"qr": PuppetASTType.Create,
"qn": PuppetASTQualifiedName.Create,
"str": PuppetASTToString.Create,
"concat": PuppetASTConcat.Create,
"resource": PuppetASTResourcesDeclaration.Create,
"resource-override": PuppetASTIgnored.Create("resource-override"),
"resource-defaults": PuppetASTIgnored.Create("resource-defaults"),
"->": PuppetASTApplyOrder.Create,
"~>": PuppetASTNotifyOrder.Create,
"access": PuppetASTAccess.Create,
"=>": PuppetASTKeyedEntry.Create,
"default": PuppetASTDefault.Create,
"?": PuppetASTSwitch.Create,
"case": PuppetASTCase.Create,
"!": PuppetASTNot.Create,
"<": PuppetASTCondition.Less,
">": PuppetASTCondition.More,
"<=": PuppetASTCondition.LessOrEqual,
">=": PuppetASTCondition.MoreOrEqual,
"==": PuppetASTCondition.Equal,
"!=": PuppetASTCondition.NotEqual,
"in": PuppetASTCondition.In,
"+": PuppetASTMath.Plus,
"-": PuppetASTMath.Minus,
"*": PuppetASTMath.Multiply,
"/": PuppetASTMath.Divide,
"and": PuppetASTAndCondition.Create,
"or": PuppetASTOrCondition.Create,
"paren": PuppetASTParenthesis.Create,
"if": PuppetASTIf.Create,
"unless": PuppetASTUnless.Create,
"function": PuppetASTFunction.Create,
"call": PuppetASTCall.Create,
"exported-query": PuppetASTIgnored.Create("exported-query"),
"collect": PuppetASTIgnored.Create("collect"),
"invoke": PuppetASTInvoke.Create,
"array": PuppetASTArray.Create,
"regexp": PuppetASTRegularExpression.Create,
"=~": PuppetASTRegularExpressionCheck.Create,
"hash": PuppetASTHash.Create,
"nop": PuppetASTNOP.Create,
"node": PuppetASTNode.Create
};
}
public parse(obj: any): PuppetASTObject
{
if (obj instanceof Object)
{
if (obj.hasOwnProperty("^"))
{
const isCall = obj["^"];
const kind = isCall[0];
if (kind in this.calls)
{
isCall.splice(0, 1);
const args = [];
for (const arg of isCall)
{
args.push(this.parse(arg));
}
return this.calls[kind](args);
}
else
{
isCall.splice(0, 1);
const args = [];
for (const arg of isCall)
{
args.push(this.parse(arg));
}
console.log("Warning: unsupported kind of call: " + kind);
return new PuppetASTUnknown(kind, args);
}
}
else if (obj.hasOwnProperty("#"))
{
const isHash = obj["#"];
const result = new OrderedDictionary();
for (let i = 0; i < isHash.length; i += 2)
{
result.put(isHash[i], this.parse(isHash[i + 1]));
}
return result;
}
else if (Array.isArray(obj))
{
const args = [];
for (const arg of obj)
{
args.push(this.parse(arg));
}
return new PuppetASTList(args);
}
}
return new PuppetASTPrimitive(obj);
}
static Parse(obj: any)
{
const parser = new PuppetASTParser();
return parser.parse(obj);
}
} | the_stack |
import {Component, ViewChild} from '@angular/core';
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {FormsModule} from '@angular/forms';
import {By} from '@angular/platform-browser';
import * as moment from 'moment';
import {DlDateTimeNumberModule, DlDateTimePickerComponent, DlDateTimePickerModule} from '../../../public-api';
import {
dispatchKeyboardEvent,
DOWN_ARROW,
END,
ENTER,
HOME,
LEFT_ARROW,
PAGE_DOWN,
PAGE_UP,
RIGHT_ARROW,
SPACE,
UP_ARROW
} from '../dispatch-events';
import {DEC, JAN} from '../month-constants';
@Component({
template: '<dl-date-time-picker startView="year"></dl-date-time-picker>'
})
class YearStartViewComponent {
@ViewChild(DlDateTimePickerComponent, {static: false}) picker: DlDateTimePickerComponent<number>;
}
@Component({
template: '<dl-date-time-picker startView="year" [(ngModel)]="selectedDate"></dl-date-time-picker>'
})
class YearStartViewWithNgModelComponent {
@ViewChild(DlDateTimePickerComponent, {static: false}) picker: DlDateTimePickerComponent<number>;
selectedDate = new Date(2017, DEC, 22).getTime();
}
@Component({
template: '<dl-date-time-picker startView="year" minView="year" maxView="year"></dl-date-time-picker>'
})
class YearSelectorComponent {
@ViewChild(DlDateTimePickerComponent, {static: false}) picker: DlDateTimePickerComponent<number>;
}
describe('DlDateTimePickerComponent', () => {
beforeEach(async(() => {
return TestBed.configureTestingModule({
imports: [
FormsModule,
DlDateTimeNumberModule,
DlDateTimePickerModule,
],
declarations: [
YearStartViewComponent,
YearStartViewWithNgModelComponent,
YearSelectorComponent
]
})
.compileComponents();
}));
describe('default behavior ', () => {
let component: YearStartViewComponent;
let fixture: ComponentFixture<YearStartViewComponent>;
beforeEach(async(() => {
fixture = TestBed.createComponent(YearStartViewComponent);
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
component = fixture.componentInstance;
});
}));
it('should start with year-view', () => {
const monthView = fixture.debugElement.query(By.css('.dl-abdtp-year-view'));
expect(monthView).toBeTruthy();
});
it('should contain 0 .dl-abdtp-col-label elements', () => {
const dayLabelElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-col-label'));
expect(dayLabelElements.length).toBe(0);
});
it('should contain 10 .dl-abdtp-year elements', () => {
const monthElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-year'));
expect(monthElements.length).toBe(10);
});
it('should contain 1 .dl-abdtp-now element for the current year', () => {
const currentElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-now'));
expect(currentElements.length).toBe(1);
expect(currentElements[0].nativeElement.textContent.trim()).toBe(moment().year().toString());
expect(currentElements[0].attributes['dl-abdtp-value']).toBe(moment().startOf('year').valueOf().toString());
});
it('should contain 1 [tabindex=1] element', () => {
const tabIndexElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-year[tabindex="0"]'));
expect(tabIndexElements.length).toBe(1);
});
it('should NOT contain an .dl-abdtp-now element in the previous decade', () => {
// click on the left button to move to the previous hour
fixture.debugElement.query(By.css('.dl-abdtp-left-button')).nativeElement.click();
fixture.detectChanges();
const currentElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-now'));
expect(currentElements.length).toBe(0);
});
it('should NOT contain an .dl-abdtp-now element in the next decade', () => {
// click on the left button to move to the previous hour
fixture.debugElement.query(By.css('.dl-abdtp-right-button')).nativeElement.click();
fixture.detectChanges();
const currentElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-now'));
expect(currentElements.length).toBe(0);
});
it('should contain 1 .dl-abdtp-active element for the current year', () => {
const activeElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-active'));
expect(activeElements.length).toBe(1);
expect(activeElements[0].nativeElement.textContent.trim()).toBe(moment().year().toString());
expect(activeElements[0].attributes['dl-abdtp-value']).toBe(moment().startOf('year').valueOf().toString());
});
it('should contain 1 .dl-abdtp-selected element for the current year', () => {
component.picker.value = moment().startOf('year').valueOf();
fixture.detectChanges();
// Bug: The value change is not detected until there is some user interaction
// **ONlY** when there is no ngModel binding on the component.
// I think it is related to https://github.com/angular/angular/issues/10816
const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active')).nativeElement;
activeElement.focus();
dispatchKeyboardEvent(activeElement, 'keydown', HOME);
fixture.detectChanges();
const selectedElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-selected'));
expect(selectedElements.length).toBe(1);
expect(selectedElements[0].nativeElement.textContent.trim()).toBe(moment().year().toString());
expect(selectedElements[0].attributes['dl-abdtp-value']).toBe(moment().startOf('year').valueOf().toString());
});
});
describe('ngModel=2017-12-22', () => {
let component: YearStartViewWithNgModelComponent;
let fixture: ComponentFixture<YearStartViewWithNgModelComponent>;
beforeEach(async(() => {
fixture = TestBed.createComponent(YearStartViewWithNgModelComponent);
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
component = fixture.componentInstance;
});
}));
it('should contain .dl-abdtp-view-label element with "2010-2019"', () => {
const viewLabel = fixture.debugElement.query(By.css('.dl-abdtp-view-label'));
expect(viewLabel.nativeElement.textContent).toBe('2010-2019');
});
it('should contain 10 .dl-abdtp-year elements with start of year utc time as class and role of gridcell', () => {
// Truncate the last digit from the current year to get the start of the decade
const startYear = (Math.trunc(moment(component.selectedDate).year() / 10) * 10);
const expectedValues = new Array(10)
.fill(startYear)
.map((year, index) => new Date(year + index, JAN, 1).getTime());
const yearElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-year'));
yearElements.forEach((yearElement, index) => {
const expectedValue = expectedValues[index];
expect(yearElement.attributes['dl-abdtp-value']).toBe(expectedValue.toString(10), index);
expect(yearElement.attributes['role']).toBe('gridcell', index);
expect(yearElement.attributes['aria-label']).toBeNull(); // why isn't this undefined?
});
});
it('should have a dl-abdtp-value attribute with the previous decade value on .dl-abdtp-left-button ', () => {
const leftButton = fixture.debugElement.query(By.css('.dl-abdtp-left-button'));
const expected = new Date(2000, JAN, 1).getTime();
expect(leftButton.attributes['dl-abdtp-value']).toBe(expected.toString());
});
it('should switch to previous decade value after clicking .dl-abdtp-left-button', () => {
const leftButton = fixture.debugElement.query(By.css('.dl-abdtp-left-button'));
leftButton.nativeElement.click();
fixture.detectChanges();
const viewLabel = fixture.debugElement.query(By.css('.dl-abdtp-view-label'));
expect(viewLabel.nativeElement.textContent).toBe('2000-2009');
const yearElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-year'));
expect(yearElements[0].nativeElement.textContent.trim()).toBe('2000');
});
it('should has a dl-abdtp-value attribute with the next decade value on .dl-abdtp-right-button ', () => {
const rightButton = fixture.debugElement.query(By.css('.dl-abdtp-right-button'));
const expected = new Date(2020, JAN, 1).getTime();
expect(rightButton.attributes['dl-abdtp-value']).toBe(expected.toString());
});
it('should switch to next decade after clicking .dl-abdtp-right-button', () => {
const rightButton = fixture.debugElement.query(By.css('.dl-abdtp-right-button'));
rightButton.nativeElement.click();
fixture.detectChanges();
const yearElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-year'));
expect(yearElements[0].nativeElement.textContent.trim()).toBe('2020');
});
it('.dl-abdtp-left-button should have a title', () => {
const leftButton = fixture.debugElement.query(By.css('.dl-abdtp-left-button'));
expect(leftButton.attributes['title']).toBe('Go to 2000-2009');
});
it('.dl-abdtp-left-button should have arial label', () => {
const leftButton = fixture.debugElement.query(By.css('.dl-abdtp-left-button'));
expect(leftButton.attributes['aria-label']).toBe('Go to 2000-2009');
});
it('.dl-abdtp-right-button should have a title', () => {
const rightButton = fixture.debugElement.query(By.css('.dl-abdtp-right-button'));
expect(rightButton.attributes['title']).toBe('Go to 2020-2029');
});
it('.dl-abdtp-right-button should have aria-label', () => {
const rightButton = fixture.debugElement.query(By.css('.dl-abdtp-right-button'));
expect(rightButton.attributes['aria-label']).toBe('Go to 2020-2029');
});
it('should not emit a change event when clicking .dl-abdtp-year', () => {
const changeSpy = jasmine.createSpy('change listener');
component.picker.change.subscribe(changeSpy);
const yearElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-year'));
yearElements[9].nativeElement.click(); // 2019
fixture.detectChanges();
expect(changeSpy).not.toHaveBeenCalled();
});
it('should change to .dl-abdtp-month-view when selecting year', () => {
const yearElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-year'));
yearElements[0].nativeElement.click(); // 2009
fixture.detectChanges();
const monthView = fixture.debugElement.query(By.css('.dl-abdtp-month-view'));
expect(monthView).toBeTruthy();
const yearView = fixture.debugElement.query(By.css('.dl-abdtp-year-view'));
expect(yearView).toBeFalsy();
});
it('should do nothing when hitting non-supported key', () => {
const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active'));
expect(activeElement.nativeElement.textContent).toBe('2017');
dispatchKeyboardEvent(activeElement.nativeElement, 'keydown', 'A');
fixture.detectChanges();
expect(activeElement.nativeElement.textContent).toBe('2017');
});
it('should change to .dl-abdtp-month-view when hitting ENTER', () => {
const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active'));
dispatchKeyboardEvent(activeElement.nativeElement, 'keydown', ENTER);
fixture.detectChanges();
const monthView = fixture.debugElement.query(By.css('.dl-abdtp-month-view'));
expect(monthView).toBeTruthy();
const yearView = fixture.debugElement.query(By.css('.dl-abdtp-year-view'));
expect(yearView).toBeFalsy();
});
it('should change to .dl-abdtp-month-view when hitting SPACE', () => {
(component.picker as any)._model.activeDate = new Date(2011, JAN, 1).getTime();
fixture.detectChanges();
const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active'));
dispatchKeyboardEvent(activeElement.nativeElement, 'keydown', SPACE);
fixture.detectChanges();
const monthView = fixture.debugElement.query(By.css('.dl-abdtp-month-view'));
expect(monthView).toBeTruthy();
const yearView = fixture.debugElement.query(By.css('.dl-abdtp-year-view'));
expect(yearView).toBeFalsy();
});
it('should have one .dl-abdtp-active element', () => {
const activeElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-active'));
expect(activeElements.length).toBe(1);
});
it('should change .dl-abdtp-active element on right arrow', () => {
const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active'));
expect(activeElement.nativeElement.textContent).toBe('2017');
activeElement.nativeElement.focus();
expect(document.activeElement).toBe(activeElement.nativeElement, document.activeElement.outerHTML);
dispatchKeyboardEvent(activeElement.nativeElement, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
const newActiveElement = fixture.debugElement.query(By.css('.dl-abdtp-active'));
expect(newActiveElement.nativeElement.textContent).toBe('2018');
});
it('should change to next decade when last .dl-abdtp-year is .dl-abdtp-active element and pressing on right arrow', () => {
(component.picker as any)._model.activeDate = new Date(2019, JAN, 1).getTime();
fixture.detectChanges();
dispatchKeyboardEvent(fixture.debugElement.query(By.css('.dl-abdtp-active')).nativeElement, 'keydown', RIGHT_ARROW); // 2019
fixture.detectChanges();
const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active'));
expect(activeElement.nativeElement.textContent).toBe('2020');
const viewLabel = fixture.debugElement.query(By.css('.dl-abdtp-view-label'));
expect(viewLabel.nativeElement.textContent).toBe('2020-2029');
});
it('should change .dl-abdtp-active element on left arrow', () => {
const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active'));
expect(activeElement.nativeElement.textContent).toBe('2017');
activeElement.nativeElement.focus();
dispatchKeyboardEvent(activeElement.nativeElement, 'keydown', LEFT_ARROW);
fixture.detectChanges();
const newActiveElement = fixture.debugElement.query(By.css('.dl-abdtp-active'));
expect(newActiveElement.nativeElement.textContent).toBe('2016');
});
it('should change to previous decade when first .dl-abdtp-year is .dl-abdtp-active element and pressing on left arrow', () => {
(component.picker as any)._model.activeDate = new Date(2010, JAN, 1).getTime();
fixture.detectChanges();
dispatchKeyboardEvent(fixture.debugElement.query(By.css('.dl-abdtp-active')).nativeElement, 'keydown', LEFT_ARROW); // 2019
fixture.detectChanges();
const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active'));
expect(activeElement.nativeElement.textContent).toBe('2009');
const viewLabel = fixture.debugElement.query(By.css('.dl-abdtp-view-label'));
expect(viewLabel.nativeElement.textContent).toBe('2000-2009');
});
it('should change .dl-abdtp-active element on up arrow', () => {
const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active'));
expect(activeElement.nativeElement.textContent).toBe('2017');
activeElement.nativeElement.focus();
dispatchKeyboardEvent(activeElement.nativeElement, 'keydown', UP_ARROW);
fixture.detectChanges();
const newActiveElement = fixture.debugElement.query(By.css('.dl-abdtp-active'));
expect(newActiveElement.nativeElement.textContent).toBe('2012');
});
it('should change to previous decade when first .dl-abdtp-year is .dl-abdtp-active element and pressing on up arrow', () => {
(component.picker as any)._model.activeDate = new Date(2014, JAN, 1).getTime();
fixture.detectChanges();
dispatchKeyboardEvent(fixture.debugElement.query(By.css('.dl-abdtp-active')).nativeElement, 'keydown', UP_ARROW); // 2019
fixture.detectChanges();
const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active'));
expect(activeElement.nativeElement.textContent).toBe('2009');
const viewLabel = fixture.debugElement.query(By.css('.dl-abdtp-view-label'));
expect(viewLabel.nativeElement.textContent).toBe('2000-2009');
});
it('should change .dl-abdtp-active element on down arrow', () => {
const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active'));
expect(activeElement.nativeElement.textContent).toBe('2017');
activeElement.nativeElement.focus();
dispatchKeyboardEvent(activeElement.nativeElement, 'keydown', DOWN_ARROW);
fixture.detectChanges();
const newActiveElement = fixture.debugElement.query(By.css('.dl-abdtp-active'));
expect(newActiveElement.nativeElement.textContent).toBe('2022');
});
it('should change .dl-abdtp-active element on page-up (fn+up-arrow)', () => {
const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active'));
expect(activeElement.nativeElement.textContent).toBe('2017');
activeElement.nativeElement.focus();
dispatchKeyboardEvent(activeElement.nativeElement, 'keydown', PAGE_UP);
fixture.detectChanges();
const newActiveElement = fixture.debugElement.query(By.css('.dl-abdtp-active'));
expect(newActiveElement.nativeElement.textContent).toBe('2007');
});
it('should change .dl-abdtp-active element on page-down (fn+down-arrow)', () => {
const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active'));
expect(activeElement.nativeElement.textContent).toBe('2017');
activeElement.nativeElement.focus();
dispatchKeyboardEvent(activeElement.nativeElement, 'keydown', PAGE_DOWN);
fixture.detectChanges();
const newActiveElement = fixture.debugElement.query(By.css('.dl-abdtp-active'));
expect(newActiveElement.nativeElement.textContent).toBe('2027');
});
it('should change .dl-abdtp-active element to first .dl-abdtp-year on HOME', () => {
const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active'));
expect(activeElement.nativeElement.textContent).toBe('2017');
activeElement.nativeElement.focus();
dispatchKeyboardEvent(activeElement.nativeElement, 'keydown', HOME);
fixture.detectChanges();
const newActiveElement = fixture.debugElement.query(By.css('.dl-abdtp-active'));
expect(newActiveElement.nativeElement.textContent).toBe('2010');
});
it('should change .dl-abdtp-active element to last .dl-abdtp-year on END', () => {
fixture.debugElement.nativeElement.dispatchEvent(new Event('input'));
const activeElement = fixture.debugElement.query(By.css('.dl-abdtp-active'));
expect(activeElement.nativeElement.textContent).toBe('2017');
activeElement.nativeElement.focus();
dispatchKeyboardEvent(activeElement.nativeElement, 'keydown', END);
fixture.detectChanges();
const newActiveElement = fixture.debugElement.query(By.css('.dl-abdtp-active'));
expect(newActiveElement.nativeElement.textContent).toBe('2019');
});
});
describe('year selector (minView=year)', () => {
let component: YearSelectorComponent;
let fixture: ComponentFixture<YearSelectorComponent>;
beforeEach(() => {
fixture = TestBed.createComponent(YearSelectorComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should store the value and emit change event when clicking a .dl-abdtp-year', function () {
const changeSpy = jasmine.createSpy('change listener');
component.picker.change.subscribe(changeSpy);
const yearElements = fixture.debugElement.queryAll(By.css('.dl-abdtp-year'));
yearElements[0].nativeElement.click();
fixture.detectChanges();
// Truncate the last digit from the current year to get the start of the decade
const startDecade = (Math.trunc(moment().year() / 10) * 10);
const expectedTime = new Date(startDecade, JAN, 1).getTime();
expect(component.picker.value).toBe(expectedTime);
expect(changeSpy).toHaveBeenCalled();
expect(changeSpy.calls.first().args[0].value).toBe(expectedTime);
});
});
}); | the_stack |
import { assert } from "chai";
import "mocha";
import * as tf from "@tensorflow/tfjs";
import * as tm from "../src/index";
import * as seedrandom from "seedrandom";
import { TeachableMobileNet } from "../src/index";
import { assertTypesMatch } from "@tensorflow/tfjs-core/dist/tensor_util";
import { cropTo } from "../src/utils/canvas";
// @ts-ignore
var Table = require("cli-table");
const SEED_WORD = "testSuite";
const seed: seedrandom.prng = seedrandom(SEED_WORD);
const FLOWER_DATASET_URL =
"https://storage.googleapis.com/teachable-machine-models/test_data/image/flowers_all/";
const ELMO_DATASET_URL =
"https://storage.googleapis.com/teachable-machine-models/test_data/image/elmo/";
const BEAN_DATASET_URL =
"https://storage.googleapis.com/teachable-machine-models/test_data/image/beans/";
const FACE_DATASET_URL =
"https://storage.googleapis.com/teachable-machine-models/test_data/image/face/";
const PLANT_DATASET_URL =
"https://storage.googleapis.com/teachable-machine-models/test_data/image/plants/"
/**
* Load a flower image from our storage bucket
*/
function loadJpgImage(c: string, i: number, dataset_url: string): Promise<HTMLImageElement> {
// tslint:disable-next-line:max-line-length
const src = dataset_url + `${c}/${i}.jpg`;
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.crossOrigin = "anonymous";
img.src = src;
});
}
function loadPngImage(c: string, i: number, dataset_url: string): Promise<HTMLImageElement> {
// tslint:disable-next-line:max-line-length
const src = dataset_url + `${c}/${i}.png`;
// console.log(src)
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.crossOrigin = "anonymous";
img.src = src;
});
}
/**
* Shuffle an array of Float32Array or Samples using Fisher-Yates algorithm
* Takes an optional seed value to make shuffling predictable
*/
function fisherYates(array: number[], seed?: seedrandom.prng) {
const length = array.length;
const shuffled = array.slice(0);
for (let i = length - 1; i > 0; i -= 1) {
let randomIndex;
if (seed) {
randomIndex = Math.floor(seed() * (i + 1));
} else {
randomIndex = Math.floor(Math.random() * (i + 1));
}
[shuffled[i], shuffled[randomIndex]] = [
shuffled[randomIndex],
shuffled[i]
];
}
return shuffled;
}
/**
* Create train/validation dataset and test dataset with unique images
*/
async function createDatasets(
dataset_url: string,
classes: string[],
trainSize: number,
testSize: number,
loadFunction: Function
) {
// fill in an array with unique numbers
let listNumbers = [];
for (let i = 0; i < trainSize + testSize; ++i) listNumbers[i] = i;
listNumbers = fisherYates(listNumbers, seed); // shuffle
const trainAndValidationIndeces = listNumbers.slice(0, trainSize);
const testIndices = listNumbers.slice(trainSize, trainSize + testSize);
const trainAndValidationImages: HTMLImageElement[][] = [];
const testImages: HTMLImageElement[][] = [];
for (const c of classes) {
let load: Array<Promise<HTMLImageElement>> = [];
for (const i of trainAndValidationIndeces) {
load.push(loadFunction(c, i, dataset_url));
}
trainAndValidationImages.push(await Promise.all(load));
load = [];
for (const i of testIndices) {
load.push(loadFunction(c, i, dataset_url));
}
testImages.push(await Promise.all(load));
}
return {
trainAndValidationImages,
testImages
};
}
/**
* Output loss and accuracy results at the end of training
* Also evaluate the test dataset
*/
function showMetrics(alpha: number, time: number, logs: tf.Logs[], testAccuracy?: number) {
const lastEpoch = logs[logs.length - 1];
const header = "α=" + alpha + ", t=" + (time/1000).toFixed(1) + "s";
const table = new Table({
head: [header, "Accuracy", "Loss"],
colWidths: [18, 10, 10]
});
table.push(
[ "Train", lastEpoch.acc.toFixed(3), lastEpoch.loss.toFixed(5) ],
[ "Validation", lastEpoch.val_acc.toFixed(3), lastEpoch.val_loss.toFixed(5) ]
);
console.log("\n" + table.toString());
}
async function testModel(
model: TeachableMobileNet,
alpha: number,
classes: string[],
trainAndValidationImages: HTMLImageElement[][],
testImages: HTMLImageElement[][],
testSizePerClass: number,
epochs: number,
learningRate: number,
showEpochResults: boolean = false,
earlyStopEpoch: number = epochs,
imageSize?: number,
) {
model.setLabels(classes);
model.setSeed(SEED_WORD); // set a seed to shuffle predictably
const logs: tf.Logs[] = [];
let time: number = 0;
await tf.nextFrame().then(async () => {
let index = 0;
for (const imgSet of trainAndValidationImages) {
for (const img of imgSet) {
if (imageSize) {
let croppedImg = cropTo(img, 96, false);
await model.addExample(index, croppedImg);
}
else {
await model.addExample(index, img);
}
}
index++;
}
const start = window.performance.now();
await model.train(
{
denseUnits: 100,
epochs,
learningRate,
batchSize: 16
},
{
onEpochBegin: async (epoch: number, logs: tf.Logs) => {
if (showEpochResults) {
console.log("Epoch: ", epoch);
}
},
onEpochEnd: async (epoch: number, log: tf.Logs) => {
if (showEpochResults) {
console.log(log);
}
if (earlyStopEpoch !== epochs && earlyStopEpoch === epoch) {
model.stopTraining().then(() => {
console.log("Stopped training early");
});
}
logs.push(log);
}
}
);
const end = window.performance.now();
time = end - start;
});
// // Analyze the test set (model has not seen for training)
// let accuracy = 0;
// for (let i = 0; i < classes.length; i++) {
// const classImages = testImages[i];
// for (const image of classImages) {
// const scores = await model.predict(image, false);
// // compare the label
// if (scores[0].className === classes[i]) {
// accuracy++;
// }
// }
// }
// const testAccuracy = accuracy / (testSizePerClass * classes.length);
showMetrics(alpha, time, logs);
return logs[logs.length - 1];
}
async function testMobilenet(dataset_url: string, version: number, loadFunction: Function, maxImages: number = 200, earlyStop: boolean = false, grayscale: boolean = false){
// classes, samplesPerClass, url
const metadata = await (await fetch(
dataset_url + "metadata.json"
)).json();
// 1. Setup dataset parameters
const classLabels = metadata.classes as string[];
let NUM_IMAGE_PER_CLASS = Math.ceil(maxImages / classLabels.length);
if(NUM_IMAGE_PER_CLASS > Math.min(...metadata.samplesPerClass)){
NUM_IMAGE_PER_CLASS = Math.min(...metadata.samplesPerClass);
}
const TRAIN_VALIDATION_SIZE_PER_CLASS = NUM_IMAGE_PER_CLASS
const table = new Table();
table.push(
{
"train/validation size":
TRAIN_VALIDATION_SIZE_PER_CLASS * classLabels.length
}
);
console.log("\n" + table.toString());
// 2. Create our datasets once
const datasets = await createDatasets(
dataset_url,
classLabels,
TRAIN_VALIDATION_SIZE_PER_CLASS,
0,
loadFunction
);
const trainAndValidationImages = datasets.trainAndValidationImages;
const testImages = datasets.testImages;
// NOTE: If testing time, test first model twice because it takes longer
// to train the very first time tf.js is training
const MOBILENET_VERSION = version;
let VALID_ALPHAS = [0.35];
// const VALID_ALPHAS = [0.25, 0.5, 0.75, 1];
// const VALID_ALPHAS = [0.4];
let EPOCHS = 50;
let LEARNING_RATE = 0.001;
if(version === 1){
LEARNING_RATE = 0.0001;
VALID_ALPHAS = [0.25];
EPOCHS = 20;
}
const earlyStopEpochs = earlyStop ? 5 : EPOCHS;
for (let a of VALID_ALPHAS) {
const lineStart = "\n//====================================";
const lineEnd = "====================================//\n\n";
console.log(lineStart);
// 3. Test data on the model
let teachableMobileNet;
let imageSize;
if (grayscale) {
imageSize = 96;
teachableMobileNet = await tm.createTeachable(
{ tfjsVersion: tf.version.tfjs, grayscale: true, imageSize },
{ version: 1, alpha: 0.25, checkpointUrl: 'https://storage.googleapis.com/teachable-machine-models/mobilenet_v1_grayscale_025_96/model.json',
trainingLayer: 'conv_pw_13_relu'}
);
}
else {
teachableMobileNet = await tm.createTeachable(
{ tfjsVersion: tf.version.tfjs },
{ version: MOBILENET_VERSION, alpha: a }
);
}
const lastEpoch = await testModel(
teachableMobileNet,
a,
classLabels,
trainAndValidationImages,
testImages,
0,
EPOCHS,
LEARNING_RATE,
false,
earlyStopEpochs,
imageSize
);
// assert.isTrue(accuracyV2 > 0.7);
console.log(lineEnd);
return { model: teachableMobileNet, lastEpoch };
}
}
// Weird workaround...
tf.util.fetch = (a, b) => window.fetch(a, b);
describe("Module exports", () => {
it("should contain ", () => {
assert.typeOf(tm, "object", "tm should be an object");
assert.typeOf(tm.Webcam, "function");
assert.typeOf(tm.version, "string", "tm.version should be a string");
assert.typeOf(tm.CustomMobileNet, "function");
assert.typeOf(tm.TeachableMobileNet, "function");
assert.typeOf(tm.load, "function");
assert.typeOf(tm.loadFromFiles, "function");
assert.equal(tm.IMAGE_SIZE, 224, "IMAGE_SIZE should be 224");
// tslint:disable-next-line: no-require-imports
assert.equal(tm.version, require('../package.json').version, "version does not match package.json.");
});
});
describe("CI Test", () => {
it("create a model", async () => {
const teachableMobileNet = await tm.createTeachable(
{ tfjsVersion: tf.version.tfjs },
{ version: 2 }
);
assert.exists(teachableMobileNet);
}).timeout(5000);
let testModel: tm.TeachableMobileNet;
it("Test tiny model (for CI)", async () => {
const { model, lastEpoch } = await testMobilenet(BEAN_DATASET_URL, 2, loadPngImage, 10);
testModel = model;
assert.isAbove(lastEpoch.val_acc, 0.8);
assert.isBelow(lastEpoch.val_loss, 0.1);
}).timeout(500000);
it("Test early stop", async () => {
const { model, lastEpoch } = await testMobilenet(BEAN_DATASET_URL, 2, loadPngImage, 10, true);
assert.isAbove(lastEpoch.val_acc, 0.8);
assert.isBelow(lastEpoch.val_loss, 0.1);
}).timeout(500000);
it("Test predict functions", async () => {
let testImage, prediction, predictionTopK;
testImage = await loadPngImage('bad_bean', 0, BEAN_DATASET_URL);
prediction = await testModel.predict(testImage, false);
assert.isAbove(prediction[1].probability, 0.9);
predictionTopK = await testModel.predictTopK(testImage, 3, false);
assert.equal(predictionTopK[0].className, 'bad_bean');
assert.isAbove(predictionTopK[0].probability, 0.9);
testImage = await loadPngImage('good_bean', 0, BEAN_DATASET_URL);
prediction = await testModel.predict(testImage, false);
assert.isAbove(prediction[0].probability, 0.9);
predictionTopK = await testModel.predictTopK(testImage, 3, false);
assert.equal(predictionTopK[0].className, 'good_bean');
assert.isAbove(predictionTopK[0].probability, 0.9);
}).timeout(500000);
it("creates a grayscale model", async() => {
const grayscaleMobilenet = await tm.createTeachable(
{ tfjsVersion: tf.version.tfjs, grayscale: true, imageSize: 96 },
{ version: 1, alpha: 0.25, checkpointUrl: 'https://storage.googleapis.com/teachable-machine-models/mobilenet_v1_grayscale_025_96/model.json',
trainingLayer: 'conv_pw_13_relu'}
)
assert.exists(grayscaleMobilenet);
}).timeout(5000);
let testGrayscaleModel: tm.TeachableMobileNet;
it('test grayscale model accuracy (for CI)', async () => {
const { model, lastEpoch } = await testMobilenet(PLANT_DATASET_URL, 1, loadJpgImage, 30, false, true);
testGrayscaleModel = model;
assert.isAbove(lastEpoch.val_acc, 0.8);
assert.isBelow(lastEpoch.val_loss, 0.2);
}).timeout(50000);
it('tests graysale predict functions', async() => {
let testImage, prediction, predictionTopK;
testImage = await loadJpgImage('ficus', 0, PLANT_DATASET_URL);
prediction = await testGrayscaleModel.predict(testImage, false);
assert.isAbove(prediction[1].probability, 0.8);
predictionTopK = await testGrayscaleModel.predictTopK(testImage, 3, false);
assert.equal(predictionTopK[0].className, 'ficus');
assert.isAbove(predictionTopK[0].probability, 0.8);
testImage = await loadJpgImage('lily', 0, PLANT_DATASET_URL);
prediction = await testGrayscaleModel.predict(testImage, false);
assert.isAbove(prediction[0].probability, 0.8);
predictionTopK = await testGrayscaleModel.predictTopK(testImage, 3, false);
assert.equal(predictionTopK[0].className, 'lily');
assert.isAbove(predictionTopK[0].probability, 0.8);
})
});
// These test compare multiple models. Needs to run in non-headless chrome
describe.skip("Performance test", () => {
it("Train flower dataset on mobilenet v1", async () => {
console.log("Flower dataset mobilenet v1");
await testMobilenet(FLOWER_DATASET_URL, 1, loadJpgImage);
}).timeout(500000);
it("Train flower dataset on mobilenet v2", async () => {
console.log("Flower dataset mobilenet v2");
await testMobilenet(FLOWER_DATASET_URL, 2, loadJpgImage);
}).timeout(500000);
it("Train elmo dataset on mobilenet v1", async () => {
console.log("Elmo dataset mobilenet v1");
await testMobilenet(ELMO_DATASET_URL, 1, loadPngImage);
}).timeout(500000);
it("Train elmo dataset on mobilenet v2", async () => {
console.log("Elmo dataset mobilenet v2");
await testMobilenet(ELMO_DATASET_URL, 2, loadPngImage);
}).timeout(500000);
it("Train bean dataset on mobilenet v1", async () => {
console.log("Bean dataset mobilenet v1");
await testMobilenet(BEAN_DATASET_URL, 1, loadPngImage);
}).timeout(500000);
it("Train bean dataset on mobilenet v2", async () => {
console.log("Bean dataset mobilenet v2");
await testMobilenet(BEAN_DATASET_URL, 2, loadPngImage);
}).timeout(500000);
it("Train face dataset on mobilenet v1", async () => {
console.log("Face dataset mobilenet v1");
await testMobilenet(FACE_DATASET_URL, 1, loadPngImage);
}).timeout(500000);
it("Train face dataset on mobilenet v2", async () => {
console.log("Face dataset mobilenet v2");
await testMobilenet(FACE_DATASET_URL, 2, loadPngImage);
}).timeout(500000);
}); | the_stack |
import BigNumber from 'bignumber.js';
import _ from 'lodash';
import initializePerpetual from './helpers/initializePerpetual';
import { expectBalances, mintAndDeposit } from './helpers/balances';
import { ITestContext, perpetualDescribe } from './helpers/perpetualDescribe';
import { buy } from './helpers/trade';
import { expect, expectBN, expectBaseValueEqual, expectThrow } from './helpers/Expect';
import {
BigNumberable,
BaseValue,
Price,
TxResult,
address,
} from '../src/lib/types';
const initialPrice = new Price(100);
const longUndercollateralizedPrice = new Price(52);
const longUnderwaterPrice = new Price(48);
const shortUndercollateralizedPrice = new Price(140);
const shortUnderwaterPrice = new Price(160);
const positionSize = new BigNumber(100);
const halfPosition = positionSize.div(2);
const ERROR_MAX_POSITION = 'Cannot liquidate if it would put liquidator past the specified maxPosition';
let admin: address;
let long: address;
let short: address;
let neutral: address;
let insuranceFund: address;
let rando: address;
let smallLong: address;
let smallShort: address;
interface LiquidateOptions {
liquidator: address;
liquidatee: address;
sender?: address;
isBuy: boolean;
maxPosition: BigNumberable;
}
interface ExpectedLogOptions {
liquidator: address;
liquidatee: address;
isBuy: boolean;
feeAmount: BigNumberable;
liquidationAmount: BigNumberable;
}
async function init(ctx: ITestContext): Promise<void> {
await initializePerpetual(ctx);
admin = ctx.accounts[0];
long = ctx.accounts[1];
short = ctx.accounts[2];
neutral = ctx.accounts[3];
insuranceFund = ctx.accounts[4];
rando = ctx.accounts[5];
smallLong = ctx.accounts[6];
smallShort = ctx.accounts[7];
// Set up initial balances:
// +------------+--------+----------+-------------------+
// | account | margin | position | collateralization |
// |------------+--------+----------+-------------------|
// | long | -5000 | 100 | 200% |
// | short | 15000 | -100 | 150% |
// | smallLong | 0 | 50 | INF% |
// | smallShort | 10000 | -50 | 200% |
// | netral | 20000 | 0 | INF% |
// +------------+--------+----------+-------------------+
await Promise.all([
ctx.perpetual.testing.oracle.setPrice(initialPrice),
ctx.perpetual.liquidatorProxy.setInsuranceFund(insuranceFund, { from: admin }),
ctx.perpetual.liquidatorProxy.approveMaximumOnPerpetual(),
mintAndDeposit(ctx, long, new BigNumber(5000)),
mintAndDeposit(ctx, short, new BigNumber(5000)),
mintAndDeposit(ctx, smallLong, new BigNumber(5000)),
mintAndDeposit(ctx, smallShort, new BigNumber(5000)),
mintAndDeposit(ctx, neutral, new BigNumber(20000)),
]);
await buy(ctx, long, short, positionSize, positionSize.times(initialPrice.value));
await buy(ctx, smallLong, smallShort, 50, new BigNumber(50).times(initialPrice.value));
// Check initial balances
const [
longBal,
shortBal,
smallLongBal,
smallShortBal,
neutralBal,
] = await Promise.all([
ctx.perpetual.getters.getAccountBalance(long),
ctx.perpetual.getters.getAccountBalance(short),
ctx.perpetual.getters.getAccountBalance(smallLong),
ctx.perpetual.getters.getAccountBalance(smallShort),
ctx.perpetual.getters.getAccountBalance(neutral),
]);
expectBN(longBal.margin).to.equal(-5000);
expectBN(shortBal.margin).to.equal(15000);
expectBN(smallLongBal.margin).to.equal(0);
expectBN(smallShortBal.margin).to.equal(10000);
expectBN(neutralBal.margin).to.equal(20000);
expectBN(longBal.position).to.equal(positionSize);
expectBN(shortBal.position).to.equal(positionSize.negated());
expectBN(smallLongBal.position).to.equal(halfPosition);
expectBN(smallShortBal.position).to.equal(halfPosition.negated());
expectBN(neutralBal.position).to.equal(0);
}
perpetualDescribe('P1LiquidatorProxy', init, (ctx: ITestContext) => {
describe('setInsuranceFund()', () => {
it('Succeeds', async () => {
await ctx.perpetual.liquidatorProxy.setInsuranceFund(
rando,
{ from: admin },
);
const newInsuranceFund = await ctx.perpetual.liquidatorProxy.getInsuranceFund();
expect(newInsuranceFund).to.equal(rando);
});
it('Fails for non-owner', async () => {
await expectThrow(
ctx.perpetual.liquidatorProxy.setInsuranceFund(
rando,
{ from: rando },
),
'Ownable: caller is not the owner',
);
});
});
describe('setInsuranceFee()', () => {
const newFee = new BaseValue(0.5);
it('Succeeds', async () => {
await ctx.perpetual.liquidatorProxy.setInsuranceFee(
newFee,
{ from: admin },
);
const newInsuranceFee = await ctx.perpetual.liquidatorProxy.getInsuranceFee();
expectBaseValueEqual(newInsuranceFee, newFee);
});
it('Fails to set above 50%', async () => {
await expectThrow(
ctx.perpetual.liquidatorProxy.setInsuranceFee(
new BaseValue(0.51),
{ from: admin },
),
'insuranceFee cannot be greater than 50%',
);
});
it('Fails for non-owner', async () => {
await expectThrow(
ctx.perpetual.liquidatorProxy.setInsuranceFee(
newFee,
{ from: rando },
),
'Ownable: caller is not the owner',
);
});
});
describe('liquidate()', () => {
describe('Basic Cases', () => {
it('Succeeds partially liquidating a long position', async () => {
const feeAmount = 10;
await ctx.perpetual.testing.oracle.setPrice(longUndercollateralizedPrice);
const txResult = await liquidate({
liquidatee: long,
liquidator: neutral,
isBuy: true,
maxPosition: halfPosition,
});
await expectFinalBalances(
txResult,
[long, neutral],
[-2500, 17500 - feeAmount],
[halfPosition, halfPosition],
feeAmount,
);
expectLogs(txResult, {
feeAmount,
liquidatee: long,
liquidator: neutral,
isBuy: true,
liquidationAmount: halfPosition,
});
});
it('Succeeds partially liquidating a short position', async () => {
const feeAmount = 50;
await ctx.perpetual.testing.oracle.setPrice(shortUndercollateralizedPrice);
const txResult = await liquidate({
liquidatee: short,
liquidator: neutral,
isBuy: false,
maxPosition: halfPosition.negated(),
});
await expectFinalBalances(
txResult,
[short, neutral],
[7500, 27500 - feeAmount],
[halfPosition.negated(), halfPosition.negated()],
feeAmount,
);
expectLogs(txResult, {
feeAmount,
liquidatee: short,
liquidator: neutral,
isBuy: false,
liquidationAmount: halfPosition,
});
});
it('Succeeds fully liquidating an undercollateralized long position', async () => {
const feeAmount = 20;
await ctx.perpetual.testing.oracle.setPrice(longUndercollateralizedPrice);
const txResult = await liquidate({
liquidatee: long,
liquidator: neutral,
isBuy: true,
maxPosition: positionSize,
});
await expectFinalBalances(
txResult,
[long, neutral],
[0, 15000 - feeAmount],
[0, positionSize],
feeAmount,
);
expectLogs(txResult, {
feeAmount,
liquidatee: long,
liquidator: neutral,
isBuy: true,
liquidationAmount: positionSize,
});
});
it('Succeeds fully liquidating an undercollateralized short position', async () => {
const feeAmount = 100;
await ctx.perpetual.testing.oracle.setPrice(shortUndercollateralizedPrice);
const txResult = await liquidate({
liquidatee: short,
liquidator: neutral,
isBuy: false,
maxPosition: positionSize.negated(),
});
await expectFinalBalances(
txResult,
[short, neutral],
[0, 35000 - feeAmount],
[0, positionSize.negated()],
feeAmount,
);
expectLogs(txResult, {
feeAmount,
liquidatee: short,
liquidator: neutral,
isBuy: false,
liquidationAmount: positionSize,
});
});
it('Succeeds fully liquidating a long position using a high maxPositionSize', async () => {
const feeAmount = 20;
await ctx.perpetual.testing.oracle.setPrice(longUndercollateralizedPrice);
const txResult = await liquidate({
liquidatee: long,
liquidator: neutral,
isBuy: true,
maxPosition: positionSize.times(2),
});
await expectFinalBalances(
txResult,
[long, neutral],
[0, 15000 - feeAmount],
[0, positionSize],
feeAmount,
);
expectLogs(txResult, {
feeAmount,
liquidatee: long,
liquidator: neutral,
isBuy: true,
liquidationAmount: positionSize,
});
});
it('Succeeds fully liquidating a short position using a high maxPositionSize', async () => {
const feeAmount = 100;
await ctx.perpetual.testing.oracle.setPrice(shortUndercollateralizedPrice);
const txResult = await liquidate({
liquidatee: short,
liquidator: neutral,
isBuy: false,
maxPosition: positionSize.negated().times(2),
});
await expectFinalBalances(
txResult,
[short, neutral],
[0, 35000 - feeAmount],
[0, positionSize.negated()],
feeAmount,
);
expectLogs(txResult, {
feeAmount,
liquidatee: short,
liquidator: neutral,
isBuy: false,
liquidationAmount: positionSize,
});
});
it('Succeeds partially liquidating an underwater long position', async () => {
const feeAmount = 0;
await ctx.perpetual.testing.oracle.setPrice(longUnderwaterPrice);
const txResult = await liquidate({
liquidatee: long,
liquidator: neutral,
isBuy: true,
maxPosition: halfPosition,
});
await expectFinalBalances(
txResult,
[long, neutral],
[-2500, 17500 - feeAmount],
[halfPosition, halfPosition],
feeAmount,
);
expectLogs(txResult, {
feeAmount,
liquidatee: long,
liquidator: neutral,
isBuy: true,
liquidationAmount: halfPosition,
});
});
it('Succeeds partially liquidating an underwater short position', async () => {
const feeAmount = 0;
await ctx.perpetual.testing.oracle.setPrice(shortUnderwaterPrice);
const txResult = await liquidate({
liquidatee: short,
liquidator: neutral,
isBuy: false,
maxPosition: halfPosition.negated(),
});
await expectFinalBalances(
txResult,
[short, neutral],
[7500, 27500 - feeAmount],
[halfPosition.negated(), halfPosition.negated()],
feeAmount,
);
expectLogs(txResult, {
feeAmount,
liquidatee: short,
liquidator: neutral,
isBuy: false,
liquidationAmount: halfPosition,
});
});
});
describe('Account Permissions', () => {
it('Succeeds for localOperator', async () => {
const feeAmount = 10;
await Promise.all([
ctx.perpetual.operator.setLocalOperator(rando, true, { from: neutral }),
ctx.perpetual.testing.oracle.setPrice(longUndercollateralizedPrice),
]);
const txResult = await liquidate({
liquidatee: long,
liquidator: neutral,
sender: rando,
isBuy: true,
maxPosition: halfPosition,
});
await expectFinalBalances(
txResult,
[long, neutral],
[-2500, 17500 - feeAmount],
[halfPosition, halfPosition],
feeAmount,
);
expectLogs(txResult, {
feeAmount,
liquidatee: long,
liquidator: neutral,
isBuy: true,
liquidationAmount: halfPosition,
});
});
it('Succeeds for globalOperator', async () => {
const feeAmount = 10;
await Promise.all([
ctx.perpetual.admin.setGlobalOperator(rando, true, { from: admin }),
ctx.perpetual.testing.oracle.setPrice(longUndercollateralizedPrice),
]);
const txResult = await liquidate({
liquidatee: long,
liquidator: neutral,
sender: rando,
isBuy: true,
maxPosition: halfPosition,
});
await expectFinalBalances(
txResult,
[long, neutral],
[-2500, 17500 - feeAmount],
[halfPosition, halfPosition],
feeAmount,
);
expectLogs(txResult, {
feeAmount,
liquidatee: long,
liquidator: neutral,
isBuy: true,
liquidationAmount: halfPosition,
});
});
it('Fails for random account', async () => {
await expectThrow(
liquidate({
liquidatee: long,
liquidator: neutral,
sender: rando,
isBuy: true,
maxPosition: halfPosition,
}),
'msg.sender cannot operate the liquidator account',
);
});
});
describe('Failures', () => {
it('Fails if isBuy=true for a short', async () => {
await expectThrow(
liquidate({
liquidatee: short,
liquidator: neutral,
isBuy: true,
maxPosition: -50,
}),
ERROR_MAX_POSITION,
);
});
it('Fails if isBuy=false for a long', async () => {
await expectThrow(
liquidate({
liquidatee: long,
liquidator: neutral,
isBuy: false,
maxPosition: 50,
}),
ERROR_MAX_POSITION,
);
});
it('Fails if already at maxPosition for a long', async () => {
await expectThrow(
liquidate({
liquidatee: long,
liquidator: short,
isBuy: true,
maxPosition: positionSize.negated(),
}),
ERROR_MAX_POSITION,
);
await expectThrow(
liquidate({
liquidatee: long,
liquidator: neutral,
isBuy: true,
maxPosition: 0,
}),
ERROR_MAX_POSITION,
);
await expectThrow(
liquidate({
liquidatee: long,
liquidator: smallLong,
isBuy: true,
maxPosition: halfPosition,
}),
ERROR_MAX_POSITION,
);
});
it('Fails if already at maxPosition for a short', async () => {
await expectThrow(
liquidate({
liquidatee: short,
liquidator: long,
isBuy: false,
maxPosition: positionSize,
}),
ERROR_MAX_POSITION,
);
await expectThrow(
liquidate({
liquidatee: short,
liquidator: neutral,
isBuy: false,
maxPosition: 0,
}),
ERROR_MAX_POSITION,
);
await expectThrow(
liquidate({
liquidatee: short,
liquidator: smallShort,
isBuy: false,
maxPosition: halfPosition.negated(),
}),
ERROR_MAX_POSITION,
);
});
it('Fails if already past maxPosition for a long', async () => {
await expectThrow(
liquidate({
liquidatee: long,
liquidator: short,
isBuy: true,
maxPosition: positionSize.negated().minus(1),
}),
ERROR_MAX_POSITION,
);
await expectThrow(
liquidate({
liquidatee: long,
liquidator: neutral,
isBuy: true,
maxPosition: -1,
}),
ERROR_MAX_POSITION,
);
await expectThrow(
liquidate({
liquidatee: long,
liquidator: smallLong,
isBuy: true,
maxPosition: halfPosition.minus(1),
}),
ERROR_MAX_POSITION,
);
});
it('Fails if already past maxPosition for a short', async () => {
await expectThrow(
liquidate({
liquidatee: short,
liquidator: long,
isBuy: false,
maxPosition: positionSize.plus(1),
}),
ERROR_MAX_POSITION,
);
await expectThrow(
liquidate({
liquidatee: short,
liquidator: neutral,
isBuy: false,
maxPosition: 1,
}),
ERROR_MAX_POSITION,
);
await expectThrow(
liquidate({
liquidatee: short,
liquidator: smallShort,
isBuy: false,
maxPosition: halfPosition.negated().plus(1),
}),
ERROR_MAX_POSITION,
);
});
});
it('Succeeds even if the insurance fund is undercollateralized', async () => {
await Promise.all([
mintAndDeposit(ctx, insuranceFund, new BigNumber(20000)),
mintAndDeposit(ctx, rando, new BigNumber(20000)),
]);
await buy(
ctx,
insuranceFund,
rando,
positionSize.times(4),
positionSize.times(4).times(initialPrice.value),
);
await ctx.perpetual.testing.oracle.setPrice(longUndercollateralizedPrice);
expect(await ctx.perpetual.getters.getNetAccountIsLiquidatable(insuranceFund)).to.be.true;
const feeAmount = 20;
const txResult = await liquidate({
liquidatee: long,
liquidator: neutral,
isBuy: true,
maxPosition: positionSize,
});
await expectFinalBalances(
txResult,
[long, neutral, insuranceFund],
[0, 15000 - feeAmount, -20000 + feeAmount],
[0, positionSize, positionSize.times(4)],
);
expectLogs(txResult, {
feeAmount,
liquidatee: long,
liquidator: neutral,
isBuy: true,
liquidationAmount: positionSize,
});
expect(await ctx.perpetual.getters.getNetAccountIsLiquidatable(insuranceFund)).to.be.true;
});
});
async function liquidate(options?: LiquidateOptions) {
return ctx.perpetual.liquidatorProxy.liquidate(
options.liquidatee,
options.liquidator,
options.isBuy,
new BigNumber(options.maxPosition),
{ from: options.sender || options.liquidator },
);
}
function expectLogs(
txResult: TxResult,
expected: ExpectedLogOptions,
): void {
const logs = ctx.perpetual.logs.parseLogs(txResult);
const filteredLogs = _.filter(logs, { name: 'LogLiquidatorProxyUsed' });
expect(filteredLogs.length).to.equal(1);
const log = filteredLogs[0];
expect(log.args.liquidatee).to.equal(expected.liquidatee);
expect(log.args.liquidator).to.equal(expected.liquidator);
expectBN(log.args.liquidationAmount).to.equal(expected.liquidationAmount);
expect(log.args.isBuy).to.equal(expected.isBuy);
expectBN(log.args.feeAmount).to.equal(expected.feeAmount);
}
async function expectFinalBalances(
txResult: TxResult,
accounts: address[],
expectedMargins: BigNumberable[],
expectedPositions: BigNumberable[],
feeAmount?: BigNumberable,
): Promise<void> {
const allAccounts = [...accounts];
const allMargins = [...expectedMargins];
const allPositions = [...expectedPositions];
if (feeAmount) {
allAccounts.push(insuranceFund);
allMargins.push(feeAmount);
allPositions.push(0);
}
return expectBalances(
ctx,
txResult,
allAccounts,
allMargins,
allPositions,
false,
false,
);
}
}); | the_stack |
import os = require('os');
import path = require('path');
import net = require('net');
import url = require('url');
import { spawn, ChildProcess } from 'child_process';
import { LanguageClient, LanguageClientOptions, StreamInfo, DocumentFilter, ErrorAction, CloseAction, RevealOutputChannelOn } from 'vscode-languageclient/node';
import { Disposable, workspace, Uri, TextDocument, WorkspaceConfiguration, OutputChannel, window, WorkspaceFolder } from 'vscode';
import { getRpath } from './util';
export class LanguageService implements Disposable {
private readonly clients: Map<string, LanguageClient> = new Map();
private readonly initSet: Set<string> = new Set();
constructor() {
this.startLanguageService(this);
}
dispose(): Thenable<void> {
return this.stopLanguageService();
}
private async createClient(config: WorkspaceConfiguration, selector: DocumentFilter[],
cwd: string, workspaceFolder: WorkspaceFolder, outputChannel: OutputChannel): Promise<LanguageClient> {
let client: LanguageClient;
const debug = config.get<boolean>('lsp.debug');
const path = await getRpath();
if (debug) {
console.log(`R binary: ${path}`);
}
const use_stdio = config.get<boolean>('lsp.use_stdio');
const env = Object.create(process.env);
const lang = config.get<string>('lsp.lang');
if (lang !== '') {
env.LANG = lang;
} else if (env.LANG === undefined) {
env.LANG = 'en_US.UTF-8';
}
if (debug) {
console.log(`LANG: ${env.LANG}`);
}
const options = { cwd: cwd, env: env };
const initArgs: string[] = config.get<string[]>('lsp.args').concat('--quiet', '--slave');
const tcpServerOptions = () => new Promise<ChildProcess | StreamInfo>((resolve, reject) => {
// Use a TCP socket because of problems with blocking STDIO
const server = net.createServer(socket => {
// 'connection' listener
console.log('R process connected');
socket.on('end', () => {
console.log('R process disconnected');
});
socket.on('error', (e: Error) => {
console.log(`R process error: ${e.message}`);
reject(e);
});
server.close();
resolve({ reader: socket, writer: socket });
});
// Listen on random port
server.listen(0, '127.0.0.1', () => {
const port = (server.address() as net.AddressInfo).port;
let args: string[];
// The server is implemented in R
if (debug) {
args = initArgs.concat(['-e', `languageserver::run(port=${port},debug=TRUE)`]);
} else {
args = initArgs.concat(['-e', `languageserver::run(port=${port})`]);
}
const childProcess = spawn(path, args, options);
client.outputChannel.appendLine(`R Language Server (${childProcess.pid}) started`);
childProcess.stderr.on('data', (chunk: Buffer) => {
client.outputChannel.appendLine(chunk.toString());
});
childProcess.on('exit', (code, signal) => {
client.outputChannel.appendLine(`R Language Server (${childProcess.pid}) exited ` +
(signal ? `from signal ${signal}` : `with exit code ${code}`));
if (code !== 0) {
client.outputChannel.show();
}
void client.stop();
});
return childProcess;
});
});
// Options to control the language client
const clientOptions: LanguageClientOptions = {
// Register the server for selected R documents
documentSelector: selector,
uriConverters: {
// VS Code by default %-encodes even the colon after the drive letter
// NodeJS handles it much better
code2Protocol: uri => new url.URL(uri.toString(true)).toString(),
protocol2Code: str => Uri.parse(str)
},
workspaceFolder: workspaceFolder,
outputChannel: outputChannel,
synchronize: {
// Synchronize the setting section 'r' to the server
configurationSection: 'r.lsp',
fileEvents: workspace.createFileSystemWatcher('**/*.{R,r}'),
},
revealOutputChannelOn: RevealOutputChannelOn.Never,
errorHandler: {
error: () => ErrorAction.Shutdown,
closed: () => CloseAction.DoNotRestart,
},
};
// Create the language client and start the client.
if (use_stdio && process.platform !== 'win32') {
let args: string[];
if (debug) {
args = initArgs.concat(['-e', `languageserver::run(debug=TRUE)`]);
} else {
args = initArgs.concat(['-e', `languageserver::run()`]);
}
client = new LanguageClient('r', 'R Language Server', { command: path, args: args, options: options }, clientOptions);
} else {
client = new LanguageClient('r', 'R Language Server', tcpServerOptions, clientOptions);
}
return client;
}
private checkClient(name: string): boolean {
if (this.initSet.has(name)) {
return true;
}
this.initSet.add(name);
const client = this.clients.get(name);
return client && client.needsStop();
}
private getKey(uri: Uri): string {
switch (uri.scheme) {
case 'untitled':
return uri.scheme;
case 'vscode-notebook-cell':
return `vscode-notebook:${uri.fsPath}`;
default:
return uri.toString(true);
}
}
private startLanguageService(self: LanguageService): void {
const config = workspace.getConfiguration('r');
const outputChannel: OutputChannel = window.createOutputChannel('R Language Server');
async function didOpenTextDocument(document: TextDocument) {
if (document.uri.scheme !== 'file' && document.uri.scheme !== 'untitled' && document.uri.scheme !== 'vscode-notebook-cell') {
return;
}
if (document.languageId !== 'r' && document.languageId !== 'rmd') {
return;
}
const folder = workspace.getWorkspaceFolder(document.uri);
// Each notebook uses a server started from parent folder
if (document.uri.scheme === 'vscode-notebook-cell') {
const key = self.getKey(document.uri);
if (!self.checkClient(key)) {
console.log(`Start language server for ${document.uri.toString(true)}`);
const documentSelector: DocumentFilter[] = [
{ scheme: 'vscode-notebook-cell', language: 'r', pattern: `${document.uri.fsPath}` },
];
const client = await self.createClient(config, documentSelector,
path.dirname(document.uri.fsPath), folder, outputChannel);
client.start();
self.clients.set(key, client);
self.initSet.delete(key);
}
return;
}
if (folder) {
// Each workspace uses a server started from the workspace folder
const key = self.getKey(folder.uri);
if (!self.checkClient(key)) {
console.log(`Start language server for ${document.uri.toString(true)}`);
const pattern = `${folder.uri.fsPath}/**/*`;
const documentSelector: DocumentFilter[] = [
{ scheme: 'file', language: 'r', pattern: pattern },
{ scheme: 'file', language: 'rmd', pattern: pattern },
];
const client = await self.createClient(config, documentSelector, folder.uri.fsPath, folder, outputChannel);
client.start();
self.clients.set(key, client);
self.initSet.delete(key);
}
} else {
// All untitled documents share a server started from home folder
if (document.uri.scheme === 'untitled') {
const key = self.getKey(document.uri);
if (!self.checkClient(key)) {
console.log(`Start language server for ${document.uri.toString(true)}`);
const documentSelector: DocumentFilter[] = [
{ scheme: 'untitled', language: 'r' },
{ scheme: 'untitled', language: 'rmd' },
];
const client = await self.createClient(config, documentSelector, os.homedir(), undefined, outputChannel);
client.start();
self.clients.set(key, client);
self.initSet.delete(key);
}
return;
}
// Each file outside workspace uses a server started from parent folder
if (document.uri.scheme === 'file') {
const key = self.getKey(document.uri);
if (!self.checkClient(key)) {
console.log(`Start language server for ${document.uri.toString(true)}`);
const documentSelector: DocumentFilter[] = [
{ scheme: 'file', pattern: document.uri.fsPath },
];
const client = await self.createClient(config, documentSelector,
path.dirname(document.uri.fsPath), undefined, outputChannel);
client.start();
self.clients.set(key, client);
self.initSet.delete(key);
}
return;
}
}
}
function didCloseTextDocument(document: TextDocument): void {
if (document.uri.scheme === 'untitled') {
const result = workspace.textDocuments.find((doc) => doc.uri.scheme === 'untitled');
if (result) {
// Stop the language server when all untitled documents are closed.
return;
}
}
if (document.uri.scheme === 'vscode-notebook-cell') {
const result = workspace.textDocuments.find((doc) =>
doc.uri.scheme === document.uri.scheme && doc.uri.fsPath === document.uri.fsPath);
if (result) {
// Stop the language server when all cell documents are closed (notebook closed).
return;
}
}
// Stop the language server when single file outside workspace is closed, or the above cases.
const key = self.getKey(document.uri);
const client = self.clients.get(key);
if (client) {
self.clients.delete(key);
self.initSet.delete(key);
void client.stop();
}
}
workspace.onDidOpenTextDocument(didOpenTextDocument);
workspace.onDidCloseTextDocument(didCloseTextDocument);
workspace.textDocuments.forEach((doc) => void didOpenTextDocument(doc));
workspace.onDidChangeWorkspaceFolders((event) => {
for (const folder of event.removed) {
const key = self.getKey(folder.uri);
const client = self.clients.get(key);
if (client) {
self.clients.delete(key);
self.initSet.delete(key);
void client.stop();
}
}
});
}
private stopLanguageService(): Thenable<void> {
const promises: Thenable<void>[] = [];
for (const client of this.clients.values()) {
promises.push(client.stop());
}
return Promise.all(promises).then(() => undefined);
}
} | the_stack |
import CurieDBEditor from '@/views/CurieDBEditor.vue'
import GitHistory from '@/components/GitHistory.vue'
import Utils from '@/assets/Utils'
import {afterEach, beforeEach, describe, expect, jest, test} from '@jest/globals'
import {mount, Wrapper} from '@vue/test-utils'
import Vue from 'vue'
import axios from 'axios'
import JSONEditor from 'jsoneditor'
import {Commit} from '@/types'
jest.mock('axios')
jest.mock('jsoneditor')
describe('CurieDBEditor.vue', () => {
let wrapper: Wrapper<Vue>
let dbData: any
let publishInfoData: any
let dbKeyLogs: Commit[]
beforeEach(async () => {
publishInfoData = {
'buckets': [{'name': 'prod', 'url': 's3://curiefense-test01/prod'}, {
'name': 'devops',
'url': 's3://curiefense-test01/devops',
}],
'branch_buckets': [{'name': 'master', 'buckets': ['prod']}, {'name': 'devops', 'buckets': ['devops']}],
}
dbData = {
'publishinfo': publishInfoData,
'tags': {
'neutral': [
'china',
'ukraine',
'internal',
'devops',
'google',
'yahoo',
'localhost',
'tor',
'bad-people',
'dev',
'test-tag',
'all',
'',
'okay',
],
},
}
dbKeyLogs = [{
'author': 'Curiefense API',
'email': 'curiefense@reblaze.com',
'date': '2020-11-10T09:41:31+02:00',
'message': 'Setting key [publishinfo] in namespace [system]',
'version': 'b104d3dd17f790b75c4e067c44bb06b914902d78',
'parents': ['ff59eb0e6d230c077dfa503c9f2d4aacec1b72ab'],
}, {
'author': 'Curiefense API',
'email': 'curiefense@reblaze.com',
'date': '2020-08-27T16:19:58+00:00',
'message': 'Added namespace [system]',
'version': 'ff59eb0e6d230c077dfa503c9f2d4aacec1b72ab',
'parents': ['a34f979217215060861b58b3f270e82580c20efb'],
}]
// @ts-ignore
JSONEditor.mockImplementation((container, options) => {
let value = {}
let onChangeFunc: Function
if (options.onChange) {
onChangeFunc = options.onChange
}
return {
set: (newValue: any) => {
value = newValue
if (typeof onChangeFunc === 'function') {
onChangeFunc()
}
},
get: () => {
return value
},
}
})
jest.spyOn(axios, 'get').mockImplementation((path) => {
if (path === '/conf/api/v2/db/') {
return Promise.resolve({data: ['system', 'namespaceCopy', 'anotherDB']})
}
const db = (wrapper.vm as any).selectedNamespace
const key = (wrapper.vm as any).selectedKey
if (path === `/conf/api/v2/db/new namespace/`) {
return Promise.resolve({data: {key: {}}})
}
if (path === `/conf/api/v2/db/${db}/`) {
return Promise.resolve({data: dbData})
}
if (path === `/conf/api/v2/db/${db}/k/${key}/v/`) {
return Promise.resolve({data: dbKeyLogs})
}
return Promise.resolve({data: {}})
})
wrapper = mount(CurieDBEditor)
await Vue.nextTick()
})
afterEach(() => {
jest.clearAllMocks()
})
test('should have a git history component', () => {
const gitHistory = wrapper.findComponent(GitHistory)
expect(gitHistory).toBeTruthy()
})
test('should log message when receiving no databases from the server', (done) => {
const originalLog = console.log
let consoleOutput: string[] = []
const mockedLog = (output: string) => consoleOutput.push(output)
consoleOutput = []
console.log = mockedLog
jest.spyOn(axios, 'get').mockImplementation((path) => {
if (path === '/conf/api/v2/db/') {
return Promise.resolve({data: []})
}
return Promise.resolve({data: {}})
})
wrapper = mount(CurieDBEditor)
// allow all requests to finish
setImmediate(() => {
expect(consoleOutput).toContain(`failed loading namespace, none are present!`)
console.log = originalLog
done()
})
})
test('should be able to switch namespaces through dropdown', (done) => {
const wantedValue = 'namespaceCopy'
const namespaceSelection = wrapper.find('.namespace-selection')
namespaceSelection.trigger('click')
const options = namespaceSelection.findAll('option')
options.at(1).setSelected()
// allow all requests to finish
setImmediate(() => {
expect((wrapper.vm as any).selectedNamespace).toEqual(wantedValue)
done()
})
})
test('should be able to switch key through dropdown', (done) => {
const wantedValue = Object.keys(dbData)[1]
const keySelection = wrapper.find('.key-selection')
keySelection.trigger('click')
const options = keySelection.findAll('option')
options.at(1).setSelected()
// allow all requests to finish
setImmediate(() => {
expect((wrapper.vm as any).selectedKey).toEqual(wantedValue)
done()
})
})
test('should send API request to restore to the correct version', async () => {
const wantedVersion = {
version: 'b104d3dd17f790b75c4e067c44bb06b914902d78',
}
const putSpy = jest.spyOn(axios, 'put')
putSpy.mockImplementation(() => Promise.resolve())
const gitHistory = wrapper.findComponent(GitHistory);
gitHistory.vm.$emit('restore-version', wantedVersion)
await Vue.nextTick()
expect(putSpy).toHaveBeenCalledWith(`/conf/api/v2/db/system/v/${wantedVersion.version}/revert/`)
})
test('should load last loaded key if still exists after restoring version', (done) => {
const restoredVersion = {
version: 'b104d3dd17f790b75c4e067c44bb06b914902d78',
}
const wantedKey = 'publishinfo';
(wrapper.vm as any).selectedKey = wantedKey
jest.spyOn(axios, 'put').mockImplementation(() => Promise.resolve())
const gitHistory = wrapper.findComponent(GitHistory);
gitHistory.vm.$emit('restore-version', restoredVersion)
// allow all requests to finish
setImmediate(() => {
expect((wrapper.vm as any).selectedKey).toEqual(wantedKey)
done()
})
})
test('should load first key if key no longer exists after restoring version', (done) => {
const restoredVersion = {
version: 'b104d3dd17f790b75c4e067c44bb06b914902d78',
}
const wantedKey = 'publishinfo';
(wrapper.vm as any).selectedKey = 'somekey'
jest.spyOn(axios, 'put').mockImplementation(() => Promise.resolve())
const gitHistory = wrapper.findComponent(GitHistory);
gitHistory.vm.$emit('restore-version', restoredVersion)
// allow all requests to finish
setImmediate(() => {
expect((wrapper.vm as any).selectedKey).toEqual(wantedKey)
done()
})
})
test('should attempt to download namespace when download button is clicked', async () => {
const wantedFileName = 'system'
const wantedFileType = 'json'
const wantedFileData = dbData
const downloadFileSpy = jest.spyOn(Utils, 'downloadFile').mockImplementation(() => {})
// force update because downloadFile is mocked after it is read to to be used as event handler
await (wrapper.vm as any).$forceUpdate()
await Vue.nextTick()
const downloadNamespaceButton = wrapper.find('.download-namespace-button')
downloadNamespaceButton.trigger('click')
await Vue.nextTick()
expect(downloadFileSpy).toHaveBeenCalledWith(wantedFileName, wantedFileType, wantedFileData)
})
test('should attempt to download key when download button is clicked', async () => {
const wantedFileName = 'publishinfo'
const wantedFileType = 'json'
const wantedFileData = publishInfoData
const downloadFileSpy = jest.spyOn(Utils, 'downloadFile').mockImplementation(() => {})
// force update because downloadFile is mocked after it is read to be used as event handler
await (wrapper.vm as any).$forceUpdate()
await Vue.nextTick()
const downloadKeyButton = wrapper.find('.download-key-button')
downloadKeyButton.trigger('click')
await Vue.nextTick()
expect(downloadFileSpy).toHaveBeenCalledWith(wantedFileName, wantedFileType, wantedFileData)
})
test('should not attempt to download key when download button is clicked if value does not exist', async () => {
const wantedFileName = 'publishinfo'
const wantedFileType = 'json'
const wantedFileData = publishInfoData
const downloadFileSpy = jest.spyOn(Utils, 'downloadFile').mockImplementation(() => {});
(wrapper.vm as any).selectedKeyValue = null
// force update because downloadFile is mocked after it is read to be used as event handler
await (wrapper.vm as any).$forceUpdate()
await Vue.nextTick()
const downloadKeyButton = wrapper.find('.download-key-button')
downloadKeyButton.trigger('click')
await Vue.nextTick()
expect(downloadFileSpy).not.toHaveBeenCalledWith(wantedFileName, wantedFileType, wantedFileData)
})
describe('namespace action buttons', () => {
test('should be able to fork namespace', async () => {
const dbData = (wrapper.vm as any).selectedNamespaceData
const putSpy = jest.spyOn(axios, 'put')
putSpy.mockImplementation(() => Promise.resolve())
const forkNamespaceButton = wrapper.find('.fork-namespace-button')
forkNamespaceButton.trigger('click')
await Vue.nextTick()
expect(putSpy).toHaveBeenCalledWith(`/conf/api/v2/db/copy of system/`, dbData)
})
test('should be able to add a new namespace', async () => {
const newNamespace = {
key: {},
}
const putSpy = jest.spyOn(axios, 'put')
putSpy.mockImplementation(() => Promise.resolve())
const newNamespaceButton = wrapper.find('.new-namespace-button')
newNamespaceButton.trigger('click')
await Vue.nextTick()
expect(putSpy).toHaveBeenCalledWith(`/conf/api/v2/db/new namespace/`, newNamespace)
})
test('should be able to delete a namespace', (done) => {
jest.spyOn(axios, 'put').mockImplementation(() => Promise.resolve())
const deleteSpy = jest.spyOn(axios, 'delete')
deleteSpy.mockImplementation(() => Promise.resolve())
// create new namespace so we can delete it
const newNamespaceButton = wrapper.find('.new-namespace-button')
newNamespaceButton.trigger('click')
setImmediate(async () => {
const namespaceName = (wrapper.vm as any).selectedNamespace
const deleteNamespaceButton = wrapper.find('.delete-namespace-button')
deleteNamespaceButton.trigger('click')
await Vue.nextTick()
expect(deleteSpy).toHaveBeenCalledWith(`/conf/api/v2/db/${namespaceName}/`)
done()
})
})
test('should not be able to delete the `system` namespace', async () => {
const deleteSpy = jest.spyOn(axios, 'delete')
deleteSpy.mockImplementation(() => Promise.resolve())
const deleteNamespaceButton = wrapper.find('.delete-namespace-button')
deleteNamespaceButton.trigger('click')
await Vue.nextTick()
expect(deleteSpy).not.toHaveBeenCalled()
})
})
describe('key action buttons', () => {
test('should be able to fork key', async () => {
const doc = JSON.parse((wrapper.vm as any).selectedKeyValue || '{}')
const putSpy = jest.spyOn(axios, 'put')
putSpy.mockImplementation(() => Promise.resolve())
const forkKeyButton = wrapper.find('.fork-key-button')
forkKeyButton.trigger('click')
await Vue.nextTick()
expect(putSpy).toHaveBeenCalledWith(`/conf/api/v2/db/system/k/copy of publishinfo/`, doc)
})
test('should be able to add a new key', async () => {
const newKey = {}
const putSpy = jest.spyOn(axios, 'put')
putSpy.mockImplementation(() => Promise.resolve())
const newKeyButton = wrapper.find('.new-key-button')
newKeyButton.trigger('click')
await Vue.nextTick()
expect(putSpy).toHaveBeenCalledWith(`/conf/api/v2/db/system/k/new key/`, newKey)
})
test('should be able to delete a key', (done) => {
jest.spyOn(axios, 'put').mockImplementation(() => Promise.resolve())
const deleteSpy = jest.spyOn(axios, 'delete')
deleteSpy.mockImplementation(() => Promise.resolve())
// create new key so we can delete it
const newKeyButton = wrapper.find('.new-key-button')
newKeyButton.trigger('click')
setImmediate(async () => {
const keyName = (wrapper.vm as any).selectedKey
const deleteKeyButton = wrapper.find('.delete-key-button')
deleteKeyButton.trigger('click')
await Vue.nextTick()
expect(deleteSpy).toHaveBeenCalledWith(`/conf/api/v2/db/system/k/${keyName}/`)
done()
})
})
test('should not be able to delete a `publishinfo` key under `system` namespace', async () => {
const deleteSpy = jest.spyOn(axios, 'delete')
deleteSpy.mockImplementation(() => Promise.resolve())
const deleteKeyButton = wrapper.find('.delete-key-button')
deleteKeyButton.trigger('click')
await Vue.nextTick()
expect(deleteSpy).not.toHaveBeenCalled()
})
})
describe('save changes button', () => {
let putSpy: any
beforeEach((done) => {
putSpy = jest.spyOn(axios, 'put')
// create a new namespace for empty environment to test changes on
putSpy.mockImplementation(() => Promise.resolve())
const newNamespaceButton = wrapper.find('.new-namespace-button')
newNamespaceButton.trigger('click')
// allow all requests to finish
setImmediate(() => {
jest.clearAllMocks()
putSpy = jest.spyOn(axios, 'put')
done()
})
})
test('should be able to save namespace changes even if namespace name changes', async (done) => {
const namespaceNameInput = wrapper.find('.namespace-name-input')
const key = 'key_name'
const value = {
buckets: {},
foo: 'bar',
}
const wantedResult = {
[key]: value,
}
// @ts-ignore
namespaceNameInput.element.value = 'newDB'
namespaceNameInput.trigger('input')
await Vue.nextTick()
const keyNameInput = wrapper.find('.key-name-input')
// @ts-ignore
keyNameInput.element.value = key
keyNameInput.trigger('input')
await Vue.nextTick()
// @ts-ignore
wrapper.vm.selectedKeyValue = JSON.stringify(value)
await Vue.nextTick()
const saveKeyButton = wrapper.find('.save-button')
saveKeyButton.trigger('click')
await Vue.nextTick()
// allow all requests to finish
setImmediate(() => {
expect(putSpy).toHaveBeenCalledWith(`/conf/api/v2/db/newDB/`, wantedResult)
done()
})
})
test('should be able to save key changes even if key name changes', async () => {
const keyNameInput = wrapper.find('.key-name-input');
(keyNameInput.element as any).value = 'key_name'
keyNameInput.trigger('input')
await Vue.nextTick()
const value = {
buckets: {},
foo: 'bar',
};
(wrapper.vm as any).selectedKeyValue = JSON.stringify(value)
await Vue.nextTick()
const saveKeyButton = wrapper.find('.save-button')
saveKeyButton.trigger('click')
await Vue.nextTick()
expect(putSpy).toHaveBeenCalledWith(`/conf/api/v2/db/new namespace/k/key_name/`, value)
})
test('should be able to save key changes', async () => {
const value = {
buckets: {},
foo: 'bar',
};
(wrapper.vm as any).selectedKeyValue = JSON.stringify(value)
await Vue.nextTick()
const saveKeyButton = wrapper.find('.save-button')
saveKeyButton.trigger('click')
await Vue.nextTick()
expect(putSpy).toHaveBeenCalledWith(`/conf/api/v2/db/new namespace/k/key/`, value)
})
test('should use correct values when saving key changes when using json editor', (done) => {
// setTimeout to allow the editor to be fully loaded before we interact with it
setTimeout(async () => {
const value = {
buckets: {},
foo: 'bar',
};
(wrapper.vm as any).editor.set(value)
await Vue.nextTick()
const saveKeyButton = wrapper.find('.save-button')
saveKeyButton.trigger('click')
await Vue.nextTick()
expect(putSpy).toHaveBeenCalledWith(`/conf/api/v2/db/new namespace/k/key/`, value)
done()
}, 300)
})
test('should not be able to save key changes' +
'if value is an invalid json when not using json editor', async () => {
(wrapper.vm as any).editor = null;
(wrapper.vm as any).isJsonEditor = false
await Vue.nextTick()
const value = '{'
const valueInput = wrapper.find('.value-input');
(valueInput.element as any).value = value
valueInput.trigger('input')
await Vue.nextTick()
const saveKeyButton = wrapper.find('.save-button')
saveKeyButton.trigger('click')
await Vue.nextTick()
expect(putSpy).not.toHaveBeenCalled()
})
test('should not render normal text area if json editor has been loaded', (done) => {
// setTimeout to allow the editor to be fully loaded before we interact with it
setTimeout(async () => {
const valueInput = wrapper.find('.value-input')
expect(valueInput.element).toBeUndefined()
done()
}, 300)
})
test('should default to normal text area when json editor cannot be loaded after 2 seconds', (done) => {
// @ts-ignore
JSONEditor.mockImplementation(() => {
throw new Error('ouchie')
})
wrapper = mount(CurieDBEditor)
// setTimeout to allow the editor to be fully loaded before we interact with it
setTimeout(async () => {
const valueInput = wrapper.find('.value-input')
expect(valueInput.element).toBeDefined()
done()
}, 2300)
})
test('should not be able to save key changes if namespace name is empty', async () => {
const namespaceNameInput = wrapper.find('.namespace-name-input');
(namespaceNameInput.element as any).value = ''
namespaceNameInput.trigger('input')
await Vue.nextTick()
const saveKeyButton = wrapper.find('.save-button')
saveKeyButton.trigger('click')
await Vue.nextTick()
expect(putSpy).not.toHaveBeenCalled()
})
test('should not be able to save key changes if namespace name is duplicate of another namespace', async () => {
const namespaceNameInput = wrapper.find('.namespace-name-input');
(namespaceNameInput.element as any).value = 'namespaceCopy'
namespaceNameInput.trigger('input')
await Vue.nextTick()
const saveKeyButton = wrapper.find('.save-button')
saveKeyButton.trigger('click')
await Vue.nextTick()
expect(putSpy).not.toHaveBeenCalled()
})
test('should not be able to save key changes if key name is empty', async () => {
const keyNameInput = wrapper.find('.key-name-input');
(keyNameInput.element as any).value = ''
keyNameInput.trigger('input')
await Vue.nextTick()
const saveKeyButton = wrapper.find('.save-button')
saveKeyButton.trigger('click')
await Vue.nextTick()
expect(putSpy).not.toHaveBeenCalled()
})
test('should not be able to save key changes if key name is duplicate of another key', async () => {
// add a new key so we would have multiple keys
const newKeyButton = wrapper.find('.new-key-button')
newKeyButton.trigger('click')
// click event
await Vue.nextTick()
// key switch
await Vue.nextTick()
// change key name
const keyNameInput = wrapper.find('.key-name-input');
(keyNameInput.element as any).value = 'key'
keyNameInput.trigger('input')
await Vue.nextTick()
// reset spy counter
jest.clearAllMocks()
putSpy = jest.spyOn(axios, 'put')
// attempt saving duplicate named key
const saveKeyButton = wrapper.find('.save-button')
saveKeyButton.trigger('click')
await Vue.nextTick()
expect(putSpy).not.toHaveBeenCalled()
})
})
describe('no data', () => {
test('should display correct message when there is no namespace list data', (done) => {
jest.spyOn(axios, 'get').mockImplementation((path) => {
if (path === '/conf/api/v2/db/') {
return Promise.resolve({data: []})
}
return Promise.resolve({data: {}})
})
wrapper = mount(CurieDBEditor)
// allow all requests to finish
setImmediate(() => {
const noDataMessage = wrapper.find('.no-data-message')
expect(noDataMessage.element).toBeDefined()
expect(noDataMessage.text().toLowerCase()).toContain('no data found!')
expect(noDataMessage.text().toLowerCase()).toContain('missing namespace.')
done()
})
})
test('should display correct message when there is no key data', (done) => {
jest.spyOn(axios, 'get').mockImplementation((path) => {
if (path === '/conf/api/v2/db/') {
return Promise.resolve({data: ['system', 'namespaceCopy', 'anotherDB']})
}
const db = (wrapper.vm as any).selectedNamespace
if (path === `/conf/api/v2/db/${db}/`) {
return Promise.resolve({data: {}})
}
return Promise.resolve({
data: {},
})
})
wrapper = mount(CurieDBEditor)
// allow all requests to finish
setImmediate(() => {
const noDataMessage = wrapper.find('.no-data-message')
expect(noDataMessage.element).toBeDefined()
expect(noDataMessage.text().toLowerCase()).toContain('no data found!')
expect(noDataMessage.text().toLowerCase()).toContain('missing key.')
done()
})
})
})
describe('loading indicator', () => {
test('should display loading indicator when namespaces list not loaded', async () => {
jest.spyOn(axios, 'get').mockImplementation((path) => {
if (path === '/conf/api/v2/db/') {
return new Promise(() => {
})
}
return Promise.resolve({data: []})
})
wrapper = mount(CurieDBEditor)
await Vue.nextTick()
const valueLoadingIndicator = wrapper.find('.value-loading')
expect(valueLoadingIndicator.element).toBeDefined()
})
test('should display loading indicator when namespace not loaded', async () => {
jest.spyOn(axios, 'get').mockImplementation((path) => {
if (path === '/conf/api/v2/db/') {
return Promise.resolve({data: ['system', 'namespaceCopy', 'anotherDB']})
}
const db = (wrapper.vm as any).selectedNamespace
if (path === `/conf/api/v2/db/${db}/`) {
return new Promise(() => {
})
}
return Promise.resolve({data: {}})
})
wrapper = mount(CurieDBEditor)
await Vue.nextTick()
const valueLoadingIndicator = wrapper.find('.value-loading')
expect(valueLoadingIndicator.element).toBeDefined()
})
test('should display loading indicator when saving value changes', async () => {
jest.spyOn(axios, 'put').mockImplementation(() => new Promise(() => {
}))
const saveDocumentButton = wrapper.find('.save-button')
saveDocumentButton.trigger('click')
await Vue.nextTick()
expect(saveDocumentButton.element.classList).toContain('is-loading')
})
test('should display loading indicator when forking namespace', async () => {
jest.spyOn(axios, 'post').mockImplementation(() => new Promise(() => {
}))
const forkNamespaceButton = wrapper.find('.fork-namespace-button')
forkNamespaceButton.trigger('click')
await Vue.nextTick()
expect(forkNamespaceButton.element.classList).toContain('is-loading')
})
test('should display loading indicator when adding a new namespace', async () => {
jest.spyOn(axios, 'post').mockImplementation(() => new Promise(() => {
}))
const newNamespaceButton = wrapper.find('.new-namespace-button')
newNamespaceButton.trigger('click')
await Vue.nextTick()
expect(newNamespaceButton.element.classList).toContain('is-loading')
})
test('should display loading indicator when deleting a namespace', (done) => {
jest.spyOn(axios, 'put').mockImplementation(() => Promise.resolve())
jest.spyOn(axios, 'delete').mockImplementation(() => new Promise(() => {
}))
// create new namespace so we can delete it
const newNamespaceButton = wrapper.find('.new-namespace-button')
newNamespaceButton.trigger('click')
setImmediate(async () => {
const deleteNamespaceButton = wrapper.find('.delete-namespace-button')
deleteNamespaceButton.trigger('click')
await Vue.nextTick()
expect(deleteNamespaceButton.element.classList).toContain('is-loading')
done()
})
})
test('should display loading indicator when forking key', async () => {
jest.spyOn(axios, 'post').mockImplementation(() => new Promise(() => {
}))
const forkKeyButton = wrapper.find('.fork-key-button')
forkKeyButton.trigger('click')
await Vue.nextTick()
expect(forkKeyButton.element.classList).toContain('is-loading')
})
test('should display loading indicator when adding a new key', async () => {
jest.spyOn(axios, 'post').mockImplementation(() => new Promise(() => {
}))
const newKeyButton = wrapper.find('.new-key-button')
newKeyButton.trigger('click')
await Vue.nextTick()
expect(newKeyButton.element.classList).toContain('is-loading')
})
test('should display loading indicator when deleting a key', (done) => {
jest.spyOn(axios, 'put').mockImplementation(() => Promise.resolve())
jest.spyOn(axios, 'delete').mockImplementation(() => new Promise(() => {
}))
// create new namespace so we can delete it
const newNamespaceButton = wrapper.find('.new-key-button')
newNamespaceButton.trigger('click')
setImmediate(async () => {
const deleteNamespaceButton = wrapper.find('.delete-key-button')
deleteNamespaceButton.trigger('click')
await Vue.nextTick()
expect(deleteNamespaceButton.element.classList).toContain('is-loading')
done()
})
})
})
}) | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* An occurrence is an instance of a Note, or type of analysis that
* can be done for a resource.
*
* To get more information about Occurrence, see:
*
* * [API documentation](https://cloud.google.com/container-analysis/api/reference/rest/)
* * How-to Guides
* * [Official Documentation](https://cloud.google.com/container-analysis/)
*
* ## Example Usage
* ### Container Analysis Occurrence Kms
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
* import * from "fs";
*
* const note = new gcp.containeranalysis.Note("note", {attestationAuthority: {
* hint: {
* humanReadableName: "Attestor Note",
* },
* }});
* const keyring = gcp.kms.getKMSKeyRing({
* name: "my-key-ring",
* location: "global",
* });
* const crypto-key = keyring.then(keyring => gcp.kms.getKMSCryptoKey({
* name: "my-key",
* keyRing: keyring.id,
* }));
* const version = crypto_key.then(crypto_key => gcp.kms.getKMSCryptoKeyVersion({
* cryptoKey: crypto_key.id,
* }));
* const attestor = new gcp.binaryauthorization.Attestor("attestor", {attestationAuthorityNote: {
* noteReference: note.name,
* publicKeys: [{
* id: version.then(version => version.id),
* pkixPublicKey: {
* publicKeyPem: version.then(version => version.publicKeys?[0]?.pem),
* signatureAlgorithm: version.then(version => version.publicKeys?[0]?.algorithm),
* },
* }],
* }});
* const occurrence = new gcp.containeranalysis.Occurence("occurrence", {
* resourceUri: "gcr.io/my-project/my-image",
* noteName: note.id,
* attestation: {
* serializedPayload: Buffer.from(fs.readFileSync("path/to/my/payload.json"), 'binary').toString('base64'),
* signatures: [{
* publicKeyId: version.then(version => version.id),
* serializedPayload: Buffer.from(fs.readFileSync("path/to/my/payload.json.sig"), 'binary').toString('base64'),
* }],
* },
* });
* ```
*
* ## Import
*
* Occurrence can be imported using any of these accepted formats
*
* ```sh
* $ pulumi import gcp:containeranalysis/occurence:Occurence default projects/{{project}}/occurrences/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:containeranalysis/occurence:Occurence default {{project}}/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:containeranalysis/occurence:Occurence default {{name}}
* ```
*/
export class Occurence extends pulumi.CustomResource {
/**
* Get an existing Occurence 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?: OccurenceState, opts?: pulumi.CustomResourceOptions): Occurence {
return new Occurence(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'gcp:containeranalysis/occurence:Occurence';
/**
* Returns true if the given object is an instance of Occurence. 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 Occurence {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === Occurence.__pulumiType;
}
/**
* Occurrence that represents a single "attestation". The authenticity
* of an attestation can be verified using the attached signature.
* If the verifier trusts the public key of the signer, then verifying
* the signature is sufficient to establish trust. In this circumstance,
* the authority to which this attestation is attached is primarily
* useful for lookup (how to find this attestation if you already
* know the authority and artifact to be verified) and intent (for
* which authority this attestation was intended to sign.
* Structure is documented below.
*/
public readonly attestation!: pulumi.Output<outputs.containeranalysis.OccurenceAttestation>;
/**
* The time when the repository was created.
*/
public /*out*/ readonly createTime!: pulumi.Output<string>;
/**
* The note kind which explicitly denotes which of the occurrence details are specified. This field can be used as a filter
* in list requests.
*/
public /*out*/ readonly kind!: pulumi.Output<string>;
/**
* The name of the occurrence.
*/
public /*out*/ readonly name!: pulumi.Output<string>;
/**
* The analysis note associated with this occurrence, in the form of
* projects/[PROJECT]/notes/[NOTE_ID]. This field can be used as a
* filter in list requests.
*/
public readonly noteName!: pulumi.Output<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
public readonly project!: pulumi.Output<string>;
/**
* A description of actions that can be taken to remedy the note.
*/
public readonly remediation!: pulumi.Output<string | undefined>;
/**
* Required. Immutable. A URI that represents the resource for which
* the occurrence applies. For example,
* https://gcr.io/project/image@sha256:123abc for a Docker image.
*/
public readonly resourceUri!: pulumi.Output<string>;
/**
* The time when the repository was last updated.
*/
public /*out*/ readonly updateTime!: pulumi.Output<string>;
/**
* Create a Occurence 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: OccurenceArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: OccurenceArgs | OccurenceState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as OccurenceState | undefined;
inputs["attestation"] = state ? state.attestation : undefined;
inputs["createTime"] = state ? state.createTime : undefined;
inputs["kind"] = state ? state.kind : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["noteName"] = state ? state.noteName : undefined;
inputs["project"] = state ? state.project : undefined;
inputs["remediation"] = state ? state.remediation : undefined;
inputs["resourceUri"] = state ? state.resourceUri : undefined;
inputs["updateTime"] = state ? state.updateTime : undefined;
} else {
const args = argsOrState as OccurenceArgs | undefined;
if ((!args || args.attestation === undefined) && !opts.urn) {
throw new Error("Missing required property 'attestation'");
}
if ((!args || args.noteName === undefined) && !opts.urn) {
throw new Error("Missing required property 'noteName'");
}
if ((!args || args.resourceUri === undefined) && !opts.urn) {
throw new Error("Missing required property 'resourceUri'");
}
inputs["attestation"] = args ? args.attestation : undefined;
inputs["noteName"] = args ? args.noteName : undefined;
inputs["project"] = args ? args.project : undefined;
inputs["remediation"] = args ? args.remediation : undefined;
inputs["resourceUri"] = args ? args.resourceUri : undefined;
inputs["createTime"] = undefined /*out*/;
inputs["kind"] = undefined /*out*/;
inputs["name"] = undefined /*out*/;
inputs["updateTime"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(Occurence.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering Occurence resources.
*/
export interface OccurenceState {
/**
* Occurrence that represents a single "attestation". The authenticity
* of an attestation can be verified using the attached signature.
* If the verifier trusts the public key of the signer, then verifying
* the signature is sufficient to establish trust. In this circumstance,
* the authority to which this attestation is attached is primarily
* useful for lookup (how to find this attestation if you already
* know the authority and artifact to be verified) and intent (for
* which authority this attestation was intended to sign.
* Structure is documented below.
*/
attestation?: pulumi.Input<inputs.containeranalysis.OccurenceAttestation>;
/**
* The time when the repository was created.
*/
createTime?: pulumi.Input<string>;
/**
* The note kind which explicitly denotes which of the occurrence details are specified. This field can be used as a filter
* in list requests.
*/
kind?: pulumi.Input<string>;
/**
* The name of the occurrence.
*/
name?: pulumi.Input<string>;
/**
* The analysis note associated with this occurrence, in the form of
* projects/[PROJECT]/notes/[NOTE_ID]. This field can be used as a
* filter in list requests.
*/
noteName?: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* A description of actions that can be taken to remedy the note.
*/
remediation?: pulumi.Input<string>;
/**
* Required. Immutable. A URI that represents the resource for which
* the occurrence applies. For example,
* https://gcr.io/project/image@sha256:123abc for a Docker image.
*/
resourceUri?: pulumi.Input<string>;
/**
* The time when the repository was last updated.
*/
updateTime?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a Occurence resource.
*/
export interface OccurenceArgs {
/**
* Occurrence that represents a single "attestation". The authenticity
* of an attestation can be verified using the attached signature.
* If the verifier trusts the public key of the signer, then verifying
* the signature is sufficient to establish trust. In this circumstance,
* the authority to which this attestation is attached is primarily
* useful for lookup (how to find this attestation if you already
* know the authority and artifact to be verified) and intent (for
* which authority this attestation was intended to sign.
* Structure is documented below.
*/
attestation: pulumi.Input<inputs.containeranalysis.OccurenceAttestation>;
/**
* The analysis note associated with this occurrence, in the form of
* projects/[PROJECT]/notes/[NOTE_ID]. This field can be used as a
* filter in list requests.
*/
noteName: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* A description of actions that can be taken to remedy the note.
*/
remediation?: pulumi.Input<string>;
/**
* Required. Immutable. A URI that represents the resource for which
* the occurrence applies. For example,
* https://gcr.io/project/image@sha256:123abc for a Docker image.
*/
resourceUri: pulumi.Input<string>;
} | the_stack |
import { Lambda1, Lambda1_deps, Lambda1_toFunction,
Lambda2, Lambda2_deps, Lambda2_toFunction,
Lambda3, Lambda3_deps, Lambda3_toFunction,
Lambda4, Lambda4_deps, Lambda4_toFunction,
Lambda5, Lambda5_deps, Lambda5_toFunction,
Lambda6, Lambda6_deps, Lambda6_toFunction,
toSources, lambda1 } from "./Lambda";
import { Source, Vertex } from "./Vertex";
import { Transaction } from "./Transaction";
import { Lazy } from "./Lazy";
import { Listener } from "./Listener";
import { Stream, StreamWithSend } from "./Stream";
import { Operational } from "./Operational";
import { Tuple2 } from "./Tuple2";
class LazySample<A> {
constructor(cell : Cell<A>) {
this.cell = cell;
}
cell : Cell<A>;
hasValue : boolean = false;
value : A = null;
}
class ApplyState<A,B> {
constructor() {}
f : (a : A) => B = null;
f_present : boolean = false;
a : A = null;
a_present : boolean = false;
}
export class Cell<A> {
private str : Stream<A>;
protected value : A;
protected valueUpdate : A;
private cleanup : () => void;
protected lazyInitValue : Lazy<A>; // Used by LazyCell
private vertex : Vertex;
constructor(initValue : A, str? : Stream<A>) {
this.value = initValue;
if (!str) {
this.str = new Stream<A>();
this.vertex = new Vertex("ConstCell", 0, []);
}
else
Transaction.run(() => this.setStream(str));
}
protected setStream(str : Stream<A>) {
this.str = str;
const me = this,
src = new Source(
str.getVertex__(),
() => {
return str.listen_(me.vertex, (a : A) => {
if (me.valueUpdate == null) {
Transaction.currentTransaction.last(() => {
me.value = me.valueUpdate;
me.lazyInitValue = null;
me.valueUpdate = null;
});
}
me.valueUpdate = a;
}, false);
}
);
this.vertex = new Vertex("Cell", 0, [src]);
// We do a trick here of registering the source for the duration of the current
// transaction so that we are guaranteed to catch any stream events that
// occur in the same transaction.
//
// A new temporary vertex null is constructed here as a performance work-around to avoid
// having too many children in Vertex.NULL as a deregister operation is O(n^2) where
// n is the number of children in the vertex.
let tmpVertexNULL = new Vertex("Cell::setStream", 1e12, []);
this.vertex.register(tmpVertexNULL);
Transaction.currentTransaction.last(() => {
this.vertex.deregister(tmpVertexNULL);
});
}
getVertex__() : Vertex {
return this.vertex;
}
getStream__() : Stream<A> { // TO DO: Figure out how to hide this
return this.str;
}
/**
* Sample the cell's current value.
* <p>
* It should generally be avoided in favour of {@link listen(Handler)} so you don't
* miss any updates, but in many circumstances it makes sense.
* <p>
* NOTE: In the Java and other versions of Sodium, using sample() inside map(), filter() and
* merge() is encouraged. In the Javascript/Typescript version, not so much, for the
* following reason: The memory management is different in the Javascript version, and this
* requires us to track all dependencies. In order for the use of sample() inside
* a closure to be correct, the cell that was sample()d inside the closure would have to be
* declared explicitly using the helpers lambda1(), lambda2(), etc. Because this is
* something that can be got wrong, we don't encourage this kind of use of sample() in
* Javascript. Better and simpler to use snapshot().
* <p>
* NOTE: If you need to sample() a cell, you have to make sure it's "alive" in terms of
* memory management or it will ignore updates. To make a cell work correctly
* with sample(), you have to ensure that it's being used. One way to guarantee this is
* to register a dummy listener on the cell. It will also work to have it referenced
* by something that is ultimately being listened to.
*/
sample() : A {
return Transaction.run(() => { return this.sampleNoTrans__(); });
}
sampleNoTrans__() : A { // TO DO figure out how to hide this
return this.value;
}
/**
* A variant of {@link sample()} that works with {@link CellLoop}s when they haven't been looped yet.
* It should be used in any code that's general enough that it could be passed a {@link CellLoop}.
* @see Stream#holdLazy(Lazy) Stream.holdLazy()
*/
sampleLazy() : Lazy<A> {
const me = this;
return Transaction.run(() => me.sampleLazyNoTrans__());
}
sampleLazyNoTrans__() : Lazy<A> { // TO DO figure out how to hide this
const me = this,
s = new LazySample<A>(me);
Transaction.currentTransaction.sample(() => {
s.value = me.valueUpdate != null ? me.valueUpdate : me.sampleNoTrans__();
s.hasValue = true;
s.cell = null;
});
return new Lazy<A>(() => {
if (s.hasValue)
return s.value;
else
return s.cell.sample();
});
}
/**
* Transform the cell's value according to the supplied function, so the returned Cell
* always reflects the value of the function applied to the input Cell's value.
* @param f Function to apply to convert the values. It must be <em>referentially transparent</em>.
*/
map<B>(f : ((a : A) => B) | Lambda1<A,B>) : Cell<B> {
const c = this;
return Transaction.run(() =>
Operational.updates(c).map(f).holdLazy(c.sampleLazy().map(Lambda1_toFunction(f)))
);
}
/**
* Lift a binary function into cells, so the returned Cell always reflects the specified
* function applied to the input cells' values.
* @param fn Function to apply. It must be <em>referentially transparent</em>.
*/
lift<B,C>(b : Cell<B>,
fn0 : ((a : A, b : B) => C) |
Lambda2<A,B,C>) : Cell<C> {
const fn = Lambda2_toFunction(fn0),
cf = this.map((aa : A) => (bb : B) => fn(aa, bb));
return Cell.apply(cf, b,
toSources(Lambda2_deps(fn0)));
}
/**
* Lift a ternary function into cells, so the returned Cell always reflects the specified
* function applied to the input cells' values.
* @param fn Function to apply. It must be <em>referentially transparent</em>.
*/
lift3<B,C,D>(b : Cell<B>, c : Cell<C>,
fn0 : ((a : A, b : B, c : C) => D) |
Lambda3<A,B,C,D>) : Cell<D> {
const fn = Lambda3_toFunction(fn0),
mf : (aa : A) => (bb : B) => (cc : C) => D =
(aa : A) => (bb : B) => (cc : C) => fn(aa, bb, cc),
cf = this.map(mf);
return Cell.apply(
Cell.apply<B, (c : C) => D>(cf, b),
c,
toSources(Lambda3_deps(fn0)));
}
/**
* Lift a quaternary function into cells, so the returned Cell always reflects the specified
* function applied to the input cells' values.
* @param fn Function to apply. It must be <em>referentially transparent</em>.
*/
lift4<B,C,D,E>(b : Cell<B>, c : Cell<C>, d : Cell<D>,
fn0 : ((a : A, b : B, c : C, d : D) => E) |
Lambda4<A,B,C,D,E>) : Cell<E> {
const fn = Lambda4_toFunction(fn0),
mf : (aa : A) => (bb : B) => (cc : C) => (dd : D) => E =
(aa : A) => (bb : B) => (cc : C) => (dd : D) => fn(aa, bb, cc, dd),
cf = this.map(mf);
return Cell.apply(
Cell.apply(
Cell.apply<B, (c : C) => (d : D) => E>(cf, b),
c),
d,
toSources(Lambda4_deps(fn0)));
}
/**
* Lift a 5-argument function into cells, so the returned Cell always reflects the specified
* function applied to the input cells' values.
* @param fn Function to apply. It must be <em>referentially transparent</em>.
*/
lift5<B,C,D,E,F>(b : Cell<B>, c : Cell<C>, d : Cell<D>, e : Cell<E>,
fn0 : ((a : A, b : B, c : C, d : D, e : E) => F) |
Lambda5<A,B,C,D,E,F>) : Cell<F> {
const fn = Lambda5_toFunction(fn0),
mf : (aa : A) => (bb : B) => (cc : C) => (dd : D) => (ee : E) => F =
(aa : A) => (bb : B) => (cc : C) => (dd : D) => (ee : E) => fn(aa, bb, cc, dd, ee),
cf = this.map(mf);
return Cell.apply(
Cell.apply(
Cell.apply(
Cell.apply<B, (c : C) => (d : D) => (e : E) => F>(cf, b),
c),
d),
e,
toSources(Lambda5_deps(fn0)));
}
/**
* Lift a 6-argument function into cells, so the returned Cell always reflects the specified
* function applied to the input cells' values.
* @param fn Function to apply. It must be <em>referentially transparent</em>.
*/
lift6<B,C,D,E,F,G>(b : Cell<B>, c : Cell<C>, d : Cell<D>, e : Cell<E>, f : Cell<F>,
fn0 : ((a : A, b : B, c : C, d : D, e : E, f : F) => G) |
Lambda6<A,B,C,D,E,F,G>) : Cell<G> {
const fn = Lambda6_toFunction(fn0),
mf : (aa : A) => (bb : B) => (cc : C) => (dd : D) => (ee : E) => (ff : F) => G =
(aa : A) => (bb : B) => (cc : C) => (dd : D) => (ee : E) => (ff : F) => fn(aa, bb, cc, dd, ee, ff),
cf = this.map(mf);
return Cell.apply(
Cell.apply(
Cell.apply(
Cell.apply(
Cell.apply<B, (c : C) => (d : D) => (e : E) => (f : F) => G>(cf, b),
c),
d),
e),
f,
toSources(Lambda6_deps(fn0)));
}
/**
* High order depenency traking. If any newly created sodium objects within a value of a cell of a sodium object
* happen to accumulate state, this method will keep the accumulation of state up to date.
*/
public tracking(extractor: (a: A) => (Stream<any>|Cell<any>)[]) : Cell<A> {
const out = new StreamWithSend<A>(null);
let vertex = new Vertex("tracking", 0, [
new Source(
this.vertex,
() => {
let cleanup2: ()=>void = () => {};
let updateDeps =
(a: A) => {
let lastCleanups2 = cleanup2;
let deps = extractor(a).map(dep => dep.getVertex__());
for (let i = 0; i < deps.length; ++i) {
let dep = deps[i];
vertex.childrn.push(dep);
dep.increment(Vertex.NULL);
}
cleanup2 = () => {
for (let i = 0; i < deps.length; ++i) {
let dep = deps[i];
for (let j = 0; j < vertex.childrn.length; ++j) {
if (vertex.childrn[j] === dep) {
vertex.childrn.splice(j, 1);
break;
}
}
dep.decrement(Vertex.NULL);
}
};
lastCleanups2();
};
updateDeps(this.sample());
var cleanup1 =
Operational.updates(this).listen_(
vertex,
(a: A) => {
updateDeps(a);
out.send_(a);
},
false
);
return () => {
cleanup1();
cleanup2();
}
}
)
]);
out.setVertex__(vertex);
return out.holdLazy(this.sampleLazy());
}
/**
* Lift an array of cells into a cell of an array.
*/
public static liftArray<A>(ca : Cell<A>[]) : Cell<A[]> {
return Cell._liftArray(ca, 0, ca.length);
}
private static _liftArray<A>(ca : Cell<A>[], fromInc: number, toExc: number) : Cell<A[]> {
if (toExc - fromInc == 0) {
return new Cell<A[]>([]);
} else if (toExc - fromInc == 1) {
return ca[fromInc].map(a => [a]);
} else {
let pivot = Math.floor((fromInc + toExc) / 2);
// the thunk boxing/unboxing here is a performance hack for lift when there are simutaneous changing cells.
return Cell._liftArray(ca, fromInc, pivot).lift(
Cell._liftArray(ca, pivot, toExc),
(array1, array2) => () => array1.concat(array2)
)
.map(x => x());
}
}
/**
* Apply a value inside a cell to a function inside a cell. This is the
* primitive for all function lifting.
*/
static apply<A,B>(cf : Cell<(a : A) => B>, ca : Cell<A>, sources? : Source[]) : Cell<B> {
return Transaction.run(() => {
let pumping = false;
const state = new ApplyState<A,B>(),
out = new StreamWithSend<B>(),
cf_updates = Operational.updates(cf),
ca_updates = Operational.updates(ca),
pump = () => {
if (pumping) {
return;
}
pumping = true;
Transaction.currentTransaction.prioritized(out.getVertex__(), () => {
let f = state.f_present ? state.f : cf.sampleNoTrans__();
let a = state.a_present ? state.a : ca.sampleNoTrans__();
out.send_(f(a));
pumping = false;
});
},
src1 = new Source(
cf_updates.getVertex__(),
() => {
return cf_updates.listen_(out.getVertex__(), (f : (a : A) => B) => {
state.f = f;
state.f_present = true;
pump();
}, false);
}
),
src2 = new Source(
ca_updates.getVertex__(),
() => {
return ca_updates.listen_(out.getVertex__(), (a : A) => {
state.a = a;
state.a_present = true;
pump();
}, false);
}
);
out.setVertex__(new Vertex("apply", 0,
[src1, src2].concat(sources ? sources : [])
));
return out.holdLazy(new Lazy<B>(() =>
cf.sampleNoTrans__()(ca.sampleNoTrans__())
));
});
}
/**
* Unwrap a cell inside another cell to give a time-varying cell implementation.
*/
static switchC<A>(cca : Cell<Cell<A>>) : Cell<A> {
return Transaction.run(() => {
const za = cca.sampleLazy().map((ba : Cell<A>) => ba.sample()),
out = new StreamWithSend<A>();
let outValue: A = null;
let pumping = false;
const pump = () => {
if (pumping) {
return;
}
pumping = true;
Transaction.currentTransaction.prioritized(out.getVertex__(), () => {
out.send_(outValue);
outValue = null;
pumping = false;
});
};
let last_ca : Cell<A> = null;
const cca_value = Operational.value(cca),
src = new Source(
cca_value.getVertex__(),
() => {
let kill2 : () => void = last_ca === null ? null :
Operational.value(last_ca).listen_(out.getVertex__(),
(a : A) => { outValue = a; pump(); }, false);
const kill1 = cca_value.listen_(out.getVertex__(), (ca : Cell<A>) => {
last_ca = ca;
// Connect before disconnect to avoid memory bounce, when switching to same cell twice.
let nextKill2 = Operational.value(ca).listen_(out.getVertex__(),
(a : A) => {
outValue = a;
pump();
},
false);
if (kill2 !== null)
kill2();
kill2 = nextKill2;
}, false);
return () => { kill1(); kill2(); };
}
);
out.setVertex__(new Vertex("switchC", 0, [src]));
return out.holdLazy(za);
});
}
/**
* Unwrap a stream inside a cell to give a time-varying stream implementation.
*/
static switchS<A>(csa : Cell<Stream<A>>) : Stream<A> {
return Transaction.run(() => {
const out = new StreamWithSend<A>(),
h2 = (a : A) => {
out.send_(a);
},
src = new Source(
csa.getVertex__(),
() => {
let kill2 = csa.sampleNoTrans__().listen_(out.getVertex__(), h2, false);
const kill1 = csa.getStream__().listen_(out.getVertex__(), (sa : Stream<A>) => {
// Connect before disconnect to avoid memory bounce, when switching to same stream twice.
let nextKill2 = sa.listen_(out.getVertex__(), h2, true);
kill2();
kill2 = nextKill2;
}, false);
return () => { kill1(); kill2(); };
}
);
out.setVertex__(new Vertex("switchS", 0, [src]));
return out;
});
}
/**
* When transforming a value from a larger type to a smaller type, it is likely for duplicate changes to become
* propergated. This function insures only distinct changes get propergated.
*/
calm(eq: (a:A,b:A)=>boolean): Cell<A> {
return Operational
.updates(this)
.collectLazy(
this.sampleLazy(),
(newValue, oldValue) => {
let result: A;
if (eq(newValue, oldValue)) {
result = null;
} else {
result = newValue;
}
return new Tuple2(result, newValue);
}
)
.filterNotNull()
.holdLazy(this.sampleLazy());
}
/**
* This function is the same as calm, except you do not need to pass an eq function. This function will use (===)
* as its eq function. I.E. calling calmRefEq() is the same as calm((a,b) => a === b).
*/
calmRefEq(): Cell<A> {
return this.calm((a, b) => a === b);
}
/**
* Listen for updates to the value of this cell. This is the observer pattern. The
* returned {@link Listener} has a {@link Listener#unlisten()} method to cause the
* listener to be removed. This is an OPERATIONAL mechanism is for interfacing between
* the world of I/O and for FRP.
* @param h The handler to execute when there's a new value.
* You should make no assumptions about what thread you are called on, and the
* handler should not block. You are not allowed to use {@link CellSink#send(Object)}
* or {@link StreamSink#send(Object)} in the handler.
* An exception will be thrown, because you are not meant to use this to create
* your own primitives.
*/
listen(h : (a : A) => void) : () => void {
return Transaction.run(() => {
return Operational.value(this).listen(h);
});
}
/**
* Fantasy-land Algebraic Data Type Compatability.
* Cell satisfies the Functor, Apply, Applicative categories
* @see {@link https://github.com/fantasyland/fantasy-land} for more info
*/
//of :: Applicative f => a -> f a
static 'fantasy-land/of'<A>(a:A):Cell<A> {
return new Cell<A>(a);
}
//map :: Functor f => f a ~> (a -> b) -> f b
'fantasy-land/map'<B>(f : ((a : A) => B)) : Cell<B> {
return this.map(f);
}
//ap :: Apply f => f a ~> f (a -> b) -> f b
'fantasy-land/ap'<B>(cf: Cell<(a : A) => B>):Cell<B> {
return Cell.apply(cf, this);
}
} | the_stack |
import { Injectable } from '@angular/core';
import { CoreSyncBaseProvider, CoreSyncBlockedError } from '@classes/base-sync';
import { CoreApp } from '@services/app';
import { CoreEvents } from '@singletons/events';
import { CoreSites } from '@services/sites';
import { CoreUtils } from '@services/utils/utils';
import {
AddonCalendar,
AddonCalendarEvent,
AddonCalendarProvider,
AddonCalendarSubmitCreateUpdateFormDataWSParams,
} from './calendar';
import { AddonCalendarOffline } from './calendar-offline';
import { AddonCalendarHelper } from './calendar-helper';
import { makeSingleton, Translate } from '@singletons';
import { CoreSync } from '@services/sync';
import { CoreNetworkError } from '@classes/errors/network-error';
/**
* Service to sync calendar.
*/
@Injectable({ providedIn: 'root' })
export class AddonCalendarSyncProvider extends CoreSyncBaseProvider<AddonCalendarSyncEvents> {
static readonly AUTO_SYNCED = 'addon_calendar_autom_synced';
static readonly MANUAL_SYNCED = 'addon_calendar_manual_synced';
static readonly SYNC_ID = 'calendar';
protected componentTranslatableString = 'addon.calendar.calendarevent';
constructor() {
super('AddonCalendarSync');
}
/**
* Try to synchronize all events in a certain site or in all sites.
*
* @param siteId Site ID to sync. If not defined, sync all sites.
* @param force Wether to force sync not depending on last execution.
* @return Promise resolved if sync is successful, rejected if sync fails.
*/
async syncAllEvents(siteId?: string, force = false): Promise<void> {
await this.syncOnSites('all calendar events', this.syncAllEventsFunc.bind(this, force), siteId);
}
/**
* Sync all events on a site.
*
* @param force Wether to force sync not depending on last execution.
* @param siteId Site ID to sync.
* @return Promise resolved if sync is successful, rejected if sync fails.
*/
protected async syncAllEventsFunc(force = false, siteId?: string): Promise<void> {
const result = force
? await this.syncEvents(siteId)
: await this.syncEventsIfNeeded(siteId);
if (result?.updated) {
// Sync successful, send event.
CoreEvents.trigger(AddonCalendarSyncProvider.AUTO_SYNCED, result, siteId);
}
}
/**
* Sync a site events only if a certain time has passed since the last time.
*
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the events are synced or if it doesn't need to be synced.
*/
async syncEventsIfNeeded(siteId?: string): Promise<AddonCalendarSyncEvents | undefined> {
siteId = siteId || CoreSites.getCurrentSiteId();
const needed = await this.isSyncNeeded(AddonCalendarSyncProvider.SYNC_ID, siteId);
if (needed) {
return this.syncEvents(siteId);
}
}
/**
* Synchronize all offline events of a certain site.
*
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved if sync is successful, rejected otherwise.
*/
async syncEvents(siteId?: string): Promise<AddonCalendarSyncEvents> {
siteId = siteId || CoreSites.getCurrentSiteId();
if (this.isSyncing(AddonCalendarSyncProvider.SYNC_ID, siteId)) {
// There's already a sync ongoing for this site, return the promise.
return this.getOngoingSync(AddonCalendarSyncProvider.SYNC_ID, siteId)!;
}
this.logger.debug('Try to sync calendar events for site ' + siteId);
// Get offline events.
const syncPromise = this.performSyncEvents(siteId);
return this.addOngoingSync(AddonCalendarSyncProvider.SYNC_ID, syncPromise, siteId);
}
/**
* Sync user preferences of a site.
*
* @param siteId Site ID to sync.
* @param Promise resolved if sync is successful, rejected if sync fails.
*/
protected async performSyncEvents(siteId: string): Promise<AddonCalendarSyncEvents> {
const result: AddonCalendarSyncEvents = {
warnings: [],
events: [],
deleted: [],
toinvalidate: [],
updated: false,
};
const eventIds: number[] = await CoreUtils.ignoreErrors(AddonCalendarOffline.getAllEventsIds(siteId), []);
if (eventIds.length > 0) {
if (!CoreApp.isOnline()) {
// Cannot sync in offline.
throw new CoreNetworkError();
}
const promises = eventIds.map((eventId) => this.syncOfflineEvent(eventId, result, siteId));
await CoreUtils.allPromises(promises);
if (result.updated) {
// Data has been sent to server. Now invalidate the WS calls.
const promises = [
AddonCalendar.invalidateEventsList(siteId),
AddonCalendarHelper.refreshAfterChangeEvents(result.toinvalidate, siteId),
];
await CoreUtils.ignoreErrors(Promise.all(promises));
}
}
// Sync finished, set sync time.
await CoreUtils.ignoreErrors(this.setSyncTime(AddonCalendarSyncProvider.SYNC_ID, siteId));
// All done, return the result.
return result;
}
/**
* Synchronize an offline event.
*
* @param eventId The event ID to sync.
* @param result Object where to store the result of the sync.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved if sync is successful, rejected otherwise.
*/
protected async syncOfflineEvent(eventId: number, result: AddonCalendarSyncEvents, siteId?: string): Promise<void> {
// Verify that event isn't blocked.
if (CoreSync.isBlocked(AddonCalendarProvider.COMPONENT, eventId, siteId)) {
this.logger.debug('Cannot sync event ' + eventId + ' because it is blocked.');
throw new CoreSyncBlockedError(Translate.instant(
'core.errorsyncblocked',
{ $a: Translate.instant('addon.calendar.calendarevent') },
));
}
// First of all, check if the event has been deleted.
try {
const data = await AddonCalendarOffline.getDeletedEvent(eventId, siteId);
// Delete the event.
try {
await AddonCalendar.deleteEventOnline(data.id, !!data.repeat, siteId);
result.updated = true;
result.deleted.push(eventId);
// Event sent, delete the offline data.
const promises: Promise<void>[] = [];
promises.push(AddonCalendarOffline.unmarkDeleted(eventId, siteId));
promises.push(AddonCalendarOffline.deleteEvent(eventId, siteId).catch(() => {
// Ignore errors, maybe there was no edit data.
}));
// We need the event data to invalidate it. Get it from local DB.
promises.push(AddonCalendar.getEventFromLocalDb(eventId, siteId).then((event) => {
result.toinvalidate.push({
id: event.id,
repeatid: event.repeatid,
timestart: event.timestart,
repeated: data?.repeat ? (event as AddonCalendarEvent).eventcount || 1 : 1,
});
return;
}).catch(() => {
// Ignore errors.
}));
await Promise.all(promises);
} catch (error) {
if (!CoreUtils.isWebServiceError(error)) {
// Local error, reject.
throw error;
}
// The WebService has thrown an error, this means that the event cannot be created. Delete it.
result.updated = true;
const promises: Promise<void>[] = [];
promises.push(AddonCalendarOffline.unmarkDeleted(eventId, siteId));
promises.push(AddonCalendarOffline.deleteEvent(eventId, siteId).catch(() => {
// Ignore errors, maybe there was no edit data.
}));
await Promise.all(promises);
// Event deleted, add a warning.
this.addOfflineDataDeletedWarning(result.warnings, data.name, error);
}
return;
} catch {
// Not deleted.
}
// Not deleted. Now get the event data.
const event = await AddonCalendarOffline.getEvent(eventId, siteId);
// Try to send the data.
const data: AddonCalendarSubmitCreateUpdateFormDataWSParams = Object.assign(
CoreUtils.clone(event),
{
description: {
text: event.description || '',
format: 1,
},
},
); // Clone the object because it will be modified in the submit function.
try {
const newEvent = await AddonCalendar.submitEventOnline(eventId > 0 ? eventId : 0, data, siteId);
result.updated = true;
result.events.push(newEvent);
// Add data to invalidate.
const numberOfRepetitions = data.repeat ? data.repeats :
(data.repeateditall && newEvent.repeatid ? newEvent.eventcount : 1);
result.toinvalidate.push({
id: newEvent.id,
repeatid: newEvent.repeatid,
timestart: newEvent.timestart,
repeated: numberOfRepetitions || 1,
});
// Event sent, delete the offline data.
return AddonCalendarOffline.deleteEvent(event.id!, siteId);
} catch (error) {
if (!CoreUtils.isWebServiceError(error)) {
// Local error, reject.
throw error;
}
// The WebService has thrown an error, this means that the event cannot be created. Delete it.
result.updated = true;
await AddonCalendarOffline.deleteEvent(event.id!, siteId);
// Event deleted, add a warning.
this.addOfflineDataDeletedWarning(result.warnings, event.name, error);
}
}
}
export const AddonCalendarSync = makeSingleton(AddonCalendarSyncProvider);
export type AddonCalendarSyncEvents = {
warnings: string[];
events: AddonCalendarEvent[];
deleted: number[];
toinvalidate: AddonCalendarSyncInvalidateEvent[];
updated: boolean;
source?: string; // Added on pages.
day?: number; // Added on day page.
month?: number; // Added on day page.
year?: number; // Added on day page.
};
export type AddonCalendarSyncInvalidateEvent = {
id: number;
repeatid?: number;
timestart: number;
repeated: number;
}; | the_stack |
import { ILoggingPayload } from "../../types/logger";
import { IVersionPackage } from "../../types/option";
import { IVSCodeObject } from "../../types/vscode";
import { EXTENSION_COMMANDS, EXTENSION_MODULES } from "../constants/commands";
import { PAYLOAD_MESSAGES_TEXT } from "../constants/constants";
const postMessageAsync = (
command: string,
paramsMessage: any,
vscode: IVSCodeObject,
scopeId: number = Math.random()
) => {
const promise = new Promise<any>((resolve) => {
paramsMessage.payload = paramsMessage.payload || {};
paramsMessage.payload.scope = scopeId;
const callbackVsCode = (event: any) => {
if (event.data.command === command) {
if (event.data.payload && event.data.payload.scope === scopeId) {
resolve(event);
window.removeEventListener("message", callbackVsCode);
}
}
};
window.addEventListener("message", callbackVsCode);
vscode.postMessage(paramsMessage);
});
return promise;
};
const projectPathValidation = (projectPath: string, projectName: string, vscode: IVSCodeObject): Promise<any> => {
const promise: Promise<any> = postMessageAsync(
EXTENSION_COMMANDS.PROJECT_PATH_VALIDATION,
{
module: EXTENSION_MODULES.VALIDATOR,
command: EXTENSION_COMMANDS.PROJECT_PATH_VALIDATION,
track: false,
projectPath,
projectName,
},
vscode
);
return promise;
};
const getFrameworks = (vscode: IVSCodeObject, projectType: string): Promise<any> => {
return postMessageAsync(
EXTENSION_COMMANDS.GET_FRAMEWORKS,
{
module: EXTENSION_MODULES.CORETS,
command: EXTENSION_COMMANDS.GET_FRAMEWORKS,
payload: { projectType },
},
vscode
);
};
const getProjectTypes = (vscode: IVSCodeObject): Promise<any> => {
return postMessageAsync(
EXTENSION_COMMANDS.GET_PROJECT_TYPES,
{
module: EXTENSION_MODULES.CORETS,
command: EXTENSION_COMMANDS.GET_PROJECT_TYPES,
},
vscode
);
};
const getTemplateInfo = (vscode: IVSCodeObject): Promise<any> => {
return postMessageAsync(
EXTENSION_COMMANDS.GET_TEMPLATE_INFO,
{
module: EXTENSION_MODULES.CORETS,
command: EXTENSION_COMMANDS.GET_TEMPLATE_INFO,
payload: {},
},
vscode
);
};
const getLatestVersion = (vscode: IVSCodeObject, checkVersionPackage: IVersionPackage): Promise<any> => {
return postMessageAsync(
EXTENSION_COMMANDS.GET_LATEST_VERSION,
{
module: EXTENSION_MODULES.DEPENDENCYCHECKER,
command: EXTENSION_COMMANDS.GET_LATEST_VERSION,
payload: {
checkVersionPackage,
},
},
vscode
).then((event) => {
const latestVersion = event.data.payload.latestVersion;
return latestVersion;
});
};
const getPages = (
vscode: IVSCodeObject,
projectTypeName: string,
frontendName: string,
backendName: string
): Promise<any> => {
return postMessageAsync(
EXTENSION_COMMANDS.GET_PAGES,
{
module: EXTENSION_MODULES.CORETS,
command: EXTENSION_COMMANDS.GET_PAGES,
payload: {
projectType: projectTypeName,
frontendFramework: frontendName,
backendFramework: backendName,
},
},
vscode
);
};
const getFeatures = (
vscode: IVSCodeObject,
projectTypeName: string,
frontendName: string,
backendName: string
): Promise<any> => {
return postMessageAsync(
EXTENSION_COMMANDS.GET_FEATURES,
{
module: EXTENSION_MODULES.CORETS,
command: EXTENSION_COMMANDS.GET_FEATURES,
payload: {
projectType: projectTypeName,
frontendFramework: frontendName,
backendFramework: backendName,
},
},
vscode
);
};
const getOutputPathFromConfig = (vscode: IVSCodeObject): Promise<any> => {
return postMessageAsync(
EXTENSION_COMMANDS.GET_OUTPUT_PATH_FROM_CONFIG,
{
module: EXTENSION_MODULES.DEFAULTS,
command: EXTENSION_COMMANDS.GET_OUTPUT_PATH_FROM_CONFIG,
},
vscode
);
};
const browseNewOutputPath = (outputPath: string, vscode: IVSCodeObject): Promise<any> => {
return postMessageAsync(
EXTENSION_COMMANDS.BROWSE_NEW_OUTPUT_PATH,
{
module: EXTENSION_MODULES.DEFAULTS,
command: EXTENSION_COMMANDS.BROWSE_NEW_OUTPUT_PATH,
payload: {
outputPath,
},
},
vscode
);
};
const azureLogout = (vscode: IVSCodeObject): Promise<any> => {
return postMessageAsync(
EXTENSION_COMMANDS.AZURE_LOGOUT,
{
module: EXTENSION_MODULES.AZURE,
command: EXTENSION_COMMANDS.AZURE_LOGOUT,
track: true,
},
vscode
);
};
const azureLogin = (vscode: IVSCodeObject): Promise<any> => {
return postMessageAsync(
EXTENSION_COMMANDS.AZURE_LOGIN,
{
command: EXTENSION_COMMANDS.AZURE_LOGIN,
module: EXTENSION_MODULES.AZURE,
track: true,
},
vscode
);
};
const getUserStatus = (vscode: IVSCodeObject): Promise<any> => {
return postMessageAsync(
EXTENSION_COMMANDS.GET_USER_STATUS,
{
module: EXTENSION_MODULES.AZURE,
command: EXTENSION_COMMANDS.GET_USER_STATUS,
track: true,
},
vscode
);
};
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
const sendTelemetry = (vscode: IVSCodeObject, command: string, payload?: any): void => {
vscode.postMessage({
module: EXTENSION_MODULES.TELEMETRY,
command,
...payload,
});
};
const GetValidAppServiceName = (projectName: string, vscode: IVSCodeObject): Promise<any> => {
return postMessageAsync(
EXTENSION_COMMANDS.GET_VALID_APP_SERVICE_NAME,
{
module: EXTENSION_MODULES.AZURE,
command: EXTENSION_COMMANDS.GET_VALID_APP_SERVICE_NAME,
projectName,
},
vscode
);
};
const GetValidCosmosAccountName = (projectName: string, vscode: IVSCodeObject): Promise<any> => {
return postMessageAsync(
EXTENSION_COMMANDS.GET_VALID_COSMOS_NAME,
{
module: EXTENSION_MODULES.AZURE,
command: EXTENSION_COMMANDS.GET_VALID_COSMOS_NAME,
projectName,
},
vscode
);
};
const ValidateAppServiceName = (
subscription: string,
appName: string,
scopeId: number,
vscode: IVSCodeObject
): Promise<any> => {
return postMessageAsync(
EXTENSION_COMMANDS.VALIDATE_APPSERVICE_NAME,
{
module: EXTENSION_MODULES.AZURE,
command: EXTENSION_COMMANDS.VALIDATE_APPSERVICE_NAME,
subscription,
appName,
},
vscode,
scopeId
);
};
const ValidateCosmosAccountName = (
subscription: string,
appName: string,
scopeId: number,
vscode: IVSCodeObject
): Promise<any> => {
return postMessageAsync(
EXTENSION_COMMANDS.VALIDATE_COSMOS_NAME,
{
module: EXTENSION_MODULES.AZURE,
command: EXTENSION_COMMANDS.VALIDATE_COSMOS_NAME,
track: false,
appName,
subscription,
},
vscode,
scopeId
);
};
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
const generateProject = (generationData: any, vscode: IVSCodeObject): Promise<any> => {
return postMessageAsync(
EXTENSION_COMMANDS.GENERATE,
{
module: EXTENSION_MODULES.GENERATE,
command: EXTENSION_COMMANDS.GENERATE,
track: false,
text: PAYLOAD_MESSAGES_TEXT.SENT_GENERATION_INFO_TEXT,
payload: generationData,
},
vscode
);
};
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
const getAllLicenses = (licenseData: any, vscode: IVSCodeObject): Promise<any> => {
return postMessageAsync(
EXTENSION_COMMANDS.GET_ALL_LICENSES,
{
module: EXTENSION_MODULES.CORETS,
command: EXTENSION_COMMANDS.GET_ALL_LICENSES,
track: false,
text: PAYLOAD_MESSAGES_TEXT.SENT_GENERATION_INFO_TEXT,
payload: licenseData,
},
vscode
);
};
const getLocations = (vscode: IVSCodeObject, subscription: string, azureServiceType: string): Promise<any> => {
return postMessageAsync(
EXTENSION_COMMANDS.GET_LOCATIONS,
{
module: EXTENSION_MODULES.AZURE,
command: EXTENSION_COMMANDS.GET_LOCATIONS,
track: true,
subscription,
azureServiceType,
},
vscode
);
};
const getResourceGroups = (vscode: IVSCodeObject, subscription: string): Promise<any> => {
return postMessageAsync(
EXTENSION_COMMANDS.GET_RESOURCE_GROUPS,
{
module: EXTENSION_MODULES.AZURE,
command: EXTENSION_COMMANDS.GET_RESOURCE_GROUPS,
track: true,
subscription,
},
vscode
);
};
const sendLog = (logData: ILoggingPayload, vscode: IVSCodeObject): Promise<any> => {
return postMessageAsync(
EXTENSION_COMMANDS.LOG,
{
module: EXTENSION_MODULES.LOGGER,
command: EXTENSION_COMMANDS.LOG,
logData,
},
vscode
);
};
const openLogFile = (vscode: IVSCodeObject): Promise<any> => {
return postMessageAsync(
EXTENSION_COMMANDS.OPEN_LOG,
{
module: EXTENSION_MODULES.LOGGER,
command: EXTENSION_COMMANDS.OPEN_LOG,
},
vscode
);
};
const openProjectInVSCode = (outputPath: string, vscode: IVSCodeObject): void => {
return vscode.postMessage({
module: EXTENSION_MODULES.GENERATE,
command: EXTENSION_COMMANDS.OPEN_PROJECT_IN_VSCODE,
track: true,
payload: {
outputPath,
},
});
};
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
const subscribeToExtensionEvents = (listener: any): void => {
window.addEventListener("message", listener);
};
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
const unsubscribeToExtensionEvents = (listener: any): void => {
window.removeEventListener("message", listener);
};
export {
azureLogin,
azureLogout,
browseNewOutputPath,
generateProject,
getAllLicenses,
getFeatures,
getFrameworks,
getLatestVersion,
getLocations,
getOutputPathFromConfig,
getPages,
getProjectTypes,
getResourceGroups,
getTemplateInfo,
getUserStatus,
GetValidAppServiceName,
GetValidCosmosAccountName,
openLogFile,
openProjectInVSCode,
projectPathValidation,
sendLog,
sendTelemetry,
subscribeToExtensionEvents,
unsubscribeToExtensionEvents,
ValidateAppServiceName,
ValidateCosmosAccountName,
}; | the_stack |
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types";
import {
CreateAssistantAssociationCommand,
CreateAssistantAssociationCommandInput,
CreateAssistantAssociationCommandOutput,
} from "./commands/CreateAssistantAssociationCommand";
import {
CreateAssistantCommand,
CreateAssistantCommandInput,
CreateAssistantCommandOutput,
} from "./commands/CreateAssistantCommand";
import {
CreateContentCommand,
CreateContentCommandInput,
CreateContentCommandOutput,
} from "./commands/CreateContentCommand";
import {
CreateKnowledgeBaseCommand,
CreateKnowledgeBaseCommandInput,
CreateKnowledgeBaseCommandOutput,
} from "./commands/CreateKnowledgeBaseCommand";
import {
CreateSessionCommand,
CreateSessionCommandInput,
CreateSessionCommandOutput,
} from "./commands/CreateSessionCommand";
import {
DeleteAssistantAssociationCommand,
DeleteAssistantAssociationCommandInput,
DeleteAssistantAssociationCommandOutput,
} from "./commands/DeleteAssistantAssociationCommand";
import {
DeleteAssistantCommand,
DeleteAssistantCommandInput,
DeleteAssistantCommandOutput,
} from "./commands/DeleteAssistantCommand";
import {
DeleteContentCommand,
DeleteContentCommandInput,
DeleteContentCommandOutput,
} from "./commands/DeleteContentCommand";
import {
DeleteKnowledgeBaseCommand,
DeleteKnowledgeBaseCommandInput,
DeleteKnowledgeBaseCommandOutput,
} from "./commands/DeleteKnowledgeBaseCommand";
import {
GetAssistantAssociationCommand,
GetAssistantAssociationCommandInput,
GetAssistantAssociationCommandOutput,
} from "./commands/GetAssistantAssociationCommand";
import {
GetAssistantCommand,
GetAssistantCommandInput,
GetAssistantCommandOutput,
} from "./commands/GetAssistantCommand";
import { GetContentCommand, GetContentCommandInput, GetContentCommandOutput } from "./commands/GetContentCommand";
import {
GetContentSummaryCommand,
GetContentSummaryCommandInput,
GetContentSummaryCommandOutput,
} from "./commands/GetContentSummaryCommand";
import {
GetKnowledgeBaseCommand,
GetKnowledgeBaseCommandInput,
GetKnowledgeBaseCommandOutput,
} from "./commands/GetKnowledgeBaseCommand";
import {
GetRecommendationsCommand,
GetRecommendationsCommandInput,
GetRecommendationsCommandOutput,
} from "./commands/GetRecommendationsCommand";
import { GetSessionCommand, GetSessionCommandInput, GetSessionCommandOutput } from "./commands/GetSessionCommand";
import {
ListAssistantAssociationsCommand,
ListAssistantAssociationsCommandInput,
ListAssistantAssociationsCommandOutput,
} from "./commands/ListAssistantAssociationsCommand";
import {
ListAssistantsCommand,
ListAssistantsCommandInput,
ListAssistantsCommandOutput,
} from "./commands/ListAssistantsCommand";
import {
ListContentsCommand,
ListContentsCommandInput,
ListContentsCommandOutput,
} from "./commands/ListContentsCommand";
import {
ListKnowledgeBasesCommand,
ListKnowledgeBasesCommandInput,
ListKnowledgeBasesCommandOutput,
} from "./commands/ListKnowledgeBasesCommand";
import {
ListTagsForResourceCommand,
ListTagsForResourceCommandInput,
ListTagsForResourceCommandOutput,
} from "./commands/ListTagsForResourceCommand";
import {
NotifyRecommendationsReceivedCommand,
NotifyRecommendationsReceivedCommandInput,
NotifyRecommendationsReceivedCommandOutput,
} from "./commands/NotifyRecommendationsReceivedCommand";
import {
QueryAssistantCommand,
QueryAssistantCommandInput,
QueryAssistantCommandOutput,
} from "./commands/QueryAssistantCommand";
import {
RemoveKnowledgeBaseTemplateUriCommand,
RemoveKnowledgeBaseTemplateUriCommandInput,
RemoveKnowledgeBaseTemplateUriCommandOutput,
} from "./commands/RemoveKnowledgeBaseTemplateUriCommand";
import {
SearchContentCommand,
SearchContentCommandInput,
SearchContentCommandOutput,
} from "./commands/SearchContentCommand";
import {
SearchSessionsCommand,
SearchSessionsCommandInput,
SearchSessionsCommandOutput,
} from "./commands/SearchSessionsCommand";
import {
StartContentUploadCommand,
StartContentUploadCommandInput,
StartContentUploadCommandOutput,
} from "./commands/StartContentUploadCommand";
import { TagResourceCommand, TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand";
import {
UntagResourceCommand,
UntagResourceCommandInput,
UntagResourceCommandOutput,
} from "./commands/UntagResourceCommand";
import {
UpdateContentCommand,
UpdateContentCommandInput,
UpdateContentCommandOutput,
} from "./commands/UpdateContentCommand";
import {
UpdateKnowledgeBaseTemplateUriCommand,
UpdateKnowledgeBaseTemplateUriCommandInput,
UpdateKnowledgeBaseTemplateUriCommandOutput,
} from "./commands/UpdateKnowledgeBaseTemplateUriCommand";
import { WisdomClient } from "./WisdomClient";
/**
* <p>All Amazon Connect Wisdom functionality is accessible using the API. For example, you can create an
* assistant and a knowledge base.</p>
*
* <p>Some more advanced features are only accessible using the Wisdom API. For example, you
* can manually manage content by uploading custom files and control their lifecycle. </p>
*/
export class Wisdom extends WisdomClient {
/**
* <p>Creates an Amazon Connect Wisdom assistant.</p>
*/
public createAssistant(
args: CreateAssistantCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateAssistantCommandOutput>;
public createAssistant(
args: CreateAssistantCommandInput,
cb: (err: any, data?: CreateAssistantCommandOutput) => void
): void;
public createAssistant(
args: CreateAssistantCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateAssistantCommandOutput) => void
): void;
public createAssistant(
args: CreateAssistantCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateAssistantCommandOutput) => void),
cb?: (err: any, data?: CreateAssistantCommandOutput) => void
): Promise<CreateAssistantCommandOutput> | void {
const command = new CreateAssistantCommand(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>Creates an association between an Amazon Connect Wisdom assistant and another resource. Currently, the
* only supported association is with a knowledge base. An assistant can have only a single
* association.</p>
*/
public createAssistantAssociation(
args: CreateAssistantAssociationCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateAssistantAssociationCommandOutput>;
public createAssistantAssociation(
args: CreateAssistantAssociationCommandInput,
cb: (err: any, data?: CreateAssistantAssociationCommandOutput) => void
): void;
public createAssistantAssociation(
args: CreateAssistantAssociationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateAssistantAssociationCommandOutput) => void
): void;
public createAssistantAssociation(
args: CreateAssistantAssociationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateAssistantAssociationCommandOutput) => void),
cb?: (err: any, data?: CreateAssistantAssociationCommandOutput) => void
): Promise<CreateAssistantAssociationCommandOutput> | void {
const command = new CreateAssistantAssociationCommand(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>Creates Wisdom content. Before to calling this API, use <a href="https://docs.aws.amazon.com/wisdom/latest/APIReference/API_StartContentUpload.html">StartContentUpload</a> to
* upload an asset.</p>
*/
public createContent(
args: CreateContentCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateContentCommandOutput>;
public createContent(
args: CreateContentCommandInput,
cb: (err: any, data?: CreateContentCommandOutput) => void
): void;
public createContent(
args: CreateContentCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateContentCommandOutput) => void
): void;
public createContent(
args: CreateContentCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateContentCommandOutput) => void),
cb?: (err: any, data?: CreateContentCommandOutput) => void
): Promise<CreateContentCommandOutput> | void {
const command = new CreateContentCommand(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>Creates a knowledge base.</p>
* <note>
* <p>When using this API, you cannot reuse <a href="https://docs.aws.amazon.com/appintegrations/latest/APIReference/Welcome.html">Amazon AppIntegrations</a>
* DataIntegrations with external knowledge bases such as Salesforce and ServiceNow. If you do,
* you'll get an <code>InvalidRequestException</code> error. </p>
*
* <p>For example, you're programmatically managing your external knowledge base, and you want
* to add or remove one of the fields that is being ingested from Salesforce. Do the
* following:</p>
* <ol>
* <li>
* <p>Call <a href="https://docs.aws.amazon.com/wisdom/latest/APIReference/API_DeleteKnowledgeBase.html">DeleteKnowledgeBase</a>.</p>
* </li>
* <li>
* <p>Call <a href="https://docs.aws.amazon.com/appintegrations/latest/APIReference/API_DeleteDataIntegration.html">DeleteDataIntegration</a>.</p>
* </li>
* <li>
* <p>Call <a href="https://docs.aws.amazon.com/appintegrations/latest/APIReference/API_CreateDataIntegration.html">CreateDataIntegration</a> to recreate the DataIntegration or a create different
* one.</p>
* </li>
* <li>
* <p>Call CreateKnowledgeBase.</p>
* </li>
* </ol>
* </note>
*/
public createKnowledgeBase(
args: CreateKnowledgeBaseCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateKnowledgeBaseCommandOutput>;
public createKnowledgeBase(
args: CreateKnowledgeBaseCommandInput,
cb: (err: any, data?: CreateKnowledgeBaseCommandOutput) => void
): void;
public createKnowledgeBase(
args: CreateKnowledgeBaseCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateKnowledgeBaseCommandOutput) => void
): void;
public createKnowledgeBase(
args: CreateKnowledgeBaseCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateKnowledgeBaseCommandOutput) => void),
cb?: (err: any, data?: CreateKnowledgeBaseCommandOutput) => void
): Promise<CreateKnowledgeBaseCommandOutput> | void {
const command = new CreateKnowledgeBaseCommand(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>Creates a session. A session is a contextual container used for generating
* recommendations. Amazon Connect creates a new Wisdom session for each contact on which Wisdom is
* enabled.</p>
*/
public createSession(
args: CreateSessionCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateSessionCommandOutput>;
public createSession(
args: CreateSessionCommandInput,
cb: (err: any, data?: CreateSessionCommandOutput) => void
): void;
public createSession(
args: CreateSessionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateSessionCommandOutput) => void
): void;
public createSession(
args: CreateSessionCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateSessionCommandOutput) => void),
cb?: (err: any, data?: CreateSessionCommandOutput) => void
): Promise<CreateSessionCommandOutput> | void {
const command = new CreateSessionCommand(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 an assistant.</p>
*/
public deleteAssistant(
args: DeleteAssistantCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteAssistantCommandOutput>;
public deleteAssistant(
args: DeleteAssistantCommandInput,
cb: (err: any, data?: DeleteAssistantCommandOutput) => void
): void;
public deleteAssistant(
args: DeleteAssistantCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteAssistantCommandOutput) => void
): void;
public deleteAssistant(
args: DeleteAssistantCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteAssistantCommandOutput) => void),
cb?: (err: any, data?: DeleteAssistantCommandOutput) => void
): Promise<DeleteAssistantCommandOutput> | void {
const command = new DeleteAssistantCommand(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 an assistant association.</p>
*/
public deleteAssistantAssociation(
args: DeleteAssistantAssociationCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteAssistantAssociationCommandOutput>;
public deleteAssistantAssociation(
args: DeleteAssistantAssociationCommandInput,
cb: (err: any, data?: DeleteAssistantAssociationCommandOutput) => void
): void;
public deleteAssistantAssociation(
args: DeleteAssistantAssociationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteAssistantAssociationCommandOutput) => void
): void;
public deleteAssistantAssociation(
args: DeleteAssistantAssociationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteAssistantAssociationCommandOutput) => void),
cb?: (err: any, data?: DeleteAssistantAssociationCommandOutput) => void
): Promise<DeleteAssistantAssociationCommandOutput> | void {
const command = new DeleteAssistantAssociationCommand(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 the content.</p>
*/
public deleteContent(
args: DeleteContentCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteContentCommandOutput>;
public deleteContent(
args: DeleteContentCommandInput,
cb: (err: any, data?: DeleteContentCommandOutput) => void
): void;
public deleteContent(
args: DeleteContentCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteContentCommandOutput) => void
): void;
public deleteContent(
args: DeleteContentCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteContentCommandOutput) => void),
cb?: (err: any, data?: DeleteContentCommandOutput) => void
): Promise<DeleteContentCommandOutput> | void {
const command = new DeleteContentCommand(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 the knowledge base.</p>
* <note>
* <p>When you use this API to delete an external knowledge base such as Salesforce or
* ServiceNow, you must also delete the <a href="https://docs.aws.amazon.com/appintegrations/latest/APIReference/Welcome.html">Amazon AppIntegrations</a> DataIntegration.
* This is because you can't reuse the DataIntegration after it's been associated with an
* external knowledge base. However, you can delete and recreate it. See <a href="https://docs.aws.amazon.com/appintegrations/latest/APIReference/API_DeleteDataIntegration.html">DeleteDataIntegration</a> and <a href="https://docs.aws.amazon.com/appintegrations/latest/APIReference/API_CreateDataIntegration.html">CreateDataIntegration</a> in the <i>Amazon AppIntegrations API
* Reference</i>.</p>
* </note>
*/
public deleteKnowledgeBase(
args: DeleteKnowledgeBaseCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteKnowledgeBaseCommandOutput>;
public deleteKnowledgeBase(
args: DeleteKnowledgeBaseCommandInput,
cb: (err: any, data?: DeleteKnowledgeBaseCommandOutput) => void
): void;
public deleteKnowledgeBase(
args: DeleteKnowledgeBaseCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteKnowledgeBaseCommandOutput) => void
): void;
public deleteKnowledgeBase(
args: DeleteKnowledgeBaseCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteKnowledgeBaseCommandOutput) => void),
cb?: (err: any, data?: DeleteKnowledgeBaseCommandOutput) => void
): Promise<DeleteKnowledgeBaseCommandOutput> | void {
const command = new DeleteKnowledgeBaseCommand(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>Retrieves information about an assistant.</p>
*/
public getAssistant(
args: GetAssistantCommandInput,
options?: __HttpHandlerOptions
): Promise<GetAssistantCommandOutput>;
public getAssistant(args: GetAssistantCommandInput, cb: (err: any, data?: GetAssistantCommandOutput) => void): void;
public getAssistant(
args: GetAssistantCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetAssistantCommandOutput) => void
): void;
public getAssistant(
args: GetAssistantCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetAssistantCommandOutput) => void),
cb?: (err: any, data?: GetAssistantCommandOutput) => void
): Promise<GetAssistantCommandOutput> | void {
const command = new GetAssistantCommand(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>Retrieves information about an assistant association.</p>
*/
public getAssistantAssociation(
args: GetAssistantAssociationCommandInput,
options?: __HttpHandlerOptions
): Promise<GetAssistantAssociationCommandOutput>;
public getAssistantAssociation(
args: GetAssistantAssociationCommandInput,
cb: (err: any, data?: GetAssistantAssociationCommandOutput) => void
): void;
public getAssistantAssociation(
args: GetAssistantAssociationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetAssistantAssociationCommandOutput) => void
): void;
public getAssistantAssociation(
args: GetAssistantAssociationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetAssistantAssociationCommandOutput) => void),
cb?: (err: any, data?: GetAssistantAssociationCommandOutput) => void
): Promise<GetAssistantAssociationCommandOutput> | void {
const command = new GetAssistantAssociationCommand(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>Retrieves content, including a pre-signed URL to download the content.</p>
*/
public getContent(args: GetContentCommandInput, options?: __HttpHandlerOptions): Promise<GetContentCommandOutput>;
public getContent(args: GetContentCommandInput, cb: (err: any, data?: GetContentCommandOutput) => void): void;
public getContent(
args: GetContentCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetContentCommandOutput) => void
): void;
public getContent(
args: GetContentCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetContentCommandOutput) => void),
cb?: (err: any, data?: GetContentCommandOutput) => void
): Promise<GetContentCommandOutput> | void {
const command = new GetContentCommand(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>Retrieves summary information about the content.</p>
*/
public getContentSummary(
args: GetContentSummaryCommandInput,
options?: __HttpHandlerOptions
): Promise<GetContentSummaryCommandOutput>;
public getContentSummary(
args: GetContentSummaryCommandInput,
cb: (err: any, data?: GetContentSummaryCommandOutput) => void
): void;
public getContentSummary(
args: GetContentSummaryCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetContentSummaryCommandOutput) => void
): void;
public getContentSummary(
args: GetContentSummaryCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetContentSummaryCommandOutput) => void),
cb?: (err: any, data?: GetContentSummaryCommandOutput) => void
): Promise<GetContentSummaryCommandOutput> | void {
const command = new GetContentSummaryCommand(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>Retrieves information about the knowledge base.</p>
*/
public getKnowledgeBase(
args: GetKnowledgeBaseCommandInput,
options?: __HttpHandlerOptions
): Promise<GetKnowledgeBaseCommandOutput>;
public getKnowledgeBase(
args: GetKnowledgeBaseCommandInput,
cb: (err: any, data?: GetKnowledgeBaseCommandOutput) => void
): void;
public getKnowledgeBase(
args: GetKnowledgeBaseCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetKnowledgeBaseCommandOutput) => void
): void;
public getKnowledgeBase(
args: GetKnowledgeBaseCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetKnowledgeBaseCommandOutput) => void),
cb?: (err: any, data?: GetKnowledgeBaseCommandOutput) => void
): Promise<GetKnowledgeBaseCommandOutput> | void {
const command = new GetKnowledgeBaseCommand(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>Retrieves recommendations for the specified session. To avoid retrieving the same
* recommendations in subsequent calls, use <a href="https://docs.aws.amazon.com/wisdom/latest/APIReference/API_NotifyRecommendationsReceived.html">NotifyRecommendationsReceived</a>. This API supports long-polling behavior with the
* <code>waitTimeSeconds</code> parameter. Short poll is the default behavior and only returns
* recommendations already available. To perform a manual query against an assistant, use <a href="https://docs.aws.amazon.com/wisdom/latest/APIReference/API_QueryAssistant.html">QueryAssistant</a>.</p>
*/
public getRecommendations(
args: GetRecommendationsCommandInput,
options?: __HttpHandlerOptions
): Promise<GetRecommendationsCommandOutput>;
public getRecommendations(
args: GetRecommendationsCommandInput,
cb: (err: any, data?: GetRecommendationsCommandOutput) => void
): void;
public getRecommendations(
args: GetRecommendationsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetRecommendationsCommandOutput) => void
): void;
public getRecommendations(
args: GetRecommendationsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetRecommendationsCommandOutput) => void),
cb?: (err: any, data?: GetRecommendationsCommandOutput) => void
): Promise<GetRecommendationsCommandOutput> | void {
const command = new GetRecommendationsCommand(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>Retrieves information for a specified session.</p>
*/
public getSession(args: GetSessionCommandInput, options?: __HttpHandlerOptions): Promise<GetSessionCommandOutput>;
public getSession(args: GetSessionCommandInput, cb: (err: any, data?: GetSessionCommandOutput) => void): void;
public getSession(
args: GetSessionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetSessionCommandOutput) => void
): void;
public getSession(
args: GetSessionCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetSessionCommandOutput) => void),
cb?: (err: any, data?: GetSessionCommandOutput) => void
): Promise<GetSessionCommandOutput> | void {
const command = new GetSessionCommand(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 information about assistant associations.</p>
*/
public listAssistantAssociations(
args: ListAssistantAssociationsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListAssistantAssociationsCommandOutput>;
public listAssistantAssociations(
args: ListAssistantAssociationsCommandInput,
cb: (err: any, data?: ListAssistantAssociationsCommandOutput) => void
): void;
public listAssistantAssociations(
args: ListAssistantAssociationsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListAssistantAssociationsCommandOutput) => void
): void;
public listAssistantAssociations(
args: ListAssistantAssociationsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListAssistantAssociationsCommandOutput) => void),
cb?: (err: any, data?: ListAssistantAssociationsCommandOutput) => void
): Promise<ListAssistantAssociationsCommandOutput> | void {
const command = new ListAssistantAssociationsCommand(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 information about assistants.</p>
*/
public listAssistants(
args: ListAssistantsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListAssistantsCommandOutput>;
public listAssistants(
args: ListAssistantsCommandInput,
cb: (err: any, data?: ListAssistantsCommandOutput) => void
): void;
public listAssistants(
args: ListAssistantsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListAssistantsCommandOutput) => void
): void;
public listAssistants(
args: ListAssistantsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListAssistantsCommandOutput) => void),
cb?: (err: any, data?: ListAssistantsCommandOutput) => void
): Promise<ListAssistantsCommandOutput> | void {
const command = new ListAssistantsCommand(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 content.</p>
*/
public listContents(
args: ListContentsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListContentsCommandOutput>;
public listContents(args: ListContentsCommandInput, cb: (err: any, data?: ListContentsCommandOutput) => void): void;
public listContents(
args: ListContentsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListContentsCommandOutput) => void
): void;
public listContents(
args: ListContentsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListContentsCommandOutput) => void),
cb?: (err: any, data?: ListContentsCommandOutput) => void
): Promise<ListContentsCommandOutput> | void {
const command = new ListContentsCommand(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 knowledge bases.</p>
*/
public listKnowledgeBases(
args: ListKnowledgeBasesCommandInput,
options?: __HttpHandlerOptions
): Promise<ListKnowledgeBasesCommandOutput>;
public listKnowledgeBases(
args: ListKnowledgeBasesCommandInput,
cb: (err: any, data?: ListKnowledgeBasesCommandOutput) => void
): void;
public listKnowledgeBases(
args: ListKnowledgeBasesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListKnowledgeBasesCommandOutput) => void
): void;
public listKnowledgeBases(
args: ListKnowledgeBasesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListKnowledgeBasesCommandOutput) => void),
cb?: (err: any, data?: ListKnowledgeBasesCommandOutput) => void
): Promise<ListKnowledgeBasesCommandOutput> | void {
const command = new ListKnowledgeBasesCommand(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>
*/
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>Removes the specified recommendations from the specified assistant's queue of newly
* available recommendations. You can use this API in conjunction with <a href="https://docs.aws.amazon.com/wisdom/latest/APIReference/API_GetRecommendations.html">GetRecommendations</a> and a <code>waitTimeSeconds</code> input for long-polling
* behavior and avoiding duplicate recommendations.</p>
*/
public notifyRecommendationsReceived(
args: NotifyRecommendationsReceivedCommandInput,
options?: __HttpHandlerOptions
): Promise<NotifyRecommendationsReceivedCommandOutput>;
public notifyRecommendationsReceived(
args: NotifyRecommendationsReceivedCommandInput,
cb: (err: any, data?: NotifyRecommendationsReceivedCommandOutput) => void
): void;
public notifyRecommendationsReceived(
args: NotifyRecommendationsReceivedCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: NotifyRecommendationsReceivedCommandOutput) => void
): void;
public notifyRecommendationsReceived(
args: NotifyRecommendationsReceivedCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: NotifyRecommendationsReceivedCommandOutput) => void),
cb?: (err: any, data?: NotifyRecommendationsReceivedCommandOutput) => void
): Promise<NotifyRecommendationsReceivedCommandOutput> | void {
const command = new NotifyRecommendationsReceivedCommand(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>Performs a manual search against the specified assistant. To retrieve recommendations for
* an assistant, use <a href="https://docs.aws.amazon.com/wisdom/latest/APIReference/API_GetRecommendations.html">GetRecommendations</a>.
* </p>
*/
public queryAssistant(
args: QueryAssistantCommandInput,
options?: __HttpHandlerOptions
): Promise<QueryAssistantCommandOutput>;
public queryAssistant(
args: QueryAssistantCommandInput,
cb: (err: any, data?: QueryAssistantCommandOutput) => void
): void;
public queryAssistant(
args: QueryAssistantCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: QueryAssistantCommandOutput) => void
): void;
public queryAssistant(
args: QueryAssistantCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: QueryAssistantCommandOutput) => void),
cb?: (err: any, data?: QueryAssistantCommandOutput) => void
): Promise<QueryAssistantCommandOutput> | void {
const command = new QueryAssistantCommand(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 a URI template from a knowledge base.</p>
*/
public removeKnowledgeBaseTemplateUri(
args: RemoveKnowledgeBaseTemplateUriCommandInput,
options?: __HttpHandlerOptions
): Promise<RemoveKnowledgeBaseTemplateUriCommandOutput>;
public removeKnowledgeBaseTemplateUri(
args: RemoveKnowledgeBaseTemplateUriCommandInput,
cb: (err: any, data?: RemoveKnowledgeBaseTemplateUriCommandOutput) => void
): void;
public removeKnowledgeBaseTemplateUri(
args: RemoveKnowledgeBaseTemplateUriCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: RemoveKnowledgeBaseTemplateUriCommandOutput) => void
): void;
public removeKnowledgeBaseTemplateUri(
args: RemoveKnowledgeBaseTemplateUriCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RemoveKnowledgeBaseTemplateUriCommandOutput) => void),
cb?: (err: any, data?: RemoveKnowledgeBaseTemplateUriCommandOutput) => void
): Promise<RemoveKnowledgeBaseTemplateUriCommandOutput> | void {
const command = new RemoveKnowledgeBaseTemplateUriCommand(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>Searches for content in a specified knowledge base. Can be used to get a specific content
* resource by its name.</p>
*/
public searchContent(
args: SearchContentCommandInput,
options?: __HttpHandlerOptions
): Promise<SearchContentCommandOutput>;
public searchContent(
args: SearchContentCommandInput,
cb: (err: any, data?: SearchContentCommandOutput) => void
): void;
public searchContent(
args: SearchContentCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: SearchContentCommandOutput) => void
): void;
public searchContent(
args: SearchContentCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: SearchContentCommandOutput) => void),
cb?: (err: any, data?: SearchContentCommandOutput) => void
): Promise<SearchContentCommandOutput> | void {
const command = new SearchContentCommand(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>Searches for sessions.</p>
*/
public searchSessions(
args: SearchSessionsCommandInput,
options?: __HttpHandlerOptions
): Promise<SearchSessionsCommandOutput>;
public searchSessions(
args: SearchSessionsCommandInput,
cb: (err: any, data?: SearchSessionsCommandOutput) => void
): void;
public searchSessions(
args: SearchSessionsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: SearchSessionsCommandOutput) => void
): void;
public searchSessions(
args: SearchSessionsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: SearchSessionsCommandOutput) => void),
cb?: (err: any, data?: SearchSessionsCommandOutput) => void
): Promise<SearchSessionsCommandOutput> | void {
const command = new SearchSessionsCommand(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>Get a URL to upload content to a knowledge base. To upload content, first make a PUT
* request to the returned URL with your file, making sure to include the required headers. Then
* use <a href="https://docs.aws.amazon.com/wisdom/latest/APIReference/API_CreateContent.html">CreateContent</a> to finalize the content creation process or <a href="https://docs.aws.amazon.com/wisdom/latest/APIReference/API_UpdateContent.html">UpdateContent</a> to modify an existing resource. You can only upload content to a
* knowledge base of type CUSTOM.</p>
*/
public startContentUpload(
args: StartContentUploadCommandInput,
options?: __HttpHandlerOptions
): Promise<StartContentUploadCommandOutput>;
public startContentUpload(
args: StartContentUploadCommandInput,
cb: (err: any, data?: StartContentUploadCommandOutput) => void
): void;
public startContentUpload(
args: StartContentUploadCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: StartContentUploadCommandOutput) => void
): void;
public startContentUpload(
args: StartContentUploadCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: StartContentUploadCommandOutput) => void),
cb?: (err: any, data?: StartContentUploadCommandOutput) => void
): Promise<StartContentUploadCommandOutput> | void {
const command = new StartContentUploadCommand(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 the specified tags to the specified resource.</p>
*/
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 from the specified resource.</p>
*/
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 the content.</p>
*/
public updateContent(
args: UpdateContentCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateContentCommandOutput>;
public updateContent(
args: UpdateContentCommandInput,
cb: (err: any, data?: UpdateContentCommandOutput) => void
): void;
public updateContent(
args: UpdateContentCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateContentCommandOutput) => void
): void;
public updateContent(
args: UpdateContentCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateContentCommandOutput) => void),
cb?: (err: any, data?: UpdateContentCommandOutput) => void
): Promise<UpdateContentCommandOutput> | void {
const command = new UpdateContentCommand(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 the template URI of a knowledge base. This is only supported for knowledge bases
* of type EXTERNAL. Include a single variable in <code>${variable}</code> format; this
* interpolated by Wisdom using ingested content. For example, if you ingest a Salesforce
* article, it has an <code>Id</code> value, and you can set the template URI to
* <code>https://myInstanceName.lightning.force.com/lightning/r/Knowledge__kav/*${Id}*\/view</code>.
* </p>
*/
public updateKnowledgeBaseTemplateUri(
args: UpdateKnowledgeBaseTemplateUriCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateKnowledgeBaseTemplateUriCommandOutput>;
public updateKnowledgeBaseTemplateUri(
args: UpdateKnowledgeBaseTemplateUriCommandInput,
cb: (err: any, data?: UpdateKnowledgeBaseTemplateUriCommandOutput) => void
): void;
public updateKnowledgeBaseTemplateUri(
args: UpdateKnowledgeBaseTemplateUriCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateKnowledgeBaseTemplateUriCommandOutput) => void
): void;
public updateKnowledgeBaseTemplateUri(
args: UpdateKnowledgeBaseTemplateUriCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateKnowledgeBaseTemplateUriCommandOutput) => void),
cb?: (err: any, data?: UpdateKnowledgeBaseTemplateUriCommandOutput) => void
): Promise<UpdateKnowledgeBaseTemplateUriCommandOutput> | void {
const command = new UpdateKnowledgeBaseTemplateUriCommand(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, {Component} from "react";
import {observer} from "mobx-react";
import {inject} from "../../common/utils/IOC";
import {notification} from "antd";
import Search from "../../cluster/view/clusterList/Search";
import {ClusterInfoVo, ClusterModel, ClusterSearchVo} from "../../cluster/model/ClusterModel";
import {BaseInfoModel} from "../../sys/model/BaseInfoModel";
import {SysUserModel} from "../../sys/model/SysUserModel";
import ClusterDynamicExpansionModal from "./ClusterDynamicExpansionModal";
import ClusterDynamicExpansionResultModal from "./ClusterDynamicExpansionResultModal";
import ClusterRestartModal from "./ClusterRestartModal";
import ClusterRestartResultModal from "./ClusterRestartResultModal";
import {ClusterOpsList} from "./ClusterOpsList";
import {ClusterOpsModel, ZKDynamicExpansionConfig} from "../model/ClusterOpsModel";
import {ServiceLineOpsModel} from "../model/ServiceLineOpsModel";
import ModifyClusterModal from "./ModifyClusterModal";
interface DetailState {
showEditModal: boolean;
showExpansionModal: boolean;
showExpansionResultModal: boolean;
showRestartModal: boolean;
showRestartResultModal: boolean;
type: string;
clusterItem: ClusterInfoVo;
isRestartOver: boolean;
isExpansionOver: boolean;
}
interface DetailPropsI {
location: any;
}
@observer
export default class ClusterOps extends Component<DetailPropsI, DetailState> {
@inject(ClusterModel)
private clusterModel: ClusterModel;
@inject(ClusterOpsModel)
private clusterOpsModel: ClusterOpsModel;
@inject(BaseInfoModel)
private baseInfoModel: BaseInfoModel;
@inject(SysUserModel)
private sysUserModel: SysUserModel;
@inject(ServiceLineOpsModel)
private serviceLineOpsModel: ServiceLineOpsModel;
constructor(props) {
super(props);
this.state = {
showEditModal: false,
showExpansionModal: false,
showExpansionResultModal: false,
showRestartModal: false,
showRestartResultModal: false,
clusterItem: null,
type: 'create',
isRestartOver: false,
isExpansionOver: false
}
}
componentDidMount(): void {
this.serviceLineOpsModel.query({});
this.clusterModel.query({});
this.setState({})
}
showModal(clusterItem: ClusterInfoVo, type: string): void {
this.setState({showExpansionModal: true, clusterItem: clusterItem, type: type});
};
hideModal(): void {
this.setState({showExpansionModal: false, clusterItem: null});
};
getSearchProps() {
let thisV = this;
return {
serviceLines: this.serviceLineOpsModel.serviceLines,
baseInfoModel: this.baseInfoModel,
onSearch(searchVo: ClusterSearchVo) {
thisV.clusterModel.query(searchVo);
}
};
};
getListProps() {
let thisV = this;
return {
dataSource: this.clusterModel.clusters,
loading: this.clusterModel.loading,
pageConfig: this.clusterModel.pageConfig,
sysUser: this.sysUserModel.sysUser,
baseInfoModel: this.baseInfoModel,
serviceLineOpsModel: this.serviceLineOpsModel,
onEdit(item) {
thisV.setState({
clusterItem: item,
showEditModal: true
})
},
onDynamicExpansion(item) {
thisV.showModal(item, 'edit');
},
onOffLine(id) {
thisV.clusterOpsModel.offLine(id, (message) => {
notification['success']({
message: message,
description: '',
});
});
},
onRestartQuorum(item) {
thisV.setState({
showRestartModal: true,
clusterItem: item,
});
}
};
};
private expansionTimer;
getExpansionModalProps() {
let thisV = this;
return {
clusterItem: this.state.clusterItem,
onOk: function (item: ZKDynamicExpansionConfig) {
thisV.clusterOpsModel.clusterDynamicExpansion(item, (message) => {
// 最后刷新一次,获取最后结果
thisV.clusterOpsModel.getClusterDynamicExpansionResult(item.clusterId);
thisV.setState({
showExpansionResultModal: thisV.clusterOpsModel.lastDynamicExpansionResult || thisV.clusterOpsModel.dynamicExpansionResult,
isExpansionOver: true
});
// 停止刷新
clearInterval(thisV.expansionTimer);
});
thisV.hideModal();
// 每1s执行一次,获取执行结果
thisV.expansionTimer = setInterval(function () {
thisV.clusterOpsModel.getClusterDynamicExpansionResult(item.clusterId, (isClear) => {
if (isClear) {
clearInterval(thisV.expansionTimer);
thisV.setState({
isExpansionOver: true
})
}
});
// 处理结果为异常的时候,不显示结果框
thisV.setState({
showExpansionResultModal: thisV.clusterOpsModel.lastDynamicExpansionResult || thisV.clusterOpsModel.dynamicExpansionResult,
})
}, 1000);
},
onCancel() {
thisV.hideModal();
},
};
};
getExpansionResultModalProps() {
let thisV = this;
return {
isExpansionOver: thisV.state.isExpansionOver,
resultList: thisV.clusterOpsModel.dynamicExpansionResultList ? thisV.clusterOpsModel.dynamicExpansionResultList : [],
onOk: function () {
thisV.setState({
showExpansionResultModal: false,
isExpansionOver: false
})
},
onCancel() {
thisV.setState({
showExpansionResultModal: false,
isExpansionOver: false
})
},
};
};
private restartTimer;
getRestartModalProps() {
let thisV = this;
return {
clusterItem: this.state.clusterItem,
onOk: function (item) {
thisV.clusterOpsModel.restartQuorum(item, (message) => {
// 最后刷新一次,获取最后结果
thisV.clusterOpsModel.getClusterRestartResult(thisV.state.clusterItem.id);
thisV.setState({
showRestartResultModal: thisV.clusterOpsModel.lastRestartResult || thisV.clusterOpsModel.restartResult,
isRestartOver: true
});
// 停止刷新
clearInterval(thisV.restartTimer);
});
thisV.setState({showRestartModal: false});
// 每1s执行一次,获取执行结果
thisV.restartTimer = setInterval(function () {
thisV.clusterOpsModel.getClusterRestartResult(thisV.state.clusterItem.id, (isClear) => {
if (isClear) {
clearInterval(thisV.restartTimer);
thisV.setState({
isRestartOver: true
});
}
});
// 处理结果为异常的时候,不显示结果框
thisV.setState({
showRestartResultModal: thisV.clusterOpsModel.lastRestartResult || thisV.clusterOpsModel.restartResult,
})
}, 1000);
},
onCancel() {
thisV.setState({
showRestartModal: false,
clusterItem: null
})
},
};
}
getRestartResultModalModalProps() {
let thisV = this;
return {
isOver: thisV.state.isRestartOver,
title: "重启中",
resultList: thisV.clusterOpsModel.restartResultList ? thisV.clusterOpsModel.restartResultList : [],
onOk: function () {
thisV.setState({
showRestartResultModal: false,
isRestartOver: false
})
},
onCancel() {
thisV.setState({
showRestartResultModal: false,
isRestartOver: false
})
},
};
}
getModalProps() {
let thisV = this;
return {
serviceLines: this.serviceLineOpsModel.serviceLines,
baseInfoModel: this.baseInfoModel,
clusterItem: this.state.clusterItem,
onOk: function (item: ClusterInfoVo) {
thisV.clusterModel.editClusterInfo(item, (message) => {
notification['success']({
message: message,
description: '',
});
});
thisV.hideEditModal();
},
onCancel() {
thisV.hideEditModal();
},
};
};
hideEditModal(): void {
this.setState({showEditModal: false, clusterItem: null});
};
render() {
return (
<div>
<Search {...this.getSearchProps()}/>
<ClusterOpsList {...this.getListProps()}/>
{this.state.showEditModal ? <ModifyClusterModal {...this.getModalProps()}/> : ''}
{this.state.showExpansionModal ?
<ClusterDynamicExpansionModal {...this.getExpansionModalProps()}/> : ''}
{this.state.showExpansionResultModal ?
<ClusterDynamicExpansionResultModal {...this.getExpansionResultModalProps()}/> : ''}
{this.state.showRestartModal ? <ClusterRestartModal {...this.getRestartModalProps()}/> : ''}
{this.state.showRestartResultModal ?
<ClusterRestartResultModal {...this.getRestartResultModalModalProps()}/> : ''}
</div>
)
}
} | the_stack |
import * as DbMigratePg from "db-migrate-pg";
// Throw together a dummy driver
let db = {} as DbMigratePg.PgDriver;
let callback = (err: any, response: any) => {
// Do nothing.
};
/// createTable(tableName, columnSpec, callback)
db.createTable('pets', {
id: { type: 'int', primaryKey: true, autoIncrement: true },
name: 'string'
}, callback);
db.createTable('pets', {
columns: {
id: { type: 'int', primaryKey: true, autoIncrement: true },
name: 'string'
},
ifNotExists: true
}, callback);
db.createTable('product_variant',
{
id: {
type: 'int',
unsigned: true,
notNull: true,
primaryKey: true,
autoIncrement: true,
length: 10
},
product_id: {
type: 'int',
unsigned: true,
length: 10,
notNull: true,
foreignKey: {
name: 'product_variant_product_id_fk',
table: 'product',
rules: {
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
},
mapping: 'id'
}
}
}, callback);
db.createTable('product_variant',
{
id: {
type: 'int',
unsigned: true,
notNull: true,
primaryKey: true,
autoIncrement: true,
length: 10
},
product_id: {
type: 'int',
unsigned: true,
length: 10,
notNull: true,
foreignKey: {
name: 'product_variant_product_id_fk',
table: 'product',
rules: {
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
},
mapping: {
product_id: 'id'
}
}
}
}, callback);
/// dropTable(tableName, [options,] callback)
db.dropTable('pets', callback);
db.dropTable('pets', { ifExists: true }, callback);
/// renameTable(tableName, newTableName, callback)
db.renameTable('pets', 'pets_OLD', callback);
/// addColumn(tableName, columnName, columnSpec, callback)
db.addColumn('pets', 'eyeColor', {
type: 'string',
length: 25,
notNull: true,
}, callback);
db.addColumn('pets', 'id', {
type: 'int',
primaryKey: true,
autoIncrement: true,
notNull: true,
unique: true
}, callback);
/// renameColumn(tableName, oldColumnName, newColumnName, callback)
db.renameColumn('pets', 'id', 'pet_id', callback);
/// changeColumn(tableName, columnName, columnSpec, callback)
db.changeColumn('pets', 'eye_color', {
type: 'int',
unsigned: true,
notNull: true,
foreignKey: {
name: 'pets_eye_color_id_fk',
table: 'eye_color',
rules: {
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
},
mapping: {
eye_color: 'id'
}
}
}, callback);
/// addIndex(tableName, indexName, columns, [unique,] callback)
db.addIndex('pets', 'pets_eye_color_idx', ['eye_color'], callback);
db.addIndex('pets', 'pets_registration_code_idx', ['registration_code'], true, callback);
/// addForeignKey(tableName, referencedTableName, keyName, fieldMapping, rules, callback)
db.addForeignKey('module_user', 'modules', 'module_user_module_id_fk',
{
'module_id': 'id'
},
{
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
}, callback);
/// removeForeignKey(tableName, keyName, options, callback)
db.removeForeignKey('module_user', 'module_uer_module_id_foreign', callback);
db.removeForeignKey('module_user', 'module_user_module_id_foreign', {
dropIndex: true,
}, callback);
/// insert(tableName, [columnNameArray,] valueArray, callback)
db.insert('module_user', ['first_name', 'last_name'], ['Test', 'Testerson'], callback);
db.insert('module_user', ['Test', 'Testerson'], callback);
/// removeIndex([tableName,] indexName, callback)
db.removeIndex('pets', 'pets_eye_color_idx', callback);
db.removeIndex('pets_eye_color_idx', callback);
/// runSql(sql, [params,] callback)
db.runSql('INSERT INTO `module_user` (`?`,`?`) VALUES (\'?\',\'?\')', [
'first_name', 'last_name',
'Test', 'Testerson'
], callback);
db.runSql('DROP TABLE `pets`', callback);
/// all(sql, [params,] callback)
db.all('SELECT * FROM `module_user` WHERE `?` = \'?\'', ['first_name', 'Test'], callback);
db.all('SELECT * FROM `module_user`', callback);
/// =========
/// Async
/// =========
let onResolve = (result: any) => {};
/// createTableAsync(tableName, columnSpec)
db.createTableAsync('pets', {
id: { type: 'int', primaryKey: true, autoIncrement: true },
name: 'string'
}).then(onResolve);
db.createTableAsync('pets', {
columns: {
id: { type: 'int', primaryKey: true, autoIncrement: true },
name: 'string'
},
ifNotExists: true
}).then(onResolve);
db.createTableAsync('product_variant',
{
id: {
type: 'int',
unsigned: true,
notNull: true,
primaryKey: true,
autoIncrement: true,
length: 10
},
product_id: {
type: 'int',
unsigned: true,
length: 10,
notNull: true,
foreignKey: {
name: 'product_variant_product_id_fk',
table: 'product',
rules: {
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
},
mapping: 'id'
}
}
}).then(onResolve);
db.createTableAsync('product_variant',
{
id: {
type: 'int',
unsigned: true,
notNull: true,
primaryKey: true,
autoIncrement: true,
length: 10
},
product_id: {
type: 'int',
unsigned: true,
length: 10,
notNull: true,
foreignKey: {
name: 'product_variant_product_id_fk',
table: 'product',
rules: {
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
},
mapping: {
product_id: 'id'
}
}
}
}).then(onResolve);
/// dropTableAsync(tableName, [options])
db.dropTableAsync('pets').then(onResolve);
db.dropTableAsync('pets', { ifExists: true }).then(onResolve);
/// renameTableAsync(tableName, newTableName)
db.renameTableAsync('pets', 'pets_OLD').then(onResolve);
/// addColumnAsync(tableName, columnName, columnSpec)
db.addColumnAsync('pets', 'eyeColor', {
type: 'string',
length: 25,
notNull: true,
}).then(onResolve);
db.addColumnAsync('pets', 'id', {
type: 'int',
primaryKey: true,
autoIncrement: true,
notNull: true,
unique: true
}).then(onResolve);
/// renameColumnAsync(tableName, oldColumnName, newColumnName)
db.renameColumnAsync('pets', 'id', 'pet_id').then(onResolve);
/// changeColumnAsync(tableName, columnName, columnSpec)
db.changeColumnAsync('pets', 'eye_color', {
type: 'int',
unsigned: true,
notNull: true,
foreignKey: {
name: 'pets_eye_color_id_fk',
table: 'eye_color',
rules: {
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
},
mapping: {
eye_color: 'id'
}
}
}).then(onResolve);
/// addIndexAsync(tableName, indexName, columns, [unique])
db.addIndexAsync('pets', 'pets_eye_color_idx', ['eye_color']).then(onResolve);
db.addIndexAsync('pets', 'pets_registration_code_idx', ['registration_code'], true).then(onResolve);
/// addForeignKeyAsync(tableName, referencedTableName, keyName, fieldMapping, rules)
db.addForeignKeyAsync('module_user', 'modules', 'module_user_module_id_fk',
{
'module_id': 'id'
},
{
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
}).then(onResolve);
/// removeForeignKeyAsync(tableName, keyName, options)
db.removeForeignKeyAsync('module_user', 'module_uer_module_id_foreign').then(onResolve);
db.removeForeignKeyAsync('module_user', 'module_user_module_id_foreign', {
dropIndex: true,
}).then(onResolve);
/// insertAsync(tableName, [columnNameArray,] valueArray)
db.insertAsync('module_user', ['first_name', 'last_name'], ['Test', 'Testerson']).then(onResolve);
db.insertAsync('module_user', ['Test', 'Testerson']).then(onResolve);
/// removeIndexAsync([tableName,] indexName)
db.removeIndexAsync('pets', 'pets_eye_color_idx').then(onResolve);
db.removeIndexAsync('pets_eye_color_idx').then(onResolve);
/// runSqlAsync(sql, [params])
db.runSqlAsync('INSERT INTO `module_user` (`?`,`?`) VALUES (\'?\',\'?\')', [
'first_name', 'last_name',
'Test', 'Testerson'
]).then(onResolve);
db.runSqlAsync('DROP TABLE `pets`').then(onResolve);
/// allAsync(sql, [params])
db.allAsync('SELECT * FROM `module_user` WHERE `?` = \'?\'', ['first_name', 'Test']).then(onResolve);
db.allAsync('SELECT * FROM `module_user`').then(onResolve);
/// ====================
/// PG-specific tests
/// ====================
/// createColumnConstraint(spec, options, tableName, columnName) (INTERNAL USE ONLY)
let constraint: DbMigratePg.ColumnConstraint;
constraint = db.createColumnConstraint({
type: 'int',
length: 10,
unsigned: true,
primaryKey: false,
autoIncrement: false,
notNull: true,
unique: false,
defaultValue: 0,
foreignKey: {
name: 'pets_eye_color_id_fk',
table: 'eye_color',
rules: {
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
},
mapping: {
'eye_color': 'id'
}
}
}, {
emitPrimaryKey: false
}, 'pets', 'eye_color');
// Print the SQL constraints
console.log(constraint.constraints);
// Invoke the foreign key builder
constraint.foreignKey(callback);
/// Public Callback Methods:
/// createDatabase(dbName, [options,] callback)
db.createDatabase('petstore', callback);
db.createDatabase('petstore', {}, callback);
/// dropDatabase(dbName, [options,] callback)
db.dropDatabase('petstore', callback);
db.dropDatabase('petstore', { ifExists: true }, callback);
/// createSequence(sqName, [options,] callback)
db.createSequence('pets_id_sq', callback);
db.createSequence('pets_id_sq', { temp: true }, callback);
/// switchDatabase(options, callback)
db.switchDatabase('petstore', callback);
db.switchDatabase({ database: 'petstore' }, callback);
/// dropSequence(sqName, [options,] callback)
db.dropSequence('pets_id_sq', callback);
db.dropSequence('pets_id_sq', {
ifExists: true,
cascade: true,
restrict: true,
}, callback);
/// Public Promisified Methods:
/// createDatabaseAsync(dbName, [options])
db.createDatabaseAsync('petstore').then(onResolve);
db.createDatabaseAsync('petstore', {}).then(onResolve);
/// dropDatabaseAsync(dbName, [options])
db.dropDatabaseAsync('petstore').then(onResolve);
db.dropDatabaseAsync('petstore', { ifExists: true }).then(onResolve);
/// createSequenceAsync(sqName, [options])
db.createSequenceAsync('pets_id_sq').then(onResolve);
db.createSequenceAsync('pets_id_sq', { temp: true }).then(onResolve);
/// switchDatabaseAsync(options)
db.switchDatabaseAsync('petstore').then(onResolve);
db.switchDatabaseAsync({ database: 'petstore' }).then(onResolve);
/// dropSequenceAsync(sqName, [options])
db.dropSequenceAsync('pets_id_sq').then(onResolve);
db.dropSequenceAsync('pets_id_sq', {
ifExists: true,
cascade: true,
restrict: true,
}).then(onResolve); | the_stack |
import * as yup from 'yup';
import {
FlatConvectorModel,
Controller,
ConvectorController,
Invokable,
Param
} from '@worldsibu/convector-core';
import * as fhirTypes from '../utils/fhirTypes';
import {
Claim, ClaimResponse, CodeableConcept, ClaimResponseItem,
InvoiceLineItemPriceComponent, Patient, Organization,
Encounter, Period, Quantity, Procedure, ProcedurePerformer,
ChargeItem, ClaimPayee, ClaimCareTeam, ClaimItem, ClaimProcedure,
SimpleQuantity, EncounterStatusHistory, Account, Invoice, Identifier, InvoiceLineItem, Extension
} from '../models/financial.model';
import {
InvoiceData, AccountData,
CreateClaim, AdjudicateClaim, ServiceItem
} from '../utils/params.model';
import {
buildIdentifier, buildNarrative, buildInvoiceLineItems, buildReference,
buildCoding, buildTotalCosts, buildTotalBenefits, buildAdjudicationItem,
buildMoney
} from '../utils/utils';
import {
IdentifierTypes, AccountStatus, InvoiceStatus,
EncounterStatus, NarrativeStatus, IdentifierUses, ClaimResponseStatus,
ClaimStatus, ClaimUses, FQDNObjects, ChargeItemStatus, ProcedureStatus,
InvoiceLineItemPriceComponentTypes, CodingTypes, ClaimResponseOutcomes,
ClaimResponseUses,
ResourceTypes
} from '../utils/enums';
import { pickRightCollections } from '../utils/privateCollections';
import { PublicModelRouter } from '../models/public.model';
import { ChaincodeTx } from '@worldsibu/convector-core-chaincode';
import { PrivateCollectionsRoutes } from '../models/privateCollectionsRoutes.model';
import { TransientInvoiceLineItem } from '../models/transient.model';
import { FeeExtensionsConfig } from '../models/feeExtensions.model';
class parse {
constructor(data) {
Object.assign(this, data);
console.log(data);
}
}
@Controller('claim')
export class ClaimController extends ConvectorController<ChaincodeTx> {
@Invokable()
public async create() {
const data: CreateClaim = await this.tx.getTransientValue<CreateClaim>('data', CreateClaim);
const collections = new PrivateCollectionsRoutes(data.patientId,
data.providerId, data.payerId);
await collections.load();
const id = data.encounterUid;
// Hydrate objects
data.patient = <Patient>(await Patient.getOne(data.patientId)).toJSON();
data.payer = <Organization>(await Organization.getOne(data.payerId)).toJSON();
data.provider = <Organization>(await Organization.getOne(data.providerId)).toJSON();
if (!data.patient) {
throw new Error(`Patient with id ${data.patientId} doesn\'t exist`);
}
if (!data.payer) {
throw new Error(`Payer with id ${data.payerId} doesn\'t exist`);
}
if (!data.provider) {
throw new Error(`Provider with id ${data.providerId} doesn\'t exist`);
}
const encounter = new Encounter(id);
// Build the identifier for the Encounter from the id
const identifier = buildIdentifier(id, IdentifierUses.USUAL, IdentifierTypes.ENCOUNTER);
encounter.identifier = [identifier];
const class_ = buildCoding(CodingTypes.OBSENC, 'observation encounter', 'https://www.hl7.org/fhir/v3/ActCode/cs.html');
class_.userSelected = false;
encounter.class_ = class_;
encounter.resourceType = ResourceTypes.ENCOUNTER;
encounter.text = buildNarrative(NarrativeStatus.GENERATED, `<div xmlns=\"http://www.w3.org/1999/xhtml\">Encounter with patient @${data.patient.id}</div>`);
encounter.status = EncounterStatus.INPROGRESS;
// Use the first identifier in patient for the subject identifier
// For this POC, patient should only ever HAVE one identifier
let patient = await Patient.getOne(data.patient.identifier[0].value);
if (!patient || !patient.id) {
throw new Error(`Patient with ID ${data.patient.identifier[0].value} not found`);
}
encounter.subject = buildReference(data.patient.identifier[0]);
// Same goes here
encounter.serviceProvider = buildReference(data.provider.identifier[0]);
// Set Encounter start-date to now
encounter.period = new Period();
encounter.period.start = fhirTypes.date(data.txDate);
data.encounter = encounter;
// Note Encounter assets are defined in the core model file
// Add the Encounter to the ledger
for (let service of data.services) {
service.encounter = encounter;
await this.createService(service, data.txDate, collections);
}
await this.closeEncounter(data, data.txDate, collections);
}
/** Returns the invoice lines to invoke the adjudication of the claim later */
@Invokable()
public async getInvoiceLineItems(
@Param(yup.string())
claimUid: string
) {
const claim = new Claim(await this.getClaim(claimUid));
const collections = new PrivateCollectionsRoutes(claim.patient.identifier.value,
claim.provider.identifier.value, claim.insurer.identifier.value);
await collections.load();
const items = await buildInvoiceLineItems(claim.item, collections, this.tx);
return items;
}
@Invokable()
public async adjudicate() {
const data: AdjudicateClaim = await this.tx.getTransientValue<AdjudicateClaim>('data', AdjudicateClaim);
const transientInvoiceLineItem =
await this.tx.getTransientValue('invoices', parse) as any;
const claim =
await this.tx.getTransientValue('claim', parse) as any;
const invoiceLineItems = transientInvoiceLineItem.items;
const id = data.uid;
const claimResponse = new ClaimResponse(id);
data.claim = claim;
const collections = new PrivateCollectionsRoutes(data.claim.patient.identifier.value,
data.claim.provider.identifier.value, data.claim.insurer.identifier.value);
await collections.load();
claimResponse.identifier = [buildIdentifier(id, IdentifierUses.USUAL, IdentifierTypes.CLAIMRESPONSE)];
claimResponse.resourceType = ResourceTypes.CLAIMRESPONSE;
claimResponse.text = buildNarrative(NarrativeStatus.GENERATED, `<div xmlns=\"http://www.w3.org/1999/xhtml\">ClaimResponse for Claim @${data.claim.id}</div>`);
claimResponse.status = ClaimResponseStatus.ACTIVE;
claimResponse.use = ClaimResponseUses.CLAIM;
claimResponse.patient = data.claim.patient;
claimResponse.created = fhirTypes.date(data.txDate);
claimResponse.insurer = data.claim.insurer;
claimResponse.requestor = buildReference(data.claim.provider.identifier);
claimResponse.request = buildReference(data.claim.identifier[0]);
claimResponse.outcome = ClaimResponseOutcomes.COMPLETE;
claimResponse.type_ = new CodeableConcept();
claimResponse.type_.coding = [];
const claimType = buildCoding(CodingTypes.PROFESSIONAL, 'Professional', 'http://hl7.org/fhir/ValueSet/claim-type');
claimResponse.type_.coding.push(claimType);
claimResponse.type_.text = 'Professional';
// Placeholder disposition
claimResponse.disposition = 'Claim fully settled as per contract.';
// Build the payee from original claim
claimResponse.payeeType = data.claim.payee.type_;
//-----------------------------
// Build the adjudicated items, processing net along the way
//-----------------------------
let { totalCost } = buildTotalCosts();
let { totalBenefit } = buildTotalBenefits();
let invoiceTotalNet = 0;
let invoiceTotalGross = 0;
claimResponse.item = [];
let counterAdjudicationItems = 0;
for (let adjudicationItem of data.adjudications) {
// Make a new ClaimResponseItem for each item
let claimResponseItem = new ClaimResponseItem();
claimResponseItem.itemSequence = adjudicationItem.sequenceNumber;
claimResponseItem.adjudication = [];
// Process possible adjudications
let itemTotalCost = 0;
let itemTotalBenefit = 0;
if (adjudicationItem.adjudication && adjudicationItem.adjudication.eligible) {
claimResponseItem.adjudication.push(
buildAdjudicationItem(CodingTypes.ELEGIBLE, adjudicationItem.adjudication.eligible));
itemTotalCost += adjudicationItem.adjudication.eligible;
}
// Copay
if (adjudicationItem.adjudication && adjudicationItem.adjudication.copay) {
claimResponseItem.adjudication.push(
buildAdjudicationItem(CodingTypes.COPAY, adjudicationItem.adjudication.copay));
}
// Eligible Percent
if (adjudicationItem.adjudication && adjudicationItem.adjudication.eligpercent) {
claimResponseItem.adjudication.push(
buildAdjudicationItem(CodingTypes.ELIGPERCENT, adjudicationItem.adjudication.eligpercent));
}
// Benefit
if (adjudicationItem.adjudication && adjudicationItem.adjudication.eligpercent) {
claimResponseItem.adjudication.push(
buildAdjudicationItem(CodingTypes.BENEFIT, adjudicationItem.adjudication.benefit));
itemTotalBenefit += adjudicationItem.adjudication.benefit;
}
// Deductible
if (adjudicationItem.adjudication && adjudicationItem.adjudication.eligpercent) {
claimResponseItem.adjudication.push(
buildAdjudicationItem(CodingTypes.DEDUCTIBLE, adjudicationItem.adjudication.deductible));
itemTotalBenefit += adjudicationItem.adjudication.benefit;
}
let lineItemPriceComponents = [];
let lineItemPriceComponent = new InvoiceLineItemPriceComponent();
lineItemPriceComponent.type_ = InvoiceLineItemPriceComponentTypes.BASE;
lineItemPriceComponent.amount = buildMoney(itemTotalCost);
lineItemPriceComponents.push(lineItemPriceComponent);
let lineItemPriceComponent2 = new InvoiceLineItemPriceComponent();
lineItemPriceComponent2.type_ = InvoiceLineItemPriceComponentTypes.DEDUCTION;
lineItemPriceComponent2.amount = buildMoney(itemTotalBenefit)
lineItemPriceComponents.push(lineItemPriceComponent2);
invoiceLineItems[counterAdjudicationItems].priceComponent = lineItemPriceComponents;
// Apply the item's cost and benefit towards the total
totalCost.amount.value += itemTotalCost;
totalBenefit.amount.value += itemTotalBenefit;
invoiceTotalGross += itemTotalCost;
invoiceTotalNet += itemTotalCost - itemTotalBenefit;
// Add the ClaimResponseItem to the ClaimResponse
claimResponse.item.push(claimResponseItem);
counterAdjudicationItems++;
}
claimResponse.total = [];
claimResponse.total.push(totalCost);
claimResponse.total.push(totalBenefit);
claimResponse.extension = await FeeExtensionsConfig.getFeeExtension(ResourceTypes.CLAIMRESPONSE)
// Save to the blockchain
await this.saveClaimResponse(claimResponse, collections.claimResponse);
// Calculate amount
let amountOwed = totalBenefit.amount.value - totalCost.amount.value;
let accountData: AccountData = {
patientUid: claimResponse.patient.identifier.value,
ownerUid: claimResponse.requestor.identifier.value,
amount: amountOwed,
accountUid: data.accountUid
};
await this.createAccount(accountData, collections);
let invoiceData: InvoiceData = {
patientUid: claimResponse.patient.identifier.value,
ownerUid: claimResponse.requestor.identifier.value,
amount: amountOwed,
claimUid: data.claimUid,
claim: data.claim,
invoiceUid: data.invoiceUid,
accountUid: data.accountUid,
invoiceLineItems: invoiceLineItems,
invoiceTotalNet: invoiceTotalNet,
invoiceTotalGross: invoiceTotalGross
};
await this.createInvoice(invoiceData, data.txDate, collections);
}
@Invokable()
public async getOne(@Param(yup.string())
claimId: string) {
return await this.getClaim(claimId);
}
async createService(data: FlatConvectorModel<ServiceItem>, txDate: Date, collections: PrivateCollectionsRoutes) {
const procedureId = data.procedureUid;
const procedure = new Procedure(procedureId);
data.procedure = procedure;
// Build the identifier for the Procedure from the id
const identifier = buildIdentifier(procedureId, IdentifierUses.USUAL, IdentifierTypes.PROCEDURE);
procedure.identifier = [identifier];
procedure.resourceType = ResourceTypes.PROCEDURE;
procedure.text = buildNarrative(NarrativeStatus.GENERATED, `<div xmlns=\"http://www.w3.org/1999/xhtml\">Procedure for encounter @${data.encounter.id}</div>`)
procedure.status = ProcedureStatus.COMPLETED;
// Use same subject as the Encounter's patient
procedure.subject = data.encounter.subject;
// Set context to be a reference to the Encounter's first identifier (Should only be one for PoC)
procedure.encounter = buildReference(data.encounter.identifier[0]);
// Set performer to the providing Organization
const performer = new ProcedurePerformer();
performer.actor = data.encounter.serviceProvider;
performer.onBehalfOf = data.encounter.serviceProvider;
procedure.performer = [performer];
// Set HCPCS code
procedure.code = new CodeableConcept();
procedure.code.coding = [buildCoding(data.hcpcsCode, null, `https://www.hl7.org/fhir/cpt.html`)];
// Add the transaction date as the performed date for the PoC
procedure.performedDateTime = fhirTypes.date(txDate);
await this.saveProcedure(procedure, collections.procedure);
//-----------------------------------------------
//-Now add ChargeItem corresponding to procedure-
//-----------------------------------------------
// Make a unique ID for ChargeItem
const chargeItem = new ChargeItem(data.chargeItemUid);
data.chargeItem = chargeItem;
// Build the identifier for the ChargeItem from the id
const chargeItemIdentifier = buildIdentifier(data.chargeItemUid, IdentifierUses.USUAL, IdentifierTypes.CHARGEITEM);
// Unlike procedures, ChargeItems have only one Identifier in data spec
chargeItem.identifier = [chargeItemIdentifier];
chargeItem.resourceType = ResourceTypes.CHARGEITEM;
chargeItem.text = buildNarrative(NarrativeStatus.GENERATED, `<div xmlns=\"http://www.w3.org/1999/xhtml\">ChargeItem for encounter @${data.encounter.id}</div>`);
chargeItem.status = ChargeItemStatus.BILLABLE;
chargeItem.code = new CodeableConcept();
chargeItem.code.text = 'TBD code';
chargeItem.subject = data.encounter.subject;
chargeItem.context = buildReference(data.encounter.identifier[0]);
chargeItem.performingOrganization = data.encounter.serviceProvider;
chargeItem.quantity = new Quantity();
chargeItem.quantity.value = data.quantity;
// In actual application, a Contract Management System would instead be implemented.
chargeItem.priceOverride = buildMoney(data.unitPrice);
chargeItem.overrideReason = `Prices will be stored here for PoC to make workflow more applicable.`;
chargeItem.enteredDate = fhirTypes.date(txDate);
chargeItem.enterer = data.encounter.serviceProvider;
const service = buildReference(procedure.identifier[0]);
chargeItem.service = [service];
await this.saveChargeItem(chargeItem, collections.chargeItem);
}
async closeEncounter(data: CreateClaim, txDate: Date, collections: PrivateCollectionsRoutes) {
//--------------------------------------------
// First, attempt to create a new Claim object
//--------------------------------------------
const id = data.claimUid.includes(FQDNObjects.CLAIM.toString()) ? data.claimUid :
`${FQDNObjects.CLAIM}#${data.claimUid}`;
const claim = new Claim(id);
const identifier = buildIdentifier(id, IdentifierUses.USUAL, IdentifierTypes.CLAIM);
claim.identifier = [identifier];
claim.resourceType = ResourceTypes.CLAIM;
claim.text = buildNarrative(NarrativeStatus.GENERATED, `<div xmlns=\"http://www.w3.org/1999/xhtml\">Claim for Encounter @${data.encounter.id}</div>`)
claim.status = ClaimStatus.ACTIVE;
claim.use = ClaimUses.COMPLETE;
// Maybe add some type coding here in the future
claim.type_ = new CodeableConcept();
const claimType = buildCoding(CodingTypes.PROFESSIONAL, 'Professional', 'http://hl7.org/fhir/ValueSet/claim-type');
claim.type_.coding = [claimType];
claim.priority = new CodeableConcept();
const priorityType = buildCoding(CodingTypes.NORMAL, 'Normal', 'http://terminology.hl7.org/CodeSystem/processpriority');
claim.priority.coding = [priorityType];
claim.priority.text = 'Normal';
// Use the reference in Encounter for the patient identifier
claim.patient = data.encounter.subject;
// Set the created date to time of transaction
claim.created = fhirTypes.date(txDate);
// Set the insurer to be the payer
// Uses the first identifier, under the assumption it should have only one
claim.insurer = buildReference(data.payer.identifier[0])
// Set the organization to be the provider
claim.provider = data.encounter.serviceProvider;
// Set the payee to be the provider
claim.payee = new ClaimPayee();
claim.payee.type_ = new CodeableConcept();
claim.payee.type_.coding = [buildCoding(CodingTypes.PROVIDER, 'http://hl7.org/fhir/remittance-outcome')];
claim.payee.party = data.encounter.serviceProvider;
// Set the care team to be the provider organization
claim.careTeam = [new ClaimCareTeam()];
claim.careTeam[0].sequence = 1;
claim.careTeam[0].provider = data.encounter.serviceProvider;
claim.careTeam[0].responsible = true;
//let results = await query('selectChargeItemsByEncounter', {encounter_id: data.encounter.id});
claim.item = [];
claim.procedure = [];
let counter = 0;
for (let serviceProvider of data.services) {
let item = new ClaimItem();
let chargeItem = data.services[counter].chargeItem;
// Skip ChargeItems not properly labeled as billable status
if (chargeItem.status != ChargeItemStatus.BILLABLE) {
continue;
}
item.sequence = counter + 1;
item.encounter = [buildReference(data.encounter.identifier[0])];
item.careTeamSequence = [1];
claim.procedure.push(new ClaimProcedure());
claim.procedure[counter].sequence = counter + 1;
claim.procedure[counter].procedureReference = chargeItem.service[0];
let procedureEntity = data.services[counter].procedure;
claim.procedure[counter].procedureCodeableConcept = procedureEntity.code;
item.procedureSequence = [counter + 1];
item.procedureSequence.push();
item.productOrService = procedureEntity.code;
item.quantity = new SimpleQuantity();
item.quantity.value = chargeItem.quantity.value;
item.unitPrice = buildMoney(chargeItem.priceOverride.value);
item.unitPrice.currency = chargeItem.priceOverride.currency;
item.net = buildMoney(chargeItem.priceOverride.value * chargeItem.quantity.value);
claim.item.push(item);
// Update the ChargeItems
chargeItem.status = ChargeItemStatus.BILLED;
this.saveChargeItem(chargeItem, collections.chargeItem);
counter++;
}
claim.extension = await FeeExtensionsConfig.getFeeExtension(ResourceTypes.CLAIM)
if(data.copay) {
claim.extension.push(
new Extension({
url: 'https://fhir-ehr.cerner.com/r4/StructureDefinition/copay-balance',
valueMoney: buildMoney(data.copay)
})
)
}
claim.total = buildMoney(0);
for (let i = 0; i < claim.item.length; i++) {
claim.total.value += claim.item[i].net.value;
}
await this.saveClaim(claim, collections.claim);
// Add Claim to registry
// Update the Encounter records
data.encounter.period.end = fhirTypes.date(txDate);
let statusHistory = new EncounterStatusHistory();
statusHistory.status = data.encounter.status;
if (!data.encounter.statusHistory) {
data.encounter.statusHistory = [];
statusHistory.period = data.encounter.period;
} else {
statusHistory.period = new Period();
statusHistory.period.start = data.encounter.statusHistory[data.encounter.statusHistory.length - 1].period.end;
statusHistory.period.end = data.encounter.period.end;
}
data.encounter.statusHistory.push(statusHistory);
data.encounter.status = EncounterStatus.FINISHED;
await this.saveEncounter(data.encounter, collections.encounter);
}
async createAccount(data: AccountData, collections: PrivateCollectionsRoutes) {
const id = data.accountUid;
data.patient = await Patient.getOne(data.patientUid);
data.owner = await Organization.getOne(data.ownerUid);
const account = new Account(id);
// Build the identifier for the Account from the id
const identifier = buildIdentifier(id, IdentifierUses.USUAL, IdentifierTypes.ACCOUNT);
account.identifier = [identifier];
// Set the necessary DomainResource stuff
account.resourceType = ResourceTypes.ACCOUNT;
account.text = buildNarrative(NarrativeStatus.GENERATED, `<div xmlns=\"http://www.w3.org/1999/xhtml\">Account record for ${data.patient.id}.</div>`);
account.status = AccountStatus.ACTIVE;
// Set account type to a patient billing invoice
account.type_ = new CodeableConcept();
account.type_.coding = [buildCoding(CodingTypes.PBILLACCT, 'patient billing account', 'http://hl7.org/fhir/v3/ActCode')];
account.type_.text = 'patient';
account.name = `Patient billing account for ${data.patient.id}`;
// Build Reference to patient
account.subject = [];
const subject = buildReference(data.patient.identifier[0]);
account.subject.push(subject);
// Build Reference to owner
account.owner = buildReference(data.owner.identifier[0]);
account.description = `Account for tracking charges incurred during encounter.`;
await this.saveAccount(account, collections.account);
}
async createInvoice(data: InvoiceData, invoiceDate: Date, collections: PrivateCollectionsRoutes) {
const id = data.invoiceUid;
data.patient = await Patient.getOne(data.patientUid);
data.owner = await Organization.getOne(data.ownerUid);
const invoice = new Invoice(id);
// Build the identifier for the Account from the id
const identifier = buildIdentifier(id, IdentifierUses.USUAL, IdentifierTypes.INVOICE);
invoice.identifier = [identifier];
// Set the necessary DomainResource stuff
invoice.resourceType = ResourceTypes.INVOICE;
invoice.text = buildNarrative(NarrativeStatus.GENERATED, `<div xmlns=\"http://www.w3.org/1999/xhtml\">Invoice record for ${data.patient.id}.</div>`);
invoice.status = InvoiceStatus.ISSUED;
// Set account type to a patient billing invoice
invoice.type_ = new CodeableConcept();
invoice.type_.coding = [buildCoding(CodingTypes.PATIENT, 'patient invoice')]
invoice.type_.text = 'patient';
// Build Reference to patient
const subject = buildReference(data.patient.identifier[0]);
invoice.subject = subject;
const recipient = buildReference(data.patient.identifier[0]);
invoice.recipient = recipient;
invoice.date = fhirTypes.date(invoiceDate);
// Build Reference to owner
invoice.issuer = buildReference(data.owner.identifier[0]);
let accountIdentifier = new Identifier();
accountIdentifier.value = data.accountUid;
invoice.account = buildReference(accountIdentifier);
invoice.lineItem = data.invoiceLineItems;
invoice.totalNet = buildMoney(data.invoiceTotalNet);
invoice.totalGross = buildMoney(data.invoiceTotalGross);
invoice.extension = await FeeExtensionsConfig.getFeeExtension(ResourceTypes.INVOICE)
// Add Account to ledger
await this.saveInvoice(invoice, collections.invoice);
}
async saveClaim(claim: Claim, collection: string) {
await claim.save({
privateCollection: collection
});
let publicClaim = new PublicModelRouter(claim.id);
publicClaim.collection = collection;
await publicClaim.save();
}
async getClaim(id: string): Promise<Claim> {
let publicCoordinates = await PublicModelRouter.getOne(id);
return await Claim.getOne(id, Claim, {
privateCollection: publicCoordinates.collection
});
}
async saveEncounter(encounter: Encounter, collection: string) {
await new Encounter(encounter).save({
privateCollection: collection
});
let publicEncounter = new PublicModelRouter(encounter.id);
publicEncounter.collection = collection;
await publicEncounter.save();
}
async saveProcedure(procedure: Procedure, collection: string) {
await procedure.save({
privateCollection: collection
});
let publicModel = new PublicModelRouter(procedure.id);
publicModel.collection = collection;
await publicModel.save();
}
async saveChargeItem(chargeItem: Procedure, collection: string) {
await chargeItem.save({
privateCollection: collection
});
let publicModel = new PublicModelRouter(chargeItem.id);
publicModel.collection = collection;
await publicModel.save();
}
async saveClaimResponse(claimResponse: ClaimResponse, collection: string) {
await claimResponse.save({
privateCollection: collection
});
let publicModel = new PublicModelRouter(claimResponse.id);
publicModel.collection = collection;
await publicModel.save();
}
async saveAccount(account: Account, collection: string) {
await account.save({
privateCollection: collection
});
let publicModel = new PublicModelRouter(account.id);
publicModel.collection = collection;
await publicModel.save();
}
async saveInvoice(invoice: Invoice, collection: string) {
await invoice.save({
privateCollection: collection
});
let publicModel = new PublicModelRouter(invoice.id);
publicModel.collection = collection;
await publicModel.save();
}
} | the_stack |
import {NgSwCache, NgSwAdapter, ScopedCache, UrlConfig, UrlMatcher, Clock} from '../../worker';
import {CompareFn, SortedLinkedList} from './linked';
import {GroupManifest} from './manifest';
const DEFAULT_CACHE_SIZE = 100;
/**
* Metadata that's tracked for every entry in the cache.
*/
export interface EntryMetadata {
/**
* Number of times this entry has been accessed. Used for LFU.
*/
accessCount: number;
/**
* Timestamp (Date.now) since this cached request was last accessed. Used for LRU.
*/
accessedTs: number;
/**
* Timestamp (Date.now) since this cached request was first added. Used for FIFO.
*/
addedTs: number;
}
/**
* Map of URLs to metadata for those URLs.
*/
export interface EntryMetadataMap {
[url: string]: EntryMetadata;
}
/**
* A function which, when called, effects a side effect that may complete
* asynchronously.
*/
export type SideEffectFn = () => Promise<any>;
/**
* A potential `Response`, with an optional side effect function. Side effects
* are used to update metadata and perform other operations outside of the critical
* path for the request.
*
* If response is `null`, then there was no response available for this request.
*/
export interface ResponseWithSideEffect {
/**
* The response, or `null` if none existed for the request.
*/
response: Response|null;
/**
* Age of this response, if available.
*/
cacheAge?: number;
/**
* An optional function which, when executed, applies an asynchronous side effect.
*/
sideEffect?: SideEffectFn;
}
/**
* Optionally applies a side effect, returning a `Promise` which waits for the
* side effect to be applied if it exists, or resolves immediately if not.
*/
export function maybeRun(sideEffect: SideEffectFn|null): Promise<any> {
return !!sideEffect ? sideEffect() : Promise.resolve();
}
/**
* A strategy that makes use of the cache information in the `DynamicGroup` to
* optimize the loading of `Request`s.
*/
export interface DynamicStrategy {
/**
* The strategy name, which will be matched against "optimizeFor" configuration
* in dynamic cache configurations.
*/
readonly name: string;
/**
* Applies the strategy to a `Request` and returns an asynchronous response with an
* optional side effect.
*
* The given delegate is used to forward the request to the remainder of the chain
* in the event the strategy cannot or elects not to use a cached response.
*/
fetch(group: DynamicGroup, req: Request, delegate: () => Promise<Response>): Promise<ResponseWithSideEffect>;
}
/**
* Map of strategy names to implementations.
*/
export interface DynamicStrategyMap {
[strategy: string]: DynamicStrategy;
}
/**
* Represents a specific cache group with a single policy.
*/
export class DynamicGroup {
/**
* A queue of cached URLs, sorted according to the caching configuration (fifo,
* lfu, or lru). This is maintained in memory only, and reconstructed by `open`
* when loading from saved state.
*/
private queue: SortedLinkedList<string>;
/**
* Metadata for entries in this group's cache. Only URLs which exist in `queue`
* should have entries in this metadata map.
*
* The metadata map is mirrored to a 'metadata' cache entry under this group's
* scoped cache, keyed by the request.
*/
private metadata: EntryMetadataMap;
/**
* The optimization strategy used for requests in this group. The actual work
* of determining whether to used cached responses or continue to the network
* is done by the `DynamicStrategy`, not the `DynamicGroup`.
*/
private strategy: DynamicStrategy;
/**
* The user-provided manifest which configures the behavior of this dynamic
* caching group.
*/
config: GroupManifest;
/**
* Facade which enables unit testing of the cache group.
*/
private adapter: NgSwAdapter;
/**
* A cache scoped to this particular dynamic group.
*/
private cache: NgSwCache;
/**
* Matchers that will detect URLs which should be handled by this group.
*/
private matchers: UrlMatcher[];
/**
* Clock which enables easy unit testing of `DynamicGroup`'s cache expiration
* operations through mocking of the current time.
*/
clock: Clock;
/**
* Consumers should use `DynamicGroup.open` instead.
*/
constructor(
strategy: DynamicStrategy,
config: GroupManifest,
adapter: NgSwAdapter,
cache: NgSwCache,
matchers: UrlMatcher[],
metadata: EntryMetadataMap,
clock: Clock) {
// Obligatory Javaesque assignment of class properties.
this.strategy = strategy;
this.config = config;
this.adapter = adapter;
this.cache = cache;
this.matchers = matchers;
this.metadata = metadata;
this.clock = clock;
// Construct the queue with a comparison strategy based on the expiration
// strategy chosen by the user.
switch (config.cache.strategy) {
case 'fifo':
this.queue = new SortedLinkedList<string>(this.fifoCompare.bind(this));
break;
case 'lfu':
this.queue = new SortedLinkedList<string>(this.lfuCompare.bind(this));
break;
case 'lru':
this.queue = new SortedLinkedList<string>(this.lruCompare.bind(this));
break;
default:
throw new Error(`Unknown cache strategy: ${config.cache.strategy}`);
}
Object.keys(this.metadata).forEach(url => this.queue.insert(url));
}
/**
* Constructs a new `DynamicGroup`, based on the given manifest. If this group has
* never existed before, it will be empty. If it has, the existing metadata will be
* read out of
*/
static open(
config: GroupManifest,
adapter: NgSwAdapter,
delegateCache: NgSwCache,
clock: Clock,
strategies: DynamicStrategyMap): Promise<DynamicGroup> {
// The cache passed to open() isn't scoped, so construct a new one that's scoped.
const cache = new ScopedCache(delegateCache, `dynamic:${config.name}:`);
// Select the desired strategy with which to process requests. If the user
// asked for an invalid strategy, complain.
const strategy = strategies[config.cache.optimizeFor];
if (!strategy) {
throw new Error(`No registered optimizeFor handler (${config.cache.optimizeFor}) for group ${config.name}`);
}
// Construct the chain of `UrlMatcher`s for all of the URL matching configurations
// provided in the manifest.
const matchers = Object
.keys(config.urls)
.map(url => new UrlMatcher(url, config.urls[url], adapter.scope));
// Look through the metadata cache for all cached requests, load the metadata for
// them, and add it to a metadata map, keyed by URL. If this is a fresh cache and
// there are no requests, then cache.keysOf() will return an empty array, and the
// resulting metadata map will be empty.
return cache
.keysOf('metadata')
// These keys are `Request`s, use them to actually load the data from the cache.
.then(keys => Promise.all(keys.map(key => cache
// For each key, load the metadata for the key.
.load('metadata', key)
// Read it out as an `EntryMetadata` object.
.then(resp => resp.json() as Promise<EntryMetadata>)
// And capture the URL as well.
.then(metadata => ({url: key.url, metadata}))
)))
// Transform the list of metadata objects into a map keyed by the URL.
.then(metadata => metadata.reduce((acc, curr) => {
acc[curr.url] = curr.metadata;
return acc;
}, {} as EntryMetadataMap))
// Finally, create the `DynamicGroup` instance with the loaded data.
.then(metadata => new DynamicGroup(strategy, config, adapter, cache, matchers, metadata, clock));
}
/**
* Match a `Request` against the URL patterns configured for this group.
*/
matches(req: Request): boolean {
return this.matchers.some(matcher => matcher.matches(req.url));
}
/**
* A comparison function for FIFO expiration, that compares two URLs by time added.
*/
private fifoCompare(urlA: string, urlB: string): number {
const a = this.metadata[urlA];
const b = this.metadata[urlB];
return compare(a.addedTs, b.addedTs);
}
/**
* A comparison function for LFU expiration, that compares two URLs by access count.
*/
private lfuCompare(urlA: string, urlB: string): number {
const a = this.metadata[urlA];
const b = this.metadata[urlB];
return compare(a.accessCount, b.accessCount);
}
/**
* A comparison function for LRU expiration, that compares two URLs by time accessed.
*/
private lruCompare(urlA: string, urlB: string): number {
const a = this.metadata[urlA];
const b = this.metadata[urlB];
return compare(a.accessedTs, b.accessedTs);
}
/**
* Fetch a given request from the cache only.
*/
fetchFromCache(req: Request): Promise<ResponseWithSideEffect> {
// Firstly, check for metadata. If it doesn't exist, there's no point in
// continuing, the request isn't cached.
const metadata = this.metadata[req.url];
if (!metadata) {
return Promise.resolve({response: null});
}
// If the user's configured a maxAgeMs value for the cache, check the age of the
// cached response against it. If it's too old, it needs to be removed from the
// cache.
const cacheAge = this.clock.dateNow() - metadata.addedTs;
if (!!this.config.cache.maxAgeMs && cacheAge > this.config.cache.maxAgeMs) {
// TODO: Possibly do this as a side effect and not inline.
// Remove from the in-memory tracking.
this.queue.remove(req.url);
delete this.metadata[req.url];
// And invalidate the entry in the actual cache.
return Promise
.all([
this.cache.invalidate('cache', req.url),
this.cache.invalidate('metadata', req.url),
])
// Finally, signal that there was no cached response for this request.
.then(() => ({response: null}));
}
// The cached response is valid and can be used.
return this
.cache
// Grab the response from the cache.
.load('cache', req.url)
.then(response => {
// Something went wrong, abort.
// TODO: maybe need to invalidate the metadata here?
if (!response) {
return {response: null};
}
// The response is ready, but the metadata needs to be updated. Since this is
// outside the critical path for servicing the request, it is done in a side
// effect.
const sideEffect = () => {
// Update the 'accessed' stats.
metadata.accessCount++;
metadata.accessedTs = this.clock.dateNow();
// Return a promise that saves the metadata to the metadata cache.
return this
.cache
.store('metadata', req.url, this.adapter.newResponse(JSON.stringify(metadata)))
// After caching, remove and insert the URL into the linked list which
// tracks expiration order, to update its position based on the new stats.
// TODO: optimize this operation to move the entry left or right in the list.
.then(() => {
this.queue.remove(req.url);
this.queue.insert(req.url);
});
};
// Finally, construct the final `ResponseWithSideEffects`.
return {response, cacheAge, sideEffect};
});
}
// Fetch a request from the network and store the response in the cache.
fetchAndCache(req: Request, delegate: () => Promise<Response>): Promise<ResponseWithSideEffect> {
// Call the delegate to run the rest of the fetch pipeline and get the response
// from downstream plugins.
return delegate()
.then(response => {
// Don't cache unsuccessful responses.
if (!response.ok) {
return {response};
}
// TODO: check response size to implement maxSizeBytes.
// Need to clone the response, as the body will be read twice
const toCache = response.clone();
// Adding to the cache is implemented as a side effect.
const sideEffect = () => {
// Check if the request already has associated metadata. If it does, then
// it needs to be updated, otherwise insert new metadata (possibly causing an
// eviction).
let metadata = this.metadata[req.url];
return !metadata
? this.insertIntoCache(req.url, toCache)
: this.updateIntoCache(req.url, toCache);
}
// Return the response together with the side effect that will cache it.
return {response, sideEffect};
});
}
/**
* Handle fetching a request, using the configured strategy. `delegate` will invoke
* the rest of the worker's fetch pipeline, ultimately fetching the request from the
* network.
*/
fetch(req: Request, delegate: () => Promise<Response>): Promise<ResponseWithSideEffect> {
// If the request is mutating (not GET, OPTIONS, or HEAD) then it needs to go to the
// server directly, bypassing the cache.
if (req.method !== 'GET' && req.method !== 'OPTIONS' && req.method !== 'HEAD') {
// TODO: invalidate cache on mutating request.
const res = delegate().then(response => ({response}));
}
// Otherwise, delegate to the dynamic caching strategy to handle this request.
return this.strategy.fetch(this, req, delegate);
}
/**
* Insert a new URL into the cache, returning a `Promise` that resolves when all
* the metadata updates are complete.
*/
private insertIntoCache(url: string, res: Response): Promise<void> {
// This should never happen, but sanity check that this entry does not have metadata
// already.
if (this.metadata[url]) {
return Promise.reject(new Error(`insertIntoCache(${url}) but url is already cached`));
}
// New metadata entry for this respones.
const now = this.clock.dateNow();
const metadata: EntryMetadata = {
addedTs: now,
accessCount: 1,
accessedTs: now,
};
// Start a Promise chain to keep the code organized.
return Promise
.resolve()
// Evict requests if necessary.
.then(() => {
let maybeEvict: Promise<any> = Promise.resolve();
// Evict items until the cache has room for the new entry.
let queueLength = this.queue.length;
while (queueLength >= (this.config.cache.maxEntries || DEFAULT_CACHE_SIZE)) {
queueLength--;
maybeEvict = maybeEvict.then(() => {
// Need to evict something. Pick the top item on the queue and remove it.
const evictUrl = this.queue.pop();
delete this.metadata[evictUrl];
// Process the eviction, removing both the cached data and its metadata.
return Promise.all([
this.cache.invalidate('cache', evictUrl),
this.cache.invalidate('metadata', evictUrl),
]);
});
}
return maybeEvict;
})
// After all evictions, perform the insertion.
.then(() => Promise.all([
this.cache.store('cache', url, res),
this.cache.store('metadata', url,
this.adapter.newResponse(JSON.stringify(metadata))),
]))
.then(() => {
// After insertion is complete, track the changes in the in-memory metadata.
this.metadata[url] = metadata;
this.queue.insert(url);
});
}
private updateIntoCache(url: string, res: Response): Promise<void> {
const metadata = this.metadata[url];
if (!metadata) {
return Promise.reject(new Error(`updateIntoCache(${url}) but url is not cached`));
}
// Update metadata.
metadata.accessCount++;
metadata.addedTs = metadata.accessedTs = this.clock.dateNow();
return Promise
// Update both data and metadata.
.all([
this.cache.store('cache', url, res),
this.cache.store('metadata', url,
this.adapter.newResponse(JSON.stringify(metadata))),
])
// Update the queue to properly track this entry.
.then(() => {
this.queue.remove(url);
this.queue.insert(url);
});
}
}
/**
* Compare two numbers, returning -1, 0, or 1 depending on order.
*/
function compare(a: number, b: number) {
if (a < b) {
return -1;
} else if (a === b) {
return 0;
} else {
return 1;
}
} | the_stack |
import { expect } from "chai";
import { MatrixEventHandler } from "../src/matrixeventhandler";
import {
RoomEvent, RoomEventContent, MembershipEvent, RedactionEvent, MessageEventContent, MessageEvent,
FileMessageEventContent, TextualMessageEventContent,
} from "@sorunome/matrix-bot-sdk";
import * as prometheus from "prom-client";
import { MessageDeduplicator } from "../src/structures/messagededuplicator";
// we are a test file and thus our linting rules are slightly different
// tslint:disable:no-unused-expression max-file-line-count no-any no-magic-numbers no-string-literal
interface IHandlerOpts {
puppetHasAvatar?: boolean;
puppetHasName?: boolean;
relayEnabled?: boolean;
featureImage?: boolean;
featureAudio?: boolean;
featureVideo?: boolean;
featureSticker?: boolean;
featureFile?: boolean;
featureEdit?: boolean;
featureReply?: boolean;
createDmHook?: boolean;
getDmRoomIdHook?: any;
createRoomHook?: any;
}
const DEDUPLICATOR_TIMEOUT = 100;
let PUPPETSTORE_JOINED_GHOST_TO_ROOM = "";
let PUPPETSTORE_LEAVE_GHOST_FROM_ROOM = "";
let PUPPETSTORE_SET_MXID_INFO = false;
let USERSYNC_SET_ROOM_OVERRIDE = false;
let ROOMSYNC_MAYBE_LEAVE_GHOST = "";
let ROOMSYNC_MARK_AS_DIRECT = "";
let BRIDGE_EVENTS_EMITTED: any[] = [];
let BRIDGE_ROOM_MXID_UNBRIDGED = "";
let BRIDGE_ROOM_ID_UNBRIDGED = "";
let BRIDGE_ROOM_ID_BRIDGED = "";
let PROVISIONER_GET_MXID_CALLED = false;
let ROOM_SYNC_GET_PARTS_FROM_MXID_CALLED = false;
let BOT_PROVISIONER_EVENT_PROCESSED = false;
let BOT_PROVISIONER_ROOM_EVENT_PROCESSED = false;
let DELAYED_FUNCTION_SET = async () => {};
let BOT_INTENT_JOIN_ROOM = "";
let GHOST_INTENT_LEAVE_ROOM = "";
let GHOST_INTENT_JOIN_ROOM = "";
let ROOM_SYNC_INSERTED_ENTRY = false;
let REACTION_HANDLER_ADDED_MATRIX = false;
let REACTION_HANDLER_HANDLED_REDACT = false;
let PRESENCE_HANDLER_SET_STATUS_IN_ROOM = "";
function getHandler(opts?: IHandlerOpts) {
if (!opts) {
opts = {};
}
PUPPETSTORE_JOINED_GHOST_TO_ROOM = "";
PUPPETSTORE_SET_MXID_INFO = false;
USERSYNC_SET_ROOM_OVERRIDE = false;
ROOMSYNC_MAYBE_LEAVE_GHOST = "";
ROOMSYNC_MARK_AS_DIRECT = "";
BRIDGE_EVENTS_EMITTED = [];
BRIDGE_ROOM_MXID_UNBRIDGED = "";
BRIDGE_ROOM_ID_UNBRIDGED = "";
BRIDGE_ROOM_ID_BRIDGED = "";
PROVISIONER_GET_MXID_CALLED = false;
ROOM_SYNC_GET_PARTS_FROM_MXID_CALLED = false;
BOT_PROVISIONER_EVENT_PROCESSED = false;
BOT_PROVISIONER_ROOM_EVENT_PROCESSED = false;
DELAYED_FUNCTION_SET = async () => {};
BOT_INTENT_JOIN_ROOM = "";
GHOST_INTENT_LEAVE_ROOM = "";
GHOST_INTENT_JOIN_ROOM = "";
ROOM_SYNC_INSERTED_ENTRY = false;
REACTION_HANDLER_ADDED_MATRIX = false;
REACTION_HANDLER_HANDLED_REDACT = false;
PRESENCE_HANDLER_SET_STATUS_IN_ROOM = "";
const bridge = {
hooks: opts!.createDmHook ? {
getDmRoomId: opts!.getDmRoomIdHook || true,
createRoom: opts!.createRoomHook || true,
} : {},
protocol: {
id: "remote",
features: {
image: opts!.featureImage || false,
audio: opts!.featureAudio || false,
video: opts!.featureVideo || false,
sticker: opts!.featureSticker || false,
file: opts!.featureFile || false,
edit: opts!.featureEdit || false,
reply: opts!.featureReply || false,
},
},
emit: (type) => {
BRIDGE_EVENTS_EMITTED.push(type);
},
getUrlFromMxc: (mxc) => "https://" + mxc,
unbridgeRoomByMxid: async (roomId) => {
BRIDGE_ROOM_MXID_UNBRIDGED = roomId;
},
unbridgeRoom: async (room) => {
BRIDGE_ROOM_ID_UNBRIDGED = room.roomId;
},
bridgeRoom: async (room) => {
BRIDGE_ROOM_ID_BRIDGED = room.roomId;
},
namespaceHandler: {
getRemoteUser: async (user, sender) => {
return user;
},
getRemoteRoom: async (room, sender) => {
return room;
},
},
getMxidForUser: async (user, override) => `@_puppet_${user.puppetId}_${user.userId}:example.org`,
AS: {
isNamespacedUser: (userId) => userId.startsWith("@_puppet"),
botIntent: {
userId: "@_puppetbot:example.org",
joinRoom: async (roomId) => {
BOT_INTENT_JOIN_ROOM = roomId;
},
},
getIntentForUserId: (userId) => {
return {
leaveRoom: async (roomId) => {
GHOST_INTENT_LEAVE_ROOM = roomId;
},
joinRoom: async (roomId) => {
GHOST_INTENT_JOIN_ROOM = roomId;
},
};
},
},
delayedFunction: {
set: (key, fn, timeout, opt) => {
DELAYED_FUNCTION_SET = fn;
},
},
botProvisioner: {
processEvent: async (roomId, event) => {
BOT_PROVISIONER_EVENT_PROCESSED = true;
},
processRoomEvent: async (roomId, event) => {
BOT_PROVISIONER_ROOM_EVENT_PROCESSED = true;
},
},
puppetStore: {
joinGhostToRoom: async (ghostId, roomId) => {
PUPPETSTORE_JOINED_GHOST_TO_ROOM = `${ghostId};${roomId}`;
},
leaveGhostFromRoom: async (ghostId, roomId) => {
PUPPETSTORE_LEAVE_GHOST_FROM_ROOM = `${ghostId};${roomId}`;
},
getOrCreateMxidInfo: async (puppetMxid) => {
const ret = {
avatarMxc: "",
name: "",
} as any;
if (opts!.puppetHasAvatar) {
ret.avatarMxc = "mxc://avatar/example.com";
}
if (opts!.puppetHasName) {
ret.name = "User";
}
return ret;
},
setMxidInfo: async (puppet) => {
PUPPETSTORE_SET_MXID_INFO = true;
},
},
userSync: {
getPartsFromMxid: (ghostId) => {
if (ghostId.startsWith("@_puppet_1_fox:")) {
return {
userId: "fox",
puppetId: 1,
};
}
if (ghostId.startsWith("@_puppet_1_newfox:")) {
return {
userId: "newfox",
puppetId: 1,
};
}
if (ghostId.startsWith("@_puppet_999_otherfox:")) {
return {
userId: "otherfox",
puppetId: 999,
};
}
return null;
},
setRoomOverride: async (userParts, roomId) => {
USERSYNC_SET_ROOM_OVERRIDE = true;
},
getClient: async (parts) => {},
},
roomSync: {
getPartsFromMxid: async (roomId) => {
ROOM_SYNC_GET_PARTS_FROM_MXID_CALLED = true;
if (roomId.startsWith("!foxdm:")) {
return {
roomId: "foxdm",
puppetId: 1,
};
}
if (roomId.startsWith("#_puppet_1_foxroom:")) {
return {
roomId: "foxroom",
puppetId: 1,
};
}
if (roomId.startsWith("!room:")) {
return {
roomId: "room",
puppetId: 1,
};
}
return null;
},
maybeLeaveGhost: async (roomId, userId) => {
ROOMSYNC_MAYBE_LEAVE_GHOST = `${userId};${roomId}`;
},
maybeGet: async (room) => {
if (room.roomId === "fox" && room.puppetId === 1) {
return room;
}
if (room.roomId === "foxdm" && room.puppetId === 1) {
return {
roomdId: "foxdm",
puppetId: 1,
isDirect: true,
};
}
return null;
},
insert: async (roomId, roomData) => {
ROOM_SYNC_INSERTED_ENTRY = true;
},
getRoomOp: async (opRoomId) => {
return {
getRoomStateEvent: async (_, state, key) => {
if (state === "m.room.member" && key === "user") {
return {
membership: "join",
displayname: "User",
avatar_url: "blah",
};
}
},
getEvent: async (roomId, eventId) => {
if (eventId === "$event:example.org") {
return {
type: "m.room.message",
content: {
msgtype: "m.text",
body: "original message",
},
sender: "user",
};
}
},
};
},
markAsDirect: (room) => {
ROOMSYNC_MARK_AS_DIRECT = `${room.puppetId};${room.roomId}`;
},
markAsUsed: (room) => { },
},
provisioner: {
get: async (puppetId) => {
if (puppetId === 1) {
return {
puppetMxid: "@user:example.org",
userId: "puppetGhost",
type: opts!.relayEnabled ? "relay" : "puppet",
autoinvite: true,
isPrivate: true,
};
}
return null;
},
getMxid: async (puppetId) => {
PROVISIONER_GET_MXID_CALLED = true;
if (puppetId === 1) {
return "@user:example.org";
}
return "";
},
getForMxid: async (puppetMxid) => {
if (puppetMxid === "@user:example.org") {
return [
{
puppetId: 1,
type: "puppet",
puppetMxid,
},
{
puppetId: 2,
type: "puppet",
puppetMxid,
},
];
}
return [];
},
canRelay: (mxid) => !mxid.startsWith("@bad"),
adjustMute: async (userId, room) => {},
},
eventSync: {
getRemote: (room, mxid) => {
if (mxid.split(";")[0] === "$bad:example.org") {
return ["bad"];
}
if (mxid.split(";")[0] === "$event:example.org") {
return ["event"];
}
return [];
},
},
reactionHandler: {
addMatrix: async (room, relEvent, eventId, key) => {
REACTION_HANDLER_ADDED_MATRIX = true;
},
handleRedactEvent: async (roomEvent) => {
REACTION_HANDLER_HANDLED_REDACT = true;
},
},
presenceHandler: {
setStatusInRoom: async (userId, roomId) => {
PRESENCE_HANDLER_SET_STATUS_IN_ROOM = `${userId};${roomId}`;
},
},
typingHandler: {
deduplicator: new MessageDeduplicator(DEDUPLICATOR_TIMEOUT, DEDUPLICATOR_TIMEOUT + DEDUPLICATOR_TIMEOUT),
},
metrics: {},
} as any;
prometheus.register.clear();
return new MatrixEventHandler(bridge);
}
describe("MatrixEventHandler", () => {
describe("handleRoomEvent", () => {
it("should route joins to the join handler", async () => {
const handler = getHandler();
let joinHandled = false;
handler["handleJoinEvent"] = async (roomId, evt) => {
joinHandled = true;
};
const event = new RoomEvent<RoomEventContent>({
type: "m.room.member",
content: {
membership: "join",
},
});
await handler["handleRoomEvent"]("!blah:example.org", event);
expect(joinHandled).to.be.true;
});
it("should route bans to the leave handler", async () => {
const handler = getHandler();
let leaveHandled = false;
handler["handleLeaveEvent"] = async (roomId, evt) => {
leaveHandled = true;
};
const event = new RoomEvent<RoomEventContent>({
type: "m.room.member",
content: {
membership: "ban",
},
});
await handler["handleRoomEvent"]("!blah:example.org", event);
expect(leaveHandled).to.be.true;
});
it("should route leaves to the leave handler", async () => {
const handler = getHandler();
let leaveHandled = false;
handler["handleLeaveEvent"] = async (roomId, evt) => {
leaveHandled = true;
};
const event = new RoomEvent<RoomEventContent>({
type: "m.room.member",
content: {
membership: "leave",
},
});
await handler["handleRoomEvent"]("!blah:example.org", event);
expect(leaveHandled).to.be.true;
});
it("should route redactions to the redaction handler", async () => {
const handler = getHandler();
let redactionHandled = false;
handler["handleRedactEvent"] = async (roomId, evt) => {
redactionHandled = true;
};
const event = new RoomEvent<RoomEventContent>({
type: "m.room.redaction",
});
await handler["handleRoomEvent"]("!blah:example.org", event);
expect(redactionHandled).to.be.true;
});
it("should route stickers to the message handler", async () => {
const handler = getHandler();
let messageHandled = false;
handler["handleMessageEvent"] = async (roomId, evt) => {
messageHandled = true;
};
const event = new RoomEvent<RoomEventContent>({
type: "m.sticker",
});
await handler["handleRoomEvent"]("!blah:example.org", event);
expect(messageHandled).to.be.true;
});
it("should route messages to the message handler", async () => {
const handler = getHandler();
let messageHandled = false;
handler["handleMessageEvent"] = async (roomId, evt) => {
messageHandled = true;
};
const event = new RoomEvent<RoomEventContent>({
type: "m.room.message",
});
await handler["handleRoomEvent"]("!blah:example.org", event);
expect(messageHandled).to.be.true;
});
});
describe("handleJoinEvent", () => {
it("should route ghosts to the ghost join handler", async () => {
const handler = getHandler();
let ghostJoinHandled = false;
handler["handleGhostJoinEvent"] = async (roomId, evt) => {
ghostJoinHandled = true;
};
const event = new MembershipEvent({
type: "m.room.member",
state_key: "@_puppet_1_blah:example.org",
content: {
membership: "join",
},
});
await handler["handleRoomEvent"]("!blah:example.org", event);
expect(ghostJoinHandled).to.be.true;
});
it("should route users to the user join handler", async () => {
const handler = getHandler();
let userJoinHandled = false;
handler["handleUserJoinEvent"] = async (roomId, evt) => {
userJoinHandled = true;
};
const event = new MembershipEvent({
type: "m.room.member",
state_key: "@user:example.org",
content: {
membership: "join",
},
});
await handler["handleRoomEvent"]("!blah:example.org", event);
expect(userJoinHandled).to.be.true;
});
});
describe("handleGhostJoinEvent", () => {
it("should add the ghost to the room cache and update status", async () => {
const handler = getHandler();
const ghostId = "@_puppet_1_blah:example.org";
const event = new MembershipEvent({
type: "m.room.member",
state_key: ghostId,
content: {
membership: "join",
},
});
const roomId = "!blah:example.org";
await handler["handleGhostJoinEvent"](roomId, event);
expect(PUPPETSTORE_JOINED_GHOST_TO_ROOM).to.equal(`${ghostId};${roomId}`);
expect(PRESENCE_HANDLER_SET_STATUS_IN_ROOM).to.equal(`${ghostId};${roomId}`);
});
it("should set a room override, are all conditions met", async () => {
const handler = getHandler();
const ghostId = "@_puppet_1_fox:example.org";
const event = new MembershipEvent({
type: "m.room.member",
state_key: ghostId,
content: {
membership: "join",
},
});
const roomId = "!foxdm:example.org";
await handler["handleGhostJoinEvent"](roomId, event);
expect(USERSYNC_SET_ROOM_OVERRIDE).to.be.true;
});
it("should not attempt leave the appservice bot, if not a dm", async () => {
const handler = getHandler();
const ghostId = "@_puppet_1_blah:example.org";
const event = new MembershipEvent({
type: "m.room.member",
state_key: ghostId,
content: {
membership: "join",
},
});
const roomId = "!blah:example.org";
await handler["handleGhostJoinEvent"](roomId, event);
expect(ROOMSYNC_MAYBE_LEAVE_GHOST).to.equal("");
});
it("should attempt to leave the appservice bot, if a dm", async () => {
const handler = getHandler();
const ghostId = "@_puppet_1_blah:example.org";
const event = new MembershipEvent({
type: "m.room.member",
state_key: ghostId,
content: {
membership: "join",
},
});
const roomId = "!foxdm:example.org";
await handler["handleGhostJoinEvent"](roomId, event);
expect(ROOMSYNC_MAYBE_LEAVE_GHOST).to.equal(`@_puppetbot:example.org;${roomId}`);
});
});
describe("handleUserJoinEvent", () => {
it("should do nothing, if no room is found", async () => {
const handler = getHandler();
let updatedCache = false;
handler["updateCachedRoomMemberInfo"] = async (rid, uid, content) => {
updatedCache = true;
};
const userId = "@user:example.org";
const event = new MembershipEvent({
type: "m.room.member",
state_key: userId,
content: {
membership: "join",
},
});
const roomId = "!nonexistant:example.org";
await handler["handleUserJoinEvent"](roomId, event);
expect(updatedCache).to.be.false;
});
it("should update the member info cache, should the room be found", async () => {
const handler = getHandler();
let updatedCache = false;
handler["updateCachedRoomMemberInfo"] = async (rid, uid, content) => {
updatedCache = true;
};
const userId = "@user:example.org";
const event = new MembershipEvent({
type: "m.room.member",
state_key: userId,
content: {
membership: "join",
},
});
const roomId = "!foxdm:example.org";
await handler["handleUserJoinEvent"](roomId, event);
expect(updatedCache).to.be.true;
});
it("should update the puppets name, if a new one is present", async () => {
const handler = getHandler();
const userId = "@user:example.org";
const event = new MembershipEvent({
type: "m.room.member",
state_key: userId,
content: {
displayname: "Fox Lover",
membership: "join",
},
});
const roomId = "!foxdm:example.org";
await handler["handleUserJoinEvent"](roomId, event);
expect(BRIDGE_EVENTS_EMITTED.length).to.equal(2);
expect(BRIDGE_EVENTS_EMITTED).to.eql(["puppetName", "puppetName"]);
expect(PUPPETSTORE_SET_MXID_INFO).to.be.true;
});
it("should update the puppets avatar, if a new one is present", async () => {
const handler = getHandler();
const userId = "@user:example.org";
const event = new MembershipEvent({
type: "m.room.member",
state_key: userId,
content: {
avatar_url: "mxc://fox/example.org",
membership: "join",
},
});
const roomId = "!foxdm:example.org";
await handler["handleUserJoinEvent"](roomId, event);
expect(BRIDGE_EVENTS_EMITTED.length).to.equal(2);
expect(BRIDGE_EVENTS_EMITTED).to.eql(["puppetAvatar", "puppetAvatar"]);
expect(PUPPETSTORE_SET_MXID_INFO).to.be.true;
});
});
describe("handleLeaveEvent", () => {
it("should leave the ghost of the room, if it was a ghost", async () => {
const handler = getHandler();
const userId = "@user:example.org";
const ghostId = "@_puppet_1_fox:example.org";
const event = new MembershipEvent({
type: "m.room.member",
state_key: ghostId,
sender: ghostId,
content: {
membership: "leave",
},
});
const roomId = "!blah:example.org";
await handler["handleLeaveEvent"](roomId, event);
expect(PUPPETSTORE_LEAVE_GHOST_FROM_ROOM).to.equal(`${ghostId};${roomId}`);
expect(BRIDGE_ROOM_MXID_UNBRIDGED).to.equal("");
});
});
describe("handleRedactEvent", () => {
it("should ignore redactions from ghosts", async () => {
const handler = getHandler();
const event = new RedactionEvent({
type: "m.room.redaction",
sender: "@_puppet_1_fox:example.org",
redacts: "$bad:example.org",
});
const roomId = "!foxdm:example.org";
await handler["handleRedactEvent"](roomId, event);
expect(BRIDGE_EVENTS_EMITTED.length).to.equal(0);
});
it("should ignore redactions from unknown rooms", async () => {
const handler = getHandler();
const event = new RedactionEvent({
type: "m.room.redaction",
sender: "@user:example.org",
redacts: "$bad:example.org",
});
const roomId = "!invalid:example.org";
await handler["handleRedactEvent"](roomId, event);
expect(BRIDGE_EVENTS_EMITTED.length).to.equal(0);
});
it("should ignore redacts, if not from the puppet user", async () => {
const handler = getHandler();
const event = new RedactionEvent({
type: "m.room.redaction",
sender: "@wronguser:example.org",
redacts: "$bad:example.org",
});
const roomId = "!foxdm:example.org";
await handler["handleRedactEvent"](roomId, event);
expect(BRIDGE_EVENTS_EMITTED.length).to.equal(0);
});
it("should not redact if the dedupe flag is set", async () => {
const handler = getHandler();
const event = new RedactionEvent({
type: "m.room.redaction",
sender: "@user:example.org",
redacts: "$bad:example.org",
content: { source: "remote" },
});
const roomId = "!foxdm:example.org";
await handler["handleRedactEvent"](roomId, event);
expect(BRIDGE_EVENTS_EMITTED.length).to.equal(0);
});
it("should redact events, should all check out", async () => {
const handler = getHandler();
const event = new RedactionEvent({
type: "m.room.redaction",
sender: "@user:example.org",
redacts: "$bad:example.org",
});
const roomId = "!foxdm:example.org";
await handler["handleRedactEvent"](roomId, event);
expect(BRIDGE_EVENTS_EMITTED.length).to.equal(1);
expect(BRIDGE_EVENTS_EMITTED[0]).to.equal("redact");
expect(REACTION_HANDLER_HANDLED_REDACT).to.be.true;
});
});
describe("handleMessageEvent", () => {
it("should drop messages from ghosts", async () => {
const handler = getHandler();
const event = new MessageEvent<MessageEventContent>({
type: "m.room.message",
sender: "@_puppet_1_fox:example.org",
});
const roomId = "!foxdm:example.org";
await handler["handleMessageEvent"](roomId, event);
expect(ROOM_SYNC_GET_PARTS_FROM_MXID_CALLED).to.be.false;
});
it("should forward messages to the bot provisioner, if no associated room is found", async () => {
const handler = getHandler();
const event = new MessageEvent<MessageEventContent>({
type: "m.room.message",
sender: "@user:example.org",
});
const roomId = "!invalid:example.org";
await handler["handleMessageEvent"](roomId, event);
expect(ROOM_SYNC_GET_PARTS_FROM_MXID_CALLED).to.be.true;
expect(BOT_PROVISIONER_EVENT_PROCESSED).to.be.true;
});
it("should drop the message, if it wasn't sent by us", async () => {
const handler = getHandler();
let messageHandled = false;
handler["handleFileEvent"] = async (rid, room, puppet, evt) => {
messageHandled = true;
};
handler["handleTextEvent"] = async (rid, room, puppet, evt) => {
messageHandled = true;
};
const event = new MessageEvent<MessageEventContent>({
type: "m.room.message",
sender: "@wronguser:example.org",
});
const roomId = "!foxdm:example.org";
await handler["handleMessageEvent"](roomId, event);
expect(messageHandled).to.be.false;
});
it("should drop the message if relay is enabled but sender is blacklisted", async () => {
const handler = getHandler({
relayEnabled: true,
});
let messageHandled = false;
handler["handleFileEvent"] = async (rid, room, puppet, evt) => {
messageHandled = true;
};
handler["handleTextEvent"] = async (rid, room, puppet, evt) => {
messageHandled = true;
};
const event = new MessageEvent<MessageEventContent>({
type: "m.room.message",
sender: "@baduser:example.org",
});
const roomId = "!foxdm:example.org";
await handler["handleMessageEvent"](roomId, event);
expect(messageHandled).to.be.false;
});
it("should apply relay formatting, if relay is enabled", async () => {
const handler = getHandler({
relayEnabled: true,
});
let relayFormattingApplied = false;
handler["applyRelayFormatting"] = async (rid, room, evt) => {
relayFormattingApplied = true;
};
const event = new MessageEvent<MessageEventContent>({
type: "m.room.message",
sender: "@gooduser:example.org",
});
const roomId = "!foxdm:example.org";
await handler["handleMessageEvent"](roomId, event);
expect(relayFormattingApplied).to.true;
});
it("should delay-leave the ghost of the puppet", async () => {
const handler = getHandler();
const event = new MessageEvent<MessageEventContent>({
type: "m.room.message",
sender: "@user:example.org",
});
const roomId = "!foxdm:example.org";
await handler["handleMessageEvent"](roomId, event);
await DELAYED_FUNCTION_SET();
expect(ROOMSYNC_MAYBE_LEAVE_GHOST).to.equal("@_puppet_1_puppetGhost:example.org;!foxdm:example.org");
});
it("should de-duplicate messages, if the remote flag is set", async () => {
const handler = getHandler();
let messageHandled = false;
handler["handleFileEvent"] = async (rid, room, puppet, evt) => {
messageHandled = true;
};
handler["handleTextEvent"] = async (rid, room, puppet, evt) => {
messageHandled = true;
};
const event = new MessageEvent<MessageEventContent>({
type: "m.room.message",
sender: "@user:example.org",
content: { source: "remote" },
});
const roomId = "!foxdm:example.org";
await handler["handleMessageEvent"](roomId, event);
expect(messageHandled).to.be.false;
});
it("should pass the message on to file handler, if it is a file msgtype", async () => {
for (const msgtype of ["m.file", "m.image", "m.audio", "m.sticker", "m.video"]) {
const handler = getHandler();
let fileMessageHandled = false;
handler["handleFileEvent"] = async (rid, room, puppet, evt) => {
fileMessageHandled = true;
};
const event = new MessageEvent<MessageEventContent>({
type: "m.room.message",
sender: "@user:example.org",
content: {
msgtype,
body: "",
},
});
const roomId = "!foxdm:example.org";
await handler["handleMessageEvent"](roomId, event);
expect(fileMessageHandled).to.be.true;
}
});
it("should pass the message on to the text handler, if it is a text msgtype", async () => {
for (const msgtype of ["m.text", "m.notice", "m.emote", "m.reaction"]) {
const handler = getHandler();
let textMessageHandled = false;
handler["handleTextEvent"] = async (rid, room, puppet, evt) => {
textMessageHandled = true;
};
const event = new MessageEvent<MessageEventContent>({
type: "m.room.message",
sender: "@user:example.org",
content: {
msgtype,
body: "",
},
});
const roomId = "!foxdm:example.org";
await handler["handleMessageEvent"](roomId, event);
expect(textMessageHandled).to.be.true;
}
});
it("should pass the message on to the bot provisioner, if it starts with the correct prefix", async () => {
const handler = getHandler();
let textMessageHandled = false;
handler["handleTextEvent"] = async (rid, room, puppet, evt) => {
textMessageHandled = true;
};
const event = new MessageEvent<MessageEventContent>({
type: "m.room.message",
sender: "@user:example.org",
content: {
msgtype: "m.text",
body: "!remote fox",
},
});
const roomId = "!foxdm:example.org";
await handler["handleMessageEvent"](roomId, event);
expect(textMessageHandled).to.be.false;
expect(BOT_PROVISIONER_ROOM_EVENT_PROCESSED).to.be.true;
});
});
describe("handleFileEvent", () => {
it("should fall back to text messages, if no features are enabled", async () => {
for (const msgtype of ["m.image", "m.audio", "m.video", "m.sticker", "m.file"]) {
const handler = getHandler();
const event = new MessageEvent<FileMessageEventContent>({
type: "m.room.message",
content: {
msgtype,
url: "https://example.org/fox.file",
},
});
const roomId = "!foxdm:example.org";
const room = {} as any;
const puppet = {} as any;
await handler["handleFileEvent"](roomId, room, puppet, event);
expect(BRIDGE_EVENTS_EMITTED).to.eql(["message"]);
}
});
it("should send files as their type, if the features are enabled", async () => {
for (const msgtype of ["m.image", "m.audio", "m.video", "m.sticker", "m.file"]) {
const handler = getHandler({
featureImage: true,
featureAudio: true,
featureVideo: true,
featureSticker: true,
featureFile: true,
});
const event = new MessageEvent<FileMessageEventContent>({
type: "m.room.message",
content: {
msgtype,
url: "https://example.org/fox.file",
},
});
const roomId = "!foxdm:example.org";
const room = {} as any;
const puppet = {} as any;
await handler["handleFileEvent"](roomId, room, puppet, event);
expect(BRIDGE_EVENTS_EMITTED).to.eql([msgtype.substring(2)]);
}
});
it("should fall everything back to file, if that is enabled", async () => {
for (const msgtype of ["m.image", "m.audio", "m.video", "m.sticker", "m.file"]) {
const handler = getHandler({
featureFile: true,
});
const event = new MessageEvent<FileMessageEventContent>({
type: "m.room.message",
content: {
msgtype,
url: "https://example.org/fox.file",
},
});
const roomId = "!foxdm:example.org";
const room = {} as any;
const puppet = {} as any;
await handler["handleFileEvent"](roomId, room, puppet, event);
expect(BRIDGE_EVENTS_EMITTED).to.eql(["file"]);
}
});
it("should fall stickers back to images, if they are enabled", async () => {
const handler = getHandler({
featureImage: true,
});
const event = new MessageEvent<FileMessageEventContent>({
type: "m.room.message",
content: {
msgtype: "m.sticker",
url: "https://example.org/fox.file",
},
});
const roomId = "!foxdm:example.org";
const room = {} as any;
const puppet = {} as any;
await handler["handleFileEvent"](roomId, room, puppet, event);
expect(BRIDGE_EVENTS_EMITTED).to.eql(["image"]);
});
});
describe("handleTextEvent", () => {
it("should detect and send edits, if the feature is enabled", async () => {
const handler = getHandler({
featureEdit: true,
});
const event = new MessageEvent<TextualMessageEventContent>({
content: {
"msgtype": "m.text",
"body": "* blah",
"m.relates_to": {
event_id: "$event:example.org",
rel_type: "m.replace",
},
"m.new_content": {
msgtype: "m.text",
body: "blah",
},
},
});
const roomId = "!foxdm:example.org";
const room = {} as any;
const puppet = {} as any;
await handler["handleTextEvent"](roomId, room, puppet, event);
expect(BRIDGE_EVENTS_EMITTED).to.eql(["edit"]);
});
it("should fall edits back to messages, if the remote id isn't found", async () => {
const handler = getHandler({
featureEdit: true,
});
const event = new MessageEvent<TextualMessageEventContent>({
content: {
"msgtype": "m.text",
"body": "* blah",
"m.relates_to": {
event_id: "$notfound:example.org",
rel_type: "m.replace",
},
"m.new_content": {
msgtype: "m.text",
body: "blah",
},
},
});
const roomId = "!foxdm:example.org";
const room = {} as any;
const puppet = {} as any;
await handler["handleTextEvent"](roomId, room, puppet, event);
expect(BRIDGE_EVENTS_EMITTED).to.eql(["message"]);
});
it("should fall edits back to messages, if the feature is disabled", async () => {
const handler = getHandler();
const event = new MessageEvent<TextualMessageEventContent>({
content: {
"msgtype": "m.text",
"body": "* blah",
"m.relates_to": {
event_id: "$event:example.org",
rel_type: "m.replace",
},
"m.new_content": {
msgtype: "m.text",
body: "blah",
},
},
});
const roomId = "!foxdm:example.org";
const room = {} as any;
const puppet = {} as any;
await handler["handleTextEvent"](roomId, room, puppet, event);
expect(BRIDGE_EVENTS_EMITTED).to.eql(["message"]);
});
it("should detect and send replies, if they are enabled", async () => {
const handler = getHandler({
featureReply: true,
});
const event = new MessageEvent<TextualMessageEventContent>({
content: {
"msgtype": "m.text",
"body": "blah",
"m.relates_to": {
"m.in_reply_to": {
event_id: "$event:example.org",
},
},
},
});
const roomId = "!foxdm:example.org";
const room = {} as any;
const puppet = {} as any;
await handler["handleTextEvent"](roomId, room, puppet, event);
expect(BRIDGE_EVENTS_EMITTED).to.eql(["reply"]);
});
it("should fall replies back to messages, if the remote isn't found", async () => {
const handler = getHandler({
featureReply: true,
});
const event = new MessageEvent<TextualMessageEventContent>({
content: {
"msgtype": "m.text",
"body": "blah",
"m.relates_to": {
"m.in_reply_to": {
event_id: "$notfound:example.org",
},
},
},
});
const roomId = "!foxdm:example.org";
const room = {} as any;
const puppet = {} as any;
await handler["handleTextEvent"](roomId, room, puppet, event);
expect(BRIDGE_EVENTS_EMITTED).to.eql(["message"]);
});
it("should fall replies back to messages, if the feature is disabled", async () => {
const handler = getHandler();
const event = new MessageEvent<TextualMessageEventContent>({
content: {
"msgtype": "m.text",
"body": "blah",
"m.relates_to": {
"m.in_reply_to": {
event_id: "$event:example.org",
},
},
},
});
const roomId = "!foxdm:example.org";
const room = {} as any;
const puppet = {} as any;
await handler["handleTextEvent"](roomId, room, puppet, event);
expect(BRIDGE_EVENTS_EMITTED).to.eql(["message"]);
});
it("should detect reactions", async () => {
const handler = getHandler();
const event = new MessageEvent<TextualMessageEventContent>({
content: {
"m.relates_to": {
event_id: "$event:example.org",
rel_type: "m.annotation",
key: "fox",
},
},
});
const roomId = "!foxdm:example.org";
const room = {} as any;
const puppet = {} as any;
await handler["handleTextEvent"](roomId, room, puppet, event);
expect(REACTION_HANDLER_ADDED_MATRIX).to.be.true;
expect(BRIDGE_EVENTS_EMITTED).to.eql(["reaction"]);
});
it("should send normal messages", async () => {
const handler = getHandler();
const event = new MessageEvent<TextualMessageEventContent>({
content: {
msgtype: "m.text",
body: "FOXIES!!!",
},
});
const roomId = "!foxdm:example.org";
const room = {} as any;
const puppet = {} as any;
await handler["handleTextEvent"](roomId, room, puppet, event);
expect(BRIDGE_EVENTS_EMITTED).to.eql(["message"]);
});
});
describe("handleInviteEvent", () => {
it("should short-circuit bot user invites", async () => {
const handler = getHandler();
const event = new MembershipEvent({
state_key: "@_puppetbot:example.org",
sender: "@user:example.org",
});
const roomId = "!blah:example.org";
await handler["handleInviteEvent"](roomId, event);
expect(BOT_INTENT_JOIN_ROOM).to.equal(roomId);
});
it("should ignore invites if no ghost got invited", async () => {
const handler = getHandler();
const event = new MembershipEvent({
state_key: "@blubb:example.org",
sender: "@user:example.org",
});
const roomId = "!blah:example.org";
await handler["handleInviteEvent"](roomId, event);
expect(GHOST_INTENT_LEAVE_ROOM).to.equal("");
expect(GHOST_INTENT_JOIN_ROOM).to.equal("");
});
it("should ignore invites, if a ghost invited", async () => {
const handler = getHandler();
const event = new MembershipEvent({
state_key: "@_puppet_1_newfox:example.org",
sender: "@_puppet_1_newfox:example.org",
});
const roomId = "!blah:example.org";
await handler["handleInviteEvent"](roomId, event);
expect(GHOST_INTENT_LEAVE_ROOM).to.equal("");
expect(GHOST_INTENT_JOIN_ROOM).to.equal("");
});
it("should ignore invites, if the corresponding room already exists", async () => {
const handler = getHandler();
const event = new MembershipEvent({
state_key: "@_puppet_1_newfox:example.org",
sender: "@user:example.org",
});
const roomId = "!foxdm:example.org";
await handler["handleInviteEvent"](roomId, event);
expect(GHOST_INTENT_LEAVE_ROOM).to.equal("");
expect(GHOST_INTENT_JOIN_ROOM).to.equal("");
});
it("should reject invites, if the protocol didn't set up the necessary hooks", async () => {
const handler = getHandler();
const event = new MembershipEvent({
state_key: "@_puppet_1_newfox:example.org",
sender: "@user:example.org",
});
const roomId = "!blah:example.org";
await handler["handleInviteEvent"](roomId, event);
expect(GHOST_INTENT_LEAVE_ROOM).to.equal(roomId);
expect(GHOST_INTENT_JOIN_ROOM).to.equal("");
});
it("should reject invites, if the invited mxid is un-parsable", async () => {
const handler = getHandler({
createDmHook: true,
});
const event = new MembershipEvent({
state_key: "@_puppet_invalid:example.org",
sender: "@user:example.org",
});
const roomId = "!blah:example.org";
await handler["handleInviteEvent"](roomId, event);
expect(GHOST_INTENT_LEAVE_ROOM).to.equal(roomId);
expect(GHOST_INTENT_JOIN_ROOM).to.equal("");
});
it("should reject invites, if we try to invite someone elses puppet", async () => {
const handler = getHandler({
createDmHook: true,
});
const event = new MembershipEvent({
state_key: "@_puppet_999_otherfox:example.org",
sender: "@user:example.org",
});
const roomId = "!blah:example.org";
await handler["handleInviteEvent"](roomId, event);
expect(GHOST_INTENT_LEAVE_ROOM).to.equal(roomId);
expect(GHOST_INTENT_JOIN_ROOM).to.equal("");
});
it("should reject invites, if no DM room ID is found", async () => {
const handler = getHandler({
createDmHook: true,
getDmRoomIdHook: async (parts) => null,
});
const event = new MembershipEvent({
state_key: "@_puppet_1_newfox:example.org",
sender: "@user:example.org",
});
const roomId = "!blah:example.org";
await handler["handleInviteEvent"](roomId, event);
expect(GHOST_INTENT_LEAVE_ROOM).to.equal(roomId);
expect(GHOST_INTENT_JOIN_ROOM).to.equal("");
});
it("should reject invites, if the room already exists", async () => {
const handler = getHandler({
createDmHook: true,
getDmRoomIdHook: async (parts) => "fox",
});
const event = new MembershipEvent({
state_key: "@_puppet_1_fox:example.org",
sender: "@user:example.org",
});
const roomId = "!blah:example.org";
await handler["handleInviteEvent"](roomId, event);
expect(GHOST_INTENT_LEAVE_ROOM).to.equal(roomId);
expect(GHOST_INTENT_JOIN_ROOM).to.equal("");
});
it("should reject invites, if the create room data doesn't match up", async () => {
const handler = getHandler({
createDmHook: true,
getDmRoomIdHook: async (parts) => "newfox",
createRoomHook: async (parts) => {
return {
puppetId: 42,
roomId: "bruhuu",
};
},
});
const event = new MembershipEvent({
state_key: "@_puppet_1_newfox:example.org",
sender: "@user:example.org",
});
const roomId = "!blah:example.org";
await handler["handleInviteEvent"](roomId, event);
expect(GHOST_INTENT_LEAVE_ROOM).to.equal(roomId);
expect(GHOST_INTENT_JOIN_ROOM).to.equal("");
});
it("should create and insert the new DM into the db, if all is ok", async () => {
const handler = getHandler({
createDmHook: true,
getDmRoomIdHook: async (parts) => "newfox",
createRoomHook: async (parts) => {
return {
puppetId: 1,
roomId: "newfox",
isDirect: true,
};
},
});
const event = new MembershipEvent({
state_key: "@_puppet_1_newfox:example.org",
sender: "@user:example.org",
});
const roomId = "!blah:example.org";
await handler["handleInviteEvent"](roomId, event);
expect(GHOST_INTENT_LEAVE_ROOM).to.equal("");
expect(GHOST_INTENT_JOIN_ROOM).to.equal(roomId);
expect(ROOM_SYNC_INSERTED_ENTRY).to.be.true;
expect(ROOMSYNC_MARK_AS_DIRECT).to.equal("1;newfox");
});
});
describe("handleRoomQuery", () => {
it("should immidiately reject the creation of a new room", async () => {
const handler = getHandler();
const alias = "#_puppet_1_foxroom:example.org";
let rejected = false;
await handler["handleRoomQuery"](alias, async (type) => {
rejected = !type;
});
expect(rejected).to.be.true;
});
it("should ignore if the room is invalid", async () => {
const handler = getHandler();
const alias = "#_puppet_invalid:example.org";
await handler["handleRoomQuery"](alias, async (type) => {});
expect(BRIDGE_ROOM_ID_BRIDGED).to.equal("");
});
it("should bridge a room, if it is valid", async () => {
const handler = getHandler();
const alias = "#_puppet_1_foxroom:example.org";
await handler["handleRoomQuery"](alias, async (type) => {});
expect(BRIDGE_ROOM_ID_BRIDGED).to.equal("foxroom");
});
});
describe("handlePresence", () => {
it("should do nothing on own presence", async () => {
const handler = getHandler();
const event = {
type: "m.presence",
sender: "@_puppet_1_fox:example.org",
content: {
presence: "online",
},
};
await handler["handlePresence"](event);
expect(BRIDGE_EVENTS_EMITTED).to.eql([]);
});
it("should emit user presence", async () => {
const handler = getHandler();
const event = {
type: "m.presence",
sender: "@user:example.org",
content: {
presence: "online",
},
};
await handler["handlePresence"](event);
expect(BRIDGE_EVENTS_EMITTED).to.eql(["presence"]);
});
});
describe("handleTyping", () => {
it("should do typing", async () => {
const handle = getHandler();
let event: any = {
type: "m.typing",
content: {
user_ids: ["@user:example.org"],
},
room_id: "!room:example.org",
};
await handle["handleTyping"]("!room:example.org", event);
expect(BRIDGE_EVENTS_EMITTED).to.eql(["typing"]);
expect(await handle["bridge"].typingHandler.deduplicator.dedupe("1;room", "puppetGhost", undefined, "true"))
.to.be.true;
await handle["handleTyping"]("!room:example.org", event);
expect(BRIDGE_EVENTS_EMITTED).to.eql(["typing"]);
event = {
type: "m.typing",
content: {
user_ids: [],
},
room_id: "!room:example.org",
};
await handle["handleTyping"]("!room:example.org", event);
expect(BRIDGE_EVENTS_EMITTED).to.eql(["typing", "typing"]);
expect(await handle["bridge"].typingHandler.deduplicator.dedupe("1;room", "puppetGhost", undefined, "false"))
.to.be.true;
});
});
describe("handleReceipt", () => {
it("should do read receipts", async () => {
const handle = getHandler();
const event = {
type: "m.receipt",
room_id: "!room:example.org",
content: {
"$event:example.org": {
"m.read": {
"@user:example.org": {
ts: 1234,
},
},
},
},
};
await handle["handleReceipt"]("!room:example.org", event);
expect(BRIDGE_EVENTS_EMITTED).to.eql(["read"]);
});
});
describe("getRoomDisplaynameCache", () => {
it("should return a blank object on new rooms", () => {
const handler = getHandler();
const ret = handler["getRoomDisplaynameCache"]("room");
expect(ret).eql({});
});
it("should return an existing entry, should it exist", () => {
const handler = getHandler();
handler["updateCachedRoomMemberInfo"]("room", "user", {
displayname: "blah",
avatar_url: "blubb",
membership: "join",
});
const ret = handler["getRoomDisplaynameCache"]("room");
expect(ret).eql({user: {
displayname: "blah",
avatar_url: "blubb",
membership: "join",
}});
});
});
describe("updateCachedRoomMemberInfo", () => {
it("should update an entry", () => {
const handler = getHandler();
handler["updateCachedRoomMemberInfo"]("room", "user", {
displayname: "blah",
avatar_url: "blubb",
membership: "join",
});
const ret = handler["getRoomDisplaynameCache"]("room");
expect(ret).eql({user: {
displayname: "blah",
avatar_url: "blubb",
membership: "join",
}});
});
});
describe("getRoomMemberInfo", () => {
it("should fetch members from the cache, if present", async () => {
const handler = getHandler();
handler["updateCachedRoomMemberInfo"]("room", "user", {
displayname: "blah",
avatar_url: "blubb",
membership: "join",
});
const ret = await handler["getRoomMemberInfo"]("room", "user");
expect(ret).eql({
displayname: "blah",
avatar_url: "blubb",
membership: "join",
});
});
it("should try to fetch from the state, if not present in cache", async () => {
const handler = getHandler();
const ret = await handler["getRoomMemberInfo"]("room", "user");
expect(ret).eql({
membership: "join",
displayname: "User",
avatar_url: "blah",
});
});
});
describe("applyRelayFormatting", () => {
it("should apply simple formatting", async () => {
const handler = getHandler();
const roomId = "room";
const userId = "user";
const content = {
msgtype: "m.text",
body: "hello world",
};
await handler["applyRelayFormatting"](roomId, userId, content);
expect(content).eql({
msgtype: "m.text",
body: "User: hello world",
formatted_body: "<strong>User</strong>: hello world",
format: "org.matrix.custom.html",
});
});
it("should apply emote formatting", async () => {
const handler = getHandler();
const roomId = "room";
const userId = "user";
const content = {
msgtype: "m.emote",
body: "hello world",
};
await handler["applyRelayFormatting"](roomId, userId, content);
expect(content).eql({
msgtype: "m.text",
body: "*User hello world",
formatted_body: "*<strong>User</strong> hello world",
format: "org.matrix.custom.html",
});
});
it("should create a fallback for files", async () => {
const handler = getHandler();
const roomId = "room";
const userId = "user";
const content = {
msgtype: "m.file",
body: "hello world",
url: "mxc://somefile",
};
await handler["applyRelayFormatting"](roomId, userId, content);
expect(content).eql({
msgtype: "m.text",
body: "User sent a file hello world: https://mxc://somefile",
format: "org.matrix.custom.html",
formatted_body: "<strong>User</strong> sent a file <em>hello world</em>: <a href=\"https://mxc://somefile\">" +
"https://mxc://somefile</a>",
});
});
it("should proceed into edits appropriately", async () => {
const handler = getHandler();
const roomId = "room";
const userId = "user";
const content = {
"msgtype": "m.text",
"body": "hello world",
"m.new_content": {
msgtype: "m.text",
body: "hello world",
},
};
await handler["applyRelayFormatting"](roomId, userId, content);
expect(content).eql({
"msgtype": "m.text",
"body": "User: hello world",
"format": "org.matrix.custom.html",
"formatted_body": "<strong>User</strong>: hello world",
"m.new_content": {
msgtype: "m.text",
body: "User: hello world",
formatted_body: "<strong>User</strong>: hello world",
format: "org.matrix.custom.html",
},
});
});
});
}); | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.