text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import {Component, Inject, OnDestroy, OnInit, ViewChild} from "@angular/core";
import {ImportComponentOption, ImportComponentType, ImportProperty, ImportService} from "../../../services/ImportComponentOptionTypes";
import {FileUpload} from "../../../../services/FileUploadService";
import {RestUrlConstants} from "../../../services/RestUrlConstants";
import {HttpClient} from "@angular/common/http";
import {KyloIcons} from "../../../../kylo-utils/kylo-icons";
import {FormControl, FormGroup, Validators} from "@angular/forms";
import * as _ from "underscore"
import {MatSnackBar} from "@angular/material/snack-bar";
import {FeedNifiErrorUtil} from "../../../services/feed-nifi-error-util";
import {CategoryAutocompleteComponent} from "../shared/category-autocomplete.component";
import {DatasetPreviewStepperSavedEvent} from "../../../catalog-dataset-preview/preview-stepper/dataset-preview-stepper.component";
import {DatasetPreviewStepperDialogComponent, DatasetPreviewStepperDialogData} from "../../../catalog-dataset-preview/preview-stepper/dataset-preview-stepper-dialog.component";
import {MatDialogConfig} from "@angular/material/dialog";
import {TdDialogService} from "@covalent/core/dialogs";
import {CatalogService} from "../../../catalog/api/services/catalog.service";
import {SparkDataSet} from "../../../model/spark-data-set.model";
import {Category} from "../../../model/category/category.model";
import {DatasourcesService} from "../../../services/DatasourcesService";
import {KyloRouterService} from "../../../../services/kylo-router.service";
import {StringUtils} from "../../../../common/utils/StringUtils";
import {DataSource} from "../../../catalog/api/models/datasource";
@Component({
selector: "import-feed",
templateUrl: "./import-feed.component.html"
})
export class ImportFeedComponent implements OnInit, OnDestroy{
/**
* The file to upload
* @type {null}
*/
feedFile: File = null;
/**
* the name of the file to upload
* @type {string}
*/
fileName: string = null;
/**
* flag if uploading
* @type {boolean}
*/
uploadInProgress: boolean = false;
/**
* Flag to indicate the upload produced validation errors
* @type {boolean}
*/
validationErrors: boolean = false;
/**
* unique key to track upload status
* @type {string}
*/
uploadKey: string = null;
/**
* Status of the current upload
* @type {Array}
*/
uploadStatusMessages: string[] = [];
/**
* handle on the $interval object to cancel later
* @type {null}
*/
uploadStatusCheck: number = undefined;
/**
* Percent upload complete
* @type {number}
*/
uploadProgress: number = 0;
errorMessage:string;
/**
* Flag to indicate additional properties exist and a header show be shown for template options
*/
additionalInputNeeded: boolean = false;
/**
* flag to force the feed to be DISABLED upon importing
* @type {boolean}
*/
disableFeedUponImport: boolean = false;
/**
* All the importOptions that will be uploaded
* @type {{}}
*/
importComponentOptions:{[key:string] :ImportComponentOption} = {};
/**
* Feed ImportOptions
*/
feedDataImportOption: ImportComponentOption;
/**
* Registered Template import options
*/
templateDataImportOption: ImportComponentOption;
/**
* NiFi template options
*/
nifiTemplateImportOption: ImportComponentOption;
/**
* Reusable template options
*/
reusableTemplateImportOption: ImportComponentOption;
/**
* User data sources options
*/
userDatasourcesOption: ImportComponentOption;
/**
* Feed ImportOptions
*/
userDataSetsOption: ImportComponentOption;
/**
* Any required feed fields
*/
feedUserFieldsImportOption: ImportComponentOption;
/**
* Any Required Category fields
*/
categoryUserFieldsImportOption: ImportComponentOption;
/**
* List of available data sources.
* @type {Array.<JdbcDatasource>}
*/
availableDatasources: any = [];
catalogDataSources:DataSource[];
/**
* The parent form group for validation checks prior to import
*/
formGroup:FormGroup;
importResult: any;
/**
* The icon for the result
*/
importResultIcon: string = "check_circle";
/**
* the color of the icon
*/
importResultIconColor: string = "#009933";
/**
* Any additional errors
*/
errorMap: any = null;
/**
* the number of errors after an import
*/
errorCount: number = 0;
/**
* Message after upload
*/
message: string;
public kyloIcons_Feed_importFeed = KyloIcons.Feed.importFeed;
@ViewChild("categoryAutoComplete")
categoryAutoComplete:CategoryAutocompleteComponent
category:Category;
/**
* The number of required properties needed to complete the upload
*/
requiredPropertyCount:number = 0;
feedOverwriteFormControl:FormControl;
disableUponImportFormControl:FormControl;
templateOverwriteFormControl:FormControl;
reusableTemplateOverwriteFormControl:FormControl;
constructor(private http:HttpClient,private snackBar:MatSnackBar,private _dialogService:TdDialogService, private catalogService:CatalogService,
@Inject("ImportService") private importService:ImportService,
@Inject("FileUpload")private fileUploadService:FileUpload,
@Inject("DatasourcesService") private datasourcesService: DatasourcesService,
private kyloRouterService:KyloRouterService) {
this.formGroup = new FormGroup({});
this.feedOverwriteFormControl = new FormControl(false);
this.disableUponImportFormControl = new FormControl(false);
this.templateOverwriteFormControl = new FormControl(false);
this.reusableTemplateOverwriteFormControl = new FormControl(false);
this.formGroup.addControl("feedOverwrite",this.feedOverwriteFormControl)
this.formGroup.addControl("disableUponImport",this.disableUponImportFormControl)
this.formGroup.addControl("templateOverwrite",this.templateOverwriteFormControl)
this.formGroup.addControl("reusableTemplateOverwrite",this.reusableTemplateOverwriteFormControl);
this.initImportOptions();
// Get the list of data sources
this.datasourcesService.findAll()
.then((datasources: any) => {
this.availableDatasources = datasources;
});
this.fetchCatalogDataSources();
}
public findDatasetPropertiesFilter(importOption:ImportComponentOption): ImportProperty[]{
if(importOption.properties == undefined){
return [];
}
return importOption.properties.filter((property:ImportProperty) => property.additionalProperties && (
Object.keys(property.additionalProperties).indexOf("legacyTableDataSource") >=0 &&
(property.additionalProperties["legacyTableDataSource"] == "true" ||property.additionalProperties["legacyTableDataSource"] == true)) ||
(Object.keys(property.additionalProperties).indexOf("dataset") &&
(property.additionalProperties["dataset"] == "true" ||property.additionalProperties["dataset"] == true)));
}
public findDataSourcePropertiesFilter(importOption:ImportComponentOption): ImportProperty[]{
if(importOption.properties == undefined){
return [];
}
return importOption.properties.filter((property:ImportProperty) => property.additionalProperties &&
(Object.keys(property.additionalProperties).indexOf("legacyQueryDataSource") >=0 &&
(property.additionalProperties["legacyQueryDataSource"] == "true" ||property.additionalProperties["legacyQueryDataSource"] == true)) ||
(Object.keys(property.additionalProperties).indexOf("catalogDataSource") &&
(property.additionalProperties["catalogDataSource"] == "true" ||property.additionalProperties["dataset"] == true)));
}
/**
* is the supplied option one for defining a Catalog DataSet?
* @param {ImportComponentOption} importOption
* @return {boolean}
*/
private isDataSetOption(importOption:ImportComponentOption):boolean {
return importOption.importComponent == ImportComponentType.USER_DATA_SETS || (importOption.importComponent == ImportComponentType.USER_DATASOURCES && this.findDatasetPropertiesFilter(importOption).length >0);
}
private fetchCatalogDataSources(): void {
this.catalogService.getDataSourcesForPluginIds(["hive","jdbc"]).subscribe(datasources => {
this.catalogDataSources = []
if(datasources && datasources.length >0){
this.catalogDataSources = _(datasources).chain().sortBy( (ds:DataSource) =>{
return ds.title;
}).sortBy((ds:DataSource) =>{
return ds.connector.pluginId;
}).value()
}
else {
this.catalogDataSources = [];
}
});
}
private initImportOptions(){
/**
* Feed ImportOptions
*/
this.feedDataImportOption = this.importService.newFeedDataImportOption();
/**
* Registered Template import options
*/
this.templateDataImportOption = this.importService.newTemplateDataImportOption();
/**
* NiFi template options
*/
this.nifiTemplateImportOption = this.importService.newNiFiTemplateImportOption();
/**
* Reusable template options
*/
this.reusableTemplateImportOption = this.importService.newReusableTemplateImportOption();
/**
* User data sources options
*/
this.userDatasourcesOption = this.importService.newUserDatasourcesImportOption();
this.userDataSetsOption = this.importService.newUserDataSetsImportOption();
this.feedUserFieldsImportOption = this.importService.newFeedUserFieldsImportOption();
this.categoryUserFieldsImportOption = this.importService.newFeedCategoryUserFieldsImportOption();
}
ngOnInit(): void {
this.indexImportOptions();
this.setDefaultImportOptions();
/**
// Get the list of data sources
this.DatasourcesService.findAll()
.then((datasources: any) => {
this.availableDatasources = datasources;
});
**/
}
ngOnDestroy() {
}
goBack(){
this.kyloRouterService.back("feeds");
}
/**
* callback after a user selects a file from the local file system
*/
onFilesChange(file:File|FileList) {
let fileChanged = false;
if(file) {
this.feedFile = (file as File);
if(this.fileName == null || this.fileName != (file as File).name) {
fileChanged = true;
}
this.fileName = (file as File).name;
}else {
this.fileName = null;
}
if(fileChanged){
//resetOptions
this.resetImportOptions();
this.errorMap = {};
this.uploadStatusMessages = []
this.message = '';
}
}
/**
* when the user changes the category
* @param {Category} $event
*/
onCategorySelected($event:Category){
this.category = $event;
}
/**
* Returns the Error keys as an array
* @return {any}
*/
getErrorMapKeys(){
if(this.errorMap) {
return Object.keys(this.errorMap);
}
else {
return [];
}
}
/**
* Upload the file and import the feed
*/
importFeed(): void {
if(this.feedFile == undefined){
//ALERT you must select a file
return;
}
//reset flags
this.uploadInProgress = true;
this.importResult = null;
//get the values from the formControls and populated the input options
this.feedDataImportOption.overwrite = this.feedOverwriteFormControl.value;
this.disableFeedUponImport = this.disableUponImportFormControl.value;
this.templateDataImportOption.overwrite = this.templateOverwriteFormControl.value;
this.reusableTemplateImportOption.overwrite = this.reusableTemplateOverwriteFormControl.value;
Object.keys(this.importComponentOptions).forEach(key => {
let option = this.importComponentOptions[key];
//skip over datasets since those are added/updated with the dialog
if(option && option.importComponent != ImportComponentType.USER_DATA_SETS && option.properties){
let nestedForm = this.formGroup.get(this.nestedFormGroupControlName(option));
if(nestedForm) {
option.properties.forEach(prop => {
//if not dataset option then set the value. Datasets are set via the dialog callback
if(!this.isDataSetOption(option) ) {
let control = nestedForm.get(prop.propertyKey);
if(control){
prop.propertyValue = control.value;
}
}
});
}
}
});
var uploadUrl = RestUrlConstants.ADMIN_IMPORT_FEED_URL;
var successFn = (response: any) => {
var responseData = response.data;
//reassign the options back from the response data
var importComponentOptions = responseData.importOptions.importComponentOptions;
//map the options back to the object map
this.updateImportOptions(importComponentOptions);
//find the number of options that have properties that require user input
if (!responseData.valid) {
//Validation Error. Additional Input is needed by the end user
this.additionalInputNeeded = true;
}
else {
var count = 0;
var errorMap: any = {"FATAL": [], "WARN": []};
this.importResult = responseData;
if (responseData.template.controllerServiceErrors) {
//angular.forEach(responseData.templateResults.errors, function (processor) {
_.each(responseData.template.controllerServiceErrors, (processor: any) => {
if (processor.validationErrors) {
_.each(processor.validationErrors, (error: any) => {
let copy: any = {};
_.extend(copy, error);
_.extend(copy, processor);
copy.validationErrors = null;
this.errorMap[error.severity].push(copy);
count++;
});
}
});
}
if (responseData.nifiFeed == null || responseData.nifiFeed == undefined) {
this.errorMap["FATAL"].push({message: "Unable to import feed"});
}
if (responseData.nifiFeed && responseData.nifiFeed) {
count += FeedNifiErrorUtil.parseNifiFeedForErrors(responseData.nifiFeed, errorMap);
}
this.errorMap = errorMap;
this.errorCount = count;
var feedName = responseData.feedName != null ? responseData.feedName : "";
if (count == 0) {
this.importResultIcon = "check_circle";
this.importResultIconColor = "#009933";
//this.message = this.$filter('translate')('views.ImportFeedController.succes') + feedName + ".";
this.message = "Success "+feedName;
this.resetImportOptions();
this.feedFile = null;
this.fileName = null;
}
else {
if (responseData.success) {
this.resetImportOptions();
this.feedFile = null;
this.fileName = null;
this.message = "Successfully imported and registered the feed " + feedName + " but some errors were found. Please review these errors";
this.importResultIcon = "warning";
this.importResultIconColor = "#FF9901";
}
else {
this.importResultIcon = "error";
this.importResultIconColor = "#FF0000";
// this.message = this.$filter('translate')('views.ImportFeedController.error2');
this.message = "error2"
}
}
}
this.uploadInProgress = false;
this.stopUploadStatus(1000);
}
var errorFn = (response: any) => {
var data = response.data
//reset the flags
this.importResult = {};
this.uploadInProgress = false;
//set error indicators and messages
this.importResultIcon = "error";
this.importResultIconColor = "#FF0000";
// var msg = this.$filter('translate')('views.ImportFeedController.error');
let msg = "Error!! ";
if (data.developerMessage) {
msg += data.developerMessage;
}
this.message = msg;
this.stopUploadStatus(1000);
}
//build up the options from the Map and into the array for uploading
var importComponentOptions = this.importService.getImportOptionsForUpload(this.importComponentOptions);
//generate a new upload key for status tracking
this.uploadKey = this.importService.newUploadKey();
let category = this.categoryAutoComplete.getCategoryValue();
var params = {
uploadKey: this.uploadKey,
categorySystemName: category != undefined ? category.systemName : "",
disableFeedUponImport: this.disableUponImportFormControl.value,
importComponents: StringUtils.stringify(importComponentOptions)
};
this.startUploadStatus();
this.fileUploadService.uploadFileToUrl(this.feedFile, uploadUrl, successFn, errorFn, params);
}
/**
* Reset the options back to their orig. state
*/
private resetImportOptions(): void {
this.importComponentOptions = {};
this.feedDataImportOption = this.importService.newFeedDataImportOption();
this.templateDataImportOption = this.importService.newTemplateDataImportOption();
this.nifiTemplateImportOption = this.importService.newNiFiTemplateImportOption();
this.reusableTemplateImportOption = this.importService.newReusableTemplateImportOption();
this.userDatasourcesOption = this.importService.newUserDatasourcesImportOption();
this.userDataSetsOption = this.importService.newUserDataSetsImportOption();
this.feedUserFieldsImportOption = this.importService.newFeedUserFieldsImportOption();
this.categoryUserFieldsImportOption = this.importService.newFeedCategoryUserFieldsImportOption();
this.indexImportOptions();
this.setDefaultImportOptions();
this.additionalInputNeeded = false;
this.disableFeedUponImport = false;
this.disableUponImportFormControl.setValue(false);
var arr = [this.feedDataImportOption, this.templateDataImportOption, this.nifiTemplateImportOption, this.reusableTemplateImportOption, this.categoryUserFieldsImportOption, this.userDatasourcesOption, this.feedUserFieldsImportOption, this.userDataSetsOption];
this.updateImportOptions(arr)
}
/**
* get the name of the nested form group for the supplied import option
* @param {ImportComponentOption} option
* @return {string}
*/
private nestedFormGroupControlName(option: ImportComponentOption){
return "form_"+option.importComponent;
}
/**
* get the actual form group for the import option
* @param {ImportComponentOption} option
* @return {AbstractControl | null}
*/
public getNestedFormGroup(option: ImportComponentOption) {
return this.formGroup.get(this.nestedFormGroupControlName(option));
}
/**
*
* @param importOptionsArr array of importOptions
*/
private updateImportOptions(importOptionsArr: ImportComponentOption[]): void {
_.each(importOptionsArr, (option: any) => {
if (option.userAcknowledged) {
option.overwriteSelectValue = "" + option.overwrite;
}
if (option.importComponent == ImportComponentType.FEED_DATA) {
this.feedDataImportOption = option;
this.feedOverwriteFormControl.setValue(this.feedDataImportOption.overwrite)
} else if (option.importComponent == ImportComponentType.TEMPLATE_DATA) {
this.templateDataImportOption = option;
this.templateOverwriteFormControl.setValue(this.templateDataImportOption.overwrite);
} else if (option.importComponent == ImportComponentType.REUSABLE_TEMPLATE) {
this.reusableTemplateImportOption = option;
this.reusableTemplateOverwriteFormControl.setValue(this.reusableTemplateImportOption.overwrite)
} else if (option.importComponent == ImportComponentType.NIFI_TEMPLATE) {
this.nifiTemplateImportOption = option;
} else if (option.importComponent === ImportComponentType.USER_DATASOURCES) {
this.userDatasourcesOption = option;
} else if (option.importComponent === ImportComponentType.USER_DATA_SETS) {
this.userDataSetsOption = option;
} else if (option.importComponent === ImportComponentType.FEED_CATEGORY_USER_FIELDS) {
this.categoryUserFieldsImportOption = option;
} else if (option.importComponent === ImportComponentType.FEED_USER_FIELDS) {
this.feedUserFieldsImportOption = option;
}
this.importComponentOptions[option.importComponent] = option;
let formName = this.nestedFormGroupControlName(option);
//add in a nested form group with required validation on the input
if(this.formGroup.contains(formName)){
this.formGroup.removeControl(formName);
}
if(option.importComponent === ImportComponentType.USER_DATA_SETS || option.importComponent === ImportComponentType.USER_DATASOURCES){
//user datasets are different than the rest
let nestedForm: FormGroup = new FormGroup({})
this.formGroup.addControl(formName, nestedForm);
if (option.properties && option.properties.length > 0) {
option.properties.forEach((prop:ImportProperty) => {
//control to ensure validity of the dataset
//add in the hidden property for the datasets
nestedForm.addControl(prop.propertyKey, new FormControl("", [Validators.required]));
});
}
}
else {
//reset and add any formControls if needed
if (option.properties && option.properties.length > 0) {
let nestedForm: FormGroup = new FormGroup({})
this.formGroup.addControl(formName, nestedForm);
option.properties.forEach((prop:ImportProperty) => {
nestedForm.addControl(prop.propertyKey, new FormControl(prop.propertyValue, [Validators.required]));
});
}
}
});
}
/**
* Stop the upload status check,
* @param delay wait xx millis before stopping (allows for the last status to be queried)
*/
private stopUploadStatus(delay: any): void {
let stopStatusCheck = () => {
this.uploadProgress = 0;
if (!_.isUndefined(this.uploadStatusCheck)) {
clearInterval(this.uploadStatusCheck);
this.uploadStatusCheck = undefined;
}
}
if (delay != undefined) {
setTimeout(() => {
stopStatusCheck();
}, delay)
}
else {
stopStatusCheck();
}
}
/**
* starts the upload status check
*/
private startUploadStatus(): void {
this.stopUploadStatus(undefined);
this.uploadStatusMessages = [];
this.uploadStatusCheck = setInterval(() => {
//poll for status
this.http.get(RestUrlConstants.ADMIN_UPLOAD_STATUS_CHECK(this.uploadKey)).subscribe((response: any) => {
if (response != null) {
this.uploadStatusMessages = response.messages;
this.uploadProgress = response.percentComplete;
}
}, (err: any) => {
// this.uploadStatusMessages = [];
});
}, 500);
}
/**
* Set the default values for the import options
*/
private setDefaultImportOptions(): void {
this.nifiTemplateImportOption.continueIfExists = true;
// this.reusableTemplateImportOption.userAcknowledged = false;
//it is assumed with a feed you will be importing the template with the feed
this.templateDataImportOption.userAcknowledged = true;
this.feedDataImportOption.continueIfExists = false;
}
private indexImportOptions(): void {
var arr = [this.feedDataImportOption, this.templateDataImportOption, this.nifiTemplateImportOption, this.reusableTemplateImportOption, this.categoryUserFieldsImportOption, this.feedUserFieldsImportOption, this.userDataSetsOption];
this.importComponentOptions = _.indexBy(arr, 'importComponent')
}
public updateDataSet(importProperty:ImportProperty, option:ImportComponentOption){
let data = new DatasetPreviewStepperDialogData(false,"Update");
let dialogConfig:MatDialogConfig = DatasetPreviewStepperDialogComponent.DIALOG_CONFIG()
dialogConfig.data = data;
this._dialogService.open(DatasetPreviewStepperDialogComponent,dialogConfig)
.afterClosed()
.filter(value => typeof value !== "undefined").subscribe( (response:DatasetPreviewStepperSavedEvent) => {
//add these to the canvas
let preview = response.previews[0];
let dataSet =preview.toSparkDataSet();
this.catalogService.createDataSetWithTitle(dataSet).subscribe((ds:SparkDataSet) => {
//find or create dataset then
let valid = true;
let schemaNeeded = "";
//validate schema
if(importProperty.additionalProperties) {
if(importProperty.additionalProperties["schema"]){
const importSchema = importProperty.additionalProperties["schema"];
let previewSchema = preview.schema.map(col => col.name+" "+col.dataType).join(",");
if(importSchema != previewSchema){
valid = false
schemaNeeded = importSchema;
}
}
}
const onSuccess = () => {
importProperty.valid = true;
importProperty.displayName = ds.paths[0];
importProperty.componentName = ds.dataSource.title;
importProperty.propertyValue = ds.id;
//update form validity
let property = this.formGroup.get(this.nestedFormGroupControlName(option)).get(importProperty.propertyKey);
if (property) {
property.setValue("true");
}
};
if (valid) {
onSuccess();
} else {
this._dialogService.openConfirm({
title: "Schemas don't match",
message: "The selected dataset schema doesnt match. Please supply a schema matching: \n" + schemaNeeded,
acceptButton: "Ignore",
cancelButton: "Cancel"
}).afterClosed().subscribe(value => {
if (value) {
onSuccess();
}
});
}
})
});
}
} | the_stack |
import fs from 'fs';
import path from 'path';
import {homedir} from 'os';
import {ChildProcess, fork} from 'child_process';
import windowStateKeeper from 'electron-window-state';
import JSZip from 'jszip';
import {
App,
BrowserWindow,
Dialog,
IpcMain,
IpcMainEvent,
Menu,
MenuItem,
MenuItemConstructorOptions,
WebContents,
} from 'electron';
import openAboutWindow, {AboutWindowInfo} from 'about-window';
import getPort from 'get-port';
import open from 'open';
import {CancellationToken, autoUpdater} from '@process-engine/electron-updater';
import ReleaseChannel from '../src/services/release-channel-service/release-channel.service';
import {solutionIsRemoteSolution} from '../src/services/solution-is-remote-solution-module/solution-is-remote-solution.module';
import {version as currentStudioVersion} from '../package.json';
import {getPortListByVersion} from '../src/services/default-ports-module/default-ports.module';
import {FeedbackData} from '../src/contracts';
// eslint-disable-next-line
import electron = require('electron');
const ipcMain: IpcMain = electron.ipcMain;
const dialog: Dialog = electron.dialog;
const app: App = electron.app;
let browserWindow: BrowserWindow;
const releaseChannel: ReleaseChannel = new ReleaseChannel(currentStudioVersion);
// If BPMN Studio was opened by double-clicking a .bpmn file, then the
// following code tells the frontend the name and content of that file;
// this 'get_opened_file' request is emmitted in src/main.ts.
let fileAssociationFilePath: string;
let isInitialized: boolean = false;
let peErrors: string = '';
/**
* This variable gets set when BPMN Studio is ready to work with Files that are
* openend via double click.
*/
let fileOpenMainEvent: IpcMainEvent;
let runtimeProcess: ChildProcess;
process.on('exit', () => {
if (runtimeProcess) {
runtimeProcess.kill('SIGTERM');
}
});
function execute(): void {
/**
* Makes Main application a Single Instance Application.
*/
app.requestSingleInstanceLock();
/**
* Check if Main application got the Single Instance Lock.
* true: This instance is the first instance.
* false: This instance is the second instance.
*/
const hasSingleInstanceLock = app.hasSingleInstanceLock();
if (hasSingleInstanceLock) {
initializeApplication();
startInternalProcessEngine();
app.on('second-instance', (event, argv, workingDirectory) => {
const noArgumentsSet = argv[1] === undefined;
if (noArgumentsSet) {
return;
}
const argumentIsFilePath = argv[1].endsWith('.bpmn');
const argumentIsSignInRedirect = argv[1].startsWith('bpmn-studio://signin-oidc');
const argumentIsSignOutRedirect = argv[1].startsWith('bpmn-studio://signout-oidc');
if (argumentIsFilePath) {
const filePath = argv[1];
bringExistingInstanceToForeground();
answerOpenFileEvent(filePath);
}
const argumentContainsRedirect = argumentIsSignInRedirect || argumentIsSignOutRedirect;
if (argumentContainsRedirect) {
const redirectUrl = argv[1];
browserWindow.loadURL(`file://${__dirname}/../../../index.html`);
browserWindow.loadURL('/');
ipcMain.once('deep-linking-ready', (): void => {
browserWindow.webContents.send('deep-linking-request', redirectUrl);
});
}
});
} else {
app.quit();
}
}
function initializeApplication(): void {
app.on('ready', (): void => {
createMainWindow();
});
app.on('activate', (): void => {
if (browserWindow === undefined) {
createMainWindow();
}
});
ipcMain.on('restart', (): void => {
app.relaunch();
app.quit();
});
ipcMain.on('isDevelop', (event) => {
event.sender.send('isDevelop', releaseChannel.isDev());
});
ipcMain.on('create-feedback-zip', async (event, feedbackData: FeedbackData) => {
createFeedbackZip(feedbackData);
});
const portableIdentifier = electron.app.getName().includes('-portable');
if (!releaseChannel.isDev() && !process.env.SPECTRON_TESTS && !portableIdentifier) {
initializeAutoUpdater();
}
initializeFileOpenFeature();
}
function initializeAutoUpdater(): void {
ipcMain.on('app_ready', async (appReadyEvent) => {
autoUpdater.autoDownload = false;
const currentVersion = app.getVersion();
const currentReleaseChannel = new ReleaseChannel(currentVersion);
const currentVersionIsPrerelease = currentReleaseChannel.isAlpha() || currentReleaseChannel.isBeta();
autoUpdater.allowPrerelease = currentVersionIsPrerelease;
autoUpdater.channel = currentReleaseChannel.getName();
const updateCheckResult = await autoUpdater.checkForUpdates();
const noUpdateAvailable = updateCheckResult.updateInfo.version === currentVersion;
if (noUpdateAvailable) {
return;
}
const newReleaseChannel = new ReleaseChannel(updateCheckResult.updateInfo.version);
if (currentVersionIsPrerelease) {
if (currentReleaseChannel.isAlpha() && !newReleaseChannel.isAlpha()) {
return;
}
if (currentReleaseChannel.isBeta() && !newReleaseChannel.isBeta()) {
return;
}
}
console.log(`CurrentVersion: ${currentVersion}, CurrentVersionIsPrerelease: ${currentVersionIsPrerelease}`);
autoUpdater.addListener('error', (error) => {
appReadyEvent.sender.send('update_error', error.message);
});
autoUpdater.addListener('download-progress', (progressObj) => {
const progressInPercent = progressObj.percent / 100;
browserWindow.setProgressBar(progressInPercent);
appReadyEvent.sender.send('update_download_progress', progressObj);
});
let downloadCancellationToken;
autoUpdater.addListener('update-available', (updateInfo) => {
appReadyEvent.sender.send('update_available', updateInfo.version);
ipcMain.on('download_update', () => {
downloadCancellationToken = new CancellationToken();
autoUpdater.downloadUpdate(downloadCancellationToken);
ipcMain.on('cancel_update', () => {
downloadCancellationToken.cancel();
});
});
ipcMain.on('show_release_notes', () => {
const releaseNotesWindow = new BrowserWindow({
width: 600,
height: 600,
title: `Release Notes ${updateInfo.version}`,
minWidth: 600,
minHeight: 600,
});
releaseNotesWindow.loadURL(`https://github.com/process-engine/bpmn-studio/releases/tag/v${updateInfo.version}`);
});
});
autoUpdater.addListener('update-downloaded', () => {
appReadyEvent.sender.send('update_downloaded');
ipcMain.on('quit_and_install', () => {
autoUpdater.quitAndInstall();
});
});
autoUpdater.checkForUpdates();
});
}
function initializeFileOpenFeature(): void {
app.on('window-all-closed', () => {
app.quit();
fileAssociationFilePath = undefined;
});
app.on('will-finish-launching', () => {
// for windows
if (process.platform === 'win32' && process.argv.length >= 2 && process.argv[1].endsWith('.bpmn')) {
fileAssociationFilePath = process.argv[1];
}
// for non-windows
app.on('open-file', (event, filePath) => {
fileAssociationFilePath = isInitialized ? undefined : filePath;
if (isInitialized) {
answerOpenFileEvent(filePath);
}
});
});
/**
* Wait for the "waiting"-event signalling the app has started and the
* component is ready to handle events.
*
* Set the fileOpenMainEvent variable to make it accesable by the sending
* function "answerOpenFileEvent".
*
* Register an "open-file"-listener to get the path to file which has been
* clicked on.
*
* "open-file" gets fired when someone double clicks a .bpmn file.
*/
ipcMain.on('waiting-for-double-file-click', (mainEvent: IpcMainEvent) => {
fileOpenMainEvent = mainEvent;
isInitialized = true;
});
ipcMain.on('get_opened_file', (event) => {
const filePathExists: boolean = fileAssociationFilePath === undefined;
if (filePathExists) {
event.returnValue = {};
return;
}
event.returnValue = {
path: fileAssociationFilePath,
content: fs.readFileSync(fileAssociationFilePath, 'utf8'),
};
fileAssociationFilePath = undefined;
app.focus();
});
}
function answerOpenFileEvent(filePath: string): void {
fileOpenMainEvent.sender.send('double-click-on-file', filePath);
}
function getProductName(): string {
switch (releaseChannel.getName()) {
case 'stable':
return 'BPMN Studio';
case 'beta':
return 'BPMN Studio (Beta)';
case 'alpha':
return 'BPMN Studio (Alpha)';
case 'dev':
return 'BPMN Studio (Dev)';
default:
return 'BPMN Studio (pre)';
}
}
function createMainWindow(): void {
console.log('create window called');
setElectronMenubar();
const mainWindowState = windowStateKeeper({
defaultWidth: 1300,
defaultHeight: 800,
});
browserWindow = new BrowserWindow({
width: mainWindowState.width,
height: mainWindowState.height,
x: mainWindowState.x,
y: mainWindowState.y,
title: getProductName(),
minWidth: 1300,
minHeight: 800,
show: false,
backgroundColor: '#f7f7f7',
icon: path.join(__dirname, '../build/icon.png'), // only for windows
titleBarStyle: 'hiddenInset',
webPreferences: {
nodeIntegration: true,
},
});
mainWindowState.manage(browserWindow);
browserWindow.on('ready-to-show', () => {
browserWindow.show();
});
browserWindow.loadURL(`file://${__dirname}/../../../index.html`);
// We need to navigate to "/" because something in the push state seems to be
// broken if we carry a file system link as the last item of the browser
// history.
browserWindow.loadURL('/');
ipcMain.on('close_bpmn-studio', (event) => {
const focusedWindow = BrowserWindow.getFocusedWindow();
focusedWindow.close();
});
browserWindow.on('closed', (event) => {
browserWindow = null;
});
browserWindow.on('enter-full-screen', () => {
browserWindow.webContents.send('toggle-fullscreen', true);
});
browserWindow.on('leave-full-screen', () => {
browserWindow.webContents.send('toggle-fullscreen', false);
});
browserWindow.webContents.on('new-window', (event: any, url: string) => {
if (url !== browserWindow.webContents.getURL()) {
event.preventDefault();
open(url);
}
});
setOpenDiagramListener();
setOpenSolutionsListener();
setSaveDiagramAsListener();
const platformIsWindows = process.platform === 'win32';
if (platformIsWindows) {
browserWindow.webContents.session.on('will-download', (event, downloadItem) => {
const defaultFilename = downloadItem.getFilename();
const fileExtension = path.extname(defaultFilename);
const fileExtensionIsBPMN = fileExtension === 'bpmn';
const fileType = fileExtensionIsBPMN ? 'BPMN (.bpmn)' : `Image (${fileExtension})`;
downloadItem.setSaveDialogOptions({
defaultPath: defaultFilename,
filters: [
{
name: fileType,
extensions: [fileExtension],
},
{
name: 'All Files',
extensions: ['*'],
},
],
});
});
}
}
function setSaveDiagramAsListener(): void {
ipcMain.on('open_save-diagram-as_dialog', async (event) => {
const saveDialogResult = await dialog.showSaveDialog({
filters: [
{
name: 'BPMN',
extensions: ['bpmn', 'xml'],
},
{
name: 'All Files',
extensions: ['*'],
},
],
});
const filePath: string = saveDialogResult.canceled ? undefined : saveDialogResult.filePath;
event.sender.send('save_diagram_as', filePath);
});
}
function setOpenDiagramListener(): void {
ipcMain.on('open_diagram', (event) => {
const openedFile = dialog.showOpenDialogSync({
filters: [
{
name: 'BPMN',
extensions: ['bpmn', 'xml'],
},
{
name: 'XML',
extensions: ['bpmn', 'xml'],
},
{
name: 'All Files',
extensions: ['*'],
},
],
});
event.sender.send('import_opened_diagram', openedFile);
});
}
function setOpenSolutionsListener(): void {
ipcMain.on('open_solution', (event) => {
const openedFile = dialog.showOpenDialogSync({
properties: ['openDirectory', 'createDirectory'],
});
event.sender.send('import_opened_solution', openedFile);
});
}
function setElectronMenubar(): void {
showFilteredMenuEntries(false, false);
ipcMain.on('menu_hide-diagram-related-entries', () => {
showFilteredMenuEntries(false, false);
});
ipcMain.on('menu_hide-save-entries', () => {
showFilteredMenuEntries(false, true);
});
ipcMain.on('menu_show-all-menu-entries', () => {
showAllMenuEntries();
});
}
function showAllMenuEntries(): void {
const template = [getApplicationMenu(), getFileMenu(), getEditMenu(), getWindowMenu(), getHelpMenu()];
electron.Menu.setApplicationMenu(electron.Menu.buildFromTemplate(template));
}
function showFilteredMenuEntries(showSaveButtons: boolean, showExportButton: boolean): void {
const filteredFileMenu: MenuItem = getFilteredFileMenu(showSaveButtons, showExportButton);
const template = [getApplicationMenu(), filteredFileMenu, getEditMenu(), getWindowMenu(), getHelpMenu()];
electron.Menu.setApplicationMenu(electron.Menu.buildFromTemplate(template));
}
function getFilteredFileMenu(showSaveButtons: boolean, showExportButton: boolean): MenuItem {
let previousEntryIsSeparator = false;
const unfilteredFileMenu = getFileMenu();
const filteredFileSubmenuItems = unfilteredFileMenu.submenu.items.filter((submenuEntry: MenuItem) => {
const isSeparator = submenuEntry.type !== undefined && submenuEntry.type === 'separator';
if (isSeparator) {
// This is used to prevent double separators
if (previousEntryIsSeparator) {
return false;
}
previousEntryIsSeparator = true;
return true;
}
const isSaveButton = submenuEntry.label !== undefined && submenuEntry.label.startsWith('Save');
if (isSaveButton && !showSaveButtons) {
return false;
}
const isExportButton = submenuEntry.label !== undefined && submenuEntry.label.startsWith('Export');
if (isExportButton && !showExportButton) {
return false;
}
previousEntryIsSeparator = false;
return true;
});
const newFileSubmenu: Menu = electron.Menu.buildFromTemplate(filteredFileSubmenuItems);
const menuOptions: MenuItemConstructorOptions = {
label: 'File',
submenu: newFileSubmenu,
};
return new MenuItem(menuOptions);
}
function getApplicationMenu(): MenuItem {
const submenuOptions: Array<MenuItemConstructorOptions> = [
{
label: `About ${getProductName()}`,
click: (): void => {
openAboutWindow(getAboutWindowInfo());
},
},
{
type: 'separator',
},
{
label: 'Preferences',
click: (): void => {
browserWindow.webContents.send('menubar__open_preferences');
},
},
{
type: 'separator',
},
{
label: 'Quit',
role: 'quit',
},
];
const submenu: Menu = electron.Menu.buildFromTemplate(submenuOptions);
const menuOptions: MenuItemConstructorOptions = {
label: getProductName(),
submenu: submenu,
};
return new MenuItem(menuOptions);
}
function getFileMenu(): MenuItem {
const submenuOptions: Array<MenuItemConstructorOptions> = [
{
label: 'New Diagram',
accelerator: 'CmdOrCtrl+N',
click: (): void => {
browserWindow.webContents.send('menubar__start_create_diagram');
},
},
{
type: 'separator',
},
{
label: 'Open Diagram',
accelerator: 'CmdOrCtrl+O',
click: (): void => {
browserWindow.webContents.send('menubar__start_opening_diagram');
},
},
{
label: 'Open Solution',
accelerator: 'CmdOrCtrl+Shift+O',
click: (): void => {
browserWindow.webContents.send('menubar__start_opening_solution');
},
},
{
type: 'separator',
},
{
label: 'Save Diagram',
accelerator: 'CmdOrCtrl+S',
click: (): void => {
browserWindow.webContents.send('menubar__start_save_diagram');
},
},
{
label: 'Save Diagram As...',
accelerator: 'CmdOrCtrl+Shift+S',
click: (): void => {
browserWindow.webContents.send('menubar__start_save_diagram_as');
},
},
{
label: 'Save All Diagrams',
accelerator: 'CmdOrCtrl+Alt+S',
click: (): void => {
browserWindow.webContents.send('menubar__start_save_all_diagrams');
},
},
{
type: 'separator',
},
{
label: 'Export Diagram As...',
submenu: [
{
label: 'BPMN',
click: (): void => {
browserWindow.webContents.send('menubar__epxort_diagram_as', 'BPMN');
},
},
{
label: 'SVG',
click: (): void => {
browserWindow.webContents.send('menubar__epxort_diagram_as', 'SVG');
},
},
{
label: 'PNG',
click: (): void => {
browserWindow.webContents.send('menubar__epxort_diagram_as', 'PNG');
},
},
{
label: 'JPEG',
click: (): void => {
browserWindow.webContents.send('menubar__epxort_diagram_as', 'JPEG');
},
},
],
},
{
type: 'separator',
},
{
label: 'Close Diagram',
accelerator: 'CmdOrCtrl+W',
click: (): void => {
browserWindow.webContents.send('menubar__start_close_diagram');
},
},
{
label: 'Close All Diagrams',
accelerator: 'CmdOrCtrl+Alt+W',
click: (): void => {
browserWindow.webContents.send('menubar__start_close_all_diagrams');
},
},
];
const submenu: Menu = electron.Menu.buildFromTemplate(submenuOptions);
const menuOptions: MenuItemConstructorOptions = {
label: 'File',
submenu: submenu,
};
return new MenuItem(menuOptions);
}
function getEditMenu(): MenuItem {
const submenuOptions: Array<MenuItemConstructorOptions> = [
{
label: 'Undo',
accelerator: 'CmdOrCtrl+Z',
role: 'undo',
},
{
label: 'Redo',
accelerator: 'CmdOrCtrl+Shift+Z',
role: 'redo',
},
{
type: 'separator',
},
{
label: 'Cut',
accelerator: 'CmdOrCtrl+X',
role: 'cut',
},
{
label: 'Copy',
accelerator: 'CmdOrCtrl+C',
role: 'copy',
},
{
label: 'Paste',
accelerator: 'CmdOrCtrl+V',
role: 'paste',
},
{
label: 'Select All',
accelerator: 'CmdOrCtrl+A',
role: 'selectAll',
},
];
const submenu: Menu = electron.Menu.buildFromTemplate(submenuOptions);
const menuOptions: MenuItemConstructorOptions = {
label: 'Edit',
submenu: submenu,
};
return new MenuItem(menuOptions);
}
function getWindowMenu(): MenuItem {
const isMac = process.platform === 'darwin';
const submenuOptions: Array<MenuItemConstructorOptions> = [
{
role: 'minimize',
},
isMac ? {role: 'close'} : {role: 'quit'},
{
type: 'separator',
},
{
role: 'reload',
},
];
const submenu: Menu = electron.Menu.buildFromTemplate(submenuOptions);
const menuOptions: MenuItemConstructorOptions = {
label: 'Window',
submenu: submenu,
};
return new MenuItem(menuOptions);
}
function getHelpMenu(): MenuItem {
const submenuOptions: Array<MenuItemConstructorOptions> = [
{
label: 'Getting Started',
click: (): void => {
const documentationUrl = 'https://www.process-engine.io/docs/getting-started/';
electron.shell.openExternal(documentationUrl);
},
},
{
label: 'BPMN Element Documentation',
click: (): void => {
const currentVersionBranch = getBranchOfCurrentVersion();
const elementDocumentationUrl = `https://github.com/process-engine/bpmn-studio/blob/${currentVersionBranch}/doc/bpmn-elements.md`;
electron.shell.openExternal(elementDocumentationUrl);
},
},
{
label: 'Release Notes',
click: (): void => {
const currentVersion = app.getVersion();
const currentReleaseNotesUrl = `https://github.com/process-engine/bpmn-studio/releases/tag/v${currentVersion}`;
electron.shell.openExternal(currentReleaseNotesUrl);
},
},
{
type: 'separator',
},
{
label: 'Developer Support',
submenu: [
{
role: 'toggleDevTools',
},
{
type: 'separator',
},
{
label: 'Export Databases to ZIP File ...',
click: async (): Promise<void> => {
try {
await exportDatabases();
} catch (error) {
browserWindow.webContents.send('database-export-error', error.message);
}
},
},
{
label: 'Open Folder for Databases',
click: async (): Promise<void> => {
electron.shell.openItem(getConfigFolder());
},
},
],
},
{
type: 'separator',
},
{
label: 'Feedback',
click: (): void => {
browserWindow.webContents.send('show-feedback-modal');
},
},
];
const submenu: Menu = electron.Menu.buildFromTemplate(submenuOptions);
const menuOptions: MenuItemConstructorOptions = {
label: 'Help',
submenu: submenu,
};
return new MenuItem(menuOptions);
}
function getAboutWindowInfo(): AboutWindowInfo {
const copyrightYear: number = new Date().getFullYear();
return {
icon_path: releaseChannel.isDev()
? path.join(__dirname, '../../../build/icon.png')
: path.join(__dirname, '../../../../../build/icon.png'),
product_name: getProductName(),
bug_report_url: 'https://github.com/process-engine/bpmn-studio/issues/new',
homepage: 'www.process-engine.io',
copyright: `Copyright © ${copyrightYear} process-engine`,
win_options: {
minimizable: false,
maximizable: false,
resizable: false,
},
package_json_dir: __dirname,
};
}
async function startInternalProcessEngine(): Promise<any> {
const configForGetPort = {
port: getPortListByVersion(releaseChannel.getVersion()),
host: '0.0.0.0',
};
console.log('Trying to start internal ProcessEngine on ports:', configForGetPort);
const port = await getPort(configForGetPort);
console.log(`Internal ProcessEngine starting on port ${port}.`);
// The forked runtime process gets these environments too.
process.env.httpServer__port = `${port}`;
process.env.iam__allowAnonymousRootAccess = 'true';
if (!releaseChannel.isDev()) {
process.env.CONFIG_PATH = path.join(__dirname, '..', '..', '..', '..', '..', 'configs', 'sqlite.json');
}
const processEngineStatusListeners = [];
let internalProcessEngineStatus;
let internalProcessEngineStartupError;
/* When someone wants to know to the internal processengine status, he
* must first send a `add_internal_processengine_status_listener` message
* to the event mechanism. We recieve this message here and add the sender
* to our listeners array.
*
* As soon, as the processengine status is updated, we send the listeners a
* notification about this change; this message contains the state and the
* error text (if there was an error).
*
* If the processengine status is known by the time the listener registers,
* we instantly respond to the listener with a notification message.
*
* This is quite a unusual pattern, the problem this approves solves is the
* following: It's impossible to do interactions between threads in
* electron like this:
*
* 'renderer process' 'main process'
* | |
* o <<<- Send Message -<<< x
*
* -------------------------------------------------
*
* Instead our interaction now locks like this:
*
* 'renderer process' 'main process'
* | |
* x >>>-- Subscribe -->>> o
* o <<<- Send Message -<<< x
* | (event occurs) |
* o <<<- Send Message -<<< x
*/
ipcMain.on('add_internal_processengine_status_listener', (event: IpcMainEvent) => {
if (!processEngineStatusListeners.includes(event.sender)) {
processEngineStatusListeners.push(event.sender);
}
if (internalProcessEngineStatus !== undefined) {
sendInternalProcessEngineStatus(event.sender, internalProcessEngineStatus, internalProcessEngineStartupError);
}
});
// This tells the frontend the location at which the electron-skeleton
// will be running; this 'get_host' request ist emitted in src/main.ts.
ipcMain.on('get_host', (event: IpcMainEvent) => {
event.returnValue = `localhost:${port}`;
});
try {
await startRuntime();
runtimeProcess.on('close', (code) => {
const error = new Error(`Runtime exited with code ${code}`);
console.error(error);
});
runtimeProcess.on('error', (err) => {
const error = new Error(err.toString());
console.error('Internal ProcessEngine Error: ', error);
});
console.log('Internal ProcessEngine started successfully.');
internalProcessEngineStatus = 'success';
publishProcessEngineStatus(
processEngineStatusListeners,
internalProcessEngineStatus,
internalProcessEngineStartupError,
);
} catch (error) {
console.error('Failed to start internal ProcessEngine: ', error);
internalProcessEngineStatus = 'error';
// eslint-disable-next-line no-multi-assign
internalProcessEngineStartupError = peErrors += error;
publishProcessEngineStatus(
processEngineStatusListeners,
internalProcessEngineStatus,
internalProcessEngineStartupError,
);
}
}
async function startRuntime(): Promise<void> {
return new Promise((resolve: Function, reject: Function): void => {
const sqlitePath = getSqlitePath();
const logFilepath = getProcessEngineLogFolder();
const pathToRuntime = path.join(
__dirname,
'..',
'..',
'..',
'node_modules',
'@atlas-engine',
'fullstack_server',
'bin',
'index.js',
);
runtimeProcess = fork(pathToRuntime, [`--sqlite-path=${sqlitePath}`, `--log-file-path=${logFilepath}`], {
stdio: 'pipe',
});
runtimeProcess.stdout.on('data', (data) => process.stdout.write(data));
runtimeProcess.stderr.on('data', (data) => {
process.stderr.write(data);
peErrors += data.toString();
});
runtimeProcess.on('message', (message) => {
if (message === 'started') {
resolve();
}
});
runtimeProcess.on('close', (code) => {
const error = new Error(`Runtime exited with code ${code}`);
reject(error);
});
runtimeProcess.on('error', (err) => {
reject(err);
});
});
}
function getProcessEngineLogFolder(): string {
return path.join(getConfigFolder(), getProcessEngineLogFolderName());
}
function getProcessEngineLogFolderName(): string {
return 'process_engine_logs';
}
function getSqlitePath(): string {
const configPath = !releaseChannel.isDev()
? path.join(__dirname, '..', '..', '..', '..', '..', 'configs', 'sqlite.json')
: path.join(__dirname, '..', '..', '..', 'configs', 'sqlite.json');
const config = JSON.parse(fs.readFileSync(configPath, {encoding: 'utf8'}));
return path.join(getProcessEngineDatabaseFolder(), config.database.storage);
}
function getProcessEngineDatabaseFolder(): string {
return path.join(getConfigFolder(), getProcessEngineDatabaseFolderName());
}
function getProcessEngineDatabaseFolderName(): string {
return 'process_engine_databases';
}
function sendInternalProcessEngineStatus(
sender: WebContents,
internalProcessEngineStatus,
internalProcessEngineStartupError,
): any {
let serializedStartupError;
const processEngineStartHasFailed =
internalProcessEngineStartupError !== undefined && internalProcessEngineStartupError !== null;
if (processEngineStartHasFailed) {
if (typeof internalProcessEngineStartupError === 'string') {
serializedStartupError = internalProcessEngineStartupError;
} else {
serializedStartupError = JSON.stringify(
internalProcessEngineStartupError,
Object.getOwnPropertyNames(internalProcessEngineStartupError),
);
}
} else {
serializedStartupError = undefined;
}
sender.send('internal_processengine_status', internalProcessEngineStatus, serializedStartupError);
}
function publishProcessEngineStatus(
processEngineStatusListeners,
internalProcessEngineStatus,
internalProcessEngineStartupError,
): void {
processEngineStatusListeners.forEach((processEngineStatusLisener) => {
sendInternalProcessEngineStatus(
processEngineStatusLisener,
internalProcessEngineStatus,
internalProcessEngineStartupError,
);
});
}
function getConfigFolder(): string {
const configPath = `bpmn-studio${getConfigPathSuffix()}`;
return path.join(getUserConfigFolder(), configPath);
}
function getConfigPathSuffix(): string {
if (process.env.SPECTRON_TESTS) {
return '-tests';
}
if (releaseChannel.isDev()) {
return '-dev';
}
if (releaseChannel.isAlpha()) {
return '-alpha';
}
if (releaseChannel.isBeta()) {
return '-beta';
}
if (releaseChannel.isStable()) {
return '';
}
throw new Error('Could not get config path suffix for internal process engine');
}
function getBranchOfCurrentVersion(): string {
if (releaseChannel.isDev()) {
return 'develop';
}
if (releaseChannel.isAlpha()) {
return 'develop';
}
if (releaseChannel.isBeta()) {
return 'beta';
}
if (releaseChannel.isStable()) {
return 'master';
}
throw new Error('Could not get the branch of the current version.');
}
function getUserConfigFolder(): string {
const userHomeDir = homedir();
switch (process.platform) {
case 'darwin':
return path.join(userHomeDir, 'Library', 'Application Support');
case 'win32':
return path.join(userHomeDir, 'AppData', 'Roaming');
default:
return path.join(userHomeDir, '.config');
}
}
function bringExistingInstanceToForeground(): void {
if (browserWindow) {
if (browserWindow.isMinimized()) {
browserWindow.restore();
}
browserWindow.focus();
}
}
async function exportDatabases(): Promise<void> {
const zip = new JSZip();
addFolderToZip(zip, getProcessEngineDatabaseFolderName(), getProcessEngineDatabaseFolder());
// eslint-disable-next-line newline-per-chained-call
const now = new Date().toISOString().replace(/:/g, '-');
const defaultFilename = `database-backup-${now}.zip`;
const pathToSaveTo: string = await getPathToSaveTo(defaultFilename);
if (!pathToSaveTo) {
return;
}
zip.generateAsync({type: 'nodebuffer'}).then((content) => {
fs.writeFileSync(pathToSaveTo, content);
});
}
async function createFeedbackZip(feedbackData: FeedbackData): Promise<void> {
const zip = new JSZip();
const feedbackFolder = zip.folder('feedback');
if (feedbackData.attachInternalDatabases) {
const processEngineFolder = feedbackFolder.folder('InternalProcessEngine');
addFolderToZip(processEngineFolder, getProcessEngineDatabaseFolderName(), getProcessEngineDatabaseFolder());
}
if (feedbackData.attachProcessEngineLogs) {
const processEngineFolder = feedbackFolder.folder('InternalProcessEngine');
addFolderToZip(processEngineFolder, getProcessEngineLogFolderName(), getProcessEngineLogFolder());
}
const bugsProvided: boolean = feedbackData.bugs.trim() !== '';
if (bugsProvided) {
feedbackFolder.file('Bugs.txt', feedbackData.bugs);
}
const suggestionsProvided: boolean = feedbackData.suggestions.trim() !== '';
if (suggestionsProvided) {
feedbackFolder.file('Suggestions.txt', feedbackData.suggestions);
}
const diagramsProvided: boolean = feedbackData.diagrams.length > 0;
if (diagramsProvided) {
const diagramFolder = feedbackFolder.folder('diagrams');
feedbackData.diagrams.forEach((diagram) => {
let diagramSolution: string = '';
if (solutionIsRemoteSolution(diagram.uri)) {
const diagramUriWithoutProtocol = diagram.uri.substring(diagram.uri.indexOf('/') + 2);
const diagramUriWithoutProtocolAndLocation = diagramUriWithoutProtocol.substring(
0,
diagramUriWithoutProtocol.indexOf('/'),
);
const diagramUriWithoutProtocolAndLocationWithEscapedPort = diagramUriWithoutProtocolAndLocation.replace(
':',
'__',
);
diagramSolution = diagramUriWithoutProtocolAndLocationWithEscapedPort;
} else {
const escapedDiagramUri = diagram.uri.substring(0, diagram.uri.lastIndexOf('/')).replace(/[/\\]/g, '__');
diagramSolution = escapedDiagramUri.startsWith('__') ? escapedDiagramUri.replace('__', '') : escapedDiagramUri;
}
const solutionFolder = diagramFolder.folder(diagramSolution);
const diagramName: string = `${diagram.name}${
diagram.name.endsWith('.bpmn') || diagram.name.endsWith('.xml') ? '' : '.bpmn'
}`;
solutionFolder.file(diagramName, diagram.xml);
});
const additionalDiagramInformationProvided: boolean = feedbackData.additionalDiagramInformation.trim() !== '';
if (additionalDiagramInformationProvided) {
diagramFolder.file('Additional Diagram Information.txt', feedbackData.additionalDiagramInformation);
}
}
// eslint-disable-next-line newline-per-chained-call
const now = new Date().toISOString().replace(/:/g, '-');
const defaultFilename = `feedback-${now}.zip`;
const pathToSaveTo: string = await getPathToSaveTo(defaultFilename);
if (!pathToSaveTo) {
return;
}
zip.generateAsync({type: 'nodebuffer'}).then((content) => {
fs.writeFileSync(pathToSaveTo, content);
});
}
function getNamesOfFilesAndFoldersInFolder(foldername): Array<fs.Dirent> {
return fs.readdirSync(foldername, {withFileTypes: true});
}
async function getPathToSaveTo(defaultFilename): Promise<string> {
const downloadPath = electron.app.getPath('downloads');
const defaultPath = path.join(downloadPath, defaultFilename);
const saveDialogResult = await dialog.showSaveDialog({
defaultPath: defaultPath,
filters: [
{
name: 'zip',
extensions: ['zip'],
},
{
name: 'All Files',
extensions: ['*'],
},
],
});
if (saveDialogResult.canceled) {
return undefined;
}
return saveDialogResult.filePath;
}
function addFolderToZip(zipFolder, folderName, folderPath): void {
if (!fs.existsSync(folderPath)) {
zipFolder.file(`${folderName} does not exist.`, '', {base64: true});
return;
}
const folderInZip = zipFolder.folder(folderName);
const filesAndFoldersInFolder: Array<fs.Dirent> = getNamesOfFilesAndFoldersInFolder(folderPath);
filesAndFoldersInFolder.forEach((fileOrFolder: fs.Dirent) => {
const currentElementsPath: string = `${folderPath}/${fileOrFolder.name}`;
if (fileOrFolder.isDirectory()) {
addFolderToZip(folderInZip, fileOrFolder.name, currentElementsPath);
} else {
addFileToZip(folderInZip, fileOrFolder.name, currentElementsPath);
}
});
}
function addFileToZip(zipFolder, filename, filePath): void {
zipFolder.file(filename, fs.readFileSync(filePath), {base64: true});
}
execute(); | the_stack |
import * as url from "url";
import { Cancelable, CancelSubscription } from "@esfx/cancelable";
import { CancelToken } from "@esfx/async-canceltoken";
import { Disposable } from '@esfx/disposable';
// NOTE: grammarkdown requires a minimum of ES5.
if (typeof Object.create !== "function") throw new Error("Grammarkdown requires a minimum host engine of ES5.");
const hasOwnProperty = Object.prototype.hasOwnProperty;
export interface DictionaryLike<T> {
[key: string]: T;
[key: number]: T;
}
export function mapFromObject<T>(object: DictionaryLike<T>) {
const map = new Map<string, T>();
for (const p in object) {
if (hasOwnProperty.call(object, p)) {
map.set(p, object[p]);
}
}
return map;
}
export function binarySearch(array: number[], value: number): number {
return binarySearchBy(array, value, identity, compareNumbers);
}
export function binarySearchBy<T, K>(array: readonly T[], key: K, selector: (value: T) => K, comparison: (x: K, y: K) => number = compare): number {
if (array.length === 0 || comparison(key, selector(array[0])) < 0) {
return -1;
}
if (comparison(key, selector(array[array.length - 1])) > 0) {
return ~array.length;
}
let low: number = 0;
let high: number = array.length - 1;
while (low <= high) {
const middle: number = low + ((high - low) >> 1);
const mid: K = selector(array[middle]);
const cmp: number = comparison(mid, key);
if (cmp > 0) {
high = middle - 1;
} else if (cmp < 0) {
low = middle + 1;
} else {
return middle;
}
}
return ~low;
}
export function compareNumbers(a: number, b: number) {
return a - b;
}
export function compareStrings(x: string | undefined, y: string | undefined, ignoreCase?: boolean) {
return ignoreCase
? compare(x && x.toLocaleLowerCase(), y && y.toLocaleLowerCase())
: compare(x, y);
}
export function compare(x: any, y: any) {
if (x === y) return 0;
if (x === undefined || x === null) return -1;
if (y === undefined || y === null) return +1;
if (x < y) return -1;
if (x > y) return +1;
return 0;
}
export function forEach<T, U>(array: ReadonlyArray<T> | undefined, cb: (value: T) => U | undefined): U | undefined {
if (array !== undefined) {
for (const item of array) {
const result = cb(item);
if (result) return result;
}
}
}
export const emptyIterable: IterableIterator<never> = {
next() { return { done: true, value: undefined as never }; },
[Symbol.iterator]() { return this; }
};
export function identity<T>(value: T) {
return value;
}
export function first<T>(iterable: Iterable<T> | T[] | undefined) {
if (iterable === undefined) return undefined;
if (iterable === emptyIterable) return undefined;
if (Array.isArray(iterable)) return iterable.length > 0 ? iterable[0] : undefined;
for (const item of iterable) return item;
}
export function last<T>(iterable: Iterable<T> | T[] | undefined) {
if (iterable === undefined) return undefined;
if (iterable === emptyIterable) return undefined;
if (Array.isArray(iterable)) return iterable.length > 0 ? iterable[iterable.length - 1] : undefined;
let last: T | undefined;
for (const item of iterable) last = item;
return last;
}
export function only<T>(iterable: Iterable<T> | T[] | undefined) {
if (iterable === undefined) return undefined;
if (iterable === emptyIterable) return undefined;
if (Array.isArray(iterable)) return iterable.length === 1 ? iterable[0] : undefined;
let only: T | undefined;
let first = true;
for (const item of iterable) {
if (!first) return undefined;
only = item;
}
return only;
}
export function stableSort<T>(array: ReadonlyArray<T>, comparer: (a: T, b: T) => number) {
const indices = array.map((_, i) => i);
indices.sort((x, y) => comparer(array[x], array[y]) || x - y);
return indices.map(i => array[i]);
}
export function concat<T>(a: T[], b: T[] | undefined): T[];
export function concat<T>(a: T[] | undefined, b: T[]): T[];
export function concat<T>(a: T[] | undefined, b: T[] | undefined): T[] | undefined;
export function concat<T>(a: T[] | undefined, b: T[] | undefined) {
return a ? b ? a.concat(b) : a : b;
}
export function deduplicateSorted<T>(array: readonly T[], comparer: (a: T, b: T) => number | boolean): T[] {
if (array.length === 0) return [];
let last = array[0];
const deduplicated: T[] = [last];
for (let i = 1; i < array.length; i++) {
const next = array[i];
const result = comparer(next, last);
if (result === true || result === 0) {
continue;
}
else if (result !== false && result < 0) {
throw new Error("Array is unsorted");
}
deduplicated.push(last = next);
}
return deduplicated;
}
export function promiseFinally<T>(promise: PromiseLike<T>, onFinally: () => void) {
return promise.then(value => {
onFinally();
return value;
}, e => {
onFinally();
throw e;
});
}
export function pipe<T, U>(result: T | Promise<T>, next: (value: T) => U | Promise<U>): U | Promise<U>;
export function pipe<T, U>(result: T | Promise<T> | undefined, next: (value: T | undefined) => U | Promise<U>): U | Promise<U>;
export function pipe<T, U>(result: T | Promise<T> | undefined, next: (value: T | undefined) => U | Promise<U> | undefined): U | Promise<U> | undefined;
export function pipe<T, U>(result: T | Promise<T>, next: (value: T) => U | Promise<U>) {
return isPromise(result) ? result.then(next) : next(result);
}
export function isPromise<T>(value: T | Promise<T> | undefined): value is Promise<T> {
return typeof value === "object" && "then" in (value as object);
}
export function forEachPossiblyAsync<T, U>(iterable: Iterable<T>, callback: (value: T) => Promise<U> | U | undefined): void | Promise<void> {
const iter = iterable[Symbol.iterator]();
const next = (): void | Promise<void> => {
while (true) {
const { value, done } = iter.next();
if (done) break;
const result = callback(value);
if (isPromise(result)) return pipe(result, next);
}
}
return next();
}
export function mapSet<K extends object, V>(map: WeakMap<K, V>, key: K, value: V): V;
export function mapSet<K, V>(map: Map<K, V>, key: K, value: V): V;
export function mapSet<K, V>(map: { set(key: K, value: V): any; }, key: K, value: V) {
map.set(key, value);
return value;
}
const enumMembers = Symbol();
/**
* Formats an enum value as a string for debugging and debug assertions.
*/
/*@internal*/
export function formatEnum(value = 0, enumObject: any, isFlags?: boolean) {
const members = getEnumMembers(enumObject);
if (value === 0) {
return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0";
}
if (isFlags) {
let result = "";
let remainingFlags = value;
for (let i = members.length - 1; i >= 0 && remainingFlags !== 0; i--) {
const [enumValue, enumName] = members[i];
if (enumValue !== 0 && (remainingFlags & enumValue) === enumValue) {
remainingFlags &= ~enumValue;
result = `${enumName}${result ? ", " : ""}${result}`;
}
}
if (remainingFlags === 0) {
return result;
}
}
else {
for (const [enumValue, enumName] of members) {
if (enumValue === value) {
return enumName;
}
}
}
return value.toString();
}
function getEnumMembers(enumObject: any): [number, string][] {
if (enumObject[enumMembers]) return enumObject[enumMembers];
const result: [number, string][] = [];
for (const name in enumObject) if (Object.prototype.hasOwnProperty.call(enumObject, name)) {
const value = enumObject[name];
if (typeof value === "number") {
result.push([value, name]);
}
}
return enumObject[enumMembers] = stableSort<[number, string]>(result, (x, y) => compare(x[0], y[0]));
}
export function toCancelToken(cancelable: Cancelable): CancelToken;
export function toCancelToken(cancelable: Cancelable | null | undefined): CancelToken | undefined;
export function toCancelToken(cancelable: Cancelable | null | undefined) {
if (Cancelable.hasInstance(cancelable)) {
return CancelToken.from(cancelable);
}
}
export class AggregateCancelable {
private _cancelSource = CancelToken.source();
private _subscriptions = new Set<CancelSubscription>();
private _cancelCount = 0;
get canBeCanceled() {
return this._cancelCount >= 0;
}
get cancelable() {
return this._cancelSource.token;
}
addCancelable(cancelable: Cancelable | undefined) {
if (this._cancelSource.token.signaled) return;
if (cancelable === undefined || cancelable instanceof CancelToken && !cancelable.canBeSignaled) {
// We have an observer that cannot be canceled
if (this._cancelCount >= 0) {
this._cancelCount = -1; // -1 indicates we cannot be canceled
// Remove all subscriptions
const subscriptions = [...this._subscriptions];
this._subscriptions.clear();
for (const subscription of subscriptions) {
subscription.unsubscribe();
}
}
return;
}
// Track that we can be canceled
this._cancelCount++;
// Create a subscription that can only be invoked once
let invoked = false;
const subscription = Cancelable.subscribe(cancelable, () => {
if (!invoked) {
invoked = true;
if (this._cancelCount > 0) {
this._cancelCount--;
if (this._cancelCount === 0) {
this._cancelCount = -2; // indicate we are now canceled.
this._cancelSource.cancel();
}
}
}
});
// Return a subscription that can remove this token.
const unsubscribe = () => {
if (this._subscriptions.delete(subscription)) {
subscription.unsubscribe();
}
};
return {
unsubscribe,
[Disposable.dispose]: unsubscribe
};
}
}
/**
* Synchronizes multiple asynchronous cancelable calls for the same resource,
* such that the operation is only canceled when all callers have canceled.
*/
export class SharedOperation<T> {
private _callback: (cancelToken?: CancelToken) => PromiseLike<T> | T;
private _sharedOperation: [AggregateCancelable, Promise<T>] | undefined;
constructor(callback: (cancelToken?: CancelToken) => PromiseLike<T> | T) {
this._callback = callback;
}
async invoke(cancelable?: Cancelable) {
const cancelToken = toCancelToken(cancelable);
cancelToken?.throwIfSignaled();
if (!this._sharedOperation) {
const operation = new AggregateCancelable();
const operationSubscription = operation.cancelable.subscribe(() => {
if (this._sharedOperation === sharedOperation) {
this._sharedOperation = undefined;
}
});
const promise = Promise.resolve((void 0, this._callback)(operation.cancelable));
const sharedOperation = this._sharedOperation = [operation, promise];
try {
return await this._invokeWorker(sharedOperation, cancelToken);
}
finally {
this._sharedOperation = undefined;
operationSubscription.unsubscribe();
}
}
else {
return await this._invokeWorker(this._sharedOperation, cancelToken);
}
}
private async _invokeWorker(sharedOperation: [AggregateCancelable, Promise<T>], cancelToken: CancelToken | undefined) {
const [operation, promise] = sharedOperation;
const subscription = operation.addCancelable(cancelToken);
try {
return await promise;
}
finally {
subscription?.unsubscribe();
}
}
}
export function isUri(file: string) {
return !/^([\\/]|[a-z]:($|[\\/]))/i.test(file)
&& !!url.parse(file).protocol;
}
export function isFileUri(file: string) {
return /^file:\/\//.test(file);
}
export function getLocalPath(file: string): string {
if (/^file:\/\//.test(file)) {
const parsed = url.parse(file);
if (parsed.path) {
if (parsed.hostname) {
file = `//${parsed.hostname}${decodeURIComponent(parsed.path)}`;
}
else {
file = decodeURIComponent(parsed.path).substr(1);
}
}
}
return file;
} | the_stack |
import {
Account,
BlockInfoFailed,
BlockInfoSucceeded,
isBlockInfoPending,
isConfirmedAndSignedTransaction,
isConfirmedTransaction,
isFailedTransaction,
isSendTransaction,
SendTransaction,
TransactionId,
TransactionState,
} from "@iov/bcp";
import { Ed25519, Sha512 } from "@iov/crypto";
import { HdPaths } from "@iov/keycontrol";
import { firstEvent, lastValue } from "@iov/stream";
import { assert, sleep } from "@iov/utils";
import Long from "long";
import { bnsCodec } from "./bnscodec";
import { BnsConnection } from "./bnsconnection";
import {
bnsdTendermintUrl,
cash,
defaultAmount,
pendingWithoutBnsd,
randomBnsAddress,
sendCash,
sendTokensFromFaucet,
tendermintSearchIndexUpdated,
userProfileWithFaucet,
} from "./testutils.spec";
import { identityToAddress } from "./util";
describe("BnsConnection (txs)", () => {
describe("getTx", () => {
it("can get a transaction by ID", async () => {
pendingWithoutBnsd();
const connection = await BnsConnection.establish(bnsdTendermintUrl);
// by non-existing ID
{
const nonExistentId = "abcd" as TransactionId;
await connection
.getTx(nonExistentId)
.then(fail.bind(null, "should not resolve"), (error) =>
expect(error).toMatch(/transaction does not exist/i),
);
}
{
const chainId = connection.chainId;
const { profile, faucet } = await userProfileWithFaucet(chainId);
const faucetAddress = bnsCodec.identityToAddress(faucet);
const memo = `Payment ${Math.random()}`;
const sendTx = await connection.withDefaultFee<SendTransaction>(
{
kind: "bcp/send",
chainId: faucet.chainId,
sender: faucetAddress,
recipient: await randomBnsAddress(),
memo: memo,
amount: defaultAmount,
},
faucetAddress,
);
const nonce = await connection.getNonce({ pubkey: faucet.pubkey });
const signed = await profile.signTransaction(faucet, sendTx, bnsCodec, nonce);
const response = await connection.postTx(bnsCodec.bytesToPost(signed));
await response.blockInfo.waitFor((info) => !isBlockInfoPending(info));
const transactionId = response.transactionId;
await tendermintSearchIndexUpdated();
const result = await connection.getTx(transactionId);
expect(result.height).toBeGreaterThanOrEqual(2);
expect(result.transactionId).toEqual(transactionId);
assert(isConfirmedTransaction(result), "Expected ConfirmedTransaction");
const transaction = result.transaction;
assert(isSendTransaction(transaction), "Expected SendTransaction");
expect(transaction.recipient).toEqual(sendTx.recipient);
expect(transaction.amount).toEqual(defaultAmount);
}
connection.disconnect();
});
it("can get a transaction by ID and verify its signature", async () => {
pendingWithoutBnsd();
const connection = await BnsConnection.establish(bnsdTendermintUrl);
const chainId = connection.chainId;
const { profile, faucet } = await userProfileWithFaucet(chainId);
const faucetAddress = bnsCodec.identityToAddress(faucet);
const memo = `Payment ${Math.random()}`;
const sendTx = await connection.withDefaultFee<SendTransaction>(
{
kind: "bcp/send",
chainId: faucet.chainId,
sender: faucetAddress,
recipient: await randomBnsAddress(),
memo: memo,
amount: defaultAmount,
},
faucetAddress,
);
const nonce = await connection.getNonce({ pubkey: faucet.pubkey });
const signed = await profile.signTransaction(faucet, sendTx, bnsCodec, nonce);
const response = await connection.postTx(bnsCodec.bytesToPost(signed));
await response.blockInfo.waitFor((info) => !isBlockInfoPending(info));
const transactionId = response.transactionId;
await tendermintSearchIndexUpdated();
const result = await connection.getTx(transactionId);
assert(isConfirmedTransaction(result), "Expected ConfirmedTransaction");
const {
transaction,
signatures: [signature],
} = result;
assert(isSendTransaction(transaction), "Expected SendTransaction");
const signingJob = bnsCodec.bytesToSign(transaction, signature.nonce);
const txBytes = new Sha512(signingJob.bytes).digest();
const valid = await Ed25519.verifySignature(signature.signature, txBytes, faucet.pubkey.data);
expect(valid).toBe(true);
connection.disconnect();
});
});
describe("searchTx", () => {
it("can search for transactions by tags", async () => {
pendingWithoutBnsd();
const connection = await BnsConnection.establish(bnsdTendermintUrl);
const chainId = connection.chainId;
const { profile, faucet } = await userProfileWithFaucet(chainId);
const faucetAddress = bnsCodec.identityToAddress(faucet);
const rcptAddress = await randomBnsAddress();
// construct a sendtx, this is normally used in the MultiChainSigner api
const memo = `Payment ${Math.random()}`;
const sendTx = await connection.withDefaultFee<SendTransaction>(
{
kind: "bcp/send",
chainId: faucet.chainId,
sender: faucetAddress,
recipient: rcptAddress,
memo: memo,
amount: defaultAmount,
},
faucetAddress,
);
const nonce = await connection.getNonce({ pubkey: faucet.pubkey });
const signed = await profile.signTransaction(faucet, sendTx, bnsCodec, nonce);
const response = await connection.postTx(bnsCodec.bytesToPost(signed));
const blockInfo = await response.blockInfo.waitFor((info) => !isBlockInfoPending(info));
expect(blockInfo.state).toEqual(TransactionState.Succeeded);
await tendermintSearchIndexUpdated();
// finds transaction using tag
const results = (await connection.searchTx({ sentFromOrTo: rcptAddress })).filter(
isConfirmedAndSignedTransaction,
);
expect(results.length).toBeGreaterThanOrEqual(1);
const mostRecentResultTransaction = results[results.length - 1].transaction;
assert(isSendTransaction(mostRecentResultTransaction), "Expected SendTransaction");
expect(mostRecentResultTransaction.memo).toEqual(memo);
connection.disconnect();
});
it("can search for transactions by height", async () => {
pendingWithoutBnsd();
const connection = await BnsConnection.establish(bnsdTendermintUrl);
const chainId = connection.chainId;
const { profile, faucet } = await userProfileWithFaucet(chainId);
const faucetAddress = bnsCodec.identityToAddress(faucet);
const rcptAddress = await randomBnsAddress();
// construct a sendtx, this is normally used in the MultiChainSigner api
const memo = `Payment ${Math.random()}`;
const sendTx = await connection.withDefaultFee<SendTransaction>(
{
kind: "bcp/send",
chainId: faucet.chainId,
sender: faucetAddress,
recipient: rcptAddress,
memo: memo,
amount: defaultAmount,
},
faucetAddress,
);
const nonce = await connection.getNonce({ pubkey: faucet.pubkey });
const signed = await profile.signTransaction(faucet, sendTx, bnsCodec, nonce);
const response = await connection.postTx(bnsCodec.bytesToPost(signed));
const blockInfo = await response.blockInfo.waitFor((info) => !isBlockInfoPending(info));
expect(blockInfo.state).toBe(TransactionState.Succeeded);
const txHeight = (blockInfo as BlockInfoSucceeded | BlockInfoFailed).height;
await tendermintSearchIndexUpdated();
// finds transaction using height
const results = (await connection.searchTx({ height: txHeight })).filter(
isConfirmedAndSignedTransaction,
);
expect(results.length).toBeGreaterThanOrEqual(1);
const mostRecentResultTransaction = results[results.length - 1].transaction;
assert(isSendTransaction(mostRecentResultTransaction), "Expected SendTransaction");
expect(mostRecentResultTransaction.memo).toEqual(memo);
connection.disconnect();
});
it("can search for transactions by ID", async () => {
pendingWithoutBnsd();
const connection = await BnsConnection.establish(bnsdTendermintUrl);
const chainId = connection.chainId;
const { profile, faucet } = await userProfileWithFaucet(chainId);
const faucetAddress = bnsCodec.identityToAddress(faucet);
const memo = `Payment ${Math.random()}`;
const sendTx = await connection.withDefaultFee<SendTransaction>(
{
kind: "bcp/send",
chainId: faucet.chainId,
sender: faucetAddress,
recipient: await randomBnsAddress(),
memo: memo,
amount: defaultAmount,
},
faucetAddress,
);
const nonce = await connection.getNonce({ pubkey: faucet.pubkey });
const signed = await profile.signTransaction(faucet, sendTx, bnsCodec, nonce);
const response = await connection.postTx(bnsCodec.bytesToPost(signed));
await response.blockInfo.waitFor((info) => !isBlockInfoPending(info));
const transactionIdToSearch = response.transactionId;
await tendermintSearchIndexUpdated();
// finds transaction using id
const searchResults = (await connection.searchTx({ id: transactionIdToSearch })).filter(
isConfirmedAndSignedTransaction,
);
expect(searchResults.length).toEqual(1);
expect(searchResults[0].transactionId).toEqual(transactionIdToSearch);
const searchResultTransaction = searchResults[0].transaction;
assert(isSendTransaction(searchResultTransaction), "Expected SendTransaction");
expect(searchResultTransaction.memo).toEqual(memo);
connection.disconnect();
});
// Fixed since tendermint v0.26.4
// see issue https://github.com/tendermint/tendermint/issues/2759
it("can search for transactions by minHeight/maxHeight", async () => {
pendingWithoutBnsd();
const connection = await BnsConnection.establish(bnsdTendermintUrl);
const chainId = connection.chainId;
const initialHeight = await connection.height();
const { profile, faucet } = await userProfileWithFaucet(chainId);
const faucetAddress = bnsCodec.identityToAddress(faucet);
const recipientAddress = await randomBnsAddress();
// construct a sendtx, this is normally used in the MultiChainSigner api
const memo = `Payment ${Math.random()}`;
const sendTx = await connection.withDefaultFee<SendTransaction>(
{
kind: "bcp/send",
chainId: faucet.chainId,
sender: faucetAddress,
recipient: recipientAddress,
memo: memo,
amount: defaultAmount,
},
faucetAddress,
);
const nonce = await connection.getNonce({ pubkey: faucet.pubkey });
const signed = await profile.signTransaction(faucet, sendTx, bnsCodec, nonce);
const response = await connection.postTx(bnsCodec.bytesToPost(signed));
await response.blockInfo.waitFor((info) => !isBlockInfoPending(info));
await tendermintSearchIndexUpdated();
{
// finds transaction using sentFromOrTo and minHeight = 1
const results = (await connection.searchTx({ sentFromOrTo: recipientAddress, minHeight: 1 })).filter(
isConfirmedAndSignedTransaction,
);
expect(results.length).toBeGreaterThanOrEqual(1);
const mostRecentResultTransaction = results[results.length - 1].transaction;
assert(isSendTransaction(mostRecentResultTransaction), "Expected SendTransaction");
expect(mostRecentResultTransaction.memo).toEqual(memo);
}
{
// finds transaction using sentFromOrTo and minHeight = initialHeight
const results = (
await connection.searchTx({
sentFromOrTo: recipientAddress,
minHeight: initialHeight,
})
).filter(isConfirmedAndSignedTransaction);
expect(results.length).toBeGreaterThanOrEqual(1);
const mostRecentResultTransaction = results[results.length - 1].transaction;
assert(isSendTransaction(mostRecentResultTransaction), "Expected SendTransaction");
expect(mostRecentResultTransaction.memo).toEqual(memo);
}
{
// finds transaction using sentFromOrTo and maxHeight = 500 million
const results = (
await connection.searchTx({
sentFromOrTo: recipientAddress,
maxHeight: 500_000_000,
})
).filter(isConfirmedAndSignedTransaction);
expect(results.length).toBeGreaterThanOrEqual(1);
const mostRecentResultTransaction = results[results.length - 1].transaction;
assert(isSendTransaction(mostRecentResultTransaction), "Expected SendTransaction");
expect(mostRecentResultTransaction.memo).toEqual(memo);
}
{
// finds transaction using sentFromOrTo and maxHeight = initialHeight + 10
const results = (
await connection.searchTx({
sentFromOrTo: recipientAddress,
maxHeight: initialHeight + 10,
})
).filter(isConfirmedAndSignedTransaction);
expect(results.length).toBeGreaterThanOrEqual(1);
const mostRecentResultTransaction = results[results.length - 1].transaction;
assert(isSendTransaction(mostRecentResultTransaction), "Expected SendTransaction");
expect(mostRecentResultTransaction.memo).toEqual(memo);
}
connection.disconnect();
});
it("reports DeliverTx errors for search by ID", async () => {
pendingWithoutBnsd();
const connection = await BnsConnection.establish(bnsdTendermintUrl);
const chainId = connection.chainId;
const initialHeight = await connection.height();
const { profile, walletId } = await userProfileWithFaucet(chainId);
// this will never have tokens, but can try to sign
const brokeIdentity = await profile.createIdentity(walletId, chainId, HdPaths.iov(1234));
const brokeAddress = bnsCodec.identityToAddress(brokeIdentity);
const sendTx = await connection.withDefaultFee<SendTransaction>(
{
kind: "bcp/send",
chainId: chainId,
sender: brokeAddress,
recipient: await randomBnsAddress(),
memo: "Sending from empty",
amount: defaultAmount,
},
brokeAddress,
);
// give the broke Identity just enough to pay the fee
await sendTokensFromFaucet(connection, identityToAddress(brokeIdentity), sendTx.fee!.tokens);
const nonce = await connection.getNonce({ pubkey: brokeIdentity.pubkey });
const signed = await profile.signTransaction(brokeIdentity, sendTx, bnsCodec, nonce);
const response = await connection.postTx(bnsCodec.bytesToPost(signed));
const transactionIdToSearch = response.transactionId;
await response.blockInfo.waitFor((info) => !isBlockInfoPending(info));
await tendermintSearchIndexUpdated();
const results = await connection.searchTx({ id: transactionIdToSearch });
expect(results.length).toEqual(1);
const result = results[0];
assert(isFailedTransaction(result), "Expected FailedTransaction");
expect(result.height).toBeGreaterThan(initialHeight);
// https://github.com/iov-one/weave/blob/v0.15.0/errors/errors.go#L52
expect(result.code).toEqual(13);
expect(result.message).toMatch(/invalid amount/i);
connection.disconnect();
});
});
describe("listenTx", () => {
it("can listen to transactions by hash", (done) => {
pendingWithoutBnsd();
(async () => {
const connection = await BnsConnection.establish(bnsdTendermintUrl);
const chainId = connection.chainId;
const { profile, faucet } = await userProfileWithFaucet(chainId);
const faucetAddress = bnsCodec.identityToAddress(faucet);
const memo = `Payment ${Math.random()}`;
const sendTx = await connection.withDefaultFee<SendTransaction>(
{
kind: "bcp/send",
chainId: faucet.chainId,
sender: faucetAddress,
recipient: await randomBnsAddress(),
memo: memo,
amount: defaultAmount,
},
faucetAddress,
);
const nonce = await connection.getNonce({ pubkey: faucet.pubkey });
const signed = await profile.signTransaction(faucet, sendTx, bnsCodec, nonce);
const transactionId = bnsCodec.identifier(signed);
const heightBeforeTransaction = await connection.height();
// start listening
const subscription = connection.listenTx({ id: transactionId }).subscribe({
next: (event) => {
if (!isConfirmedTransaction(event)) {
done.fail("Confirmed transaction expected");
return;
}
expect(event.transactionId).toEqual(transactionId);
expect(event.height).toEqual(heightBeforeTransaction + 1);
subscription.unsubscribe();
connection.disconnect();
done();
},
complete: () => done.fail("Stream completed before we are done"),
error: done.fail,
});
// post transaction
await connection.postTx(bnsCodec.bytesToPost(signed));
})().catch(done.fail);
});
});
describe("liveTx", () => {
it("finds an existing transaction", async () => {
pendingWithoutBnsd();
const connection = await BnsConnection.establish(bnsdTendermintUrl);
const chainId = connection.chainId;
const { profile, faucet } = await userProfileWithFaucet(chainId);
const faucetAddress = bnsCodec.identityToAddress(faucet);
const memo = `Payment ${Math.random()}`;
const sendTx = await connection.withDefaultFee<SendTransaction>(
{
kind: "bcp/send",
chainId: faucet.chainId,
sender: faucetAddress,
recipient: await randomBnsAddress(),
memo: memo,
amount: defaultAmount,
},
faucetAddress,
);
const nonce = await connection.getNonce({ pubkey: faucet.pubkey });
const signed = await profile.signTransaction(faucet, sendTx, bnsCodec, nonce);
const response = await connection.postTx(bnsCodec.bytesToPost(signed));
const transactionIdToSearch = response.transactionId;
await response.blockInfo.waitFor((info) => !isBlockInfoPending(info));
await tendermintSearchIndexUpdated();
// finds transaction using id
const result = await firstEvent(connection.liveTx({ id: transactionIdToSearch }));
assert(isConfirmedTransaction(result), "Expected ConfirmedTransaction");
const searchResultTransaction = result.transaction;
expect(result.transactionId).toEqual(transactionIdToSearch);
assert(isSendTransaction(searchResultTransaction), "Expected SendTransaction");
expect(searchResultTransaction.memo).toEqual(memo);
connection.disconnect();
});
it("can wait for a future transaction", async () => {
pendingWithoutBnsd();
const connection = await BnsConnection.establish(bnsdTendermintUrl);
const chainId = connection.chainId;
const { profile, faucet } = await userProfileWithFaucet(chainId);
const faucetAddress = bnsCodec.identityToAddress(faucet);
const memo = `Payment ${Math.random()}`;
const sendTx = await connection.withDefaultFee<SendTransaction>(
{
kind: "bcp/send",
chainId: faucet.chainId,
sender: faucetAddress,
recipient: await randomBnsAddress(),
memo: memo,
amount: defaultAmount,
},
faucetAddress,
);
const nonce = await connection.getNonce({ pubkey: faucet.pubkey });
const signed = await profile.signTransaction(faucet, sendTx, bnsCodec, nonce);
const response = await connection.postTx(bnsCodec.bytesToPost(signed));
const transactionIdToSearch = response.transactionId;
const result = await firstEvent(connection.liveTx({ id: transactionIdToSearch }));
assert(isConfirmedTransaction(result), "Expected ConfirmedTransaction");
const searchResultTransaction = result.transaction;
expect(result.transactionId).toEqual(transactionIdToSearch);
assert(isSendTransaction(searchResultTransaction), "Expected SendTransaction");
expect(searchResultTransaction.memo).toEqual(memo);
connection.disconnect();
});
it("reports DeliverTx error for an existing transaction", async () => {
pendingWithoutBnsd();
const connection = await BnsConnection.establish(bnsdTendermintUrl);
const chainId = connection.chainId;
const initialHeight = await connection.height();
const { profile, walletId } = await userProfileWithFaucet(chainId);
// this will never have tokens, but can try to sign
const brokeIdentity = await profile.createIdentity(walletId, chainId, HdPaths.iov(1234));
const brokeAddress = bnsCodec.identityToAddress(brokeIdentity);
const sendTx = await connection.withDefaultFee<SendTransaction>(
{
kind: "bcp/send",
chainId: chainId,
sender: brokeAddress,
recipient: await randomBnsAddress(),
memo: "Sending from empty",
amount: defaultAmount,
},
brokeAddress,
);
// give the broke Identity just enough to pay the fee
await sendTokensFromFaucet(connection, identityToAddress(brokeIdentity), sendTx.fee!.tokens);
const nonce = await connection.getNonce({ pubkey: brokeIdentity.pubkey });
const signed = await profile.signTransaction(brokeIdentity, sendTx, bnsCodec, nonce);
const response = await connection.postTx(bnsCodec.bytesToPost(signed));
const transactionIdToSearch = response.transactionId;
await response.blockInfo.waitFor((info) => !isBlockInfoPending(info));
await tendermintSearchIndexUpdated();
const result = await firstEvent(connection.liveTx({ id: transactionIdToSearch }));
assert(isFailedTransaction(result), "Expected FailedTransaction");
expect(result.height).toBeGreaterThan(initialHeight);
// https://github.com/iov-one/weave/blob/v0.15.0/errors/errors.go#L52
expect(result.code).toEqual(13);
expect(result.message).toMatch(/invalid amount/i);
connection.disconnect();
});
it("reports DeliverTx error for a future transaction", async () => {
pendingWithoutBnsd();
const connection = await BnsConnection.establish(bnsdTendermintUrl);
const chainId = connection.chainId;
const { profile, walletId } = await userProfileWithFaucet(chainId);
// this will never have tokens, but can try to sign
const brokeIdentity = await profile.createIdentity(walletId, chainId, HdPaths.iov(1234));
const brokeAddress = bnsCodec.identityToAddress(brokeIdentity);
// Sending tokens from an empty account will trigger a failure in DeliverTx
const sendTx = await connection.withDefaultFee<SendTransaction>(
{
kind: "bcp/send",
chainId: chainId,
sender: brokeAddress,
recipient: await randomBnsAddress(),
memo: "Sending from empty",
amount: defaultAmount,
},
brokeAddress,
);
// give the broke Identity just enough to pay the fee
await sendTokensFromFaucet(connection, identityToAddress(brokeIdentity), sendTx.fee!.tokens);
const nonce = await connection.getNonce({ pubkey: brokeIdentity.pubkey });
const signed = await profile.signTransaction(brokeIdentity, sendTx, bnsCodec, nonce);
const response = await connection.postTx(bnsCodec.bytesToPost(signed));
const transactionIdToSearch = response.transactionId;
const result = await firstEvent(connection.liveTx({ id: transactionIdToSearch }));
assert(isFailedTransaction(result), "Expected FailedTransaction");
// https://github.com/iov-one/weave/blob/v0.15.0/errors/errors.go#L52
expect(result.code).toEqual(13);
expect(result.message).toMatch(/invalid amount/i);
connection.disconnect();
});
});
// make sure we can get a reactive account balance (as well as nonce)
it("can watch accounts", async () => {
pendingWithoutBnsd();
const connection = await BnsConnection.establish(bnsdTendermintUrl);
const { profile, faucet } = await userProfileWithFaucet(connection.chainId);
const recipientAddr = await randomBnsAddress();
// watch account by pubkey and by address
const faucetAccountStream = connection.watchAccount({ pubkey: faucet.pubkey });
const recipientAccountStream = connection.watchAccount({ address: recipientAddr });
// let's watch for all changes, capture them in a value sink
const faucetAcct = lastValue<Account | undefined>(faucetAccountStream);
const rcptAcct = lastValue<Account | undefined>(recipientAccountStream);
// give it a chance to get initial feed before checking and proceeding
await sleep(200);
// make sure there are original values sent on the wire
expect(rcptAcct.value()).toBeUndefined();
expect(faucetAcct.value()).toBeDefined();
expect(faucetAcct.value()!.balance.length).toEqual(2);
const faucetStartBalance = faucetAcct.value()!.balance.find(({ tokenTicker }) => tokenTicker === cash)!;
// send some cash
const post = await sendCash(connection, profile, faucet, recipientAddr);
await post.blockInfo.waitFor((info) => !isBlockInfoPending(info));
// give it a chance to get updates before checking and proceeding
await sleep(100);
// rcptAcct should now have a value
expect(rcptAcct.value()).toBeDefined();
expect(rcptAcct.value()!.balance.length).toEqual(1);
expect(rcptAcct.value()!.balance.find(({ tokenTicker }) => tokenTicker === cash)!.quantity).toEqual(
"68000000000",
);
// facuetAcct should have gone down a bit
expect(faucetAcct.value()).toBeDefined();
expect(faucetAcct.value()!.balance.length).toEqual(2);
const faucetEndBalance = faucetAcct.value()!.balance.find(({ tokenTicker }) => tokenTicker === cash)!;
expect(faucetEndBalance).not.toEqual(faucetStartBalance);
expect(faucetEndBalance.quantity).toEqual(
Long.fromString(faucetStartBalance.quantity)
.subtract(68_000000000)
.subtract(0_010000000) // the fee (0.01 CASH)
.toString(),
);
connection.disconnect();
});
}); | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as Models from "../models";
import * as Mappers from "../models/labAccountsMappers";
import * as Parameters from "../models/parameters";
import { ManagedLabsClientContext } from "../managedLabsClientContext";
/** Class representing a LabAccounts. */
export class LabAccounts {
private readonly client: ManagedLabsClientContext;
/**
* Create a LabAccounts.
* @param {ManagedLabsClientContext} client Reference to the service client.
*/
constructor(client: ManagedLabsClientContext) {
this.client = client;
}
/**
* List lab accounts in a subscription.
* @param [options] The optional parameters
* @returns Promise<Models.LabAccountsListBySubscriptionResponse>
*/
listBySubscription(options?: Models.LabAccountsListBySubscriptionOptionalParams): Promise<Models.LabAccountsListBySubscriptionResponse>;
/**
* @param callback The callback
*/
listBySubscription(callback: msRest.ServiceCallback<Models.ResponseWithContinuationLabAccount>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
listBySubscription(options: Models.LabAccountsListBySubscriptionOptionalParams, callback: msRest.ServiceCallback<Models.ResponseWithContinuationLabAccount>): void;
listBySubscription(options?: Models.LabAccountsListBySubscriptionOptionalParams | msRest.ServiceCallback<Models.ResponseWithContinuationLabAccount>, callback?: msRest.ServiceCallback<Models.ResponseWithContinuationLabAccount>): Promise<Models.LabAccountsListBySubscriptionResponse> {
return this.client.sendOperationRequest(
{
options
},
listBySubscriptionOperationSpec,
callback) as Promise<Models.LabAccountsListBySubscriptionResponse>;
}
/**
* List lab accounts in a resource group.
* @param resourceGroupName The name of the resource group.
* @param [options] The optional parameters
* @returns Promise<Models.LabAccountsListByResourceGroupResponse>
*/
listByResourceGroup(resourceGroupName: string, options?: Models.LabAccountsListByResourceGroupOptionalParams): Promise<Models.LabAccountsListByResourceGroupResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.ResponseWithContinuationLabAccount>): void;
/**
* @param resourceGroupName The name of the resource group.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, options: Models.LabAccountsListByResourceGroupOptionalParams, callback: msRest.ServiceCallback<Models.ResponseWithContinuationLabAccount>): void;
listByResourceGroup(resourceGroupName: string, options?: Models.LabAccountsListByResourceGroupOptionalParams | msRest.ServiceCallback<Models.ResponseWithContinuationLabAccount>, callback?: msRest.ServiceCallback<Models.ResponseWithContinuationLabAccount>): Promise<Models.LabAccountsListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
options
},
listByResourceGroupOperationSpec,
callback) as Promise<Models.LabAccountsListByResourceGroupResponse>;
}
/**
* Get lab account
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param [options] The optional parameters
* @returns Promise<Models.LabAccountsGetResponse>
*/
get(resourceGroupName: string, labAccountName: string, options?: Models.LabAccountsGetOptionalParams): Promise<Models.LabAccountsGetResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param callback The callback
*/
get(resourceGroupName: string, labAccountName: string, callback: msRest.ServiceCallback<Models.LabAccount>): void;
/**
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, labAccountName: string, options: Models.LabAccountsGetOptionalParams, callback: msRest.ServiceCallback<Models.LabAccount>): void;
get(resourceGroupName: string, labAccountName: string, options?: Models.LabAccountsGetOptionalParams | msRest.ServiceCallback<Models.LabAccount>, callback?: msRest.ServiceCallback<Models.LabAccount>): Promise<Models.LabAccountsGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
labAccountName,
options
},
getOperationSpec,
callback) as Promise<Models.LabAccountsGetResponse>;
}
/**
* Create or replace an existing Lab Account.
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labAccount Represents a lab account.
* @param [options] The optional parameters
* @returns Promise<Models.LabAccountsCreateOrUpdateResponse>
*/
createOrUpdate(resourceGroupName: string, labAccountName: string, labAccount: Models.LabAccount, options?: msRest.RequestOptionsBase): Promise<Models.LabAccountsCreateOrUpdateResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labAccount Represents a lab account.
* @param callback The callback
*/
createOrUpdate(resourceGroupName: string, labAccountName: string, labAccount: Models.LabAccount, callback: msRest.ServiceCallback<Models.LabAccount>): void;
/**
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labAccount Represents a lab account.
* @param options The optional parameters
* @param callback The callback
*/
createOrUpdate(resourceGroupName: string, labAccountName: string, labAccount: Models.LabAccount, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.LabAccount>): void;
createOrUpdate(resourceGroupName: string, labAccountName: string, labAccount: Models.LabAccount, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.LabAccount>, callback?: msRest.ServiceCallback<Models.LabAccount>): Promise<Models.LabAccountsCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
labAccountName,
labAccount,
options
},
createOrUpdateOperationSpec,
callback) as Promise<Models.LabAccountsCreateOrUpdateResponse>;
}
/**
* Delete lab account. This operation can take a while to complete
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(resourceGroupName: string, labAccountName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> {
return this.beginDeleteMethod(resourceGroupName,labAccountName,options)
.then(lroPoller => lroPoller.pollUntilFinished());
}
/**
* Modify properties of lab accounts.
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labAccount Represents a lab account.
* @param [options] The optional parameters
* @returns Promise<Models.LabAccountsUpdateResponse>
*/
update(resourceGroupName: string, labAccountName: string, labAccount: Models.LabAccountFragment, options?: msRest.RequestOptionsBase): Promise<Models.LabAccountsUpdateResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labAccount Represents a lab account.
* @param callback The callback
*/
update(resourceGroupName: string, labAccountName: string, labAccount: Models.LabAccountFragment, callback: msRest.ServiceCallback<Models.LabAccount>): void;
/**
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labAccount Represents a lab account.
* @param options The optional parameters
* @param callback The callback
*/
update(resourceGroupName: string, labAccountName: string, labAccount: Models.LabAccountFragment, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.LabAccount>): void;
update(resourceGroupName: string, labAccountName: string, labAccount: Models.LabAccountFragment, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.LabAccount>, callback?: msRest.ServiceCallback<Models.LabAccount>): Promise<Models.LabAccountsUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
labAccountName,
labAccount,
options
},
updateOperationSpec,
callback) as Promise<Models.LabAccountsUpdateResponse>;
}
/**
* Create a lab in a lab account.
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param createLabProperties Properties for creating a managed lab and a default environment
* setting
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
createLab(resourceGroupName: string, labAccountName: string, createLabProperties: Models.CreateLabProperties, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param createLabProperties Properties for creating a managed lab and a default environment
* setting
* @param callback The callback
*/
createLab(resourceGroupName: string, labAccountName: string, createLabProperties: Models.CreateLabProperties, callback: msRest.ServiceCallback<void>): void;
/**
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param createLabProperties Properties for creating a managed lab and a default environment
* setting
* @param options The optional parameters
* @param callback The callback
*/
createLab(resourceGroupName: string, labAccountName: string, createLabProperties: Models.CreateLabProperties, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
createLab(resourceGroupName: string, labAccountName: string, createLabProperties: Models.CreateLabProperties, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
labAccountName,
createLabProperties,
options
},
createLabOperationSpec,
callback);
}
/**
* Get regional availability information for each size category configured under a lab account
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param [options] The optional parameters
* @returns Promise<Models.LabAccountsGetRegionalAvailabilityResponse>
*/
getRegionalAvailability(resourceGroupName: string, labAccountName: string, options?: msRest.RequestOptionsBase): Promise<Models.LabAccountsGetRegionalAvailabilityResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param callback The callback
*/
getRegionalAvailability(resourceGroupName: string, labAccountName: string, callback: msRest.ServiceCallback<Models.GetRegionalAvailabilityResponse>): void;
/**
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param options The optional parameters
* @param callback The callback
*/
getRegionalAvailability(resourceGroupName: string, labAccountName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.GetRegionalAvailabilityResponse>): void;
getRegionalAvailability(resourceGroupName: string, labAccountName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.GetRegionalAvailabilityResponse>, callback?: msRest.ServiceCallback<Models.GetRegionalAvailabilityResponse>): Promise<Models.LabAccountsGetRegionalAvailabilityResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
labAccountName,
options
},
getRegionalAvailabilityOperationSpec,
callback) as Promise<Models.LabAccountsGetRegionalAvailabilityResponse>;
}
/**
* Delete lab account. This operation can take a while to complete
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginDeleteMethod(resourceGroupName: string, labAccountName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
labAccountName,
options
},
beginDeleteMethodOperationSpec,
options);
}
/**
* List lab accounts in a subscription.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.LabAccountsListBySubscriptionNextResponse>
*/
listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.LabAccountsListBySubscriptionNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listBySubscriptionNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ResponseWithContinuationLabAccount>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listBySubscriptionNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ResponseWithContinuationLabAccount>): void;
listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ResponseWithContinuationLabAccount>, callback?: msRest.ServiceCallback<Models.ResponseWithContinuationLabAccount>): Promise<Models.LabAccountsListBySubscriptionNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listBySubscriptionNextOperationSpec,
callback) as Promise<Models.LabAccountsListBySubscriptionNextResponse>;
}
/**
* List lab accounts in a resource group.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.LabAccountsListByResourceGroupNextResponse>
*/
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.LabAccountsListByResourceGroupNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ResponseWithContinuationLabAccount>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ResponseWithContinuationLabAccount>): void;
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ResponseWithContinuationLabAccount>, callback?: msRest.ServiceCallback<Models.ResponseWithContinuationLabAccount>): Promise<Models.LabAccountsListByResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByResourceGroupNextOperationSpec,
callback) as Promise<Models.LabAccountsListByResourceGroupNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listBySubscriptionOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.LabServices/labaccounts",
urlParameters: [
Parameters.subscriptionId
],
queryParameters: [
Parameters.expand,
Parameters.filter,
Parameters.top,
Parameters.orderby,
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ResponseWithContinuationLabAccount
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listByResourceGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.expand,
Parameters.filter,
Parameters.top,
Parameters.orderby,
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ResponseWithContinuationLabAccount
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.labAccountName
],
queryParameters: [
Parameters.expand,
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.LabAccount
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const createOrUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.labAccountName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "labAccount",
mapper: {
...Mappers.LabAccount,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.LabAccount
},
201: {
bodyMapper: Mappers.LabAccount
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const updateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.labAccountName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "labAccount",
mapper: {
...Mappers.LabAccountFragment,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.LabAccount
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const createLabOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/createLab",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.labAccountName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "createLabProperties",
mapper: {
...Mappers.CreateLabProperties,
required: true
}
},
responses: {
200: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const getRegionalAvailabilityOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/getRegionalAvailability",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.labAccountName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.GetRegionalAvailabilityResponse
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginDeleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.labAccountName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
202: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listBySubscriptionNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ResponseWithContinuationLabAccount
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listByResourceGroupNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ResponseWithContinuationLabAccount
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
}; | the_stack |
import useHandler from "./useHandler";
import { ApwContentTypes } from "~/types";
import {
ApwScheduleAction,
ApwScheduleActionCrud,
ApwScheduleActionTypes
} from "~/scheduler/types";
const ONE_MINUTE = 1000 * 60;
const TIME_SEPARATOR = ":";
const getIsoStringTillMinutes = (datetime: string): string => {
// "2022-03-08T05:41:13.230Z"
return datetime.slice(0, datetime.lastIndexOf(TIME_SEPARATOR));
};
const EXPECTED_APW_SCHEDULED_ACTION_DATA = expect.objectContaining({
datetime: expect.stringMatching(/^20/),
type: "page",
action: "publish",
entryId: expect.any(String)
});
describe("Schedule action CRUD Test", () => {
const { handler } = useHandler();
test("Should able to create, update, list, get and delete schedule action items", async () => {
const context = await handler();
const scheduleActionCrud: ApwScheduleActionCrud = context.scheduleAction;
/**
* Let's create one schedule action item.
*/
const scheduledAction = await scheduleActionCrud.create({
datetime: new Date().toISOString(),
action: ApwScheduleActionTypes.PUBLISH,
type: ApwContentTypes.PAGE,
entryId: "62303be79cfe6e0009d8d9cf#0001"
});
expect(scheduledAction).toEqual({
id: expect.any(String),
createdOn: expect.stringMatching(/^20/),
savedOn: expect.stringMatching(/^20/),
createdBy: expect.any(Object),
tenant: expect.any(String),
locale: expect.any(String),
data: EXPECTED_APW_SCHEDULED_ACTION_DATA
});
/**
* Should able to get schedule action item by id.
*/
const getItemResult = await scheduleActionCrud.get(scheduledAction.id);
expect(getItemResult).toEqual({
id: expect.any(String),
createdOn: expect.stringMatching(/^20/),
savedOn: expect.stringMatching(/^20/),
createdBy: expect.any(Object),
tenant: expect.any(String),
locale: expect.any(String),
data: EXPECTED_APW_SCHEDULED_ACTION_DATA
});
/**
* Should able to list schedule action items.
*/
const [listItemResult, meta] = await scheduleActionCrud.list({ where: {} });
expect(listItemResult).toEqual([
{
id: expect.any(String),
createdOn: expect.stringMatching(/^20/),
savedOn: expect.stringMatching(/^20/),
createdBy: expect.any(Object),
tenant: expect.any(String),
locale: expect.any(String),
data: EXPECTED_APW_SCHEDULED_ACTION_DATA
}
]);
expect(meta).toEqual({
hasMoreItems: false,
totalCount: 1,
cursor: expect.any(String)
});
/**
* Doing partial update should return an error.
*/
let updateItemResultWithError;
try {
// @ts-ignore
updateItemResultWithError = await scheduleActionCrud.update(scheduledAction.id, {
action: ApwScheduleActionTypes.UNPUBLISH
});
} catch (e) {
expect(e.message).toBe("Validation failed.");
expect(updateItemResultWithError).toBe(undefined);
}
/**
* Should able to update a schedule action item.
*/
const updateItemResult = await scheduleActionCrud.update(scheduledAction.id, {
datetime: new Date().toISOString(),
action: ApwScheduleActionTypes.UNPUBLISH,
type: ApwContentTypes.PAGE,
entryId: "62303be79cfe6e0009d8d9cf#0001"
});
expect(updateItemResult).toEqual({
id: expect.any(String),
createdOn: expect.stringMatching(/^20/),
savedOn: expect.stringMatching(/^20/),
createdBy: expect.any(Object),
tenant: expect.any(String),
locale: expect.any(String),
data: EXPECTED_APW_SCHEDULED_ACTION_DATA
});
/**
* Should able to delete a schedule action item by id.
*/
const deleteItemResult = await scheduleActionCrud.delete(scheduledAction.id);
expect(deleteItemResult).toBe(true);
/**
* Should not be able to get schedule action item by id.
*/
const notFoundResult = await scheduleActionCrud.get(scheduledAction.id);
expect(notFoundResult).toBe(null);
/**
* Should return empty list in case of no schedule action items.
*/
const [listItemEmptyResult, listItemEmptyMeta] = await scheduleActionCrud.list({
where: {}
});
expect(listItemEmptyResult).toEqual([]);
expect(listItemEmptyMeta).toEqual({
hasMoreItems: false,
totalCount: 0,
cursor: null
});
});
test("Should able to sort schedule action items by datetime", async () => {
const context = await handler();
const scheduleActionCrud: ApwScheduleActionCrud = context.scheduleAction;
/**
* Let's create five schedule action item.
*/
const scheduledActions = [];
for (let i = 0; i < 5; i++) {
const now = new Date().getTime() + 1000;
const scheduledAction = await scheduleActionCrud.create({
datetime: new Date(now).toISOString(),
action: ApwScheduleActionTypes.PUBLISH,
type: ApwContentTypes.PAGE,
entryId: "62303be79cfe6e0009d8d9cf#0001"
});
scheduledActions.push(scheduledAction);
}
/**
* Should able to list schedule action items.
*/
const [listItemResult, meta] = await scheduleActionCrud.list({ where: {} });
expect(listItemResult).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: expect.any(String),
createdOn: expect.stringMatching(/^20/),
savedOn: expect.stringMatching(/^20/),
createdBy: expect.any(Object),
tenant: expect.any(String),
locale: expect.any(String),
data: EXPECTED_APW_SCHEDULED_ACTION_DATA
})
])
);
expect(meta).toEqual({
hasMoreItems: false,
totalCount: 5,
cursor: expect.any(String)
});
/**
* Sorted by datetime(ISO string) in ascending order.
*/
for (let i = 0; i < listItemResult.length - 1; i++) {
const currentItem = listItemResult[i];
const nextItem = listItemResult[i + 1];
expect(currentItem.data.datetime < nextItem.data.datetime).toBe(true);
}
/**
* Should able to list schedule action items in descending order of datetime.
*/
const [listItemDescendingResult, listItemDescendingMeta] = await scheduleActionCrud.list({
where: {},
sort: ["datetime_DESC"]
});
expect(listItemDescendingResult).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: expect.any(String),
createdOn: expect.stringMatching(/^20/),
savedOn: expect.stringMatching(/^20/),
createdBy: expect.any(Object),
tenant: expect.any(String),
locale: expect.any(String),
data: EXPECTED_APW_SCHEDULED_ACTION_DATA
})
])
);
expect(listItemDescendingMeta).toEqual({
hasMoreItems: false,
totalCount: 5,
cursor: expect.any(String)
});
/**
* Sorted by datetime(ISO string) in ascending order.
*/
for (let i = 0; i < listItemDescendingResult.length - 1; i++) {
const currentItem = listItemDescendingResult[i];
const nextItem = listItemDescendingResult[i + 1];
expect(currentItem.data.datetime > nextItem.data.datetime).toBe(true);
}
});
test("Should able to get all schedule action items with same datetime", async () => {
const context = await handler();
const scheduleActionCrud: ApwScheduleActionCrud = context.scheduleAction;
/**
* Let's create five schedule action item.
*/
const scheduledActions: ApwScheduleAction[] = [];
for (let i = 0; i < 5; i++) {
let now = new Date().getTime();
if (i % 2 === 0) {
now += ONE_MINUTE;
}
const scheduledAction = await scheduleActionCrud.create({
datetime: new Date(now).toISOString(),
action: ApwScheduleActionTypes.PUBLISH,
type: ApwContentTypes.PAGE,
entryId: "62303be79cfe6e0009d8d9cf#0001"
});
scheduledActions.push(scheduledAction);
}
const [firstAction, secondAction] = scheduledActions;
const firstDateTime = getIsoStringTillMinutes(firstAction.data.datetime);
const secondDateTime = getIsoStringTillMinutes(secondAction.data.datetime);
/**
* Should able to list schedule action items by datetime.
*/
const [listItemFirstDateResult] = await scheduleActionCrud.list({
where: { datetime_startsWith: firstDateTime }
});
expect(listItemFirstDateResult).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: expect.any(String),
createdOn: expect.stringMatching(/^20/),
savedOn: expect.stringMatching(/^20/),
createdBy: expect.any(Object),
tenant: expect.any(String),
locale: expect.any(String),
data: EXPECTED_APW_SCHEDULED_ACTION_DATA
})
])
);
expect(listItemFirstDateResult.length).toBe(3);
/**
* Should able to list schedule action items datetime.
*/
const [listItemSecondDateResult] = await scheduleActionCrud.list({
where: { datetime_startsWith: secondDateTime }
});
expect(listItemSecondDateResult).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: expect.any(String),
createdOn: expect.stringMatching(/^20/),
savedOn: expect.stringMatching(/^20/),
createdBy: expect.any(Object),
tenant: expect.any(String),
locale: expect.any(String),
data: EXPECTED_APW_SCHEDULED_ACTION_DATA
})
])
);
expect(listItemSecondDateResult.length).toBe(2);
});
test("Should able to get and update current schedule action item", async () => {
const context = await handler();
const scheduleActionCrud: ApwScheduleActionCrud = context.scheduleAction;
/**
* Let's create two schedule action item.
*/
const TOTAL = 2;
const scheduledActions: ApwScheduleAction[] = [];
for (let i = 0; i < TOTAL; i++) {
let now = new Date().getTime();
if (i % 2 === 0) {
now += ONE_MINUTE;
}
const scheduledAction = await scheduleActionCrud.create({
datetime: new Date(now).toISOString(),
action: ApwScheduleActionTypes.PUBLISH,
type: ApwContentTypes.PAGE,
entryId: "62303be79cfe6e0009d8d9cf#0001"
});
scheduledActions.push(scheduledAction);
}
/**
* Should able to list schedule action items by datetime.
*/
const [listItemResult] = await scheduleActionCrud.list({
where: {}
});
expect(listItemResult).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: expect.any(String),
createdOn: expect.stringMatching(/^20/),
savedOn: expect.stringMatching(/^20/),
createdBy: expect.any(Object),
tenant: expect.any(String),
locale: expect.any(String),
data: EXPECTED_APW_SCHEDULED_ACTION_DATA
})
])
);
expect(listItemResult.length).toBe(TOTAL);
/**
* Should return null as currentTask
*/
const currentTaskNull = await scheduleActionCrud.getCurrentTask();
expect(currentTaskNull).toBe(null);
const [firstAction, secondAction] = scheduledActions;
/**
* Let's set the currentTask for the very first time.
*/
await scheduleActionCrud.updateCurrentTask(firstAction);
/**
* Now we should have it.
*/
const currentTaskFirstAction = await scheduleActionCrud.getCurrentTask();
if (currentTaskFirstAction) {
expect(currentTaskFirstAction.id).toBe(firstAction.id);
}
/**
* Let's set the currentTask for the very first time.
*/
await scheduleActionCrud.updateCurrentTask(secondAction);
/**
* Now we should have it.
*/
const currentTaskSecondAction = await scheduleActionCrud.getCurrentTask();
if (currentTaskSecondAction) {
expect(currentTaskSecondAction.id).toBe(secondAction.id);
}
/**
* Let's delete the current task.
*/
const deleteCurrentTask = await scheduleActionCrud.deleteCurrentTask();
expect(deleteCurrentTask).toBe(true);
/**
* Now we should not have it.
*/
const currentTaskNoTasks = await scheduleActionCrud.getCurrentTask();
expect(currentTaskNoTasks).toBe(null);
});
}); | the_stack |
import { MathTmp } from './preallocatedVariables'
import { FloatArray, Epsilon } from './types'
import { Matrix } from './Matrix'
import { Quaternion } from './Quaternion'
import { Scalar } from './Scalar'
/** @public */
export type ReadOnlyVector3 = {
readonly y: number
readonly x: number
readonly z: number
}
/**
* Classed used to store (x,y,z) vector representation
* A Vector3 is the main object used in 3D geometry
* It can represent etiher the coordinates of a point the space, either a direction
* Reminder: Babylon.js uses a left handed forward facing system
* @public
*/
export class Vector3 {
/**
* Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
*/
public get isNonUniform(): boolean {
let absX = Math.abs(this.x)
let absY = Math.abs(this.y)
if (absX !== absY) {
return true
}
let absZ = Math.abs(this.z)
if (absX !== absZ) {
return true
}
if (absY !== absZ) {
return true
}
return false
}
/**
* Creates a new Vector3 object from the given x, y, z (floats) coordinates.
* @param x - defines the first coordinates (on X axis)
* @param y - defines the second coordinates (on Y axis)
* @param z - defines the third coordinates (on Z axis)
*/
constructor(
/**
* Defines the first coordinates (on X axis)
*/
public x: number = 0,
/**
* Defines the second coordinates (on Y axis)
*/
public y: number = 0,
/**
* Defines the third coordinates (on Z axis)
*/
public z: number = 0
) {}
// Statics
/**
* Returns a new Vector3 as the result of the addition of the two given vectors.
* @param vector1 - the first vector
* @param vector2 - the second vector
* @returns the resulting vector
*/
public static Add(vector1: ReadOnlyVector3, vector2: ReadOnlyVector3): Vector3 {
return new Vector3(vector1.x, vector1.y, vector1.z).addInPlace(vector2)
}
/**
* Get the clip factor between two vectors
* @param vector0 - defines the first operand
* @param vector1 - defines the second operand
* @param axis - defines the axis to use
* @param size - defines the size along the axis
* @returns the clip factor
*/
public static GetClipFactor(vector0: ReadOnlyVector3, vector1: ReadOnlyVector3, axis: ReadOnlyVector3, size: number) {
let d0 = Vector3.Dot(vector0, axis) - size
let d1 = Vector3.Dot(vector1, axis) - size
let s = d0 / (d0 - d1)
return s
}
/**
* Get angle between two vectors
* @param vector0 - angle between vector0 and vector1
* @param vector1 - angle between vector0 and vector1
* @param normal - direction of the normal
* @returns the angle between vector0 and vector1
*/
public static GetAngleBetweenVectors(vector0: Vector3, vector1: Vector3, normal: ReadOnlyVector3): number {
const v0: Vector3 = vector0.normalizeToRef(MathTmp.Vector3[1])
const v1: Vector3 = vector1.normalizeToRef(MathTmp.Vector3[2])
const dot: number = Vector3.Dot(v0, v1)
const n = MathTmp.Vector3[3]
Vector3.CrossToRef(v0, v1, n)
if (Vector3.Dot(n, normal) > 0) {
return Math.acos(dot)
}
return -Math.acos(dot)
}
/**
* Returns a new Vector3 set from the index "offset" of the given array
* @param array - defines the source array
* @param offset - defines the offset in the source array
* @returns the new Vector3
*/
public static FromArray(array: ArrayLike<number>, offset: number = 0): Vector3 {
return new Vector3(array[offset], array[offset + 1], array[offset + 2])
}
/**
* Returns a new Vector3 set from the index "offset" of the given FloatArray
* This function is deprecated. Use FromArray instead
* @param array - defines the source array
* @param offset - defines the offset in the source array
* @returns the new Vector3
*/
public static FromFloatArray(array: FloatArray, offset?: number): Vector3 {
return Vector3.FromArray(array, offset)
}
/**
* Sets the given vector "result" with the element values from the index "offset" of the given array
* @param array - defines the source array
* @param offset - defines the offset in the source array
* @param result - defines the Vector3 where to store the result
*/
public static FromArrayToRef(array: ArrayLike<number>, offset: number, result: Vector3): void {
result.x = array[offset]
result.y = array[offset + 1]
result.z = array[offset + 2]
}
/**
* Sets the given vector "result" with the element values from the index "offset" of the given FloatArray
* This function is deprecated. Use FromArrayToRef instead.
* @param array - defines the source array
* @param offset - defines the offset in the source array
* @param result - defines the Vector3 where to store the result
*/
public static FromFloatArrayToRef(array: FloatArray, offset: number, result: Vector3): void {
return Vector3.FromArrayToRef(array, offset, result)
}
/**
* Sets the given vector "result" with the given floats.
* @param x - defines the x coordinate of the source
* @param y - defines the y coordinate of the source
* @param z - defines the z coordinate of the source
* @param result - defines the Vector3 where to store the result
*/
public static FromFloatsToRef(x: number, y: number, z: number, result: Vector3): void {
result.copyFromFloats(x, y, z)
}
/**
* Returns a new Vector3 set to (0.0, 0.0, 0.0)
* @returns a new empty Vector3
*/
public static Zero(): Vector3 {
return new Vector3(0.0, 0.0, 0.0)
}
/**
* Returns a new Vector3 set to (1.0, 1.0, 1.0)
* @returns a new unit Vector3
*/
public static One(): Vector3 {
return new Vector3(1.0, 1.0, 1.0)
}
/**
* Returns a new Vector3 set to (0.0, 1.0, 0.0)
* @returns a new up Vector3
*/
public static Up(): Vector3 {
return new Vector3(0.0, 1.0, 0.0)
}
/**
* Returns a new Vector3 set to (0.0, -1.0, 0.0)
* @returns a new down Vector3
*/
public static Down(): Vector3 {
return new Vector3(0.0, -1.0, 0.0)
}
/**
* Returns a new Vector3 set to (0.0, 0.0, 1.0)
* @returns a new forward Vector3
*/
public static Forward(): Vector3 {
return new Vector3(0.0, 0.0, 1.0)
}
/**
* Returns a new Vector3 set to (0.0, 0.0, -1.0)
* @returns a new forward Vector3
*/
public static Backward(): Vector3 {
return new Vector3(0.0, 0.0, -1.0)
}
/**
* Returns a new Vector3 set to (1.0, 0.0, 0.0)
* @returns a new right Vector3
*/
public static Right(): Vector3 {
return new Vector3(1.0, 0.0, 0.0)
}
/**
* Returns a new Vector3 set to (-1.0, 0.0, 0.0)
* @returns a new left Vector3
*/
public static Left(): Vector3 {
return new Vector3(-1.0, 0.0, 0.0)
}
/**
* Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
* This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
* @param vector - defines the Vector3 to transform
* @param transformation - defines the transformation matrix
* @returns the transformed Vector3
*/
public static TransformCoordinates(vector: ReadOnlyVector3, transformation: Matrix): Vector3 {
let result = Vector3.Zero()
Vector3.TransformCoordinatesToRef(vector, transformation, result)
return result
}
/**
* Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
* This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
* @param vector - defines the Vector3 to transform
* @param transformation - defines the transformation matrix
* @param result - defines the Vector3 where to store the result
*/
public static TransformCoordinatesToRef(
vector: ReadOnlyVector3,
transformation: Readonly<Matrix>,
result: Vector3
): void {
return Vector3.TransformCoordinatesFromFloatsToRef(vector.x, vector.y, vector.z, transformation, result)
}
/**
* Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
* This method computes tranformed coordinates only, not transformed direction vectors
* @param x - define the x coordinate of the source vector
* @param y - define the y coordinate of the source vector
* @param z - define the z coordinate of the source vector
* @param transformation - defines the transformation matrix
* @param result - defines the Vector3 where to store the result
*/
public static TransformCoordinatesFromFloatsToRef(
x: number,
y: number,
z: number,
transformation: Readonly<Matrix>,
result: Vector3
): void {
const m = transformation.m
let rx = x * m[0] + y * m[4] + z * m[8] + m[12]
let ry = x * m[1] + y * m[5] + z * m[9] + m[13]
let rz = x * m[2] + y * m[6] + z * m[10] + m[14]
let rw = 1 / (x * m[3] + y * m[7] + z * m[11] + m[15])
result.x = rx * rw
result.y = ry * rw
result.z = rz * rw
}
/**
* Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
* This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
* @param vector - defines the Vector3 to transform
* @param transformation - defines the transformation matrix
* @returns the new Vector3
*/
public static TransformNormal(vector: ReadOnlyVector3, transformation: Matrix): Vector3 {
let result = Vector3.Zero()
Vector3.TransformNormalToRef(vector, transformation, result)
return result
}
/**
* Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
* This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
* @param vector - defines the Vector3 to transform
* @param transformation - defines the transformation matrix
* @param result - defines the Vector3 where to store the result
*/
public static TransformNormalToRef(vector: ReadOnlyVector3, transformation: Readonly<Matrix>, result: Vector3): void {
this.TransformNormalFromFloatsToRef(vector.x, vector.y, vector.z, transformation, result)
}
/**
* Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
* This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
* @param x - define the x coordinate of the source vector
* @param y - define the y coordinate of the source vector
* @param z - define the z coordinate of the source vector
* @param transformation - defines the transformation matrix
* @param result - defines the Vector3 where to store the result
*/
public static TransformNormalFromFloatsToRef(
x: number,
y: number,
z: number,
transformation: Readonly<Matrix>,
result: Vector3
): void {
const m = transformation.m
result.x = x * m[0] + y * m[4] + z * m[8]
result.y = x * m[1] + y * m[5] + z * m[9]
result.z = x * m[2] + y * m[6] + z * m[10]
}
/**
* Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
* @param value1 - defines the first control point
* @param value2 - defines the second control point
* @param value3 - defines the third control point
* @param value4 - defines the fourth control point
* @param amount - defines the amount on the spline to use
* @returns the new Vector3
*/
public static CatmullRom(
value1: ReadOnlyVector3,
value2: ReadOnlyVector3,
value3: ReadOnlyVector3,
value4: ReadOnlyVector3,
amount: number
): Vector3 {
let squared = amount * amount
let cubed = amount * squared
let x =
0.5 *
(2.0 * value2.x +
(-value1.x + value3.x) * amount +
(2.0 * value1.x - 5.0 * value2.x + 4.0 * value3.x - value4.x) * squared +
(-value1.x + 3.0 * value2.x - 3.0 * value3.x + value4.x) * cubed)
let y =
0.5 *
(2.0 * value2.y +
(-value1.y + value3.y) * amount +
(2.0 * value1.y - 5.0 * value2.y + 4.0 * value3.y - value4.y) * squared +
(-value1.y + 3.0 * value2.y - 3.0 * value3.y + value4.y) * cubed)
let z =
0.5 *
(2.0 * value2.z +
(-value1.z + value3.z) * amount +
(2.0 * value1.z - 5.0 * value2.z + 4.0 * value3.z - value4.z) * squared +
(-value1.z + 3.0 * value2.z - 3.0 * value3.z + value4.z) * cubed)
return new Vector3(x, y, z)
}
/**
* Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
* If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
* If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
* @param value - defines the current value
* @param min - defines the lower range value
* @param max - defines the upper range value
* @returns the new Vector3
*/
public static Clamp(value: ReadOnlyVector3, min: ReadOnlyVector3, max: ReadOnlyVector3): Vector3 {
const v = new Vector3()
Vector3.ClampToRef(value, min, max, v)
return v
}
/**
* Sets the given vector "result" with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
* If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
* If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
* @param value - defines the current value
* @param min - defines the lower range value
* @param max - defines the upper range value
* @param result - defines the Vector3 where to store the result
*/
public static ClampToRef(value: ReadOnlyVector3, min: ReadOnlyVector3, max: ReadOnlyVector3, result: Vector3): void {
let x = value.x
x = x > max.x ? max.x : x
x = x < min.x ? min.x : x
let y = value.y
y = y > max.y ? max.y : y
y = y < min.y ? min.y : y
let z = value.z
z = z > max.z ? max.z : z
z = z < min.z ? min.z : z
result.copyFromFloats(x, y, z)
}
/**
* Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
* @param value1 - defines the first control point
* @param tangent1 - defines the first tangent vector
* @param value2 - defines the second control point
* @param tangent2 - defines the second tangent vector
* @param amount - defines the amount on the interpolation spline (between 0 and 1)
* @returns the new Vector3
*/
public static Hermite(
value1: ReadOnlyVector3,
tangent1: ReadOnlyVector3,
value2: ReadOnlyVector3,
tangent2: ReadOnlyVector3,
amount: number
): Vector3 {
let squared = amount * amount
let cubed = amount * squared
let part1 = 2.0 * cubed - 3.0 * squared + 1.0
let part2 = -2.0 * cubed + 3.0 * squared
let part3 = cubed - 2.0 * squared + amount
let part4 = cubed - squared
let x = value1.x * part1 + value2.x * part2 + tangent1.x * part3 + tangent2.x * part4
let y = value1.y * part1 + value2.y * part2 + tangent1.y * part3 + tangent2.y * part4
let z = value1.z * part1 + value2.z * part2 + tangent1.z * part3 + tangent2.z * part4
return new Vector3(x, y, z)
}
/**
* Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
* @param start - defines the start value
* @param end - defines the end value
* @param amount - max defines amount between both (between 0 and 1)
* @returns the new Vector3
*/
public static Lerp(start: ReadOnlyVector3, end: ReadOnlyVector3, amount: number): Vector3 {
let result = new Vector3(0, 0, 0)
Vector3.LerpToRef(start, end, amount, result)
return result
}
/**
* Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
* @param start - defines the start value
* @param end - defines the end value
* @param amount - max defines amount between both (between 0 and 1)
* @param result - defines the Vector3 where to store the result
*/
public static LerpToRef(start: ReadOnlyVector3, end: ReadOnlyVector3, amount: number, result: Vector3): void {
result.x = start.x + (end.x - start.x) * amount
result.y = start.y + (end.y - start.y) * amount
result.z = start.z + (end.z - start.z) * amount
}
/**
* Returns the dot product (float) between the vectors "left" and "right"
* @param left - defines the left operand
* @param right - defines the right operand
* @returns the dot product
*/
public static Dot(left: ReadOnlyVector3, right: ReadOnlyVector3): number {
return left.x * right.x + left.y * right.y + left.z * right.z
}
/**
* Returns a new Vector3 as the cross product of the vectors "left" and "right"
* The cross product is then orthogonal to both "left" and "right"
* @param left - defines the left operand
* @param right - defines the right operand
* @returns the cross product
*/
public static Cross(left: ReadOnlyVector3, right: ReadOnlyVector3): Vector3 {
let result = Vector3.Zero()
Vector3.CrossToRef(left, right, result)
return result
}
/**
* Sets the given vector "result" with the cross product of "left" and "right"
* The cross product is then orthogonal to both "left" and "right"
* @param left - defines the left operand
* @param right - defines the right operand
* @param result - defines the Vector3 where to store the result
*/
public static CrossToRef(left: ReadOnlyVector3, right: ReadOnlyVector3, result: Vector3): void {
const x = left.y * right.z - left.z * right.y
const y = left.z * right.x - left.x * right.z
const z = left.x * right.y - left.y * right.x
result.copyFromFloats(x, y, z)
}
/**
* Returns a new Vector3 as the normalization of the given vector
* @param vector - defines the Vector3 to normalize
* @returns the new Vector3
*/
public static Normalize(vector: Vector3): Vector3 {
let result = Vector3.Zero()
Vector3.NormalizeToRef(vector, result)
return result
}
/**
* Sets the given vector "result" with the normalization of the given first vector
* @param vector - defines the Vector3 to normalize
* @param result - defines the Vector3 where to store the result
*/
public static NormalizeToRef(vector: Vector3, result: Vector3): void {
vector.normalizeToRef(result)
}
/**
* Gets the minimal coordinate values between two Vector3
* @param left - defines the first operand
* @param right - defines the second operand
* @returns the new Vector3
*/
public static Minimize(left: ReadOnlyVector3, right: ReadOnlyVector3): Vector3 {
let min = new Vector3(left.x, left.y, left.z)
min.minimizeInPlace(right)
return min
}
/**
* Gets the maximal coordinate values between two Vector3
* @param left - defines the first operand
* @param right - defines the second operand
* @returns the new Vector3
*/
public static Maximize(left: Vector3, right: Vector3): Vector3 {
let max = new Vector3(left.x, left.y, left.z)
max.maximizeInPlace(right)
return max
}
/**
* Returns the distance between the vectors "value1" and "value2"
* @param value1 - defines the first operand
* @param value2 - defines the second operand
* @returns the distance
*/
public static Distance(value1: ReadOnlyVector3, value2: ReadOnlyVector3): number {
return Math.sqrt(Vector3.DistanceSquared(value1, value2))
}
/**
* Returns the squared distance between the vectors "value1" and "value2"
* @param value1 - defines the first operand
* @param value2 - defines the second operand
* @returns the squared distance
*/
public static DistanceSquared(value1: ReadOnlyVector3, value2: ReadOnlyVector3): number {
let x = value1.x - value2.x
let y = value1.y - value2.y
let z = value1.z - value2.z
return x * x + y * y + z * z
}
/**
* Returns a new Vector3 located at the center between "value1" and "value2"
* @param value1 - defines the first operand
* @param value2 - defines the second operand
* @returns the new Vector3
*/
public static Center(value1: ReadOnlyVector3, value2: ReadOnlyVector3): Vector3 {
let center = Vector3.Add(value1, value2)
center.scaleInPlace(0.5)
return center
}
/**
* Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
* RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
* to something in order to rotate it from its local system to the given target system
* Note: axis1, axis2 and axis3 are normalized during this operation
* @param axis1 - defines the first axis
* @param axis2 - defines the second axis
* @param axis3 - defines the third axis
* @returns a new Vector3
*/
public static RotationFromAxis(axis1: Vector3, axis2: Vector3, axis3: Vector3): Vector3 {
let rotation = Vector3.Zero()
Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation)
return rotation
}
/**
* The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
* @param axis1 - defines the first axis
* @param axis2 - defines the second axis
* @param axis3 - defines the third axis
* @param ref - defines the Vector3 where to store the result
*/
public static RotationFromAxisToRef(axis1: Vector3, axis2: Vector3, axis3: Vector3, ref: Vector3): void {
let quat = MathTmp.Quaternion[0]
Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat)
ref.copyFrom(quat.eulerAngles)
}
/**
* Creates a string representation of the Vector3
* @returns a string with the Vector3 coordinates.
*/
public toString(): string {
return `(${this.x}, ${this.y}, ${this.z})`
}
/**
* Gets the class name
* @returns the string "Vector3"
*/
public getClassName(): string {
return 'Vector3'
}
/**
* Creates the Vector3 hash code
* @returns a number which tends to be unique between Vector3 instances
*/
public getHashCode(): number {
let hash = this.x || 0
hash = (hash * 397) ^ (this.y || 0)
hash = (hash * 397) ^ (this.z || 0)
return hash
}
// Operators
/**
* Creates an array containing three elements : the coordinates of the Vector3
* @returns a new array of numbers
*/
public asArray(): number[] {
let result: number[] = []
this.toArray(result, 0)
return result
}
/**
* Populates the given array or FloatArray from the given index with the successive coordinates of the Vector3
* @param array - defines the destination array
* @param index - defines the offset in the destination array
* @returns the current Vector3
*/
public toArray(array: FloatArray, index: number = 0): Vector3 {
array[index] = this.x
array[index + 1] = this.y
array[index + 2] = this.z
return this
}
/**
* Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
* @returns a new Quaternion object, computed from the Vector3 coordinates
*/
public toQuaternion(): Quaternion {
return Quaternion.Identity.setEuler(this.y, this.x, this.z)
}
/**
* Adds the given vector to the current Vector3
* @param otherVector - defines the second operand
* @returns the current updated Vector3
*/
public addInPlace(otherVector: ReadOnlyVector3): Vector3 {
return this.addInPlaceFromFloats(otherVector.x, otherVector.y, otherVector.z)
}
/**
* Adds the given coordinates to the current Vector3
* @param x - defines the x coordinate of the operand
* @param y - defines the y coordinate of the operand
* @param z - defines the z coordinate of the operand
* @returns the current updated Vector3
*/
public addInPlaceFromFloats(x: number, y: number, z: number): Vector3 {
this.x += x
this.y += y
this.z += z
return this
}
/**
* Gets a new Vector3, result of the addition the current Vector3 and the given vector
* @param otherVector - defines the second operand
* @returns the resulting Vector3
*/
public add(otherVector: ReadOnlyVector3): Vector3 {
return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z)
}
/**
* Adds the current Vector3 to the given one and stores the result in the vector "result"
* @param otherVector - defines the second operand
* @param result - defines the Vector3 object where to store the result
* @returns the current Vector3
*/
public addToRef(otherVector: ReadOnlyVector3, result: Vector3): Vector3 {
return result.copyFromFloats(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z)
}
/**
* Subtract the given vector from the current Vector3
* @param otherVector - defines the second operand
* @returns the current updated Vector3
*/
public subtractInPlace(otherVector: ReadOnlyVector3): Vector3 {
this.x -= otherVector.x
this.y -= otherVector.y
this.z -= otherVector.z
return this
}
/**
* Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
* @param otherVector - defines the second operand
* @returns the resulting Vector3
*/
public subtract(otherVector: ReadOnlyVector3): Vector3 {
return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z)
}
/**
* Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
* @param otherVector - defines the second operand
* @param result - defines the Vector3 object where to store the result
* @returns the current Vector3
*/
public subtractToRef(otherVector: ReadOnlyVector3, result: Vector3): Vector3 {
return this.subtractFromFloatsToRef(otherVector.x, otherVector.y, otherVector.z, result)
}
/**
* Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
* @param x - defines the x coordinate of the operand
* @param y - defines the y coordinate of the operand
* @param z - defines the z coordinate of the operand
* @returns the resulting Vector3
*/
public subtractFromFloats(x: number, y: number, z: number): Vector3 {
return new Vector3(this.x - x, this.y - y, this.z - z)
}
/**
* Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
* @param x - defines the x coordinate of the operand
* @param y - defines the y coordinate of the operand
* @param z - defines the z coordinate of the operand
* @param result - defines the Vector3 object where to store the result
* @returns the current Vector3
*/
public subtractFromFloatsToRef(x: number, y: number, z: number, result: Vector3): Vector3 {
return result.copyFromFloats(this.x - x, this.y - y, this.z - z)
}
/**
* Multiplies this vector (with an implicit 1 in the 4th dimension) and m, and divides by perspective
* @param matrix - The transformation matrix
*/
public applyMatrix4(matrix: Matrix) {
this.applyMatrix4ToRef(matrix, this)
}
/**
* Multiplies this vector (with an implicit 1 in the 4th dimension) and m, and divides by perspective and set the given vector "result" with this result
* @param matrix - The transformation matrix
* @param result - defines the Vector3 object where to store the result
* @returns the current Vector3
*/
public applyMatrix4ToRef(matrix: Matrix, result: Vector3) {
const { x, y, z } = this
const { m } = matrix
const w = 1 / (m[3] * x + m[7] * y + m[11] * z + m[15])
result.x = (m[0] * x + m[4] * y + m[8] * z + m[12]) * w
result.y = (m[1] * x + m[5] * y + m[9] * z + m[13]) * w
result.z = (m[2] * x + m[6] * y + m[10] * z + m[14]) * w
return result
}
/**
* Rotates the current Vector3 based on the given quaternion
* @param q - defines the Quaternion
* @returns the current Vector3
*/
public rotate(q: Quaternion) {
return this.rotateToRef(q, this)
}
/**
* Rotates current Vector3 based on the given quaternion, but applies the rotation to target Vector3.
* @param q - defines the Quaternion
* @param result - defines the target Vector3
* @returns the current Vector3
*/
public rotateToRef(q: Quaternion, result: Vector3) {
const { x, y, z } = this
const { x: qx, y: qy, z: qz, w: qw } = q
// calculate quat * vector
const ix = qw * x + qy * z - qz * y
const iy = qw * y + qz * x - qx * z
const iz = qw * z + qx * y - qy * x
const iw = -qx * x - qy * y - qz * z
// calculate result * inverse quat
result.x = ix * qw + iw * -qx + iy * -qz - iz * -qy
result.y = iy * qw + iw * -qy + iz * -qx - ix * -qz
result.z = iz * qw + iw * -qz + ix * -qy - iy * -qx
return result
}
/**
* Gets a new Vector3 set with the current Vector3 negated coordinates
* @returns a new Vector3
*/
public negate(): Vector3 {
return new Vector3(-this.x, -this.y, -this.z)
}
/**
* Multiplies the Vector3 coordinates by the float "scale"
* @param scale - defines the multiplier factor
* @returns the current updated Vector3
*/
public scaleInPlace(scale: number): Vector3 {
this.x *= scale
this.y *= scale
this.z *= scale
return this
}
/**
* Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
* @param scale - defines the multiplier factor
* @returns a new Vector3
*/
public scale(scale: number): Vector3 {
return new Vector3(this.x * scale, this.y * scale, this.z * scale)
}
/**
* Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
* @param scale - defines the multiplier factor
* @param result - defines the Vector3 object where to store the result
* @returns the current Vector3
*/
public scaleToRef(scale: number, result: Vector3): Vector3 {
return result.copyFromFloats(this.x * scale, this.y * scale, this.z * scale)
}
/**
* Scale the current Vector3 values by a factor and add the result to a given Vector3
* @param scale - defines the scale factor
* @param result - defines the Vector3 object where to store the result
* @returns the unmodified current Vector3
*/
public scaleAndAddToRef(scale: number, result: Vector3): Vector3 {
return result.addInPlaceFromFloats(this.x * scale, this.y * scale, this.z * scale)
}
/**
* Returns true if the current Vector3 and the given vector coordinates are strictly equal
* @param otherVector - defines the second operand
* @returns true if both vectors are equals
*/
public equals(otherVector: ReadOnlyVector3): boolean {
return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z
}
/**
* Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
* @param otherVector - defines the second operand
* @param epsilon - defines the minimal distance to define values as equals
* @returns true if both vectors are distant less than epsilon
*/
public equalsWithEpsilon(otherVector: ReadOnlyVector3, epsilon: number = Epsilon): boolean {
return (
otherVector &&
Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) &&
Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) &&
Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
)
}
/**
* Returns true if the current Vector3 coordinates equals the given floats
* @param x - defines the x coordinate of the operand
* @param y - defines the y coordinate of the operand
* @param z - defines the z coordinate of the operand
* @returns true if both vectors are equals
*/
public equalsToFloats(x: number, y: number, z: number): boolean {
return this.x === x && this.y === y && this.z === z
}
/**
* Multiplies the current Vector3 coordinates by the given ones
* @param otherVector - defines the second operand
* @returns the current updated Vector3
*/
public multiplyInPlace(otherVector: ReadOnlyVector3): Vector3 {
this.x *= otherVector.x
this.y *= otherVector.y
this.z *= otherVector.z
return this
}
/**
* Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
* @param otherVector - defines the second operand
* @returns the new Vector3
*/
public multiply(otherVector: ReadOnlyVector3): Vector3 {
return this.multiplyByFloats(otherVector.x, otherVector.y, otherVector.z)
}
/**
* Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
* @param otherVector - defines the second operand
* @param result - defines the Vector3 object where to store the result
* @returns the current Vector3
*/
public multiplyToRef(otherVector: ReadOnlyVector3, result: Vector3): Vector3 {
return result.copyFromFloats(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z)
}
/**
* Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
* @param x - defines the x coordinate of the operand
* @param y - defines the y coordinate of the operand
* @param z - defines the z coordinate of the operand
* @returns the new Vector3
*/
public multiplyByFloats(x: number, y: number, z: number): Vector3 {
return new Vector3(this.x * x, this.y * y, this.z * z)
}
/**
* Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
* @param otherVector - defines the second operand
* @returns the new Vector3
*/
public divide(otherVector: ReadOnlyVector3): Vector3 {
return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z)
}
/**
* Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
* @param otherVector - defines the second operand
* @param result - defines the Vector3 object where to store the result
* @returns the current Vector3
*/
public divideToRef(otherVector: ReadOnlyVector3, result: Vector3): Vector3 {
return result.copyFromFloats(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z)
}
/**
* Divides the current Vector3 coordinates by the given ones.
* @param otherVector - defines the second operand
* @returns the current updated Vector3
*/
public divideInPlace(otherVector: ReadOnlyVector3): Vector3 {
return this.divideToRef(otherVector, this)
}
/**
* Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
* @param other - defines the second operand
* @returns the current updated Vector3
*/
public minimizeInPlace(other: ReadOnlyVector3): Vector3 {
return this.minimizeInPlaceFromFloats(other.x, other.y, other.z)
}
/**
* Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
* @param other - defines the second operand
* @returns the current updated Vector3
*/
public maximizeInPlace(other: ReadOnlyVector3): Vector3 {
return this.maximizeInPlaceFromFloats(other.x, other.y, other.z)
}
/**
* Updates the current Vector3 with the minimal coordinate values between its and the given coordinates
* @param x - defines the x coordinate of the operand
* @param y - defines the y coordinate of the operand
* @param z - defines the z coordinate of the operand
* @returns the current updated Vector3
*/
public minimizeInPlaceFromFloats(x: number, y: number, z: number): Vector3 {
if (x < this.x) {
this.x = x
}
if (y < this.y) {
this.y = y
}
if (z < this.z) {
this.z = z
}
return this
}
/**
* Updates the current Vector3 with the maximal coordinate values between its and the given coordinates.
* @param x - defines the x coordinate of the operand
* @param y - defines the y coordinate of the operand
* @param z - defines the z coordinate of the operand
* @returns the current updated Vector3
*/
public maximizeInPlaceFromFloats(x: number, y: number, z: number): Vector3 {
if (x > this.x) {
this.x = x
}
if (y > this.y) {
this.y = y
}
if (z > this.z) {
this.z = z
}
return this
}
/**
* Gets a new Vector3 from current Vector3 floored values
* @returns a new Vector3
*/
public floor(): Vector3 {
return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z))
}
/**
* Gets a new Vector3 from current Vector3 floored values
* @returns a new Vector3
*/
public fract(): Vector3 {
return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z))
}
// Properties
/**
* Gets the length of the Vector3
* @returns the length of the Vecto3
*/
public length(): number {
return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z)
}
/**
* Gets the squared length of the Vector3
* @returns squared length of the Vector3
*/
public lengthSquared(): number {
return this.x * this.x + this.y * this.y + this.z * this.z
}
/**
* Normalize the current Vector3.
* Please note that this is an in place operation.
* @returns the current updated Vector3
*/
public normalize(): Vector3 {
return this.normalizeFromLength(this.length())
}
/**
* Normalize the current Vector3 with the given input length.
* Please note that this is an in place operation.
* @param len - the length of the vector
* @returns the current updated Vector3
*/
public normalizeFromLength(len: number): Vector3 {
if (len === 0 || len === 1.0) {
return this
}
return this.scaleInPlace(1.0 / len)
}
/**
* Normalize the current Vector3 to a new vector
* @returns the new Vector3
*/
public normalizeToNew(): Vector3 {
const normalized = new Vector3(0, 0, 0)
this.normalizeToRef(normalized)
return normalized
}
/**
* Normalize the current Vector3 to the reference
* @param reference - define the Vector3 to update
* @returns the updated Vector3
*/
public normalizeToRef(reference: Vector3): Vector3 {
let len = this.length()
if (len === 0 || len === 1.0) {
return reference.copyFromFloats(this.x, this.y, this.z)
}
return this.scaleToRef(1.0 / len, reference)
}
/**
* Creates a new Vector3 copied from the current Vector3
* @returns the new Vector3
*/
public clone(): Vector3 {
return new Vector3(this.x, this.y, this.z)
}
/**
* Copies the given vector coordinates to the current Vector3 ones
* @param source - defines the source Vector3
* @returns the current updated Vector3
*/
public copyFrom(source: ReadOnlyVector3): Vector3 {
return this.copyFromFloats(source.x, source.y, source.z)
}
/**
* Copies the given floats to the current Vector3 coordinates
* @param x - defines the x coordinate of the operand
* @param y - defines the y coordinate of the operand
* @param z - defines the z coordinate of the operand
* @returns the current updated Vector3
*/
public copyFromFloats(x: number, y: number, z: number): Vector3 {
this.x = x
this.y = y
this.z = z
return this
}
/**
* Copies the given floats to the current Vector3 coordinates
* @param x - defines the x coordinate of the operand
* @param y - defines the y coordinate of the operand
* @param z - defines the z coordinate of the operand
* @returns the current updated Vector3
*/
public set(x: number, y: number, z: number): Vector3 {
return this.copyFromFloats(x, y, z)
}
/**
* Copies the given float to the current Vector3 coordinates
* @param v - defines the x, y and z coordinates of the operand
* @returns the current updated Vector3
*/
public setAll(v: number): Vector3 {
this.x = this.y = this.z = v
return this
}
} | the_stack |
import { request as ghRequest } from "@octokit/request";
import { Octokit } from "@deliverybot/core";
import {
config as getConfig,
EnvLockStore,
WatchStore,
Targets,
Watch,
} from "@deliverybot/deploybot";
import get from "lodash.get";
import { Repo } from "../auth";
import { timeAgoInWords, hash } from "../util";
import { Measure, Measurements } from "./metrics";
import { newDeployFileUrl, editDeployFileUrl, yamlEncode } from "../util";
export async function gql(token: string, query: string, variables: any) {
const resp = await ghRequest({
data: { query, variables },
method: "POST",
url: "/graphql",
headers: {
authorization: `token ${token}`,
accept: "application/vnd.github.antiope-preview+json",
},
});
if (resp.data.errors && resp.data.errors.length > 0) {
throw new Error(
`Graphql request failure: ${JSON.stringify(resp.data.errors)}`,
);
}
return resp.data.data;
}
export interface Options {
minimal?: boolean;
before?: string;
after?: string;
count?: number;
}
const CommitData = ({ minimal }: Options) => `
messageHeadline oid message
author { user { login } }
${
minimal
? ""
: `
status { contexts { context state } }
checkSuites(last: 50) { nodes { conclusion status checkRuns(last: 1) { nodes { name } } } }
deployments(last: 50) {
nodes {
id environment description createdAt
creator { login }
latestStatus { logUrl state }
}
}`
}
`;
const CommitsQuery = (opts: Options) => `
query commits(
$owner: String!, $repo: String!, $branch: String!,
$after: String, $before: String, $first: Int, $last: Int
) {
repository(owner:$owner,name:$repo) {
refs(refPrefix:"refs/heads/",first:50) { nodes { name } }
ref(qualifiedName:$branch) {
target {
... on Commit {
history(first:$first, last:$last, before:$before, after:$after) {
edges { node { ${CommitData(opts)} } }
pageInfo {
hasNextPage
endCursor
startCursor
hasPreviousPage
}
}
}
}
}
}
}
`;
const AllDeployments = () => `
query deployments($owner:String!,$repo:String!) {
repository(owner:$owner,name:$repo) {
deployments(first:100,orderBy:{field:CREATED_AT,direction:DESC}) {
pageInfo {
hasNextPage
endCursor
}
nodes {
state environment createdAt
latestStatus { createdAt }
commit {
authoredDate
associatedPullRequests(first: 1) {
nodes {
createdAt
}
}
}
}
}
}
}
`;
interface Watches {
[k: string]: Watch[];
}
async function getWatches(watch: WatchStore, repoId: number, shas: string[]) {
return Promise.all(shas.map(sha => watch.listWatchBySha(repoId, sha))).then(
watches =>
shas.reduce<Watches>((acc, sha, i) => {
acc[sha] = watches[i];
return acc;
}, {}),
);
}
export async function commits(
watch: WatchStore,
token: string,
owner: string,
repo: string,
repoId: number,
branch: string,
opts: Options,
) {
const variables: any = { owner, repo, branch };
if (opts.before) {
variables.last = opts.count;
variables.before = opts.before;
} else if (opts.after) {
variables.first = opts.count;
variables.after = opts.after;
} else {
variables.first = opts.count;
}
const result = await gql(token, CommitsQuery(opts), variables);
const shas = get(result, "repository.ref.target.history.edges", []).map(
(edge: any) => edge.node.oid,
);
const watches = await getWatches(watch, repoId, shas);
// For generating test files:
// require("fs").writeFileSync(`./test/fixtures/query-commits.${opts.minimal ? "minimal" : "full"}.json`, JSON.stringify(result, null, 2));
return View(owner, repo, branch, watches, result);
}
export async function metrics(
token: string,
owner: string,
repo: string,
start: Date,
end: Date,
) {
const result = await gql(token, AllDeployments(), { owner, repo });
// For generating test files:
// require('fs').writeFileSync(`./test/fixtures/metrics.json`, JSON.stringify(result, null, 2));
const measures = Measures(result, start, end);
return new Measurements(start, end, measures).toJSON();
}
export function View(
owner: string,
repo: string,
branch: string,
watches: Watches,
data: any,
) {
const branches = Branches(branch, get(data, "repository.refs.nodes", []));
const commits = Commits(
owner,
repo,
branch,
watches,
get(data, "repository.ref.target.history.edges", []),
);
const pagination = get(data, "repository.ref.target.history.pageInfo", {});
return { branches, pagination: Pagination(pagination), ...commits };
}
export function Measures(data: any, start: Date, end: Date): Measure[] {
return get(data, "repository.deployments.nodes", [])
.map((node: any): Measure | null => {
const createdAt = get(node, "createdAt");
const committedAt = get(node, "commit.authoredDate");
const deployedAt = get(node, "latestStatus.createdAt");
const startedAt = get(
node,
"associatedPullRequests[0].createdAt",
committedAt,
);
const state = get(node, "state");
const env = get(node, "environment");
if (!createdAt || !committedAt) {
return null;
}
const time = new Date(Date.parse(createdAt)).getTime();
if (time < start.getTime() || time > end.getTime()) {
return null;
}
return {
createdAt: new Date(Date.parse(createdAt)),
committedAt: new Date(Date.parse(committedAt)),
deployedAt: (deployedAt && new Date(Date.parse(deployedAt))) || null,
startedAt: (startedAt && new Date(Date.parse(startedAt))) || null,
env,
state,
};
})
.filter((m: any) => !!m);
}
export function Pagination(pagination: any) {
return {
next: pagination.hasNextPage && encodeURIComponent(pagination.endCursor),
prev:
pagination.hasPreviousPage && encodeURIComponent(pagination.startCursor),
};
}
const failing = ["FAILURE", "FAILING", "ERROR", "CANCELLED", "TIMED_OUT"];
const pending = ["PENDING", "ACTION_REQUIRED", "QUEUED", "IN_PROGRESS"];
const success = ["SUCCESS"];
const waiting = ["WAITING"];
export function AggregateStatus(statuses: string[]) {
if (statuses.find(s => failing.includes(s.toUpperCase()))) {
return "FAILURE";
}
if (statuses.find(s => pending.includes(s.toUpperCase()))) {
return "PENDING";
}
if (statuses.find(s => success.includes(s.toUpperCase()))) {
return "SUCCESS";
}
if (statuses.find(s => waiting.includes(s.toUpperCase()))) {
return "WAITING";
}
return "NOTHING";
}
export function Checks(
node: any,
): Array<{ context: string; status: ReturnType<typeof Status> }> {
return (((node.status && node.status.contexts) || []) as any[])
.map(ctx => ({
context: ctx.context as string,
status: Status(ctx.state),
}))
.concat(
(get(node, "checkSuites.nodes", []) as any)
// If no check run exists for this checkSuite then we just simply ignore
// this checkSuite for the time being. I believe that checkSuite's are
// sometimes created but never 'fulfilled' which would cause this to sit
// in a pending state forever.
.filter((cs: any) => get(cs, "checkRuns.nodes[0]"))
.map((cs: any) => ({
context: get(cs, "checkRuns.nodes[0].name") as string,
status: Status(cs.conclusion || cs.status),
})),
)
.filter(
(el, i, arr) => arr.findIndex(el2 => el2.context === el.context) == i,
);
}
export function Check(node: any) {
return {
status: Status(AggregateStatus(Checks(node).map(c => c.status.name))),
};
}
export function Status(status?: string) {
const s = [(status || "WAITING").toUpperCase()];
const name = AggregateStatus(s);
switch (AggregateStatus(s)) {
case "FAILURE":
return { failure: true, color: "red", name };
case "PENDING":
return { pending: true, color: "yellow", name };
case "SUCCESS":
return { success: true, color: "green", name };
case "WAITING":
return { waiting: true, color: "gray", name };
default:
return { nothing: true, color: "gray", name };
}
}
export function Deployment(node: any) {
const deployments = get(node, "deployments.nodes", []);
const statuses = deployments.map((deploy: any) =>
get(deploy, "latestStatus.state", "WAITING"),
);
const lastDeployedAt: number = deployments
.map((deploy: any) => Date.parse(deploy.createdAt))
.sort()
.pop();
const lastDeployedAtWords = lastDeployedAt && timeAgoInWords(lastDeployedAt);
return {
// Use the latest status to make a decision:
status: Status(
AggregateStatus([statuses[statuses.length - 1] || "NOTHING"]),
),
lastDeployedAt,
lastDeployedAtWords,
};
}
export function Undeployed(node: any) {
const deployment = Deployment(node);
const check = Check(node);
if (
check.status.success &&
(deployment.status.nothing || deployment.status.waiting)
) {
return true;
}
return false;
}
export function Deployments(node: any) {
return (get(node, "deployments.nodes", []) as any[])
.map((deploy: any) => ({
status: Status(deploy.latestStatus && deploy.latestStatus.state),
description: truncate(deploy.description, 20),
environment: deploy.environment,
creator: get(deploy, "creator.login"),
createdAt: Date.parse(deploy.createdAt),
createdAtWords: timeAgoInWords(Date.parse(deploy.createdAt)),
url: get(deploy, "latestStatus.logUrl"),
}))
.sort((a, b) => b.createdAt - a.createdAt)
.filter(
(el, i, arr) =>
arr.findIndex(el2 => el2.environment === el.environment) == i,
);
}
function truncate(s: string | undefined | null, t: number) {
if (!s) {
return "";
}
if (s.length > t) {
return s.substr(0, t) + "...";
}
return s;
}
export function Previous(commits: any[]) {
const latest = Latest(commits);
if (!latest) {
return null;
}
const latestIdx = commits.findIndex(c => c.oid === latest.oid);
return commits[latestIdx + 1] || null;
}
export function Latest(commits: any[]) {
const latest = commits
.slice()
.filter((c: any) => c.deployment.lastDeployedAt)
.sort(
(f: any, s: any) =>
f.deployment.lastDeployedAt - s.deployment.lastDeployedAt,
)
.pop();
if (latest) latest.deployment.latest = true;
return latest;
}
export function Commits(
owner: string,
repo: string,
branch: string,
watches: Watches,
edges: any,
) {
const commits = edges.map((edge: any) =>
Commit(owner, repo, branch, watches, edge),
);
const latest = Latest(commits);
const previous = Previous(commits);
return { commits, latest, previous };
}
export function DeploymentWatch(watch: Watch) {
return {
status: Status("WAITING"),
description: "Waiting...",
environment: watch.targetVal.environment,
creator: "deliverybot",
createdAt: Date.now(),
createdAtWords: timeAgoInWords(Date.now()),
url: null,
};
}
export function Promoted(node: any) {
return !!get(node, "status.contexts", []).find(
(ctx: any) => ctx.context === "deliverybot/promotion",
);
}
export function Commit(
owner: string,
repo: string,
branch: string,
watches: Watches,
edge: any,
) {
const watchList = watches[get(edge, "node.oid", "")] || [];
const data = {
owner,
repo,
branch,
message: get(edge, "node.messageHeadline", ""),
body: get(edge, "node.message"),
oid: get(edge, "node.oid"),
oidShort: get(edge, "node.oid", "").substr(0, 7),
author: get(edge, "node.author.user.login"),
undeployed: Undeployed(edge.node),
deployment: Deployment(edge.node),
promoted: Promoted(edge.node),
deployments: Deployments(edge.node).concat(watchList.map(DeploymentWatch)),
check: Check(edge.node),
checks: Checks(edge.node),
};
return {
hash: hash(data),
...data,
};
}
export function Branches(
active: string,
branches: any[],
): Array<{ name: string; active: boolean }> {
return branches.map(n => ({
name: n.name,
active: active === n.name,
}));
}
export function Targets(conf: Targets | null) {
return (
conf &&
Object.keys(conf).map((name: string) => ({
name,
}))
);
}
interface Config {
newFileUrl: string;
editFileUrl: string;
notExists: boolean;
yaml: string;
error: Error | null;
config: Targets | null;
}
export async function config(
github: Octokit,
owner: string,
repo: string,
branch: string,
): Promise<Config> {
const newFileUrl = newDeployFileUrl(owner, repo);
const editFileUrl = editDeployFileUrl(owner, repo);
const conf: Config = {
yaml: "",
notExists: true,
editFileUrl,
newFileUrl,
error: null,
config: null,
};
try {
conf.config = await getConfig(github, {
owner,
repo,
ref: branch ? `refs/heads/${branch}` : `refs/heads/master`,
});
conf.yaml = yamlEncode(conf.config) || "";
conf.notExists = false;
} catch (e) {
if (e.status !== 404) {
conf.error = e;
}
}
return conf;
}
export async function locks(config: Config, repo: Repo, lock: EnvLockStore) {
const locked = await lock.list(repo.id);
const targets = Object.keys(config.config || {}).map(target => {
const environment = get(config, `config.${target}.environment`, "");
return {
target,
lockable: environment && !environment.includes("${{"),
locked: locked.includes(environment),
environment,
};
});
return { any: locked.length > 0, locked, targets };
} | the_stack |
import { MockProvider } from '@ethereum-waffle/provider'
import type { TransactionRequest } from '@ethersproject/abstract-provider'
import { constants } from 'ethers'
import { Contract } from 'ethers'
import { expect } from 'chai'
import { BigNumber, ethers } from 'ethers'
import { getAddress } from 'ethers/lib/utils'
import { ERC20MockInterface } from '../constants'
import {
deployMockToken,
MOCK_TOKEN_INITIAL_BALANCE,
renderWeb3Hook,
SECOND_MOCK_TOKEN_INITIAL_BALANCE,
SECOND_TEST_CHAIN_ID,
} from '../testing'
import { useLogs } from './useLogs'
import { useSendTransaction } from './useSendTransaction'
const AddressZero = constants.AddressZero
describe('useLogs', () => {
const mockProvider = new MockProvider()
const secondMockProvider = new MockProvider({ ganacheOptions: { _chainIdRpc: SECOND_TEST_CHAIN_ID } as any })
const [deployer, receiver] = mockProvider.getWallets()
const [secondDeployer] = secondMockProvider.getWallets()
let token: Contract
let secondToken: Contract
beforeEach(async () => {
token = await deployMockToken(deployer)
secondToken = await deployMockToken(secondDeployer, SECOND_MOCK_TOKEN_INITIAL_BALANCE)
})
async function sendToken(signer: ethers.Wallet, to: string, amount: BigNumber) {
const { result, waitForCurrent, waitForNextUpdate } = await renderWeb3Hook(
() =>
useSendTransaction({
signer,
}),
{ mockProvider }
)
await waitForNextUpdate()
const txData = ERC20MockInterface.encodeFunctionData('transfer(address,uint)', [to, amount])
const tx: TransactionRequest = {
to: token.address,
value: BigNumber.from(0),
data: txData,
gasPrice: 0,
}
await result.current.sendTransaction(tx)
await waitForCurrent((val) => val.state !== undefined)
expect(result.current.state.status).to.eq('Success')
return result.current.state
}
it('Can get only the recent token transfer log', async () => {
const blockNumber = await mockProvider.getBlockNumber()
const from = deployer
const to = receiver
const fromAddress = from.address
const toAddress = to.address
const amount = BigNumber.from(1)
await sendToken(from, toAddress, amount)
const { result, waitForCurrent } = await renderWeb3Hook(
() =>
useLogs(
{
contract: token,
event: 'Transfer',
args: [],
},
{
fromBlock: blockNumber + 1,
toBlock: blockNumber + 2,
}
),
{ mockProvider }
)
await waitForCurrent((val) => val !== undefined)
expect(result.error).to.be.undefined
expect(result.current?.value).to.not.be.undefined
expect(result.current?.error).to.be.undefined
expect(result.current?.value?.length).to.equal(1, 'Number of logs')
const log = result.current!.value![0]
expect(getAddress(log.data['from'])).to.equal(getAddress(fromAddress), 'From')
expect(getAddress(log.data['to'])).to.equal(getAddress(toAddress), 'To')
expect(log.data['value']).to.equal(amount, 'Amount')
})
it('Can get all token transfer logs using the default log query parameters', async () => {
const from = deployer
const to = receiver
const fromAddress = from.address
const toAddress = to.address
const amount = BigNumber.from(1)
await sendToken(from, toAddress, amount)
const { result, waitForCurrent } = await renderWeb3Hook(
() =>
useLogs({
contract: token,
event: 'Transfer',
args: [],
}),
{ mockProvider }
)
await waitForCurrent((val) => val !== undefined)
expect(result.error).to.be.undefined
expect(result.current?.value).to.not.be.undefined
expect(result.current?.error).to.be.undefined
expect(result.current?.value?.length).to.equal(2, 'Number of logs')
// Mint transfer event
const log1 = result.current!.value![0]
expect(getAddress(log1.data['from'])).to.equal(getAddress(AddressZero), 'From')
expect(getAddress(log1.data['to'])).to.equal(getAddress(deployer.address), 'To')
expect(log1.data['value']).to.equal(MOCK_TOKEN_INITIAL_BALANCE, 'Amount')
// Recent transfer transaction log
const log = result.current!.value![1]
expect(getAddress(log.data['from'])).to.equal(getAddress(fromAddress), 'From')
expect(getAddress(log.data['to'])).to.equal(getAddress(toAddress), 'To')
expect(log.data['value']).to.equal(amount, 'Amount')
})
it('Can get the mint transfer log', async () => {
const { result, waitForCurrent } = await renderWeb3Hook(
() =>
useLogs(
{
contract: token,
event: 'Transfer',
args: [],
},
{
fromBlock: 0,
toBlock: 'latest',
}
),
{ mockProvider }
)
await waitForCurrent((val) => val !== undefined)
expect(result.error).to.be.undefined
expect(result.current?.value).to.not.be.undefined
expect(result.current?.error).to.be.undefined
expect(result.current?.value?.length).to.equal(1, 'Number of logs')
const log = result.current!.value![0]
expect(getAddress(log.data['from'])).to.equal(getAddress(AddressZero), 'From')
expect(getAddress(log.data['to'])).to.equal(getAddress(deployer.address), 'To')
expect(log.data['value']).to.equal(MOCK_TOKEN_INITIAL_BALANCE, 'Amount')
})
it('Can get the mint transfer log on the alternative chain', async () => {
const { result, waitForCurrent } = await renderWeb3Hook(
() =>
useLogs(
{
contract: secondToken,
event: 'Transfer',
args: [],
},
{
fromBlock: 0,
toBlock: 'latest',
}
),
{
mockProvider: secondMockProvider,
}
)
await waitForCurrent((val) => val !== undefined)
expect(result.error).to.be.undefined
expect(result.current?.value).to.not.be.undefined
expect(result.current?.error).to.be.undefined
expect(result.current?.value?.length).to.equal(1, 'Number of logs')
const log = result.current!.value![0]
expect(getAddress(log.data['from'])).to.equal(getAddress(AddressZero), 'From')
expect(getAddress(log.data['to'])).to.equal(getAddress(secondDeployer.address), 'To')
expect(log.data['value']).to.equal(SECOND_MOCK_TOKEN_INITIAL_BALANCE, 'Amount')
})
it('Works if there are no logs', async () => {
const { result, waitForCurrent } = await renderWeb3Hook(
() =>
useLogs(
{
contract: secondToken, // Token on the other chain... doesn't exist so there should be no logs
event: 'Transfer',
args: [],
},
{
fromBlock: 0,
toBlock: 'latest',
}
),
{ mockProvider }
)
await waitForCurrent((val) => val !== undefined)
expect(result.error).to.be.undefined
expect(result.current?.value).to.not.be.undefined
expect(result.current?.error).to.be.undefined
expect(result.current?.value?.length).to.equal(0, 'Number of logs')
})
it('Can query mint transfer logs by sender', async () => {
// Send to emit another Transfer token that our filter should filter out
await sendToken(deployer, receiver.address, BigNumber.from(1))
const { result, waitForCurrent } = await renderWeb3Hook(
() =>
useLogs(
{
contract: token,
event: 'Transfer',
args: [AddressZero],
},
{
fromBlock: 0,
toBlock: 'latest',
}
),
{ mockProvider }
)
await waitForCurrent((val) => val !== undefined)
expect(result.error).to.be.undefined
expect(result.current?.value).to.not.be.undefined
expect(result.current?.error).to.be.undefined
expect(result.current?.value?.length).to.equal(1, 'Number of logs')
const log = result.current!.value![0]
expect(getAddress(log.data['from'])).to.equal(getAddress(AddressZero), 'From')
expect(getAddress(log.data['to'])).to.equal(getAddress(deployer.address), 'To')
expect(log.data['value']).to.equal(MOCK_TOKEN_INITIAL_BALANCE, 'Amount')
})
it('Can query mint transfer logs by receiver', async () => {
// Send to emit another Transfer token that our filter should filter out
await sendToken(deployer, receiver.address, BigNumber.from(1))
const { result, waitForCurrent } = await renderWeb3Hook(
() =>
useLogs(
{
contract: token,
event: 'Transfer',
args: [null, deployer.address],
},
{
fromBlock: 0,
toBlock: 'latest',
}
),
{ mockProvider }
)
await waitForCurrent((val) => val !== undefined)
expect(result.error).to.be.undefined
expect(result.current?.value).to.not.be.undefined
expect(result.current?.error).to.be.undefined
expect(result.current?.value?.length).to.equal(1, 'Number of logs')
const log = result.current!.value![0]
expect(getAddress(log.data['from'])).to.equal(getAddress(AddressZero), 'From')
expect(getAddress(log.data['to'])).to.equal(getAddress(deployer.address), 'To')
expect(log.data['value']).to.equal(MOCK_TOKEN_INITIAL_BALANCE, 'Amount')
})
it('We get an error when we query by un-indexed values', async () => {
// Send to emit another Transfer token that our filter should filter out
await sendToken(deployer, receiver.address, BigNumber.from(1))
const { result, waitForCurrent } = await renderWeb3Hook(
() =>
useLogs(
{
contract: token,
event: 'Transfer',
args: [null, null, MOCK_TOKEN_INITIAL_BALANCE],
},
{
fromBlock: 0,
toBlock: 'latest',
}
),
{ mockProvider }
)
await waitForCurrent((val) => val !== undefined)
expect(result.error).to.be.undefined
expect(result.current?.value).to.be.undefined
expect(result.current?.error).to.not.be.undefined
})
it('Can query by block hash', async () => {
// Send to emit another Transfer token that our filter should filter out
const { receipt } = await sendToken(deployer, receiver.address, BigNumber.from(1))
const { result, waitForCurrent } = await renderWeb3Hook(
() =>
useLogs(
{
contract: token,
event: 'Transfer',
args: [],
},
{
blockHash: receipt?.blockHash,
}
),
{ mockProvider }
)
await waitForCurrent((val) => val !== undefined)
expect(result.error).to.be.undefined
expect(result.current?.value).to.not.be.undefined
expect(result.current?.error).to.be.undefined
expect(result.current?.value?.length).to.equal(1, 'Number of logs')
const log = result.current!.value![0]
expect(getAddress(log.data['from'])).to.equal(getAddress(deployer.address), 'From')
expect(getAddress(log.data['to'])).to.equal(getAddress(receiver.address), 'To')
expect(log.data['value']).to.equal(BigNumber.from(1), 'Amount')
expect(log.blockHash).to.equal(receipt?.blockHash, 'Block hash')
expect(log.blockNumber).to.equal(receipt?.blockNumber, 'Block number')
expect(log.transactionHash).to.equal(receipt?.transactionHash, 'Transaction hash')
expect(log.transactionIndex).to.equal(receipt?.transactionIndex, 'Transaction index')
})
}) | the_stack |
module Spriter {
export class SpriterBin extends SpriterFile {
// spriter data
private static ATTR_VERSION = 0;
private static ATTR_GENERATOR = 1;
private static ATTR_GENERATOR_VERSION = 2;
// folder
private static ATTR_FOLDER_ID = 0;
private static ATTR_FOLDER_NAME = 1;
// file
private static ATTR_FILE_ID = 0;
private static ATTR_FILE_NAME = 1;
private static ATTR_FILE_WIDTH = 2;
private static ATTR_FILE_HEIGHT = 3;
private static ATTR_FILE_PIVOT_X = 4;
private static ATTR_FILE_PIVOT_Y = 5;
// entity
private static ATTR_ENTITY_ID = 0;
private static ATTR_ENTITY_NAME = 1;
// obj_info
private static ATTR_OBJ_INFO_NAME = 0;
private static ATTR_OBJ_INFO_TYPE = 1;
private static ATTR_OBJ_INFO_WIDTH = 2;
private static ATTR_OBJ_INFO_HEIGHT = 3;
// frames
private static ATTR_FRAMES_I_FOLDER = 0;
private static ATTR_FRAMES_I_FILE = 1;
// animation
private static ATTR_ANIMATION_ID = 0;
private static ATTR_ANIMATION_NAME = 1;
private static ATTR_ANIMATION_LENGTH = 2;
private static ATTR_ANIMATION_INTERVAL = 3;
private static ATTR_ANIMATION_LOOPING = 4;
// key
private static ATTR_MAINLINE_KEY_ID = 0;
private static ATTR_MAINLINE_KEY_TIME = 1;
// bone_ref
private static ATTR_BONE_REF_ID = 0;
private static ATTR_BONE_REF_PARENT = 1;
private static ATTR_BONE_REF_TIMELINE = 2;
private static ATTR_BONE_REF_KEY = 3;
// object_ref
private static ATTR_OBJ_REF_ID = 4;
private static ATTR_OBJ_REF_PARENT = 5;
private static ATTR_OBJ_REF_TIMELINE = 6;
private static ATTR_OBJ_REF_KEY = 7;
private static ATTR_OBJ_REF_NAME = 8;
private static ATTR_OBJ_REF_Z = 9;
private static ATTR_OBJ_REF_FOLDER = 10;
private static ATTR_OBJ_REF_FILE = 11;
private static ATTR_OBJ_REF_ABS_X = 12;
private static ATTR_OBJ_REF_ABS_Y = 13;
private static ATTR_OBJ_REF_ABS_PIVOT_X = 14;
private static ATTR_OBJ_REF_ABS_PIVOT_Y = 15;
private static ATTR_OBJ_REF_ABS_SCALE_X = 16;
private static ATTR_OBJ_REF_ABS_SCALE_Y = 17;
private static ATTR_OBJ_REF_ANGLE = 18;
private static ATTR_OBJ_REF_ALPHA = 19;
// timeline
private static ATTR_TIMELINE_ID = 0;
private static ATTR_TIMELINE_NAME = 1;
private static ATTR_TIMELINE_OBJ = 2;
private static ATTR_TIMELINE_OBJ_TYPE = 3;
// key
private static ATTR_TIMELINE_KEY_ID = 0;
private static ATTR_TIMELINE_KEY_TIME = 1;
private static ATTR_TIMELINE_KEY_SPIN = 2;
private static ATTR_TIMELINE_KEY_CURVE = 3;
private static ATTR_TIMELINE_KEY_C1 = 4;
private static ATTR_TIMELINE_KEY_C2 = 5;
// bone
private static ATTR_BONE_X = 0;
private static ATTR_BONE_Y = 1;
private static ATTR_BONE_ANGLE = 2;
private static ATTR_BONE_SCALE_X = 3;
private static ATTR_BONE_SCALE_Y = 4;
// object
private static ATTR_OBJ_FOLDER = 5;
private static ATTR_OBJ_FILE = 6;
private static ATTR_OBJ_X = 7;
private static ATTR_OBJ_Y = 8;
private static ATTR_OBJ_SCALE_X = 9;
private static ATTR_OBJ_SCALE_Y = 10;
private static ATTR_OBJ_PIVOT_X = 11;
private static ATTR_OBJ_PIVOT_Y = 12;
private static ATTR_OBJ_ANGLE = 13;
private static ATTR_OBJ_ALPHA = 14;
private _elements: any = {
"spriter_data": 1,
"folder": 2,
"file": 3,
"entity": 4,
"obj_info": 5,
"frames": 6,
"i": 7,
"animation": 8,
"mainline": 9,
"key": 10,
"bone_ref": 11,
"object_ref": 12,
"timeline": 13,
"bone": 14,
"object": 15
};
private _bin: DataView;
private _smallOffset: boolean = false;
private _tmpPosition: number;
// -------------------------------------------------------------------------
constructor(binData: ArrayBuffer) {
super(null);
this._bin = new DataView(binData);
this._smallOffset = this._bin.getUint8(0) === 1;
}
// -------------------------------------------------------------------------
public getType(): eFileType {
return eFileType.BIN;
}
// -------------------------------------------------------------------------
private readUint8(): number {
return this._bin.getUint8(this._tmpPosition++);
}
// -------------------------------------------------------------------------
private readInt8(): number {
return this._bin.getInt8(this._tmpPosition++);
}
// -------------------------------------------------------------------------
private readUint16(): number {
var value = this._bin.getUint16(this._tmpPosition, true);
this._tmpPosition += 2;
return value;
}
// -------------------------------------------------------------------------
private readInt16(): number {
var value = this._bin.getInt16(this._tmpPosition, true);
this._tmpPosition += 2;
return value;
}
// -------------------------------------------------------------------------
private readUint32(): number {
var value = this._bin.getUint32(this._tmpPosition, true);
this._tmpPosition += 4;
return value;
}
// -------------------------------------------------------------------------
private readInt32(): number {
var value = this._bin.getInt32(this._tmpPosition, true);
this._tmpPosition += 4;
return value;
}
// -------------------------------------------------------------------------
private readFixed16_16(): number {
var value = this._bin.getInt32(this._tmpPosition, true);
this._tmpPosition += 4;
return value / 65536;
}
// -------------------------------------------------------------------------
private readFixed1_7(): number {
var value = this._bin.getInt8(this._tmpPosition++) & 0xFF;
return value / 128;
}
// -------------------------------------------------------------------------
private readString(): string {
var chars = [];
for (var i = this._bin.getUint8(this._tmpPosition++) - 1; i >= 0; i--) {
chars.push(this._bin.getUint8(this._tmpPosition++));
}
return String.fromCharCode.apply(null, chars);
}
// -------------------------------------------------------------------------
public getNodes(nodeName: string): ISpriterNodeList {
return new NodeListBin(this, this.getSubNodesOfElementType(1, this._elements[nodeName]));
}
// -------------------------------------------------------------------------
public getNodesForElement(elementPosition: number, nodeName: string): ISpriterNodeList {
return new NodeListBin(this, this.getSubNodesOfElementType(elementPosition, this._elements[nodeName]));
}
// -------------------------------------------------------------------------
private getSubNodesOfElementType(positon: number, elementType: number): number[] {
var result: number[] = [];
var subelementsCount = this._bin.getUint8(positon + 1);
positon += 2;
for (var i = 0; i < subelementsCount; i++) {
var subelementOffset = this._smallOffset ? this._bin.getUint16(positon + i * 2, true) : this._bin.getUint32(positon + i * 4, true);
var subelementType = this._bin.getUint8(positon + subelementOffset);
if (subelementType === elementType) {
result.push(positon + subelementOffset);
}
}
return result;
}
// -------------------------------------------------------------------------
private getAttribsPosition(position: number): number {
var subelementsCount = this._bin.getUint8(position + 1)
return position + 2 + subelementsCount * (this._smallOffset ? 2 : 4);
}
// -------------------------------------------------------------------------
public getFolder(position: number): Folder {
this._tmpPosition = this.getAttribsPosition(position);
var id = 0;
var name = "";
for (var i = this._bin.getUint8(this._tmpPosition++) - 1; i >= 0; i--) {
switch (this._bin.getUint8(this._tmpPosition ++)) {
case SpriterBin.ATTR_FOLDER_ID:
id = this.readUint8();
break;
case SpriterBin.ATTR_FOLDER_NAME:
name = this.readString();
break;
}
}
return new Folder(id, name);
}
// -------------------------------------------------------------------------
public getFile(position: number): File {
console.log("skip sound loading");
this._tmpPosition = this.getAttribsPosition(position);
var id = 0;
var name = "";
var pivotX = 0;
var pivotY = 0;
for (var i = this._bin.getUint8(this._tmpPosition++) - 1; i >= 0; i--) {
switch (this._bin.getUint8(this._tmpPosition++)) {
case SpriterBin.ATTR_FILE_ID:
id = this.readUint8();
break;
case SpriterBin.ATTR_FILE_NAME:
name = this.readString();
break;
case SpriterBin.ATTR_FILE_PIVOT_X:
pivotX = this.readFixed16_16();
break;
case SpriterBin.ATTR_FILE_PIVOT_Y:
pivotY = this.readFixed16_16();
break;
case SpriterBin.ATTR_FILE_WIDTH:
case SpriterBin.ATTR_FILE_HEIGHT:
// ignore - just skip
this._tmpPosition += 2;
break;
}
}
return new File(id, this.getFileName(name), pivotX, 1 - pivotY);
}
// -------------------------------------------------------------------------
public getTag(position: number): Item {
console.error("implement loading Tag");
return null;
}
// -------------------------------------------------------------------------
public getEntity(position: number): Entity {
this._tmpPosition = this.getAttribsPosition(position);
var id = 0;
var name = "";
for (var i = this._bin.getUint8(this._tmpPosition++) - 1; i >= 0; i--) {
switch (this._bin.getUint8(this._tmpPosition++)) {
case SpriterBin.ATTR_ENTITY_ID:
id = this.readUint8();
break;
case SpriterBin.ATTR_ENTITY_NAME:
name = this.readString();
break;
}
}
return new Entity(id, name);
}
// -------------------------------------------------------------------------
public getObjectInfo(position: number, index: number): ObjectInfo {
this._tmpPosition = this.getAttribsPosition(position);
var name = "";
var type = eObjectType.SPRITE;
var width = 0;
var height = 0;
for (var i = this._bin.getUint8(this._tmpPosition++) - 1; i >= 0; i--) {
switch (this._bin.getUint8(this._tmpPosition++)) {
case SpriterBin.ATTR_OBJ_INFO_NAME:
name = this.readString();
break;
case SpriterBin.ATTR_OBJ_INFO_TYPE:
if (this.readUint8() === 1) {
type = eObjectType.BONE;
}
break;
case SpriterBin.ATTR_OBJ_INFO_WIDTH:
width = this.readFixed16_16();
break;
case SpriterBin.ATTR_OBJ_INFO_HEIGHT:
height = this.readFixed16_16();
break;
}
}
console.error("add loading of pivots");
return new ObjectInfo(index, name, type, width, height, 0, 0);
}
// -------------------------------------------------------------------------
public getCharMap(position: number): CharMap {
console.error("add loading of charmaps");
return null;
}
// -------------------------------------------------------------------------
public getCharMapEntry(position: number, charMap: CharMap, spriter: Spriter): void {
console.error("add loading of charmap entries");
return null;
}
// -------------------------------------------------------------------------
public getVariable(position: number): Variable {
console.error("add loading of variables");
return null;
}
// -------------------------------------------------------------------------
public getAnimation(position: number): Animation {
this._tmpPosition = this.getAttribsPosition(position);
var id = 0;
var name = "";
var length = 0;
var interval = 0;
var looping = eAnimationLooping.LOOPING;
for (var i = this._bin.getUint8(this._tmpPosition++) - 1; i >= 0; i--) {
switch (this._bin.getUint8(this._tmpPosition++)) {
case SpriterBin.ATTR_ANIMATION_ID:
id = this.readUint8();
break;
case SpriterBin.ATTR_ANIMATION_NAME:
name = this.readString();
break;
case SpriterBin.ATTR_ANIMATION_LENGTH:
length = this.readUint32();
break;
case SpriterBin.ATTR_ANIMATION_INTERVAL:
// ignore - skip
this._tmpPosition += 2;
break;
case SpriterBin.ATTR_ANIMATION_LOOPING:
looping = (this.readUint8() === 1) ? eAnimationLooping.LOOPING : eAnimationLooping.NO_LOOPING;
break;
}
}
return new Animation(id, name, length, looping);
}
// -------------------------------------------------------------------------
public getMainlineKey(position: number): KeyMainline {
this._tmpPosition = this.getAttribsPosition(position);
var id = 0;
var time = 0;
for (var i = this._bin.getUint8(this._tmpPosition++) - 1; i >= 0; i--) {
switch (this._bin.getUint8(this._tmpPosition++)) {
case SpriterBin.ATTR_MAINLINE_KEY_ID:
id = this.readUint8();
break;
case SpriterBin.ATTR_MAINLINE_KEY_TIME:
time = this.readUint32();
break;
}
}
return new KeyMainline(id, time);
}
// -------------------------------------------------------------------------
public getRef(position: number): Ref {
this._tmpPosition = this.getAttribsPosition(position);
var id = 0;
var parent = -1;
var timeline = 0;
var key = 0;
var z_index = 0;
for (var i = this._bin.getUint8(this._tmpPosition++) - 1; i >= 0; i--) {
switch (this._bin.getUint8(this._tmpPosition++)) {
case SpriterBin.ATTR_BONE_REF_ID:
case SpriterBin.ATTR_OBJ_REF_ID:
id = this.readUint8();
break;
case SpriterBin.ATTR_BONE_REF_PARENT:
case SpriterBin.ATTR_OBJ_REF_PARENT:
parent = this.readUint8();
break;
case SpriterBin.ATTR_BONE_REF_TIMELINE:
case SpriterBin.ATTR_OBJ_REF_TIMELINE:
timeline = this.readUint8();
break;
case SpriterBin.ATTR_BONE_REF_KEY:
case SpriterBin.ATTR_OBJ_REF_KEY:
key = this.readUint8();
break;
case SpriterBin.ATTR_OBJ_REF_Z:
z_index = this.readUint8();
break;
case SpriterBin.ATTR_OBJ_REF_NAME:
// waste
this.readString();
break;
case SpriterBin.ATTR_OBJ_REF_FOLDER:
case SpriterBin.ATTR_OBJ_REF_FILE:
++this._tmpPosition;
break;
case SpriterBin.ATTR_OBJ_REF_ABS_X:
case SpriterBin.ATTR_OBJ_REF_ABS_Y:
case SpriterBin.ATTR_OBJ_REF_ABS_PIVOT_X:
case SpriterBin.ATTR_OBJ_REF_ABS_PIVOT_Y:
case SpriterBin.ATTR_OBJ_REF_ABS_SCALE_X:
case SpriterBin.ATTR_OBJ_REF_ABS_SCALE_Y:
case SpriterBin.ATTR_OBJ_REF_ANGLE:
// skip
this._tmpPosition += 4;
break;
case SpriterBin.ATTR_OBJ_REF_ALPHA:
// skip
++this._tmpPosition;
break;
}
}
return new Ref(id, parent, timeline, key, z_index);
}
// -------------------------------------------------------------------------
public getTimeline(position: number): Timeline {
console.error("add loading of all types of objects");
this._tmpPosition = this.getAttribsPosition(position);
var id = 0;
var name = "";
var obj = 0;
var type = eObjectType.SPRITE;
for (var i = this._bin.getUint8(this._tmpPosition++) - 1; i >= 0; i--) {
switch (this._bin.getUint8(this._tmpPosition++)) {
case SpriterBin.ATTR_TIMELINE_ID:
id = this.readUint8();
break;
case SpriterBin.ATTR_TIMELINE_NAME:
name = this.readString();
break;
case SpriterBin.ATTR_TIMELINE_OBJ:
obj = this.readUint8();
break;
case SpriterBin.ATTR_TIMELINE_OBJ_TYPE:
if (this.readUint8() === 1) {
type = eObjectType.BONE;
}
break;
}
}
return new Timeline(id, name, type, obj);
}
// -------------------------------------------------------------------------
public getBaseline(position: number): Baseline {
console.error("add loading of baselines");
return null;
}
// -------------------------------------------------------------------------
public getVarline(position: number): Varline {
console.error("add loading of varlines");
return null;
}
// -------------------------------------------------------------------------
public getKey(position: number): Key {
console.error("add loading of keys");
return null;
}
// -------------------------------------------------------------------------
public getTagKey(position: number): KeyTag {
console.error("add loading of tag keys");
return null;
}
// -------------------------------------------------------------------------
public getVariableKey(position: number, type: eVariableType): KeyVariable {
console.error("add loading of variable keys");
return null;
}
// -------------------------------------------------------------------------
public getTimelineKey(position: number, index: number, spriter: Spriter): KeyTimeline {
this._tmpPosition = this.getAttribsPosition(position);
var time = 0;
var spin = 1;
// curve and params
var curve = eCurveType.LINEAR;
var c1 = 0;
var c2 = 0;
var c3 = 0;
var c4 = 0;
for (var i = this._bin.getUint8(this._tmpPosition++) - 1; i >= 0; i--) {
switch (this._bin.getUint8(this._tmpPosition++)) {
case SpriterBin.ATTR_TIMELINE_KEY_ID:
// skip
++this._tmpPosition;
break;
case SpriterBin.ATTR_TIMELINE_KEY_TIME:
time = this.readUint32();
break;
case SpriterBin.ATTR_TIMELINE_KEY_SPIN:
spin = this.readInt8();
break;
case SpriterBin.ATTR_TIMELINE_KEY_CURVE:
curve = <eCurveType>this.readUint8();
break;
case SpriterBin.ATTR_TIMELINE_KEY_C1:
c1 = this.readFixed1_7();
break;
case SpriterBin.ATTR_TIMELINE_KEY_C2:
c2 = this.readFixed1_7();
break;
}
}
// get child element
position += 2
var offset = position + (this._smallOffset ? this._bin.getUint16(position, true) : this._bin.getUint32(position, true));
var elementType = this._bin.getUint8(offset);
var key: KeyTimeline = null;
var keyDataElm = null;
var sprite: boolean = false;
if (elementType === 14 /* bone */) {
key = new KeyBone(index, time, spin);
} else if (elementType === 15 /* object */) {
key = new KeyObject(index, time, spin);
sprite = true;
}
// other curve than linear?
if (curve !== eCurveType.LINEAR) {
key.setCurve(curve, c1, c2, c3, c4);
}
this._tmpPosition = this.getAttribsPosition(offset);
// spatial info
var info = key.info;
info.x = 0; //this.parseFloat(keyDataElm, "x");
info.y = 0; //-this.parseFloat(keyDataElm, "y");
info.scaleX = 1; // this.parseFloat(keyDataElm, "scale_x", 1);
info.scaleY = 1; //this.parseFloat(keyDataElm, "scale_y", 1);
info.angle = 0; //360 - this.parseFloat(keyDataElm, "angle");
info.alpha = 1; //this.parseFloat(keyDataElm, "a", 1);
var pivotX = 0;
var hasPivotX = false;
var pivotY = 0;
var hasPivotY = false;
var folder = 0;
var file = 0;
for (var i = this._bin.getUint8(this._tmpPosition++) - 1; i >= 0; i--) {
switch (this._bin.getUint8(this._tmpPosition++)) {
case SpriterBin.ATTR_BONE_X:
case SpriterBin.ATTR_OBJ_X:
info.x = this.readFixed16_16();
break;
case SpriterBin.ATTR_BONE_Y:
case SpriterBin.ATTR_OBJ_Y:
info.y = -this.readFixed16_16();
break;
case SpriterBin.ATTR_BONE_ANGLE:
case SpriterBin.ATTR_OBJ_ANGLE:
info.angle = 360 - this.readFixed16_16();
break;
case SpriterBin.ATTR_BONE_SCALE_X:
case SpriterBin.ATTR_OBJ_SCALE_X:
info.scaleX = this.readFixed16_16();
break;
case SpriterBin.ATTR_BONE_SCALE_Y:
case SpriterBin.ATTR_OBJ_SCALE_Y:
info.scaleY = this.readFixed16_16();
break;
case SpriterBin.ATTR_OBJ_FOLDER:
folder = this.readUint8();
break;
case SpriterBin.ATTR_OBJ_FILE:
file = this.readUint8();
break;
case SpriterBin.ATTR_OBJ_PIVOT_X:
pivotX = this.readFixed16_16();
hasPivotX = true;
break;
case SpriterBin.ATTR_OBJ_PIVOT_Y:
pivotY = this.readFixed16_16();
hasPivotY = true;
break;
case SpriterBin.ATTR_OBJ_ALPHA:
info.alpha = this.readFixed1_7();
break;
}
}
if (sprite) {
(<KeyObject>key).setFolderAndFile(folder, file);
// set pivot in spatial info different from default (based on pivot in file)
var fileObj = spriter.getFolderById(folder).getFileById(file);
info.pivotX = hasPivotX ? pivotX : fileObj.pivotX;
// 1 - to flip Y, default anchor is already flipped, so it needs to be flipped back to avoid double flipping
info.pivotY = 1 - (hasPivotY ? pivotY : 1 - fileObj.pivotY);
}
return key;
}
// -------------------------------------------------------------------------
public getTagChange(position: number): number {
console.error("add loading of tag changes");
return null;
}
}
} | the_stack |
import * as moment from 'moment';
import { Order } from 'ccxt';
import { Influx } from '../../Influx/Influx';
import { Candle } from '../../Env/Candle';
import { logger } from '../../../logger';
import { MEASUREMENT_PORTFOLIO, MEASUREMENT_TRADES } from '../../Influx/constants';
import { PortfolioModel } from './model';
export interface PortfolioConfig {
name: string;
capital: number;
base: string;
quote: string;
exchange: string;
backtest: boolean;
}
export interface PortfolioIndicators {
currentCapital: number;
assetCapital: number;
totalValue: number;
fees: number;
currentProfit: number;
holdProfit: number;
nbTradeWin: number;
percentTradeWin: number;
}
export interface PortfolioTrade {
orderBuy: Order;
orderSell: Order | undefined;
orderProfit: number;
maxProfit: number;
}
/**
* Portfolio class help to track and calculate statistic about different metrics (buy/sell/profit/...)
*
* @export
* @class Portfolio
*/
export class Portfolio {
public indicators: PortfolioIndicators;
public trade: PortfolioTrade | undefined;
public indicatorHistory: PortfolioIndicators[] = [];
public tradeHistory: PortfolioTrade[] = [];
private lastCandle: Candle;
private firstCandle: Candle | undefined;
// Buffer size of history (indicator/trades)
private bufferSize: number = 2000;
// InfluxDb client
private influx: Influx;
/**
* Flush (Help to write data to influxDB efficiently in backtest mode)
* - BACKTEST => will flush data to influxDB every 5 secondes
* - STREAMING => will flush every minutes "normal behavior"
*/
private flushTimeout = 10;
private lastFlushTime: number = new Date().getTime();
private lastPersistTime: number = new Date().getTime();
private updateBuffer: any[] = [];
private buyBuffer: any[] = [];
private sellBuffer: any[] = [];
private hasInitSeries: boolean;
constructor(public conf: PortfolioConfig) {}
/**
* Init the portfolio
*
* @param {Influx} influx
* @returns {Promise<void>}
* @memberof Portfolio
*/
public async init(influx: Influx, flush: boolean = true): Promise<void> {
this.influx = influx;
if (flush) await this.cleanInflux();
this.hasInitSeries = false;
this.reset();
}
/**
* Reload portfolio state from MongoDB
*
* @param {Influx} influx
* @param {boolean} [flush=true]
* @returns {Promise<void>}
* @memberof Portfolio
*/
public async reload(influx: Influx, flush: boolean = false): Promise<void> {
this.influx = influx;
if (flush) await this.cleanInflux();
this.hasInitSeries = false;
let portfolio = await PortfolioModel.findOne({ name: this.conf.name });
if (!portfolio) throw Error(`Cannot find portoflio ${this.conf.name}`);
portfolio = portfolio.toJSON() as PortfolioModel;
this.indicators = portfolio.indicators;
this.trade = portfolio.trade;
this.tradeHistory = portfolio.tradeHistory;
this.indicatorHistory = portfolio.indicatorHistory;
this.firstCandle = portfolio.firstCandle;
}
/**
* Reset portfolio
*
* @memberof Portfolio
*/
public reset(): void {
this.indicators = {
currentCapital: this.conf.capital,
totalValue: this.conf.capital,
assetCapital: 0,
fees: 0,
currentProfit: 0,
holdProfit: 0,
nbTradeWin: 0,
percentTradeWin: 0,
};
this.indicatorHistory = [];
this.trade = undefined;
this.tradeHistory = [];
this.firstCandle = undefined;
}
/**
* Clean influx db data
*
* @returns {Promise<void>}
* @memberof Portfolio
*/
public async cleanInflux(): Promise<void> {
const tags = { name: this.conf.name };
await this.influx.dropSerie(MEASUREMENT_PORTFOLIO, tags);
await this.influx.dropSerie(MEASUREMENT_TRADES, tags);
}
/**
* Notify portfolio for a new buy order
*
* @param {Order} order
* @memberof Portfolio
*/
public async notifyBuy(order: Order): Promise<void> {
// on Buy currentCapital decrease by the cost
this.indicators.currentCapital -= order.cost + order.fee.cost;
this.indicators.assetCapital += order.filled;
this.indicators.fees += order.fee.cost;
this.buyBuffer.push({
time: order.timestamp,
values: {
price: order.price,
cost: order.cost,
fee: order.fee.cost,
amount: order.amount,
},
});
this.trade = {
orderBuy: order,
orderSell: undefined,
orderProfit: 0,
maxProfit: 0,
};
this.pushTrade();
await this.flush();
await this.persistMongo();
}
/**
* Notify portfolio for a new sell order
*
* @param {Order} order
* @memberof Portfolio
*/
public async notifySell(order: Order): Promise<void> {
this.indicators.currentCapital += order.cost - order.fee.cost;
this.indicators.assetCapital -= order.filled;
this.indicators.fees += order.fee.cost;
this.sellBuffer.push({
time: order.timestamp,
values: {
price: order.price,
cost: order.cost,
fee: order.fee.cost,
amount: order.amount,
},
});
// Update trade sell order and refresh tradeHistory with new sell order
this.trade!.orderSell = order;
// Profit % => (SellPrice - BuyPrice (-fees)) / BuyPrice
this.trade!.orderProfit =
(order.cost - this.trade!.orderBuy.cost - (this.trade!.orderBuy.fee.cost + order.fee.cost)) /
this.trade!.orderBuy.cost;
// Update others indicators
if (this.trade!.orderProfit > 0) this.indicators.nbTradeWin += 1;
this.indicators.percentTradeWin = this.indicators.nbTradeWin / this.tradeHistory.length;
this.tradeHistory.pop();
this.pushTrade();
this.trade = undefined;
await this.flush();
await this.persistMongo();
}
/**
* Update portofolio statistics with new candle
*
* @param {Candle} lastCandle
* @memberof Portfolio
*/
public update(lastCandle: Candle): void {
if (!this.firstCandle) this.firstCandle = lastCandle;
this.lastCandle = lastCandle;
this.indicators.totalValue = this.indicators.currentCapital + this.indicators.assetCapital * lastCandle.close;
this.indicators.currentProfit = (this.indicators.totalValue - this.conf.capital) / this.conf.capital;
this.indicators.holdProfit = (this.lastCandle.close - this.firstCandle.close) / this.firstCandle.close;
if (this.trade) {
this.trade.orderProfit =
(lastCandle.close * this.trade.orderBuy.filled - this.trade.orderBuy.cost - this.trade.orderBuy.fee.cost) /
this.trade.orderBuy.cost;
if (this.trade.orderProfit > this.trade.maxProfit) {
this.trade.maxProfit = this.trade.orderProfit;
}
}
// If first call to Update (init buffer serie)
if (!this.hasInitSeries) {
// Copy indicator
const indicator: PortfolioIndicators = JSON.parse(JSON.stringify(this.indicators));
this.pushIndicator(indicator);
this.updateBuffer.push({ values: indicator, time: lastCandle.time });
this.hasInitSeries = true;
}
}
/**
* Save portfolio data to influx
*
* @param {Candle} lastCandle
* @returns {Promise<void>}
* @memberof Portfolio
*/
public async save(): Promise<void> {
// Copy indicator
const indicator: PortfolioIndicators = JSON.parse(JSON.stringify(this.indicators));
this.pushIndicator(indicator);
this.updateBuffer.push({ values: indicator, time: this.lastCandle.time });
await this.flush();
await this.persistMongo();
}
/**
* Persist portfolio data to MongoDB
*
* @memberof Portfolio
*/
public async persistMongo(force = false) {
if (!this.conf.backtest || force || moment().diff(moment(this.lastPersistTime), 's') >= this.flushTimeout) {
const portfolio = {
...this.conf,
indicators: this.indicators,
trade: this.trade,
indicatorHistory: this.indicatorHistory,
tradeHistory: this.tradeHistory,
firstCandle: this.firstCandle,
};
try {
await PortfolioModel.findOneAndUpdate({ name: this.conf.name }, portfolio, { upsert: true });
} catch (error) {
logger.error(error);
logger.error(new Error(`[${this.conf.name}] Error while saving portfolio ${this.conf.name}`));
}
// reset persist time (even if error, will try to persist again later)
this.lastPersistTime = new Date().getTime();
}
}
/**
* Flush data to influxDB
*
* @param {boolean} [force=false]
* @returns {Promise<void>}
* @memberof Portfolio
*/
public async flush(force: boolean = false): Promise<void> {
// If lastFlushTime > flushTimeout flush buffer
// - Backtest every 5 second
// - Streaming every minutes "normal behavior"
if (!this.conf.backtest || force || moment().diff(moment(this.lastFlushTime), 's') >= this.flushTimeout) {
// Write async (update/buy/sell)
const tags = { name: this.conf.name };
try {
await this.influx.writeData(tags, this.updateBuffer, MEASUREMENT_PORTFOLIO);
await this.influx.writeData({ ...tags, side: 'buy' }, this.buyBuffer, MEASUREMENT_TRADES);
await this.influx.writeData({ ...tags, side: 'sell' }, this.sellBuffer, MEASUREMENT_TRADES);
this.updateBuffer = [];
this.buyBuffer = [];
this.sellBuffer = [];
} catch (error) {
logger.error(error);
logger.error(new Error(`[${this.conf.name}] Problem while saving portfolio state to influx`));
}
// reset flush time (even if error, will try to flush again later)
this.lastFlushTime = new Date().getTime();
}
}
/**
* Helper push an indicator
*
* @private
* @param {PortfolioIndicators} indicators
* @memberof Portfolio
*/
private pushIndicator(indicators: PortfolioIndicators): void {
this.indicatorHistory.push(indicators);
if (this.indicatorHistory.length > this.bufferSize) {
this.indicatorHistory.splice(0, this.indicatorHistory.length - this.bufferSize);
}
}
/**
* Helper push the current trade in history
*
* @private
* @memberof Portfolio
*/
private pushTrade(): void {
const trade = JSON.parse(JSON.stringify(this.trade));
this.tradeHistory.push(trade);
if (this.tradeHistory.length > this.bufferSize) {
this.tradeHistory.splice(0, this.tradeHistory.length - this.bufferSize);
}
}
} | the_stack |
import { Component, OnInit, ViewChild } from '@angular/core';
import { TabsetComponent } from 'ngx-bootstrap/tabs';
import { ReportDescriptorVO, ReportRequestVO, ReportRequestParameterVO, Pair } from './../shared/model/index';
import { ShopVO, FulfilmentCentreInfoVO } from './../shared/model/index';
import { FormValidationEvent } from './../shared/event/index';
import { ReportsService, ImpexService, I18nEventBus, UserEventBus } from './../shared/services/index';
import { ModalComponent, ModalResult, ModalAction } from './../shared/modal/index';
import { FulfilmentCentreSelectComponent } from "./../shared/fulfilment/index";
import { Futures, Future } from './../shared/event/index';
import { Config } from './../../environments/environment';
import { LogUtil } from './../shared/log/index';
import { UiUtil } from './../shared/ui/uiutil';
@Component({
selector: 'cw-reports',
templateUrl: 'reports.component.html',
})
export class ReportsComponent implements OnInit {
private static tabs:Array<QueryTabData> = [];
public reports:Array<ReportDescriptorVO> = [];
public filteredReports:Array<ReportDescriptorVO> = [];
public reportFilter:string = null;
public runnableReportTab:boolean = false;
public selectedReport:ReportDescriptorVO = null;
private delayedFiltering:Future;
private delayedFilteringMs:number = Config.UI_INPUT_DELAY;
public selectedTab:number = 0;
public fileFilter:string = null;
public selectedFile:Pair<string,string> = null;
@ViewChild('selectFileModalDialog')
private selectFileModalDialog:ModalComponent;
@ViewChild('selectShopModalDialog')
private selectShopModalDialog:ModalComponent;
@ViewChild('selectReportModalDialog')
private selectReportModalDialog:ModalComponent;
@ViewChild('selectCentreModalDialog')
private selectCentreModalDialog:FulfilmentCentreSelectComponent;
private selectedParam:ReportRequestParameterVO = null;
public selectedShop:ShopVO = null;
@ViewChild('reportTabs')
private reportTabs:TabsetComponent;
/**
* Construct reports panel
*
* @param _reportsService reports service
*/
constructor(private _reportsService: ReportsService,
private _fileService : ImpexService) {
LogUtil.debug('ReportsComponent constructed');
}
get tabs():Array<QueryTabData> {
return ReportsComponent.tabs;
}
set tabs(tabs:Array<QueryTabData>) {
ReportsComponent.tabs = tabs;
}
public ngOnInit() {
LogUtil.debug('ReportsComponent ngOnInit');
this.onRefreshHandler();
let that = this;
this.delayedFiltering = Futures.perpetual(function() {
that.reloadReportList();
}, this.delayedFilteringMs);
}
tabSelected(idx:number) {
this.selectedTab = idx;
this.validateCurrentTabForm();
}
onNewTabHandler() {
if (this.selectedReport != null) {
let descriptor:ReportDescriptorVO = this.selectedReport;
if (descriptor != null) {
let lang = I18nEventBus.getI18nEventBus().current();
let request:ReportRequestVO = {
reportId: descriptor.reportId,
displayNames : descriptor.displayNames,
parameters: [],
reportType : descriptor.reportType,
reportFileExtension : descriptor.reportFileExtension,
reportFileMimeType : descriptor.reportFileMimeType,
lang: lang
};
descriptor.parameters.forEach(param => {
let rp:ReportRequestParameterVO = {
parameterId: param.parameterId,
displayNames: param.displayNames,
options: [],
value: null,
displayValue: null,
businesstype: param.businesstype,
mandatory : param.mandatory,
editorType: param.editorType,
editorProperty: param.editorProperty,
displayProperty: param.displayProperty
};
request.parameters.push(rp);
});
LogUtil.debug('ReportsComponent onNewTabHandler', descriptor, request);
this._reportsService.updateReportRequestValues(request).subscribe((res:ReportRequestVO) => {
LogUtil.debug('ReportsComponent request', res);
let _tab:QueryTabData = { descriptor: descriptor, request: res, running: false, completed: false, filename: null, success: true };
this.tabs.push(_tab);
let that = this;
Futures.once(function () {
if (that.reportTabs.tabs.length == that.tabs.length) {
that.selectedTab = that.tabs.length - 1;
if (!that.reportTabs.tabs[that.selectedTab].active) {
that.reportTabs.tabs[that.selectedTab].active = true;
}
} else if (that.tabs.length == 1) {
that.selectedTab = 0;
}
}, 50).delay();
});
}
}
}
onDateValueChange(event:any, requestParam:ReportRequestParameterVO) {
LogUtil.debug('ReportsComponent date change', event);
if (event.valid) {
let data:QueryTabData = this.tabs[this.selectedTab];
data.completed = false;
requestParam.value = event.source;
this.validateCurrentTabForm();
}
}
onDataChange(event:any) {
LogUtil.debug('ReportsComponent data change', event);
let data:QueryTabData = this.tabs[this.selectedTab];
data.completed = false;
this.validateCurrentTabForm();
}
validateCurrentTabForm() {
let data:QueryTabData = this.tabs[this.selectedTab];
LogUtil.debug('ReportsComponent validating tab', data);
let valid = data != null && !data.running;
if (valid) {
data.request.parameters.forEach((param:ReportRequestParameterVO) => {
if (param.mandatory && (param.value == null || param.value == '')) {
valid = false;
}
});
}
this.runnableReportTab = valid;
LogUtil.debug('ReportsComponent tab is valid', this.runnableReportTab);
}
onTabDeleteTab(tab:QueryTabData) {
if (tab != null) {
let idx = this.tabs.indexOf(tab);
if (idx != -1) {
let wasActive = this.selectedTab == idx;
this.tabs.splice(idx, 1);
this.tabs = this.tabs.slice(0, this.tabs.length);
if (wasActive) {
this.selectedTab = -1;
}
}
}
}
onRunHandler() {
LogUtil.debug('ReportsComponent Run handler');
let data = this.tabs[this.selectedTab];
data.running = true;
this._reportsService.generateReport(data.request).subscribe(res => {
LogUtil.debug('ReportsComponent res', res);
data.running = false;
data.filename = res;
data.success = res != null && res != '';
data.completed = data.success;
this.validateCurrentTabForm();
});
}
onDownloadClick() {
let data = this.tabs[this.selectedTab];
LogUtil.debug('ReportsComponent onDownloadClick handler', data);
if (data.completed) {
this.fileFilter = data.filename;
this.downloadSingleFile(this.fileFilter);
}
}
onNewReportClick() {
if (this.reports.length == 0) {
this.onRefreshHandler();
}
this.selectReportModalDialog.show();
}
onFileSelect(file:Pair<string, string>) {
LogUtil.debug('ReportsComponent onFileSelect', file);
this.selectedFile = file;
}
onFileDownload() {
LogUtil.debug('ReportsComponent onFileSelect');
this.selectFileModalDialog.show();
}
onFilesConfirmationResult(modalresult: ModalResult) {
LogUtil.debug('ReportsComponent onFilesConfirmationResult modal result is ', modalresult);
if (ModalAction.POSITIVE === modalresult.action) {
if (this.selectedFile != null) {
this._reportsService.downloadReport(this.selectedFile.first).subscribe(res => {
LogUtil.debug('ReportsComponent downloaded report', this.selectedFile, res);
});
}
}
this.selectedFile = null;
}
onSelectClick(report: ReportDescriptorVO) {
LogUtil.debug('ReportsComponent onSelectClick', report);
this.selectedReport = report;
}
onRefreshHandler() {
LogUtil.debug('ReportsComponent refresh handler');
if (UserEventBus.getUserEventBus().current() != null) {
this.getReportInfo();
}
}
onFilterChange() {
this.delayedFiltering.delay();
}
onClearFilter() {
this.reportFilter = '';
this.delayedFiltering.delay();
}
getReportName(report:ReportDescriptorVO):string {
let lang = I18nEventBus.getI18nEventBus().current();
let i18n = report.displayNames;
let def = report.reportId;
return UiUtil.toI18nString(i18n, def, lang);
}
getReportParamName(param:ReportRequestParameterVO):string {
let lang = I18nEventBus.getI18nEventBus().current();
let i18n = param.displayNames;
let def = param.parameterId;
return UiUtil.toI18nString(i18n, def, lang);
}
onEditParameterValueClick(param:ReportRequestParameterVO) {
LogUtil.debug('ReportsComponent onEditParameterValueClick', param);
switch (param.editorType) {
case 'FulfilmentCentreSelect':
this.selectedParam = param;
this.selectCentreModalDialog.showDialog();
break;
case 'ShopSelect':
this.selectedParam = param;
this.selectShopModalDialog.show();
break;
}
}
onShopSelected(event:ShopVO) {
LogUtil.debug('ReportsComponent onShopSelected', event);
this.selectedShop = event;
}
onSelectShopResult(modalresult: ModalResult) {
LogUtil.debug('ReportsComponent onSelectShopResult modal result is ', modalresult, this.selectedShop);
if (ModalAction.POSITIVE === modalresult.action) {
if (this.selectedShop != null) {
this.selectedParam.value = this.selectedShop[this.selectedParam.editorProperty];
this.selectedParam.displayValue = this.selectedShop[this.selectedParam.displayProperty];
} else {
this.selectedParam.value = null;
this.selectedParam.displayValue = null;
}
LogUtil.debug('ReportsComponent onSelectShopResult selectedParam is ', this.selectedParam);
this.onDataChange(null);
}
}
onFulfilmentCentreSelected(event:FormValidationEvent<FulfilmentCentreInfoVO>) {
LogUtil.debug('ReportsComponent onFulfilmentCentreSelected', event);
if (event.valid) {
this.selectedParam.value = event.source[this.selectedParam.editorProperty];
this.selectedParam.displayValue = event.source[this.selectedParam.displayProperty];
} else {
this.selectedParam.value = null;
this.selectedParam.displayValue = null;
}
LogUtil.debug('ReportsComponent onSelectShopResult selectedParam is ', this.selectedParam);
this.onDataChange(null);
}
onSelectReportResult(modalresult: ModalResult) {
LogUtil.debug('ReportsComponent onSelectReportResult modal result is ', modalresult, this.selectedReport);
if (ModalAction.POSITIVE === modalresult.action) {
if (this.selectedReport != null) {
this.onNewTabHandler();
}
}
}
/**
* Read attributes.
*/
private getReportInfo() {
LogUtil.debug('ReportsComponent get reports');
let lang = I18nEventBus.getI18nEventBus().current();
this._reportsService.getReportDescriptors(lang).subscribe(reports => {
LogUtil.debug('ReportsComponent reports', reports);
this.reports = reports;
this.selectedReport = this.reports[0];
this.reloadReportList();
});
}
private reloadReportList() {
if (this.reports != null) {
if (this.reportFilter) {
let _filter = this.reportFilter.toLowerCase();
this.filteredReports = this.reports.filter(report =>
this.getReportName(report).toLowerCase().indexOf(_filter) !== -1
);
LogUtil.debug('ReportsComponent reloadReportList filter: ' + _filter, this.filteredReports);
} else {
this.filteredReports = this.reports;
LogUtil.debug('ReportsComponent reloadReportList no filter', this.filteredReports);
}
}
}
private downloadSingleFile(fileName:string) {
this._fileService.getFiles('export').subscribe(list => {
LogUtil.debug('ReportsComponent res reading list', list);
let _file = list.find(file => file.first.indexOf(fileName) != -1);
if (_file != null) {
LogUtil.debug('ReportsComponent res downloading', _file);
this._reportsService.downloadReport(_file.first).subscribe(downloaded => {
LogUtil.debug('ReportsComponent res downloaded', _file, downloaded);
});
}
});
}
}
interface QueryTabData {
descriptor : ReportDescriptorVO;
request : ReportRequestVO;
running : boolean;
completed : boolean;
filename : string;
success : boolean;
} | the_stack |
import NoodeDefinition from '../types/NoodeDefinition';
import NoodelOptions from '../types/NoodelOptions';
import NoodeState from '../types/NoodeState';
import NoodelState from '../types/NoodelState';
import { showActiveSubtree } from './noodel-mutate';
import { setupRouting, unsetRouting } from './noodel-routing';
import NoodeOptions from '../types/NoodeOptions';
import { generateNoodeId, registerNoodeSubtree, findNoodeViewState, isIdRegistered, findNoodeViewModel } from './id-register';
import { alignNoodelOnJump } from './noodel-navigate';
import { cancelPan } from './noodel-pan';
import { resetAlignment } from './noodel-align';
import { traverseDescendents } from './noodel-traverse';
import { attachBranchResizeSensor, attachCanvasResizeSensor, attachResizeSensor, detachBranchResizeSensor, detachResizeSensor } from './resize-detect';
export function setupNoodel(root: NoodeDefinition, options: NoodelOptions): NoodelState {
let noodel: NoodelState = {
idCount: -1,
idMap: new Map([]),
throttleMap: new Map([]),
debounceMap: new Map([]),
eventQueue: [],
root: null,
focalParent: null,
focalLevel: 1,
trunkOffset: 0,
applyTrunkMove: false,
branchStartReached: false,
branchEndReached: false,
trunkStartReached: false,
trunkEndReached: false,
panOriginTrunk: null,
panOriginBranch: null,
panAxis: null,
isInInspectMode: false,
containerHeight: 0,
containerWidth: 0,
options: {
visibleSubtreeDepth: 1,
retainDepthOnTapNavigation: false,
swipeMultiplierBranch: 1,
swipeMultiplierTrunk: 1,
snapMultiplierBranch: 1,
snapMultiplierTrunk: 1,
subtreeDebounceInterval: 360,
useRouting: true,
useKeyNavigation: true,
useWheelNavigation: true,
useSwipeNavigation: true,
useTapNavigation: true,
useInspectModeKey: true,
useInspectModeDoubleTap: true,
useResizeDetection: true,
useOverflowDetection: false,
showLimitIndicators: true,
showBranchBackdrops: false,
showChildIndicators: true,
onMount: null,
onEnterInspectMode: null,
onExitInspectMode: null,
onFocalNoodeChange: null,
onFocalParentChange: null,
orientation: "ltr",
branchDirection: "normal"
},
onHashChanged: null,
lastPanTimestamp: null,
swipeVelocityBuffer: []
}
let rootNoode = buildNoodeView(noodel, root, 0, null, true, 0);
noodel.root = rootNoode;
noodel.focalParent = rootNoode;
registerNoodeSubtree(noodel, rootNoode);
parseAndApplyOptions(options, noodel);
showActiveSubtree(noodel, rootNoode, noodel.options.visibleSubtreeDepth);
if (noodel.options.useRouting) {
let hash = window.location.hash;
if (hash) {
let target = findNoodeViewState(noodel, hash.substr(1));
if (target && target.parent) {
alignNoodelOnJump(noodel, target);
}
}
}
return noodel;
}
/**
* Recursively parses the given HTML element into a noode tree.
*/
export function parseHTMLToNoode(el: Element): NoodeDefinition {
let id = el.getAttribute('data-id');
let className = el.getAttribute('data-class');
let style = el.getAttribute('data-style');
let isActive = el.hasAttribute('data-active');
let content = '';
let noodeCount = 0;
let children: NoodeDefinition[] = [];
for (let i = 0; i < el.childNodes.length; i++) {
const node = el.childNodes[i];
if (node.nodeType === Node.TEXT_NODE) {
content += node.textContent; // Depends on css white-space property for ignoring white spaces
}
else if (node.nodeType === Node.ELEMENT_NODE) {
if (node.nodeName === "DIV" && (node as Element).className.split(' ').some(c => c === 'noode')) {
noodeCount++;
children.push(parseHTMLToNoode(node as Element));
}
else {
content += (node as Element).outerHTML; // Depends on css white-space property for ignoring white spaces
}
}
}
return {
id: id,
content: content || null,
isActive: isActive,
children: children,
className: className,
style: style
};
}
export function setupCanvasEl(noodel: NoodelState) {
let rect = noodel.canvasEl.getBoundingClientRect();
noodel.containerWidth = rect.width;
noodel.containerHeight = rect.height;
attachCanvasResizeSensor(noodel);
}
export function parseAndApplyOptions(options: NoodelOptions, noodel: NoodelState) {
let oldOrientation = noodel.options.orientation;
let oldBranchDirection = noodel.options.branchDirection;
let oldUseResizeDetection = noodel.options.useResizeDetection;
noodel.options = {
...noodel.options,
...options
}
if (!options.useSwipeNavigation) cancelPan(noodel);
if (noodel.options.useRouting) {
setupRouting(noodel);
}
else {
unsetRouting(noodel);
}
if (noodel.isMounted) {
let newOrientation = noodel.options.orientation;
let newBranchDirection = noodel.options.branchDirection;
if (((oldOrientation === 'ltr' || oldOrientation === 'rtl') && (newOrientation === 'ttb' || newOrientation === 'btt')) ||
((oldOrientation === 'ttb' || oldOrientation === 'btt') && (newOrientation === 'ltr' || newOrientation === 'rtl'))) {
resetAlignment(noodel);
}
else if (newBranchDirection !== oldBranchDirection) {
// prevents transition going haywire, not necessary if orientation also changes since
// realignAll will do it
traverseDescendents(noodel.root, noode => noode.applyBranchMove = false, true);
}
let newUseResizeDetection = noodel.options.useResizeDetection;
if (oldUseResizeDetection && !newUseResizeDetection) {
traverseDescendents(noodel.root, desc => {
detachBranchResizeSensor(desc);
detachResizeSensor(desc);
}, true);
}
else if (newUseResizeDetection && !oldUseResizeDetection) {
traverseDescendents(noodel.root, desc => {
attachBranchResizeSensor(noodel, desc);
attachResizeSensor(noodel, desc);
}, true);
}
}
}
export function parseAndApplyNoodeOptions(noodel: NoodelState, options: NoodeOptions, noode: NoodeState) {
let oldUseResizeDetection = typeof noode.options.useResizeDetection === "boolean"
? noode.options.useResizeDetection
: noodel.options.useResizeDetection;
let oldUseBranchResizeDetection = typeof noode.options.useBranchResizeDetection === 'boolean'
? noode.options.useBranchResizeDetection
: noodel.options.useResizeDetection;
noode.options = {
...noode.options,
...options
};
if (noodel.isMounted) {
let newUseResizeDetection = typeof noode.options.useResizeDetection === "boolean"
? noode.options.useResizeDetection
: noodel.options.useResizeDetection;
let newUseBranchResizeDetection = typeof noode.options.useBranchResizeDetection === 'boolean'
? noode.options.useBranchResizeDetection
: noodel.options.useResizeDetection;
if (oldUseResizeDetection && !newUseResizeDetection) {
detachResizeSensor(noode);
}
else if (newUseResizeDetection && !oldUseResizeDetection) {
attachResizeSensor(noodel, noode);
}
if (oldUseBranchResizeDetection && !newUseBranchResizeDetection) {
detachBranchResizeSensor(noode);
}
else if (newUseBranchResizeDetection && !oldUseBranchResizeDetection) {
attachBranchResizeSensor(noodel, noode);
}
}
}
export function buildNoodeView(noodel: NoodelState, def: NoodeDefinition, index: number, parent: NoodeState, isActive: boolean, branchRelativeOffset: number): NoodeState {
let isRoot = parent === null;
if (!def.children) def.children = [];
// parse and validate ID
let newId = null;
if (typeof def.id === 'string') {
if (isIdRegistered(noodel, def.id)) {
throw new Error("Duplicate ID for new noode: " + def.id);
}
newId = def.id;
}
else {
newId = generateNoodeId(noodel);
}
// parse and validate active child index
let activeChildIndex = def.children.length > 0 ? 0 : null;
for (let i = 0; i < def.children.length; i++) {
if (def.children[i].isActive) {
activeChildIndex = i;
break;
}
}
let newView: NoodeState = {
index: index,
level: isRoot ? 0 : parent.level + 1,
isBranchVisible: false,
isBranchTransparent: true, // initialize to transparent state for capturing size
isFocalParent: isRoot, // only initialze root as focal parent
isActive: isActive,
size: 0,
trunkRelativeOffset: isRoot ? 0 : parent.trunkRelativeOffset + parent.branchSize,
branchOffset: 0,
applyBranchMove: false,
isInInspectMode: false,
branchRelativeOffset: branchRelativeOffset,
branchSize: 0,
parent: parent,
id: newId,
children: [],
content: def.content || null,
className: parseClassName(def.className),
style: parseStyle(def.style),
activeChildIndex: activeChildIndex,
options: {
useResizeDetection: null,
useBranchResizeDetection: null,
showBranchBackdrop: null,
showChildIndicator: null,
onChildrenEnterFocus: null,
onChildrenExitFocus: null,
onEnterFocus: null,
onExitFocus: null,
},
hasOverflowTop: false,
hasOverflowLeft: false,
hasOverflowBottom: false,
hasOverflowRight: false
}
// temporarily use the view object as a holder for custom data, will be removed later
if (def.data !== undefined) newView["data"] = def.data;
if (def.options && typeof def.options === "object") {
parseAndApplyNoodeOptions(noodel, def.options, newView);
}
for (let i = 0; i < def.children.length; i++) {
newView.children.push(buildNoodeView(noodel, def.children[i], i, newView, i === activeChildIndex, 0));
}
return newView;
}
export function extractNoodeDefinition(noodel: NoodelState, noode: NoodeState): NoodeDefinition {
let data = findNoodeViewModel(noodel, noode.id).data;
let def: NoodeDefinition = {
id: noode.id,
content: noode.content,
isActive: noode.isActive,
children: noode.children.map(c => extractNoodeDefinition(noodel, c)),
className: noode.className,
style: noode.style,
options: {
...noode.options
}
};
if (data !== undefined) def.data = data;
return def;
}
export function parseClassName(className: string | string[]): string[] {
if (Array.isArray(className)) return className;
if (className && typeof className === 'string') return className.split(' ');
return [];
}
export function parseStyle(style: string | object): object {
if (style && typeof style === 'object') return style;
if (style && typeof style === 'string') {
let styles = style.split(';').map(s => s.split(':').map(t => t.trim())).filter(s => s.length === 2);
let styleObj = {};
styles.forEach(s => {
styleObj[s[0]] = s[1];
});
return styleObj;
}
return {};
} | the_stack |
declare class AudioHelper {
constructor();
/**
* The primary Audio Context used to play client-facing sounds.
* The context is undefined until the user's first gesture is observed.
* @defaultValue `undefined`
*/
context: AudioContext | undefined;
/**
* The set of AudioBuffer objects which are cached for different audio paths
*/
buffers: Map<string, AudioBuffer>;
/**
* The set of singleton Sound instances which are cached for different audio paths
*/
sounds: Map<string, Sound>;
/**
* Get a map of the Sound objects which are currently playing.
* @remarks It's not actually an `Array` but a `Map`.
*/
playing: Map<number, Sound>;
/**
* A user gesture must be registered before audio can be played.
* This Array contains the Sound instances which are requested for playback prior to a gesture.
* Once a gesture is observed, we begin playing all elements of this Array.
* @see Sound
* @defaultValue `[]`
*/
pending: (() => void)[];
/**
* A flag for whether video playback is currently locked by awaiting a user gesture
* @defaultValue `true`
*/
locked: boolean;
/**
* Audio Context singleton used for analysing audio levels of each stream
* Only created if necessary to listen to audio streams.
* @defaultValue `null`
* @internal
*/
protected _audioContext: AudioContext | null;
/**
* Map of all streams that we listen to for determining the decibel levels.
* Used for analyzing audio levels of each stream.
* Format of the object stored is :
* ```
* {id:
* {
* stream: MediaStream,
* analyser: AudioAnalyser,
* interval: Number,
* callback: Function
* }
* }
* ```
* @internal
*/
protected _analyserStreams: Record<string, AudioHelper.AnalyserStream>;
/**
* Interval ID as returned by setInterval for analysing the volume of streams
* When set to 0, means no timer is set.
* @defaultValue `0`
* @internal
*/
protected _analyserInterval: number;
/**
* Fast Fourier Transform Array.
* Used for analysing the decibel level of streams. The array is allocated only once
* then filled by the analyser repeatedly. We only generate it when we need to listen to
* a stream's level, so we initialize it to null.
* @defaultValue `null`
* @internal
*/
protected _fftArray: Float32Array | null;
/**
* The Native interval for the AudioHelper to analyse audio levels from streams
* Any interval passed to startLevelReports() would need to be a multiple of this value.
* @defaultValue `50`
*/
static levelAnalyserNativeInterval: number;
/**
* Register client-level settings for global volume overrides
*/
static registerSettings(): void;
/**
* Create a Sound instance for a given audio source URL
* @param options - Audio creation options
*/
create(options: AudioHelper.CreateOptions): Sound;
/**
* Test whether a source file has a supported audio extension type
* @param src - A requested audio source path
* @returns Does the filename end with a valid audio extension?
*/
static hasAudioExtension(src: string): boolean;
/**
* Given an input file path, determine a default name for the sound based on the filename
* @param src - An input file path
* @returns A default sound name for the path
*/
static getDefaultSoundName(src: string): string;
/**
* Play a single Sound by providing its source.
* @param src - The file path to the audio source being played
* @param options - Additional options passed to Sound#play
* @returns The created Sound which is now playing
*/
play(src: string, options?: Sound.PlayOptions): Promise<Sound>;
/**
* Register an event listener to await the first mousemove gesture and begin playback once observed
*/
awaitFirstGesture(): void;
/**
* Request that other connected clients begin preloading a certain sound path.
* @param src - The source file path requested for preload
* @returns A Promise which resolves once the preload is complete
*/
preload(src: string): Promise<Sound>;
/**
* Open socket listeners which transact ChatMessage data
* @internal
*/
static _activateSocketListeners(socket: io.Socket): void;
/**
* Play a one-off sound effect which is not part of a Playlist
*
* @param data - An object configuring the audio data to play
* @param push - Push the audio sound effect to other connected clients?
* (default: `false`)
*
* @returns A Sound instance which controls audio playback.
*
* @example
* ```typescript
* // Play the sound of a locked door for all players
* AudioHelper.play({src: "sounds/lock.wav", volume: 0.8, loop: false}, true);
* ```
*/
static play(data: AudioHelper.PlayData, push?: boolean): Promise<Sound>;
/**
* Begin loading the sound for a provided source URL adding its
* @param src - The audio source path to preload
* @returns The created and loaded Sound ready for playback
*/
static preloadSound(src: string): Promise<Sound>;
/**
* Returns the volume value based on a range input volume control's position.
* This is using an exponential approximation of the logarithmic nature of audio level perception
* @param value - Value between [0, 1] of the range input
* @param order - The exponent of the curve
* (default: `1.5`)
*/
static inputToVolume(value: number | string, order?: number): number;
/**
* Counterpart to inputToVolume()
* Returns the input range value based on a volume
* @param volume - Value between [0, 1] of the volume level
* @param order - The exponent of the curve
*/
static volumeToInput(volume: number, order?: number): number;
/**
* Returns a singleton AudioContext if one can be created.
* An audio context may not be available due to limited resources or browser compatibility
* in which case null will be returned
*
* @returns A singleton AudioContext or null if one is not available
*/
getAudioContext(): AudioContext | null;
/**
* Registers a stream for periodic reports of audio levels.
* Once added, the callback will be called with the maximum decibel level of
* the audio tracks in that stream since the last time the event was fired.
* The interval needs to be a multiple of `AudioHelper.levelAnalyserNativeInterval` which defaults at 50ms
*
* @param id - An id to assign to this report. Can be used to stop reports
* @param stream - The MediaStream instance to report activity on.
* @param callback - The callback function to call with the decibel level.
* @param interval - The interval at which to produce reports.
* (default: `50`)
* @param smoothing - The smoothingTimeConstant to set on the audio analyser. Refer to AudioAnalyser API docs.
* (default: `0.1`)
* @returns Returns whether or not listening to the stream was successful
*/
startLevelReports(
id: string,
stream: MediaStream,
callback: (maxDecibel: number, fftArray: Float32Array) => void,
interval?: number,
smoothing?: number
): boolean | undefined;
/**
* Stop sending audio level reports
* This stops listening to a stream and stops sending reports.
* If we aren't listening to any more streams, cancel the global analyser timer.
* @param id - The id of the reports that passed to startLevelReports.
*/
stopLevelReports(id: string): void;
/**
* Ensures the global analyser timer is started
*
* We create only one timer that runs every 50ms and only create it if needed, this is meant to optimize things
* and avoid having multiple timers running if we want to analyse multiple streams at the same time.
* I don't know if it actually helps much with performance but it's expected that limiting the number of timers
* running at the same time is good practice and with JS itself, there's a potential for a timer congestion
* phenomenon if too many are created.
* @internal
*/
protected _ensureAnalyserTimer(): void;
/**
* Cancel the global analyser timer
* If the timer is running and has become unnecessary, stops it.
* @internal
*/
protected _cancelAnalyserTimer(): void;
/**
* Capture audio level for all speakers and emit a webrtcVolumes custom event with all the volume levels
* detected since the last emit.
* The event's detail is in the form of `{userId: decibelLevel}`
* @internal
*/
protected _emitVolumes(): void;
/**
* Handle the first observed user gesture
* @param event - The mouse-move event which enables playback
* @internal
*/
protected _onFirstGesture(event: Event): void;
/**
* Additional standard callback events that occur whenever a global volume slider is adjusted
* @param key - The setting key
* @param volume - The new volume level
* @internal
*/
protected _onChangeGlobalVolume(key: string, volume: number): void;
}
declare namespace AudioHelper {
interface AnalyserStream {
stream: MediaStream;
analyser: AnalyserNode;
interval: number;
callback: (maxDecibel: number, fftArray: Float32Array) => void;
/**
* Used as a counter of 50ms increments in case the interval is more than 50
* @defaultValue `0`
* @internal
*/
_lastEmit: number;
}
interface CreateOptions {
/**
* The source URL for the audio file
*/
src: string;
/**
* Reuse an existing Sound for this source?
* @defaultValue `true`
*/
singleton?: boolean;
/**
* Begin loading the audio immediately?
* @defaultValue `false`
*/
preload?: boolean;
/**
* Begin playing the audio as soon as it is ready?
* @defaultValue `false`
*/
autoplay?: boolean;
/**
* Additional options passed to the play method if autoplay is true
* @defaultValue `{}`
*/
autoplayOptions?: Sound.PlayOptions;
}
interface PlayData {
/**
* The audio source file path, either a public URL or a local path relative to the public directory
*/
src: string;
/**
* The volume level at which to play the audio, between 0 and 1.
* @defaultValue `1.0`
*/
volume?: number;
/**
* Begin playback of the audio effect immediately once it is loaded.
* @deprecated You are using the autoplay option of AudioHelper.play which is no longer supported in 0.8.0
*/
autoplay?: boolean;
/**
* Loop the audio effect and continue playing it until it is manually stopped.
* @defaultValue `false`
*/
loop?: boolean;
}
} | the_stack |
import "jest-extended";
import { DatabaseService } from "@packages/core-database";
import { Container, Enums } from "@packages/core-kernel";
import { DatabaseInteraction } from "@packages/core-state/src/database-interactions";
const app = {
get: jest.fn(),
terminate: jest.fn(),
};
const connection = {
query: jest.fn(),
close: jest.fn(),
};
const blockRepository = {
findOne: jest.fn(),
findByHeightRange: jest.fn(),
findByHeightRangeWithTransactions: jest.fn(),
findByHeightRangeWithTransactionsForDownload: jest.fn(),
findByHeights: jest.fn(),
findLatest: jest.fn(),
findByIds: jest.fn(),
findRecent: jest.fn(),
findTop: jest.fn(),
count: jest.fn(),
getStatistics: jest.fn(),
saveBlocks: jest.fn(),
deleteBlocks: jest.fn(),
};
const transactionRepository = {
find: jest.fn(),
findOne: jest.fn(),
findByBlockIds: jest.fn(),
getStatistics: jest.fn(),
};
const roundRepository = {
getRound: jest.fn(),
save: jest.fn(),
deleteFrom: jest.fn(),
};
const stateStore = {
setGenesisBlock: jest.fn(),
getGenesisBlock: jest.fn(),
setLastBlock: jest.fn(),
getLastBlock: jest.fn(),
getLastBlocksByHeight: jest.fn(),
getCommonBlocks: jest.fn(),
getLastBlockIds: jest.fn(),
};
const stateBlockStore = {
resize: jest.fn(),
};
const stateTransactionStore = {
resize: jest.fn(),
};
const handlerRegistry = {
getActivatedHandlerForData: jest.fn(),
};
const walletRepository = {
createWallet: jest.fn(),
findByPublicKey: jest.fn(),
findByUsername: jest.fn(),
};
const blockState = {
applyBlock: jest.fn(),
revertBlock: jest.fn(),
};
const dposState = {
buildDelegateRanking: jest.fn(),
setDelegatesRound: jest.fn(),
getRoundDelegates: jest.fn(),
};
const getDposPreviousRoundState = jest.fn();
const triggers = {
call: jest.fn(),
};
const events = {
call: jest.fn(),
dispatch: jest.fn(),
};
const logger = {
error: jest.fn(),
warning: jest.fn(),
info: jest.fn(),
debug: jest.fn(),
};
const roundState = {
applyBlock: jest.fn(),
revertBlock: jest.fn(),
getActiveDelegates: jest.fn(),
restore: jest.fn(),
detectMissedBlocks: jest.fn(),
};
const container = new Container.Container();
container.bind(Container.Identifiers.Application).toConstantValue(app);
container.bind(Container.Identifiers.DatabaseConnection).toConstantValue(connection);
container.bind(Container.Identifiers.DatabaseBlockRepository).toConstantValue(blockRepository);
container.bind(Container.Identifiers.DatabaseTransactionRepository).toConstantValue(transactionRepository);
container.bind(Container.Identifiers.DatabaseRoundRepository).toConstantValue(roundRepository);
container.bind(Container.Identifiers.DatabaseService).to(DatabaseService);
container.bind(Container.Identifiers.StateStore).toConstantValue(stateStore);
container.bind(Container.Identifiers.StateBlockStore).toConstantValue(stateBlockStore);
container.bind(Container.Identifiers.StateTransactionStore).toConstantValue(stateTransactionStore);
container.bind(Container.Identifiers.TransactionHandlerRegistry).toConstantValue(handlerRegistry);
container.bind(Container.Identifiers.WalletRepository).toConstantValue(walletRepository);
container.bind(Container.Identifiers.BlockState).toConstantValue(blockState);
container.bind(Container.Identifiers.DposState).toConstantValue(dposState);
container.bind(Container.Identifiers.DposPreviousRoundStateProvider).toConstantValue(getDposPreviousRoundState);
container.bind(Container.Identifiers.TriggerService).toConstantValue(triggers);
container.bind(Container.Identifiers.EventDispatcherService).toConstantValue(events);
container.bind(Container.Identifiers.LogService).toConstantValue(logger);
container.bind(Container.Identifiers.RoundState).toConstantValue(roundState);
beforeEach(() => {
jest.resetAllMocks();
});
describe("DatabaseInteractions", () => {
it("should dispatch starting event", async () => {
const databaseInteraction: DatabaseInteraction = container.resolve(DatabaseInteraction);
await databaseInteraction.initialize();
expect(events.dispatch).toBeCalledWith(Enums.StateEvent.Starting);
});
it("should reset database when CORE_RESET_DATABASE variable is set", async () => {
try {
const databaseInteraction: DatabaseInteraction = container.resolve(DatabaseInteraction);
process.env.CORE_RESET_DATABASE = "1";
const genesisBlock = {};
stateStore.getGenesisBlock.mockReturnValue(genesisBlock);
await databaseInteraction.initialize();
// expect(databaseInteraction.reset).toBeCalled();
expect(stateStore.getGenesisBlock).toBeCalled();
// expect(databaseInteraction.saveBlocks).toBeCalledWith([genesisBlock]);
expect(stateStore.setGenesisBlock).toBeCalled();
} finally {
delete process.env.CORE_RESET_DATABASE;
}
});
it("should terminate app if exception was raised", async () => {
const databaseInteraction: DatabaseInteraction = container.resolve(DatabaseInteraction);
stateStore.setGenesisBlock.mockImplementationOnce(() => {
throw new Error("Fail");
});
await databaseInteraction.initialize();
expect(app.terminate).toBeCalled();
});
it("should terminate if unable to deserialize last 5 blocks", async () => {
const databaseInteraction: DatabaseInteraction = container.resolve(DatabaseInteraction);
const block101data = { id: "block101", height: 101 };
const block102data = { id: "block102", height: 102 };
const block103data = { id: "block103", height: 103 };
const block104data = { id: "block104", height: 104 };
const block105data = { id: "block105", height: 105 };
const block106data = { id: "block106", height: 105 };
blockRepository.findLatest.mockResolvedValueOnce(block106data);
blockRepository.findLatest.mockResolvedValueOnce(block106data); // this.getLastBlock
transactionRepository.findByBlockIds.mockResolvedValueOnce([]); // this.getLastBlock
blockRepository.findLatest.mockResolvedValueOnce(block106data); // blockRepository.deleteBlocks
blockRepository.findLatest.mockResolvedValueOnce(block105data); // this.getLastBlock
transactionRepository.findByBlockIds.mockResolvedValueOnce([]); // this.getLastBlock
blockRepository.findLatest.mockResolvedValueOnce(block105data); // blockRepository.deleteBlocks
blockRepository.findLatest.mockResolvedValueOnce(block104data); // this.getLastBlock
transactionRepository.findByBlockIds.mockResolvedValueOnce([]); // this.getLastBlock
blockRepository.findLatest.mockResolvedValueOnce(block104data); // blockRepository.deleteBlocks
blockRepository.findLatest.mockResolvedValueOnce(block103data); // this.getLastBlock
transactionRepository.findByBlockIds.mockResolvedValueOnce([]); // this.getLastBlock
blockRepository.findLatest.mockResolvedValueOnce(block103data); // blockRepository.deleteBlocks
blockRepository.findLatest.mockResolvedValueOnce(block102data); // this.getLastBlock
transactionRepository.findByBlockIds.mockResolvedValueOnce([]); // this.getLastBlock
blockRepository.findLatest.mockResolvedValueOnce(block102data); // blockRepository.deleteBlocks
blockRepository.findLatest.mockResolvedValueOnce(block101data); // this.getLastBlock
transactionRepository.findByBlockIds.mockResolvedValueOnce([]); // this.getLastBlock
await databaseInteraction.initialize();
expect(stateStore.setGenesisBlock).toBeCalled();
expect(blockRepository.findLatest).toBeCalledTimes(12);
expect(transactionRepository.findByBlockIds).toBeCalledWith([block106data.id]);
expect(blockRepository.deleteBlocks).toBeCalledWith([block106data]);
expect(transactionRepository.findByBlockIds).toBeCalledWith([block105data.id]);
expect(blockRepository.deleteBlocks).toBeCalledWith([block105data]);
expect(transactionRepository.findByBlockIds).toBeCalledWith([block104data.id]);
expect(blockRepository.deleteBlocks).toBeCalledWith([block104data]);
expect(transactionRepository.findByBlockIds).toBeCalledWith([block103data.id]);
expect(blockRepository.deleteBlocks).toBeCalledWith([block103data]);
expect(transactionRepository.findByBlockIds).toBeCalledWith([block102data.id]);
expect(blockRepository.deleteBlocks).toBeCalledWith([block102data]);
expect(transactionRepository.findByBlockIds).toBeCalledWith([block101data.id]);
expect(app.terminate).toBeCalled();
});
});
describe("DatabaseInteraction.restoreCurrentRound", () => {
it("should call roundState.restore", async () => {
const databaseInteraction: DatabaseInteraction = container.resolve(DatabaseInteraction);
await databaseInteraction.restoreCurrentRound();
expect(roundState.restore).toHaveBeenCalled();
});
});
describe("DatabaseInteraction.reset", () => {
it("should reset database", async () => {
const databaseInteraction: DatabaseInteraction = container.resolve(DatabaseInteraction);
const genesisBlock = {};
stateStore.getGenesisBlock.mockReturnValueOnce(genesisBlock);
// @ts-ignore
await databaseInteraction.reset();
expect(connection.query).toBeCalledWith("TRUNCATE TABLE blocks, rounds, transactions RESTART IDENTITY;");
expect(blockRepository.saveBlocks).toBeCalledWith([genesisBlock]);
});
});
describe("DatabaseInteraction.applyBlock", () => {
it("should apply block, round, detect missing blocks, and fire events", async () => {
const databaseInteraction: DatabaseInteraction = container.resolve(DatabaseInteraction);
const handler = { emitEvents: jest.fn() };
handlerRegistry.getActivatedHandlerForData.mockResolvedValueOnce(handler);
const transaction = { data: { id: "dummy_id" } };
const block = { data: { height: 54, timestamp: 35 }, transactions: [transaction] };
await databaseInteraction.applyBlock(block as any);
expect(roundState.detectMissedBlocks).toBeCalledWith(block);
expect(blockState.applyBlock).toBeCalledWith(block);
expect(roundState.applyBlock).toBeCalledWith(block);
expect(handler.emitEvents).toBeCalledWith(transaction, events);
expect(events.dispatch).toBeCalledWith(Enums.TransactionEvent.Applied, transaction.data);
expect(events.dispatch).toBeCalledWith(Enums.BlockEvent.Applied, block.data);
});
});
describe("DatabaseInteraction.revertBlock", () => {
it("should revert state, and fire events", async () => {
const databaseInteraction: DatabaseInteraction = container.resolve(DatabaseInteraction);
const transaction1 = { data: {} };
const transaction2 = { data: {} };
const block = {
data: { id: "123", height: 100 },
transactions: [transaction1, transaction2],
};
await databaseInteraction.revertBlock(block as any);
expect(blockState.revertBlock).toBeCalledWith(block);
expect(roundState.revertBlock).toBeCalledWith(block);
expect(events.dispatch).toBeCalledWith(Enums.TransactionEvent.Reverted, transaction1.data);
expect(events.dispatch).toBeCalledWith(Enums.TransactionEvent.Reverted, transaction2.data);
expect(events.dispatch).toBeCalledWith(Enums.BlockEvent.Reverted, block.data);
});
}); | the_stack |
import { Reducer } from "redux";
import moment from 'moment';
import { INetatmoState, NetatmoActionTypes } from "./types";
import {DataTypes} from "../../types/netatmo";
const initialState: INetatmoState = {
client_id: '',
client_secret: '',
username: '',
password: '',
loading_auth: false,
loading_refresh_token: false,
auth_errors: undefined,
access_token: '',
refresh_token: window.localStorage.getItem('NetatmoRefreshToken') || '',
access_token_expire_in: 0,
loading_station_data: true,
station_data_last_updated: 0,
station_data_errors: undefined,
station_data: undefined,
first_fetch: true,
selected_indoor_module: 0,
loading_measure: false,
measure_errors: undefined,
measure_data: [],
selected_module: window.localStorage.getItem('selected_module') || '',
selected_types: window.localStorage.getItem('selected_types') ? JSON.parse(window.localStorage.getItem('selected_types') as string) : ['Temperature'],
selected_timelapse: window.localStorage.getItem('selected_timelapse') as '12h'|'1d'|'1m' || '12h',
loading_rain_measure: false,
measure_rain_errors: undefined,
measure_rain_data: [],
loading_indoor_measure: false,
measure_indoor_errors: undefined,
measure_indoor_data: [],
selected_indoor_type: window.localStorage.getItem('selected_indoor_type') as DataTypes || 'Temperature',
loading_indoor_second_measure: false,
measure_indoor_second_errors: undefined,
measure_indoor_second_data: [],
selected_indoor_second_type: window.localStorage.getItem('selected_indoor_second_type') as DataTypes || 'Temperature',
loading_indoor_third_measure: false,
measure_indoor_third_errors: undefined,
measure_indoor_third_data: [],
selected_indoor_third_type: window.localStorage.getItem('selected_indoor_third_type') as DataTypes || 'Temperature',
loading_outdoor_measure: false,
measure_outdoor_errors: undefined,
measure_outdoor_data: [],
selected_outdoor_type: window.localStorage.getItem('selected_outdoor_type') as DataTypes || 'Temperature',
loading_station_measure: false,
measure_station_errors: undefined,
measure_station_data: [],
selected_station_type: window.localStorage.getItem('selected_station_type') as DataTypes || 'Temperature',
};
const reducer: Reducer<INetatmoState> = (state = initialState, action) => {
if (typeof state === 'undefined') {
// No preloadedState from server. Use local state.
state = { ...initialState }
} else {
// PreloadedState supplied by the server, but it's not merged with our local initial state yet.
state = { ...initialState, ...state }
}
switch (action.type) {
/** NETATMO AUTH **/
case NetatmoActionTypes.AUTH_REQUEST:
return { ...state, loading_auth: true };
case NetatmoActionTypes.AUTH_SUCCESS:
return { ...state,
loading_auth: false,
auth_errors: undefined,
access_token: action.payload.access_token,
refresh_token: action.payload.refresh_token,
access_token_expire_in: moment().unix() + action.payload.expire_in
};
case NetatmoActionTypes.AUTH_FAILURE:
return { ...state, loading_auth: false, auth_errors: action.error };
/** NETATMO REFRESH TOKEN **/
case NetatmoActionTypes.REFRESH_TOKEN_REQUEST:
return { ...state, loading_auth: true };
case NetatmoActionTypes.REFRESH_TOKEN_SUCCESS:
return { ...state,
loading_auth: false,
auth_errors: undefined,
access_token: action.payload.access_token,
refresh_token: action.payload.refresh_token,
access_token_expire_in: moment().unix() + action.payload.expire_in
};
case NetatmoActionTypes.REFRESH_TOKEN_FAILURE:
return { ...state, loading_auth: false, auth_errors: action.error };
/** NETATMO STATION DATA **/
case NetatmoActionTypes.STATION_DATA_REQUEST:
return { ...state, loading_station_data: true };
case NetatmoActionTypes.STATION_DATA_SUCCESS:
return { ...state,
loading_station_data: false,
station_data: action.payload,
station_data_last_updated: action.receivedAt,
station_data_errors: undefined,
first_fetch: false,
selected_module: state.selected_module || action.payload.modules.OUTDOOR.id
};
case NetatmoActionTypes.STATION_DATA_FAILURE:
return { ...state, loading_station_data: false, station_data_errors: action.error };
/** NETATMO MEASURE DATA **/
case NetatmoActionTypes.MEASURE_REQUEST:
return { ...state, loading_measure: true };
case NetatmoActionTypes.MEASURE_SUCCESS:
// Store in localStorage selected module, types and timelapse
window.localStorage.setItem('selected_module', action.module);
window.localStorage.setItem('selected_types', JSON.stringify(action.types));
window.localStorage.setItem('selected_timelapse', action.timelapse);
return { ...state,
loading_measure: false,
measure_data: action.payload,
selected_module: action.module,
selected_types: action.types,
selected_timelapse: action.timelapse,
measure_errors: undefined
};
case NetatmoActionTypes.MEASURE_FAILURE:
return { ...state, loading_measure: false, measure_errors: action.error };
/** NETATMO MEASURE RAIN DATA **/
case NetatmoActionTypes.MEASURE_RAIN_REQUEST:
return { ...state, loading_rain_measure: true };
case NetatmoActionTypes.MEASURE_RAIN_SUCCESS:
return { ...state,
loading_rain_measure: false,
measure_rain_data: action.payload,
measure_rain_errors: undefined
};
case NetatmoActionTypes.MEASURE_RAIN_FAILURE:
return { ...state, loading_rain_measure: false, measure_rain_errors: action.error };
/** NETATMO MEASURE DATA **/
case NetatmoActionTypes.MEASURES_REQUEST:
switch (action.module) {
case 'indoor':
return { ...state, loading_indoor_measure: true };
case 'indoor_second':
return { ...state, loading_indoor_second_measure: true };
case 'indoor_third':
return { ...state, loading_indoor_third_measure: true };
case 'outdoor':
return { ...state, loading_outdoor_measure: true };
case 'station':
return { ...state, loading_station_measure: true };
default:
return state;
}
case NetatmoActionTypes.MEASURES_SUCCESS:
switch (action.module) {
case 'indoor':
return { ...state,
loading_indoor_measure: false,
measure_indoor_data: action.payload,
measure_indoor_errors: undefined
};
case 'indoor_second':
return { ...state,
loading_indoor_second_measure: false,
measure_indoor_second_data: action.payload,
measure_indoor_second_errors: undefined
};
case 'indoor_third':
return { ...state,
loading_indoor_third_measure: false,
measure_indoor_third_data: action.payload,
measure_indoor_third_errors: undefined
};
case 'outdoor':
return { ...state,
loading_outdoor_measure: false,
measure_outdoor_data: action.payload,
measure_outdoor_errors: undefined
};
case 'station':
return { ...state,
loading_station_measure: false,
measure_station_data: action.payload,
measure_station_errors: undefined
};
default:
return state;
}
case NetatmoActionTypes.MEASURES_FAILURE:
switch (action.module) {
case 'indoor':
return { ...state, loading_indoor_measure: false, measure_indoor_errors: action.error };
case 'indoor_second':
return { ...state, loading_indoor_second_measure: false, measure_indoor_second_errors: action.error };
case 'indoor_third':
return { ...state, loading_indoor_third_measure: false, measure_indoor_third_errors: action.error };
case 'outdoor':
return { ...state, loading_outdoor_measure: false, measure_outdoor_errors: action.error };
case 'station':
return { ...state, loading_station_measure: false, measure_station_errors: action.error };
default:
return state;
}
case NetatmoActionTypes.CHANGE_SELECTED_TYPE:
switch (action.module) {
case 'indoor':
window.localStorage.setItem('selected_indoor_type', action.payload);
return { ...state, selected_indoor_type: action.payload };
case 'indoor_second':
window.localStorage.setItem('selected_indoor_second_type', action.payload);
return { ...state, selected_indoor_second_type: action.payload };
case 'indoor_third':
window.localStorage.setItem('selected_indoor_third_type', action.payload);
return { ...state, selected_indoor_third_type: action.payload };
case 'outdoor':
window.localStorage.setItem('selected_outdoor_type', action.payload);
return { ...state, selected_outdoor_type: action.payload };
case 'station':
window.localStorage.setItem('selected_station_type', action.payload);
return { ...state, selected_station_type: action.payload };
default:
return state;
}
case NetatmoActionTypes.CHANGE_SELECTED_INSIDE_MODULE:
return { ...state, selected_indoor_module: action.payload };
default:
return state;
}
};
export {reducer as netatmoReducer} | the_stack |
// We can elide a lot of nodes especially tokens and keywords
// because we don't create the AST from text
import * as ts from "typescript";
import { LuaLibFeature } from "./transformation/utils/lualib";
import { castArray } from "./utils";
export enum SyntaxKind {
File,
Block,
// Statements
DoStatement,
VariableDeclarationStatement,
AssignmentStatement,
IfStatement,
WhileStatement,
RepeatStatement,
ForStatement,
ForInStatement,
GotoStatement,
LabelStatement,
ReturnStatement,
BreakStatement,
ExpressionStatement,
// Expression
StringLiteral,
NumericLiteral,
NilKeyword,
DotsKeyword,
TrueKeyword,
FalseKeyword,
FunctionExpression,
TableFieldExpression,
TableExpression,
UnaryExpression,
BinaryExpression,
CallExpression,
MethodCallExpression,
Identifier,
TableIndexExpression,
// Operators
// Arithmetic
AdditionOperator, // Maybe use abbreviations for those add, sub, mul ...
SubtractionOperator,
MultiplicationOperator,
DivisionOperator,
FloorDivisionOperator,
ModuloOperator,
PowerOperator,
NegationOperator, // Unary minus
// Concat
ConcatOperator,
// Length
LengthOperator, // Unary
// Relational Ops
EqualityOperator,
InequalityOperator,
LessThanOperator,
LessEqualOperator,
// Syntax Sugar `x > y` <=> `not (y <= x)`
// but we should probably use them to make the output code more readable
GreaterThanOperator,
GreaterEqualOperator, // Syntax Sugar `x >= y` <=> `not (y < x)`
// Logical
AndOperator,
OrOperator,
NotOperator, // Unary
// Bitwise
BitwiseAndOperator,
BitwiseOrOperator,
BitwiseExclusiveOrOperator,
BitwiseRightShiftOperator,
BitwiseLeftShiftOperator,
BitwiseNotOperator, // Unary
}
// TODO maybe name this PrefixUnary? not sure it makes sense to do so, because all unary ops in Lua are prefix
export type UnaryBitwiseOperator = SyntaxKind.BitwiseNotOperator;
export type UnaryOperator =
| SyntaxKind.NegationOperator
| SyntaxKind.LengthOperator
| SyntaxKind.NotOperator
| UnaryBitwiseOperator;
export type BinaryBitwiseOperator =
| SyntaxKind.BitwiseAndOperator
| SyntaxKind.BitwiseOrOperator
| SyntaxKind.BitwiseExclusiveOrOperator
| SyntaxKind.BitwiseRightShiftOperator
| SyntaxKind.BitwiseLeftShiftOperator;
export type BinaryOperator =
| SyntaxKind.AdditionOperator
| SyntaxKind.SubtractionOperator
| SyntaxKind.MultiplicationOperator
| SyntaxKind.DivisionOperator
| SyntaxKind.FloorDivisionOperator
| SyntaxKind.ModuloOperator
| SyntaxKind.PowerOperator
| SyntaxKind.ConcatOperator
| SyntaxKind.EqualityOperator
| SyntaxKind.InequalityOperator
| SyntaxKind.LessThanOperator
| SyntaxKind.LessEqualOperator
| SyntaxKind.GreaterThanOperator
| SyntaxKind.GreaterEqualOperator
| SyntaxKind.AndOperator
| SyntaxKind.OrOperator
| BinaryBitwiseOperator;
export type Operator = UnaryOperator | BinaryOperator;
export type SymbolId = number & { _symbolIdBrand: any };
export enum NodeFlags {
None = 0,
Inline = 1 << 0, // Keep function body on same line
Declaration = 1 << 1, // Prefer declaration syntax `function foo()` over assignment syntax `foo = function()`
TableUnpackCall = 1 << 2, // This is a table.unpack call
}
export interface TextRange {
line?: number;
column?: number;
}
export interface Node extends TextRange {
kind: SyntaxKind;
flags: NodeFlags;
}
export function createNode(kind: SyntaxKind, tsOriginal?: ts.Node): Node {
if (tsOriginal === undefined) {
return { kind, flags: NodeFlags.None };
}
const sourcePosition = getSourcePosition(tsOriginal);
if (sourcePosition) {
return { kind, line: sourcePosition.line, column: sourcePosition.column, flags: NodeFlags.None };
} else {
return { kind, flags: NodeFlags.None };
}
}
export function cloneNode<T extends Node>(node: T): T {
return { ...node };
}
export function setNodePosition<T extends Node>(node: T, position: TextRange): T {
node.line = position.line;
node.column = position.column;
return node;
}
export function setNodeOriginal<T extends Node>(node: T, tsOriginal: ts.Node): T;
export function setNodeOriginal<T extends Node>(node: T | undefined, tsOriginal: ts.Node): T | undefined;
export function setNodeOriginal<T extends Node>(node: T | undefined, tsOriginal: ts.Node): T | undefined {
if (node === undefined) {
return undefined;
}
const sourcePosition = getSourcePosition(tsOriginal);
if (sourcePosition) {
setNodePosition(node, sourcePosition);
}
return node;
}
function getSourcePosition(sourceNode: ts.Node): TextRange | undefined {
const parseTreeNode = ts.getParseTreeNode(sourceNode) ?? sourceNode;
const sourceFile = parseTreeNode.getSourceFile();
if (sourceFile !== undefined && parseTreeNode.pos >= 0) {
const { line, character } = ts.getLineAndCharacterOfPosition(
sourceFile,
parseTreeNode.pos + parseTreeNode.getLeadingTriviaWidth()
);
return { line, column: character };
}
}
export function getOriginalPos(node: Node): TextRange {
return { line: node.line, column: node.column };
}
export function setNodeFlags<T extends Node>(node: T, flags: NodeFlags): T {
node.flags = flags;
return node;
}
export interface File extends Node {
kind: SyntaxKind.File;
statements: Statement[];
luaLibFeatures: Set<LuaLibFeature>;
trivia: string;
}
export function isFile(node: Node): node is File {
return node.kind === SyntaxKind.File;
}
export function createFile(
statements: Statement[],
luaLibFeatures: Set<LuaLibFeature>,
trivia: string,
tsOriginal?: ts.Node
): File {
const file = createNode(SyntaxKind.File, tsOriginal) as File;
file.statements = statements;
file.luaLibFeatures = luaLibFeatures;
file.trivia = trivia;
return file;
}
export interface Block extends Node {
kind: SyntaxKind.Block;
statements: Statement[];
}
export function isBlock(node: Node): node is Block {
return node.kind === SyntaxKind.Block;
}
export function createBlock(statements: Statement[], tsOriginal?: ts.Node): Block {
const block = createNode(SyntaxKind.Block, tsOriginal) as Block;
block.statements = statements;
return block;
}
export interface Statement extends Node {
_statementBrand: any;
leadingComments?: Array<string | string[]>;
trailingComments?: Array<string | string[]>;
}
export interface DoStatement extends Statement {
kind: SyntaxKind.DoStatement;
statements: Statement[];
}
export function isDoStatement(node: Node): node is DoStatement {
return node.kind === SyntaxKind.DoStatement;
}
export function createDoStatement(statements: Statement[], tsOriginal?: ts.Node): DoStatement {
const statement = createNode(SyntaxKind.DoStatement, tsOriginal) as DoStatement;
statement.statements = statements;
return statement;
}
// `local test1, test2 = 12, 42` or `local test1, test2`
export interface VariableDeclarationStatement extends Statement {
kind: SyntaxKind.VariableDeclarationStatement;
left: Identifier[];
right?: Expression[];
}
export function isVariableDeclarationStatement(node: Node): node is VariableDeclarationStatement {
return node.kind === SyntaxKind.VariableDeclarationStatement;
}
export function createVariableDeclarationStatement(
left: Identifier | Identifier[],
right?: Expression | Expression[],
tsOriginal?: ts.Node
): VariableDeclarationStatement {
const statement = createNode(SyntaxKind.VariableDeclarationStatement, tsOriginal) as VariableDeclarationStatement;
statement.left = castArray(left);
if (right) statement.right = castArray(right);
return statement;
}
// `test1, test2 = 12, 42`
export interface AssignmentStatement extends Statement {
kind: SyntaxKind.AssignmentStatement;
left: AssignmentLeftHandSideExpression[];
right: Expression[];
}
export function isAssignmentStatement(node: Node): node is AssignmentStatement {
return node.kind === SyntaxKind.AssignmentStatement;
}
export function createAssignmentStatement(
left: AssignmentLeftHandSideExpression | AssignmentLeftHandSideExpression[],
right?: Expression | Expression[],
tsOriginal?: ts.Node
): AssignmentStatement {
const statement = createNode(SyntaxKind.AssignmentStatement, tsOriginal) as AssignmentStatement;
statement.left = castArray(left);
statement.right = right ? castArray(right) : [];
return statement;
}
export interface IfStatement extends Statement {
kind: SyntaxKind.IfStatement;
condition: Expression;
ifBlock: Block;
elseBlock?: Block | IfStatement;
}
export function isIfStatement(node: Node): node is IfStatement {
return node.kind === SyntaxKind.IfStatement;
}
export function createIfStatement(
condition: Expression,
ifBlock: Block,
elseBlock?: Block | IfStatement,
tsOriginal?: ts.Node
): IfStatement {
const statement = createNode(SyntaxKind.IfStatement, tsOriginal) as IfStatement;
statement.condition = condition;
statement.ifBlock = ifBlock;
statement.elseBlock = elseBlock;
return statement;
}
export interface IterationStatement extends Statement {
body: Block;
}
export function isIterationStatement(node: Node): node is IterationStatement {
return (
node.kind === SyntaxKind.WhileStatement ||
node.kind === SyntaxKind.RepeatStatement ||
node.kind === SyntaxKind.ForStatement ||
node.kind === SyntaxKind.ForInStatement
);
}
export interface WhileStatement extends IterationStatement {
kind: SyntaxKind.WhileStatement;
condition: Expression;
}
export function isWhileStatement(node: Node): node is WhileStatement {
return node.kind === SyntaxKind.WhileStatement;
}
export function createWhileStatement(body: Block, condition: Expression, tsOriginal?: ts.Node): WhileStatement {
const statement = createNode(SyntaxKind.WhileStatement, tsOriginal) as WhileStatement;
statement.body = body;
statement.condition = condition;
return statement;
}
export interface RepeatStatement extends IterationStatement {
kind: SyntaxKind.RepeatStatement;
condition: Expression;
}
export function isRepeatStatement(node: Node): node is RepeatStatement {
return node.kind === SyntaxKind.RepeatStatement;
}
export function createRepeatStatement(body: Block, condition: Expression, tsOriginal?: ts.Node): RepeatStatement {
const statement = createNode(SyntaxKind.RepeatStatement, tsOriginal) as RepeatStatement;
statement.body = body;
statement.condition = condition;
return statement;
}
// TODO maybe rename to ForNumericStatement
export interface ForStatement extends IterationStatement {
kind: SyntaxKind.ForStatement;
controlVariable: Identifier;
controlVariableInitializer: Expression;
limitExpression: Expression;
stepExpression?: Expression;
}
export function isForStatement(node: Node): node is ForStatement {
return node.kind === SyntaxKind.ForStatement;
}
export function createForStatement(
body: Block,
controlVariable: Identifier,
controlVariableInitializer: Expression,
limitExpression: Expression,
stepExpression?: Expression,
tsOriginal?: ts.Node
): ForStatement {
const statement = createNode(SyntaxKind.ForStatement, tsOriginal) as ForStatement;
statement.body = body;
statement.controlVariable = controlVariable;
statement.controlVariableInitializer = controlVariableInitializer;
statement.limitExpression = limitExpression;
statement.stepExpression = stepExpression;
return statement;
}
export interface ForInStatement extends IterationStatement {
kind: SyntaxKind.ForInStatement;
names: Identifier[];
expressions: Expression[];
}
export function isForInStatement(node: Node): node is ForInStatement {
return node.kind === SyntaxKind.ForInStatement;
}
export function createForInStatement(
body: Block,
names: Identifier[],
expressions: Expression[],
tsOriginal?: ts.Node
): ForInStatement {
const statement = createNode(SyntaxKind.ForInStatement, tsOriginal) as ForInStatement;
statement.body = body;
statement.names = names;
statement.expressions = expressions;
return statement;
}
export interface GotoStatement extends Statement {
kind: SyntaxKind.GotoStatement;
label: string; // or identifier ?
}
export function isGotoStatement(node: Node): node is GotoStatement {
return node.kind === SyntaxKind.GotoStatement;
}
export function createGotoStatement(label: string, tsOriginal?: ts.Node): GotoStatement {
const statement = createNode(SyntaxKind.GotoStatement, tsOriginal) as GotoStatement;
statement.label = label;
return statement;
}
export interface LabelStatement extends Statement {
kind: SyntaxKind.LabelStatement;
name: string; // or identifier ?
}
export function isLabelStatement(node: Node): node is LabelStatement {
return node.kind === SyntaxKind.LabelStatement;
}
export function createLabelStatement(name: string, tsOriginal?: ts.Node): LabelStatement {
const statement = createNode(SyntaxKind.LabelStatement, tsOriginal) as LabelStatement;
statement.name = name;
return statement;
}
export interface ReturnStatement extends Statement {
kind: SyntaxKind.ReturnStatement;
expressions: Expression[];
}
export function isReturnStatement(node: Node): node is ReturnStatement {
return node.kind === SyntaxKind.ReturnStatement;
}
export function createReturnStatement(expressions: Expression[], tsOriginal?: ts.Node): ReturnStatement {
const statement = createNode(SyntaxKind.ReturnStatement, tsOriginal) as ReturnStatement;
statement.expressions = expressions;
return statement;
}
export interface BreakStatement extends Statement {
kind: SyntaxKind.BreakStatement;
}
export function isBreakStatement(node: Node): node is BreakStatement {
return node.kind === SyntaxKind.BreakStatement;
}
export function createBreakStatement(tsOriginal?: ts.Node): BreakStatement {
return createNode(SyntaxKind.BreakStatement, tsOriginal) as BreakStatement;
}
export interface ExpressionStatement extends Statement {
kind: SyntaxKind.ExpressionStatement;
expression: Expression;
}
export function isExpressionStatement(node: Node): node is ExpressionStatement {
return node.kind === SyntaxKind.ExpressionStatement;
}
export function createExpressionStatement(expressions: Expression, tsOriginal?: ts.Node): ExpressionStatement {
const statement = createNode(SyntaxKind.ExpressionStatement, tsOriginal) as ExpressionStatement;
statement.expression = expressions;
return statement;
}
export interface Expression extends Node {
_expressionBrand: any;
}
// Expressions
// TODO maybe create subexport interface for Literals/PrimaryExpressions
export interface NilLiteral extends Expression {
kind: SyntaxKind.NilKeyword;
}
export function isNilLiteral(node: Node): node is NilLiteral {
return node.kind === SyntaxKind.NilKeyword;
}
export function createNilLiteral(tsOriginal?: ts.Node): NilLiteral {
return createNode(SyntaxKind.NilKeyword, tsOriginal) as NilLiteral;
}
export interface BooleanLiteral extends Expression {
kind: SyntaxKind.TrueKeyword | SyntaxKind.FalseKeyword;
}
export function isBooleanLiteral(node: Node): node is BooleanLiteral {
return node.kind === SyntaxKind.TrueKeyword || node.kind === SyntaxKind.FalseKeyword;
}
export function createBooleanLiteral(value: boolean, tsOriginal?: ts.Node): BooleanLiteral {
return createNode(value ? SyntaxKind.TrueKeyword : SyntaxKind.FalseKeyword, tsOriginal) as BooleanLiteral;
}
// TODO Call this DotsLiteral or DotsKeyword?
export interface DotsLiteral extends Expression {
kind: SyntaxKind.DotsKeyword;
}
export function isDotsLiteral(node: Node): node is DotsLiteral {
return node.kind === SyntaxKind.DotsKeyword;
}
export function createDotsLiteral(tsOriginal?: ts.Node): DotsLiteral {
return createNode(SyntaxKind.DotsKeyword, tsOriginal) as DotsLiteral;
}
// StringLiteral / NumberLiteral
// TODO TS uses the export interface "LiteralLikeNode" with a "text: string" member
// but since we don't parse from text I think we can simplify by just having a value member
// TODO NumericLiteral or NumberLiteral?
export interface NumericLiteral extends Expression {
kind: SyntaxKind.NumericLiteral;
value: number;
}
export function isNumericLiteral(node: Node): node is NumericLiteral {
return node.kind === SyntaxKind.NumericLiteral;
}
export function createNumericLiteral(value: number, tsOriginal?: ts.Node): NumericLiteral {
const expression = createNode(SyntaxKind.NumericLiteral, tsOriginal) as NumericLiteral;
expression.value = value;
return expression;
}
export interface StringLiteral extends Expression {
kind: SyntaxKind.StringLiteral;
value: string;
}
export function isStringLiteral(node: Node): node is StringLiteral {
return node.kind === SyntaxKind.StringLiteral;
}
export function createStringLiteral(value: string, tsOriginal?: ts.Node): StringLiteral {
const expression = createNode(SyntaxKind.StringLiteral, tsOriginal) as StringLiteral;
expression.value = value;
return expression;
}
export function isLiteral(
node: Node
): node is NilLiteral | DotsLiteral | BooleanLiteral | NumericLiteral | StringLiteral {
return (
isNilLiteral(node) ||
isDotsLiteral(node) ||
isBooleanLiteral(node) ||
isNumericLiteral(node) ||
isStringLiteral(node)
);
}
export interface FunctionExpression extends Expression {
kind: SyntaxKind.FunctionExpression;
params?: Identifier[];
dots?: DotsLiteral;
body: Block;
}
export function isFunctionExpression(node: Node): node is FunctionExpression {
return node.kind === SyntaxKind.FunctionExpression;
}
export function createFunctionExpression(
body: Block,
params?: Identifier[],
dots?: DotsLiteral,
flags = NodeFlags.None,
tsOriginal?: ts.Node
): FunctionExpression {
const expression = createNode(SyntaxKind.FunctionExpression, tsOriginal) as FunctionExpression;
expression.body = body;
expression.params = params;
expression.dots = dots;
expression.flags = flags;
return expression;
}
export interface TableFieldExpression extends Expression {
kind: SyntaxKind.TableFieldExpression;
value: Expression;
key?: Expression;
}
export function isTableFieldExpression(node: Node): node is TableFieldExpression {
return node.kind === SyntaxKind.TableFieldExpression;
}
export function createTableFieldExpression(
value: Expression,
key?: Expression,
tsOriginal?: ts.Node
): TableFieldExpression {
const expression = createNode(SyntaxKind.TableFieldExpression, tsOriginal) as TableFieldExpression;
expression.value = value;
expression.key = key;
return expression;
}
export interface TableExpression extends Expression {
kind: SyntaxKind.TableExpression;
fields: TableFieldExpression[];
}
export function isTableExpression(node: Node): node is TableExpression {
return node.kind === SyntaxKind.TableExpression;
}
export function createTableExpression(fields: TableFieldExpression[] = [], tsOriginal?: ts.Node): TableExpression {
const expression = createNode(SyntaxKind.TableExpression, tsOriginal) as TableExpression;
expression.fields = fields;
return expression;
}
export interface UnaryExpression extends Expression {
kind: SyntaxKind.UnaryExpression;
operand: Expression;
operator: UnaryOperator;
}
export function isUnaryExpression(node: Node): node is UnaryExpression {
return node.kind === SyntaxKind.UnaryExpression;
}
export function createUnaryExpression(
operand: Expression,
operator: UnaryOperator,
tsOriginal?: ts.Node
): UnaryExpression {
const expression = createNode(SyntaxKind.UnaryExpression, tsOriginal) as UnaryExpression;
expression.operand = operand;
expression.operator = operator;
return expression;
}
export interface BinaryExpression extends Expression {
kind: SyntaxKind.BinaryExpression;
operator: BinaryOperator;
left: Expression;
right: Expression;
}
export function isBinaryExpression(node: Node): node is BinaryExpression {
return node.kind === SyntaxKind.BinaryExpression;
}
export function createBinaryExpression(
left: Expression,
right: Expression,
operator: BinaryOperator,
tsOriginal?: ts.Node
): BinaryExpression {
const expression = createNode(SyntaxKind.BinaryExpression, tsOriginal) as BinaryExpression;
expression.left = left;
expression.right = right;
expression.operator = operator;
return expression;
}
export interface CallExpression extends Expression {
kind: SyntaxKind.CallExpression;
expression: Expression;
params: Expression[];
}
export function isCallExpression(node: Node): node is CallExpression {
return node.kind === SyntaxKind.CallExpression;
}
export function createCallExpression(
expression: Expression,
params: Expression[],
tsOriginal?: ts.Node
): CallExpression {
const callExpression = createNode(SyntaxKind.CallExpression, tsOriginal) as CallExpression;
callExpression.expression = expression;
callExpression.params = params;
return callExpression;
}
export interface MethodCallExpression extends Expression {
kind: SyntaxKind.MethodCallExpression;
prefixExpression: Expression;
name: Identifier;
params: Expression[];
}
export function isMethodCallExpression(node: Node): node is MethodCallExpression {
return node.kind === SyntaxKind.MethodCallExpression;
}
export function createMethodCallExpression(
prefixExpression: Expression,
name: Identifier,
params: Expression[],
tsOriginal?: ts.Node
): MethodCallExpression {
const callExpression = createNode(SyntaxKind.MethodCallExpression, tsOriginal) as MethodCallExpression;
callExpression.prefixExpression = prefixExpression;
callExpression.name = name;
callExpression.params = params;
return callExpression;
}
export interface Identifier extends Expression {
kind: SyntaxKind.Identifier;
exportable: boolean;
text: string;
originalName?: string;
symbolId?: SymbolId;
}
export function isIdentifier(node: Node): node is Identifier {
return node.kind === SyntaxKind.Identifier;
}
export function createIdentifier(
text: string,
tsOriginal?: ts.Node,
symbolId?: SymbolId,
originalName?: string
): Identifier {
const expression = createNode(SyntaxKind.Identifier, tsOriginal) as Identifier;
expression.exportable = true;
expression.text = text;
expression.symbolId = symbolId;
expression.originalName = originalName;
return expression;
}
export function cloneIdentifier(identifier: Identifier, tsOriginal?: ts.Node): Identifier {
return createIdentifier(identifier.text, tsOriginal, identifier.symbolId, identifier.originalName);
}
export function createAnonymousIdentifier(tsOriginal?: ts.Node): Identifier {
const expression = createNode(SyntaxKind.Identifier, tsOriginal) as Identifier;
expression.exportable = false;
expression.text = "____";
return expression;
}
export interface TableIndexExpression extends Expression {
kind: SyntaxKind.TableIndexExpression;
table: Expression;
index: Expression;
}
export function isTableIndexExpression(node: Node): node is TableIndexExpression {
return node.kind === SyntaxKind.TableIndexExpression;
}
export function createTableIndexExpression(
table: Expression,
index: Expression,
tsOriginal?: ts.Node
): TableIndexExpression {
const expression = createNode(SyntaxKind.TableIndexExpression, tsOriginal) as TableIndexExpression;
expression.table = table;
expression.index = index;
return expression;
}
export type AssignmentLeftHandSideExpression = Identifier | TableIndexExpression;
export function isAssignmentLeftHandSideExpression(node: Node): node is AssignmentLeftHandSideExpression {
return isIdentifier(node) || isTableIndexExpression(node);
}
export type FunctionDefinition = (VariableDeclarationStatement | AssignmentStatement) & {
right: [FunctionExpression];
};
export function isFunctionDefinition(
statement: VariableDeclarationStatement | AssignmentStatement
): statement is FunctionDefinition {
return statement.left.length === 1 && statement.right?.length === 1 && isFunctionExpression(statement.right[0]);
}
export type InlineFunctionExpression = FunctionExpression & {
body: { statements: [ReturnStatement & { expressions: Expression[] }] };
};
export function isInlineFunctionExpression(expression: FunctionExpression): expression is InlineFunctionExpression {
return (
expression.body.statements?.length === 1 &&
isReturnStatement(expression.body.statements[0]) &&
expression.body.statements[0].expressions !== undefined &&
(expression.flags & NodeFlags.Inline) !== 0
);
} | the_stack |
declare module 'stripe' {
namespace Stripe {
/**
* The Product object.
*/
interface Product {
/**
* Unique identifier for the object.
*/
id: string;
/**
* String representing the object's type. Objects of the same type share the same value.
*/
object: 'product';
/**
* Whether the product is currently available for purchase.
*/
active: boolean;
/**
* A list of up to 5 attributes that each SKU can provide values for (e.g., `["color", "size"]`).
*/
attributes: Array<string> | null;
/**
* A short one-line description of the product, meant to be displayable to the customer. Only applicable to products of `type=good`.
*/
caption: string | null;
/**
* Time at which the object was created. Measured in seconds since the Unix epoch.
*/
created: number;
/**
* An array of connect application identifiers that cannot purchase this product. Only applicable to products of `type=good`.
*/
deactivate_on?: Array<string>;
deleted?: void;
/**
* The product's description, meant to be displayable to the customer. Use this field to optionally store a long form explanation of the product being sold for your own rendering purposes.
*/
description: string | null;
/**
* A list of up to 8 URLs of images for this product, meant to be displayable to the customer.
*/
images: Array<string>;
/**
* Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode.
*/
livemode: boolean;
/**
* Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
*/
metadata: Stripe.Metadata;
/**
* The product's name, meant to be displayable to the customer. Whenever this product is sold via a subscription, name will show up on associated invoice line item descriptions.
*/
name: string;
/**
* The dimensions of this product for shipping purposes.
*/
package_dimensions: Product.PackageDimensions | null;
/**
* Whether this product is shipped (i.e., physical goods).
*/
shippable: boolean | null;
/**
* Extra information about a product which will appear on your customer's credit card statement. In the case that multiple products are billed at once, the first statement descriptor will be used.
*/
statement_descriptor: string | null;
/**
* A [tax code](https://stripe.com/docs/tax/tax-codes) ID.
*/
tax_code: string | Stripe.TaxCode | null;
/**
* The type of the product. The product is either of type `good`, which is eligible for use with Orders and SKUs, or `service`, which is eligible for use with Subscriptions and Plans.
*/
type: Product.Type;
/**
* A label that represents units of this product in Stripe and on customers' receipts and invoices. When set, this will be included in associated invoice line item descriptions.
*/
unit_label: string | null;
/**
* Time at which the object was last updated. Measured in seconds since the Unix epoch.
*/
updated: number;
/**
* A URL of a publicly-accessible webpage for this product.
*/
url: string | null;
}
namespace Product {
interface PackageDimensions {
/**
* Height, in inches.
*/
height: number;
/**
* Length, in inches.
*/
length: number;
/**
* Weight, in ounces.
*/
weight: number;
/**
* Width, in inches.
*/
width: number;
}
type Type = 'good' | 'service';
}
/**
* The DeletedProduct object.
*/
interface DeletedProduct {
/**
* Unique identifier for the object.
*/
id: string;
/**
* String representing the object's type. Objects of the same type share the same value.
*/
object: 'product';
/**
* Always true for a deleted object
*/
deleted: true;
}
interface ProductCreateParams {
/**
* The product's name, meant to be displayable to the customer. Whenever this product is sold via a subscription, name will show up on associated invoice line item descriptions.
*/
name: string;
/**
* Whether the product is currently available for purchase. Defaults to `true`.
*/
active?: boolean;
/**
* A list of up to 5 alphanumeric attributes. Should only be set if type=`good`.
*/
attributes?: Array<string>;
/**
* A short one-line description of the product, meant to be displayable to the customer. May only be set if type=`good`.
*/
caption?: string;
/**
* An array of Connect application names or identifiers that should not be able to order the SKUs for this product. May only be set if type=`good`.
*/
deactivate_on?: Array<string>;
/**
* The product's description, meant to be displayable to the customer. Use this field to optionally store a long form explanation of the product being sold for your own rendering purposes.
*/
description?: string;
/**
* Specifies which fields in the response should be expanded.
*/
expand?: Array<string>;
/**
* An identifier will be randomly generated by Stripe. You can optionally override this ID, but the ID must be unique across all products in your Stripe account.
*/
id?: string;
/**
* A list of up to 8 URLs of images for this product, meant to be displayable to the customer.
*/
images?: Array<string>;
/**
* Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`.
*/
metadata?: Stripe.MetadataParam;
/**
* The dimensions of this product for shipping purposes.
*/
package_dimensions?: ProductCreateParams.PackageDimensions;
/**
* Whether this product is shipped (i.e., physical goods).
*/
shippable?: boolean;
/**
* An arbitrary string to be displayed on your customer's credit card or bank statement. While most banks display this information consistently, some may display it incorrectly or not at all.
*
* This may be up to 22 characters. The statement description may not include `<`, `>`, `\`, `"`, `'` characters, and will appear on your customer's statement in capital letters. Non-ASCII characters are automatically stripped.
* It must contain at least one letter.
*/
statement_descriptor?: string;
/**
* A [tax code](https://stripe.com/docs/tax/tax-codes) ID.
*/
tax_code?: string;
/**
* The type of the product. Defaults to `service` if not explicitly specified, enabling use of this product with Subscriptions and Plans. Set this parameter to `good` to use this product with Orders and SKUs. On API versions before `2018-02-05`, this field defaults to `good` for compatibility reasons.
*/
type?: ProductCreateParams.Type;
/**
* A label that represents units of this product in Stripe and on customers' receipts and invoices. When set, this will be included in associated invoice line item descriptions.
*/
unit_label?: string;
/**
* A URL of a publicly-accessible webpage for this product.
*/
url?: string;
}
namespace ProductCreateParams {
interface PackageDimensions {
/**
* Height, in inches. Maximum precision is 2 decimal places.
*/
height: number;
/**
* Length, in inches. Maximum precision is 2 decimal places.
*/
length: number;
/**
* Weight, in ounces. Maximum precision is 2 decimal places.
*/
weight: number;
/**
* Width, in inches. Maximum precision is 2 decimal places.
*/
width: number;
}
type Type = 'good' | 'service';
}
interface ProductRetrieveParams {
/**
* Specifies which fields in the response should be expanded.
*/
expand?: Array<string>;
}
interface ProductUpdateParams {
/**
* Whether the product is available for purchase.
*/
active?: boolean;
/**
* A list of up to 5 alphanumeric attributes that each SKU can provide values for (e.g., `["color", "size"]`). If a value for `attributes` is specified, the list specified will replace the existing attributes list on this product. Any attributes not present after the update will be deleted from the SKUs for this product.
*/
attributes?: Stripe.Emptyable<Array<string>>;
/**
* A short one-line description of the product, meant to be displayable to the customer. May only be set if `type=good`.
*/
caption?: string;
/**
* An array of Connect application names or identifiers that should not be able to order the SKUs for this product. May only be set if `type=good`.
*/
deactivate_on?: Array<string>;
/**
* The product's description, meant to be displayable to the customer. Use this field to optionally store a long form explanation of the product being sold for your own rendering purposes.
*/
description?: string;
/**
* Specifies which fields in the response should be expanded.
*/
expand?: Array<string>;
/**
* A list of up to 8 URLs of images for this product, meant to be displayable to the customer.
*/
images?: Stripe.Emptyable<Array<string>>;
/**
* Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`.
*/
metadata?: Stripe.Emptyable<Stripe.MetadataParam>;
/**
* The product's name, meant to be displayable to the customer. Whenever this product is sold via a subscription, name will show up on associated invoice line item descriptions.
*/
name?: string;
/**
* The dimensions of this product for shipping purposes.
*/
package_dimensions?: Stripe.Emptyable<
ProductUpdateParams.PackageDimensions
>;
/**
* Whether this product is shipped (i.e., physical goods).
*/
shippable?: boolean;
/**
* An arbitrary string to be displayed on your customer's credit card or bank statement. While most banks display this information consistently, some may display it incorrectly or not at all.
*
* This may be up to 22 characters. The statement description may not include `<`, `>`, `\`, `"`, `'` characters, and will appear on your customer's statement in capital letters. Non-ASCII characters are automatically stripped.
* It must contain at least one letter. May only be set if `type=service`.
*/
statement_descriptor?: string;
/**
* A [tax code](https://stripe.com/docs/tax/tax-codes) ID.
*/
tax_code?: Stripe.Emptyable<string>;
/**
* A label that represents units of this product in Stripe and on customers' receipts and invoices. When set, this will be included in associated invoice line item descriptions. May only be set if `type=service`.
*/
unit_label?: string;
/**
* A URL of a publicly-accessible webpage for this product.
*/
url?: string;
}
namespace ProductUpdateParams {
interface PackageDimensions {
/**
* Height, in inches. Maximum precision is 2 decimal places.
*/
height: number;
/**
* Length, in inches. Maximum precision is 2 decimal places.
*/
length: number;
/**
* Weight, in ounces. Maximum precision is 2 decimal places.
*/
weight: number;
/**
* Width, in inches. Maximum precision is 2 decimal places.
*/
width: number;
}
}
interface ProductListParams extends PaginationParams {
/**
* Only return products that are active or inactive (e.g., pass `false` to list all inactive products).
*/
active?: boolean;
/**
* Only return products that were created during the given date interval.
*/
created?: Stripe.RangeQueryParam | number;
/**
* Specifies which fields in the response should be expanded.
*/
expand?: Array<string>;
/**
* Only return products with the given IDs.
*/
ids?: Array<string>;
/**
* Only return products that can be shipped (i.e., physical, not digital products).
*/
shippable?: boolean;
/**
* Only return products of this type.
*/
type?: ProductListParams.Type;
/**
* Only return products with the given url.
*/
url?: string;
}
namespace ProductListParams {
type Type = 'good' | 'service';
}
interface ProductDeleteParams {}
class ProductsResource {
/**
* Creates a new product object.
*/
create(
params: ProductCreateParams,
options?: RequestOptions
): Promise<Stripe.Response<Stripe.Product>>;
/**
* Retrieves the details of an existing product. Supply the unique product ID from either a product creation request or the product list, and Stripe will return the corresponding product information.
*/
retrieve(
id: string,
params?: ProductRetrieveParams,
options?: RequestOptions
): Promise<Stripe.Response<Stripe.Product>>;
retrieve(
id: string,
options?: RequestOptions
): Promise<Stripe.Response<Stripe.Product>>;
/**
* Updates the specific product by setting the values of the parameters passed. Any parameters not provided will be left unchanged.
*/
update(
id: string,
params?: ProductUpdateParams,
options?: RequestOptions
): Promise<Stripe.Response<Stripe.Product>>;
/**
* Returns a list of your products. The products are returned sorted by creation date, with the most recently created products appearing first.
*/
list(
params?: ProductListParams,
options?: RequestOptions
): ApiListPromise<Stripe.Product>;
list(options?: RequestOptions): ApiListPromise<Stripe.Product>;
/**
* Delete a product. Deleting a product is only possible if it has no prices associated with it. Additionally, deleting a product with type=good is only possible if it has no SKUs associated with it.
*/
del(
id: string,
params?: ProductDeleteParams,
options?: RequestOptions
): Promise<Stripe.Response<Stripe.DeletedProduct>>;
del(
id: string,
options?: RequestOptions
): Promise<Stripe.Response<Stripe.DeletedProduct>>;
}
}
} | the_stack |
import {Request} from '../lib/request';
import {Response} from '../lib/response';
import {AWSError} from '../lib/error';
import {Service} from '../lib/service';
import {ServiceConfigurationOptions} from '../lib/service';
import {ConfigBase as Config} from '../lib/config-base';
interface Blob {}
declare class ServerlessApplicationRepository extends Service {
/**
* Constructs a service object. This object has one method for each API operation.
*/
constructor(options?: ServerlessApplicationRepository.Types.ClientConfiguration)
config: Config & ServerlessApplicationRepository.Types.ClientConfiguration;
/**
* Creates an application, optionally including an AWS SAM file to create the first application version in the same call.
*/
createApplication(params: ServerlessApplicationRepository.Types.CreateApplicationRequest, callback?: (err: AWSError, data: ServerlessApplicationRepository.Types.CreateApplicationResponse) => void): Request<ServerlessApplicationRepository.Types.CreateApplicationResponse, AWSError>;
/**
* Creates an application, optionally including an AWS SAM file to create the first application version in the same call.
*/
createApplication(callback?: (err: AWSError, data: ServerlessApplicationRepository.Types.CreateApplicationResponse) => void): Request<ServerlessApplicationRepository.Types.CreateApplicationResponse, AWSError>;
/**
* Creates an application version.
*/
createApplicationVersion(params: ServerlessApplicationRepository.Types.CreateApplicationVersionRequest, callback?: (err: AWSError, data: ServerlessApplicationRepository.Types.CreateApplicationVersionResponse) => void): Request<ServerlessApplicationRepository.Types.CreateApplicationVersionResponse, AWSError>;
/**
* Creates an application version.
*/
createApplicationVersion(callback?: (err: AWSError, data: ServerlessApplicationRepository.Types.CreateApplicationVersionResponse) => void): Request<ServerlessApplicationRepository.Types.CreateApplicationVersionResponse, AWSError>;
/**
* Creates an AWS CloudFormation change set for the given application.
*/
createCloudFormationChangeSet(params: ServerlessApplicationRepository.Types.CreateCloudFormationChangeSetRequest, callback?: (err: AWSError, data: ServerlessApplicationRepository.Types.CreateCloudFormationChangeSetResponse) => void): Request<ServerlessApplicationRepository.Types.CreateCloudFormationChangeSetResponse, AWSError>;
/**
* Creates an AWS CloudFormation change set for the given application.
*/
createCloudFormationChangeSet(callback?: (err: AWSError, data: ServerlessApplicationRepository.Types.CreateCloudFormationChangeSetResponse) => void): Request<ServerlessApplicationRepository.Types.CreateCloudFormationChangeSetResponse, AWSError>;
/**
* Creates an AWS CloudFormation template.
*/
createCloudFormationTemplate(params: ServerlessApplicationRepository.Types.CreateCloudFormationTemplateRequest, callback?: (err: AWSError, data: ServerlessApplicationRepository.Types.CreateCloudFormationTemplateResponse) => void): Request<ServerlessApplicationRepository.Types.CreateCloudFormationTemplateResponse, AWSError>;
/**
* Creates an AWS CloudFormation template.
*/
createCloudFormationTemplate(callback?: (err: AWSError, data: ServerlessApplicationRepository.Types.CreateCloudFormationTemplateResponse) => void): Request<ServerlessApplicationRepository.Types.CreateCloudFormationTemplateResponse, AWSError>;
/**
* Deletes the specified application.
*/
deleteApplication(params: ServerlessApplicationRepository.Types.DeleteApplicationRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Deletes the specified application.
*/
deleteApplication(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Gets the specified application.
*/
getApplication(params: ServerlessApplicationRepository.Types.GetApplicationRequest, callback?: (err: AWSError, data: ServerlessApplicationRepository.Types.GetApplicationResponse) => void): Request<ServerlessApplicationRepository.Types.GetApplicationResponse, AWSError>;
/**
* Gets the specified application.
*/
getApplication(callback?: (err: AWSError, data: ServerlessApplicationRepository.Types.GetApplicationResponse) => void): Request<ServerlessApplicationRepository.Types.GetApplicationResponse, AWSError>;
/**
* Retrieves the policy for the application.
*/
getApplicationPolicy(params: ServerlessApplicationRepository.Types.GetApplicationPolicyRequest, callback?: (err: AWSError, data: ServerlessApplicationRepository.Types.GetApplicationPolicyResponse) => void): Request<ServerlessApplicationRepository.Types.GetApplicationPolicyResponse, AWSError>;
/**
* Retrieves the policy for the application.
*/
getApplicationPolicy(callback?: (err: AWSError, data: ServerlessApplicationRepository.Types.GetApplicationPolicyResponse) => void): Request<ServerlessApplicationRepository.Types.GetApplicationPolicyResponse, AWSError>;
/**
* Gets the specified AWS CloudFormation template.
*/
getCloudFormationTemplate(params: ServerlessApplicationRepository.Types.GetCloudFormationTemplateRequest, callback?: (err: AWSError, data: ServerlessApplicationRepository.Types.GetCloudFormationTemplateResponse) => void): Request<ServerlessApplicationRepository.Types.GetCloudFormationTemplateResponse, AWSError>;
/**
* Gets the specified AWS CloudFormation template.
*/
getCloudFormationTemplate(callback?: (err: AWSError, data: ServerlessApplicationRepository.Types.GetCloudFormationTemplateResponse) => void): Request<ServerlessApplicationRepository.Types.GetCloudFormationTemplateResponse, AWSError>;
/**
* Retrieves the list of applications nested in the containing application.
*/
listApplicationDependencies(params: ServerlessApplicationRepository.Types.ListApplicationDependenciesRequest, callback?: (err: AWSError, data: ServerlessApplicationRepository.Types.ListApplicationDependenciesResponse) => void): Request<ServerlessApplicationRepository.Types.ListApplicationDependenciesResponse, AWSError>;
/**
* Retrieves the list of applications nested in the containing application.
*/
listApplicationDependencies(callback?: (err: AWSError, data: ServerlessApplicationRepository.Types.ListApplicationDependenciesResponse) => void): Request<ServerlessApplicationRepository.Types.ListApplicationDependenciesResponse, AWSError>;
/**
* Lists versions for the specified application.
*/
listApplicationVersions(params: ServerlessApplicationRepository.Types.ListApplicationVersionsRequest, callback?: (err: AWSError, data: ServerlessApplicationRepository.Types.ListApplicationVersionsResponse) => void): Request<ServerlessApplicationRepository.Types.ListApplicationVersionsResponse, AWSError>;
/**
* Lists versions for the specified application.
*/
listApplicationVersions(callback?: (err: AWSError, data: ServerlessApplicationRepository.Types.ListApplicationVersionsResponse) => void): Request<ServerlessApplicationRepository.Types.ListApplicationVersionsResponse, AWSError>;
/**
* Lists applications owned by the requester.
*/
listApplications(params: ServerlessApplicationRepository.Types.ListApplicationsRequest, callback?: (err: AWSError, data: ServerlessApplicationRepository.Types.ListApplicationsResponse) => void): Request<ServerlessApplicationRepository.Types.ListApplicationsResponse, AWSError>;
/**
* Lists applications owned by the requester.
*/
listApplications(callback?: (err: AWSError, data: ServerlessApplicationRepository.Types.ListApplicationsResponse) => void): Request<ServerlessApplicationRepository.Types.ListApplicationsResponse, AWSError>;
/**
* Sets the permission policy for an application. For the list of actions supported for this operation, see
Application
Permissions
.
*/
putApplicationPolicy(params: ServerlessApplicationRepository.Types.PutApplicationPolicyRequest, callback?: (err: AWSError, data: ServerlessApplicationRepository.Types.PutApplicationPolicyResponse) => void): Request<ServerlessApplicationRepository.Types.PutApplicationPolicyResponse, AWSError>;
/**
* Sets the permission policy for an application. For the list of actions supported for this operation, see
Application
Permissions
.
*/
putApplicationPolicy(callback?: (err: AWSError, data: ServerlessApplicationRepository.Types.PutApplicationPolicyResponse) => void): Request<ServerlessApplicationRepository.Types.PutApplicationPolicyResponse, AWSError>;
/**
* Unshares an application from an AWS Organization.This operation can be called only from the organization's master account.
*/
unshareApplication(params: ServerlessApplicationRepository.Types.UnshareApplicationRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Unshares an application from an AWS Organization.This operation can be called only from the organization's master account.
*/
unshareApplication(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Updates the specified application.
*/
updateApplication(params: ServerlessApplicationRepository.Types.UpdateApplicationRequest, callback?: (err: AWSError, data: ServerlessApplicationRepository.Types.UpdateApplicationResponse) => void): Request<ServerlessApplicationRepository.Types.UpdateApplicationResponse, AWSError>;
/**
* Updates the specified application.
*/
updateApplication(callback?: (err: AWSError, data: ServerlessApplicationRepository.Types.UpdateApplicationResponse) => void): Request<ServerlessApplicationRepository.Types.UpdateApplicationResponse, AWSError>;
}
declare namespace ServerlessApplicationRepository {
export interface ApplicationDependencySummary {
/**
* The Amazon Resource Name (ARN) of the nested application.
*/
ApplicationId: __string;
/**
* The semantic version of the nested application.
*/
SemanticVersion: __string;
}
export interface ApplicationPolicyStatement {
/**
* For the list of actions supported for this operation, see Application
Permissions.
*/
Actions: __listOf__string;
/**
* An array of PrinciplalOrgIDs, which corresponds to AWS IAM aws:PrincipalOrgID global condition key.
*/
PrincipalOrgIDs?: __listOf__string;
/**
* An array of AWS account IDs, or * to make the application public.
*/
Principals: __listOf__string;
/**
* A unique ID for the statement.
*/
StatementId?: __string;
}
export interface ApplicationSummary {
/**
* The application Amazon Resource Name (ARN).
*/
ApplicationId: __string;
/**
* The name of the author publishing the app.Minimum length=1. Maximum length=127.Pattern "^[a-z0-9](([a-z0-9]|-(?!-))*[a-z0-9])?$";
*/
Author: __string;
/**
* The date and time this resource was created.
*/
CreationTime?: __string;
/**
* The description of the application.Minimum length=1. Maximum length=256
*/
Description: __string;
/**
* A URL with more information about the application, for example the location of your GitHub repository for the application.
*/
HomePageUrl?: __string;
/**
* Labels to improve discovery of apps in search results.Minimum length=1. Maximum length=127. Maximum number of labels: 10Pattern: "^[a-zA-Z0-9+\\-_:\\/@]+$";
*/
Labels?: __listOf__string;
/**
* The name of the application.Minimum length=1. Maximum length=140Pattern: "[a-zA-Z0-9\\-]+";
*/
Name: __string;
/**
* A valid identifier from https://spdx.org/licenses/.
*/
SpdxLicenseId?: __string;
}
export type Capability = "CAPABILITY_IAM"|"CAPABILITY_NAMED_IAM"|"CAPABILITY_AUTO_EXPAND"|"CAPABILITY_RESOURCE_POLICY"|string;
export interface CreateApplicationRequest {
/**
* The name of the author publishing the app.Minimum length=1. Maximum length=127.Pattern "^[a-z0-9](([a-z0-9]|-(?!-))*[a-z0-9])?$";
*/
Author: __string;
/**
* The description of the application.Minimum length=1. Maximum length=256
*/
Description: __string;
/**
* A URL with more information about the application, for example the location of your GitHub repository for the application.
*/
HomePageUrl?: __string;
/**
* Labels to improve discovery of apps in search results.Minimum length=1. Maximum length=127. Maximum number of labels: 10Pattern: "^[a-zA-Z0-9+\\-_:\\/@]+$";
*/
Labels?: __listOf__string;
/**
* A local text file that contains the license of the app that matches the spdxLicenseID value of your application.
The file has the format file://<path>/<filename>.Maximum size 5 MBYou can specify only one of licenseBody and licenseUrl; otherwise, an error results.
*/
LicenseBody?: __string;
/**
* A link to the S3 object that contains the license of the app that matches the spdxLicenseID value of your application.Maximum size 5 MBYou can specify only one of licenseBody and licenseUrl; otherwise, an error results.
*/
LicenseUrl?: __string;
/**
* The name of the application that you want to publish.Minimum length=1. Maximum length=140Pattern: "[a-zA-Z0-9\\-]+";
*/
Name: __string;
/**
* A local text readme file in Markdown language that contains a more detailed description of the application and how it works.
The file has the format file://<path>/<filename>.Maximum size 5 MBYou can specify only one of readmeBody and readmeUrl; otherwise, an error results.
*/
ReadmeBody?: __string;
/**
* A link to the S3 object in Markdown language that contains a more detailed description of the application and how it works.Maximum size 5 MBYou can specify only one of readmeBody and readmeUrl; otherwise, an error results.
*/
ReadmeUrl?: __string;
/**
* The semantic version of the application:
https://semver.org/
*/
SemanticVersion?: __string;
/**
* A link to the S3 object that contains the ZIP archive of the source code for this version of your application.Maximum size 50 MB
*/
SourceCodeArchiveUrl?: __string;
/**
* A link to a public repository for the source code of your application, for example the URL of a specific GitHub commit.
*/
SourceCodeUrl?: __string;
/**
* A valid identifier from https://spdx.org/licenses/.
*/
SpdxLicenseId?: __string;
/**
* The local raw packaged AWS SAM template file of your application.
The file has the format file://<path>/<filename>.You can specify only one of templateBody and templateUrl; otherwise an error results.
*/
TemplateBody?: __string;
/**
* A link to the S3 object containing the packaged AWS SAM template of your application.You can specify only one of templateBody and templateUrl; otherwise an error results.
*/
TemplateUrl?: __string;
}
export interface CreateApplicationResponse {
/**
* The application Amazon Resource Name (ARN).
*/
ApplicationId?: __string;
/**
* The name of the author publishing the app.Minimum length=1. Maximum length=127.Pattern "^[a-z0-9](([a-z0-9]|-(?!-))*[a-z0-9])?$";
*/
Author?: __string;
/**
* The date and time this resource was created.
*/
CreationTime?: __string;
/**
* The description of the application.Minimum length=1. Maximum length=256
*/
Description?: __string;
/**
* A URL with more information about the application, for example the location of your GitHub repository for the application.
*/
HomePageUrl?: __string;
/**
* Whether the author of this application has been verified. This means means that AWS has made a good faith review, as a reasonable and prudent service provider, of the information provided by the requester and has confirmed that the requester's identity is as claimed.
*/
IsVerifiedAuthor?: __boolean;
/**
* Labels to improve discovery of apps in search results.Minimum length=1. Maximum length=127. Maximum number of labels: 10Pattern: "^[a-zA-Z0-9+\\-_:\\/@]+$";
*/
Labels?: __listOf__string;
/**
* A link to a license file of the app that matches the spdxLicenseID value of your application.Maximum size 5 MB
*/
LicenseUrl?: __string;
/**
* The name of the application.Minimum length=1. Maximum length=140Pattern: "[a-zA-Z0-9\\-]+";
*/
Name?: __string;
/**
* A link to the readme file in Markdown language that contains a more detailed description of the application and how it works.Maximum size 5 MB
*/
ReadmeUrl?: __string;
/**
* A valid identifier from https://spdx.org/licenses/.
*/
SpdxLicenseId?: __string;
/**
* The URL to the public profile of a verified author. This URL is submitted by the author.
*/
VerifiedAuthorUrl?: __string;
/**
* Version information about the application.
*/
Version?: Version;
}
export interface CreateApplicationVersionRequest {
/**
* The Amazon Resource Name (ARN) of the application.
*/
ApplicationId: __string;
/**
* The semantic version of the new version.
*/
SemanticVersion: __string;
/**
* A link to the S3 object that contains the ZIP archive of the source code for this version of your application.Maximum size 50 MB
*/
SourceCodeArchiveUrl?: __string;
/**
* A link to a public repository for the source code of your application, for example the URL of a specific GitHub commit.
*/
SourceCodeUrl?: __string;
/**
* The raw packaged AWS SAM template of your application.
*/
TemplateBody?: __string;
/**
* A link to the packaged AWS SAM template of your application.
*/
TemplateUrl?: __string;
}
export interface CreateApplicationVersionResponse {
/**
* The application Amazon Resource Name (ARN).
*/
ApplicationId?: __string;
/**
* The date and time this resource was created.
*/
CreationTime?: __string;
/**
* An array of parameter types supported by the application.
*/
ParameterDefinitions?: __listOfParameterDefinition;
/**
* A list of values that you must specify before you can deploy certain applications.
Some applications might include resources that can affect permissions in your AWS
account, for example, by creating new AWS Identity and Access Management (IAM) users.
For those applications, you must explicitly acknowledge their capabilities by
specifying this parameter.The only valid values are CAPABILITY_IAM, CAPABILITY_NAMED_IAM,
CAPABILITY_RESOURCE_POLICY, and CAPABILITY_AUTO_EXPAND.The following resources require you to specify CAPABILITY_IAM or
CAPABILITY_NAMED_IAM:
AWS::IAM::Group,
AWS::IAM::InstanceProfile,
AWS::IAM::Policy, and
AWS::IAM::Role.
If the application contains IAM resources, you can specify either CAPABILITY_IAM
or CAPABILITY_NAMED_IAM. If the application contains IAM resources
with custom names, you must specify CAPABILITY_NAMED_IAM.The following resources require you to specify CAPABILITY_RESOURCE_POLICY:
AWS::Lambda::Permission,
AWS::IAM:Policy,
AWS::ApplicationAutoScaling::ScalingPolicy,
AWS::S3::BucketPolicy,
AWS::SQS::QueuePolicy, and
AWS::SNS::TopicPolicy.Applications that contain one or more nested applications require you to specify
CAPABILITY_AUTO_EXPAND.If your application template contains any of the above resources, we recommend that you review
all permissions associated with the application before deploying. If you don't specify
this parameter for an application that requires capabilities, the call will fail.
*/
RequiredCapabilities?: __listOfCapability;
/**
* Whether all of the AWS resources contained in this application are supported in the region
in which it is being retrieved.
*/
ResourcesSupported?: __boolean;
/**
* The semantic version of the application:
https://semver.org/
*/
SemanticVersion?: __string;
/**
* A link to the S3 object that contains the ZIP archive of the source code for this version of your application.Maximum size 50 MB
*/
SourceCodeArchiveUrl?: __string;
/**
* A link to a public repository for the source code of your application, for example the URL of a specific GitHub commit.
*/
SourceCodeUrl?: __string;
/**
* A link to the packaged AWS SAM template of your application.
*/
TemplateUrl?: __string;
}
export interface CreateCloudFormationChangeSetRequest {
/**
* The Amazon Resource Name (ARN) of the application.
*/
ApplicationId: __string;
/**
* A list of values that you must specify before you can deploy certain applications.
Some applications might include resources that can affect permissions in your AWS
account, for example, by creating new AWS Identity and Access Management (IAM) users.
For those applications, you must explicitly acknowledge their capabilities by
specifying this parameter.The only valid values are CAPABILITY_IAM, CAPABILITY_NAMED_IAM,
CAPABILITY_RESOURCE_POLICY, and CAPABILITY_AUTO_EXPAND.The following resources require you to specify CAPABILITY_IAM or
CAPABILITY_NAMED_IAM:
AWS::IAM::Group,
AWS::IAM::InstanceProfile,
AWS::IAM::Policy, and
AWS::IAM::Role.
If the application contains IAM resources, you can specify either CAPABILITY_IAM
or CAPABILITY_NAMED_IAM. If the application contains IAM resources
with custom names, you must specify CAPABILITY_NAMED_IAM.The following resources require you to specify CAPABILITY_RESOURCE_POLICY:
AWS::Lambda::Permission,
AWS::IAM:Policy,
AWS::ApplicationAutoScaling::ScalingPolicy,
AWS::S3::BucketPolicy,
AWS::SQS::QueuePolicy, and
AWS::SNS:TopicPolicy.Applications that contain one or more nested applications require you to specify
CAPABILITY_AUTO_EXPAND.If your application template contains any of the above resources, we recommend that you review
all permissions associated with the application before deploying. If you don't specify
this parameter for an application that requires capabilities, the call will fail.
*/
Capabilities?: __listOf__string;
/**
* This property corresponds to the parameter of the same name for the AWS CloudFormation CreateChangeSet
API.
*/
ChangeSetName?: __string;
/**
* This property corresponds to the parameter of the same name for the AWS CloudFormation CreateChangeSet
API.
*/
ClientToken?: __string;
/**
* This property corresponds to the parameter of the same name for the AWS CloudFormation CreateChangeSet
API.
*/
Description?: __string;
/**
* This property corresponds to the parameter of the same name for the AWS CloudFormation CreateChangeSet
API.
*/
NotificationArns?: __listOf__string;
/**
* A list of parameter values for the parameters of the application.
*/
ParameterOverrides?: __listOfParameterValue;
/**
* This property corresponds to the parameter of the same name for the AWS CloudFormation CreateChangeSet
API.
*/
ResourceTypes?: __listOf__string;
/**
* This property corresponds to the parameter of the same name for the AWS CloudFormation CreateChangeSet
API.
*/
RollbackConfiguration?: RollbackConfiguration;
/**
* The semantic version of the application:
https://semver.org/
*/
SemanticVersion?: __string;
/**
* This property corresponds to the parameter of the same name for the AWS CloudFormation CreateChangeSet
API.
*/
StackName: __string;
/**
* This property corresponds to the parameter of the same name for the AWS CloudFormation CreateChangeSet
API.
*/
Tags?: __listOfTag;
/**
* The UUID returned by CreateCloudFormationTemplate.Pattern: [0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}
*/
TemplateId?: __string;
}
export interface CreateCloudFormationChangeSetResponse {
/**
* The application Amazon Resource Name (ARN).
*/
ApplicationId?: __string;
/**
* The Amazon Resource Name (ARN) of the change set.Length constraints: Minimum length of 1.Pattern: ARN:[-a-zA-Z0-9:/]*
*/
ChangeSetId?: __string;
/**
* The semantic version of the application:
https://semver.org/
*/
SemanticVersion?: __string;
/**
* The unique ID of the stack.
*/
StackId?: __string;
}
export interface CreateCloudFormationTemplateRequest {
/**
* The Amazon Resource Name (ARN) of the application.
*/
ApplicationId: __string;
/**
* The semantic version of the application:
https://semver.org/
*/
SemanticVersion?: __string;
}
export interface CreateCloudFormationTemplateResponse {
/**
* The application Amazon Resource Name (ARN).
*/
ApplicationId?: __string;
/**
* The date and time this resource was created.
*/
CreationTime?: __string;
/**
* The date and time this template expires. Templates
expire 1 hour after creation.
*/
ExpirationTime?: __string;
/**
* The semantic version of the application:
https://semver.org/
*/
SemanticVersion?: __string;
/**
* Status of the template creation workflow.Possible values: PREPARING | ACTIVE | EXPIRED
*/
Status?: Status;
/**
* The UUID returned by CreateCloudFormationTemplate.Pattern: [0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}
*/
TemplateId?: __string;
/**
* A link to the template that can be used to deploy the application using
AWS CloudFormation.
*/
TemplateUrl?: __string;
}
export interface DeleteApplicationRequest {
/**
* The Amazon Resource Name (ARN) of the application.
*/
ApplicationId: __string;
}
export interface GetApplicationPolicyRequest {
/**
* The Amazon Resource Name (ARN) of the application.
*/
ApplicationId: __string;
}
export interface GetApplicationPolicyResponse {
/**
* An array of policy statements applied to the application.
*/
Statements?: __listOfApplicationPolicyStatement;
}
export interface GetApplicationRequest {
/**
* The Amazon Resource Name (ARN) of the application.
*/
ApplicationId: __string;
/**
* The semantic version of the application to get.
*/
SemanticVersion?: __string;
}
export interface GetApplicationResponse {
/**
* The application Amazon Resource Name (ARN).
*/
ApplicationId?: __string;
/**
* The name of the author publishing the app.Minimum length=1. Maximum length=127.Pattern "^[a-z0-9](([a-z0-9]|-(?!-))*[a-z0-9])?$";
*/
Author?: __string;
/**
* The date and time this resource was created.
*/
CreationTime?: __string;
/**
* The description of the application.Minimum length=1. Maximum length=256
*/
Description?: __string;
/**
* A URL with more information about the application, for example the location of your GitHub repository for the application.
*/
HomePageUrl?: __string;
/**
* Whether the author of this application has been verified. This means means that AWS has made a good faith review, as a reasonable and prudent service provider, of the information provided by the requester and has confirmed that the requester's identity is as claimed.
*/
IsVerifiedAuthor?: __boolean;
/**
* Labels to improve discovery of apps in search results.Minimum length=1. Maximum length=127. Maximum number of labels: 10Pattern: "^[a-zA-Z0-9+\\-_:\\/@]+$";
*/
Labels?: __listOf__string;
/**
* A link to a license file of the app that matches the spdxLicenseID value of your application.Maximum size 5 MB
*/
LicenseUrl?: __string;
/**
* The name of the application.Minimum length=1. Maximum length=140Pattern: "[a-zA-Z0-9\\-]+";
*/
Name?: __string;
/**
* A link to the readme file in Markdown language that contains a more detailed description of the application and how it works.Maximum size 5 MB
*/
ReadmeUrl?: __string;
/**
* A valid identifier from https://spdx.org/licenses/.
*/
SpdxLicenseId?: __string;
/**
* The URL to the public profile of a verified author. This URL is submitted by the author.
*/
VerifiedAuthorUrl?: __string;
/**
* Version information about the application.
*/
Version?: Version;
}
export interface GetCloudFormationTemplateRequest {
/**
* The Amazon Resource Name (ARN) of the application.
*/
ApplicationId: __string;
/**
* The UUID returned by CreateCloudFormationTemplate.Pattern: [0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}
*/
TemplateId: __string;
}
export interface GetCloudFormationTemplateResponse {
/**
* The application Amazon Resource Name (ARN).
*/
ApplicationId?: __string;
/**
* The date and time this resource was created.
*/
CreationTime?: __string;
/**
* The date and time this template expires. Templates
expire 1 hour after creation.
*/
ExpirationTime?: __string;
/**
* The semantic version of the application:
https://semver.org/
*/
SemanticVersion?: __string;
/**
* Status of the template creation workflow.Possible values: PREPARING | ACTIVE | EXPIRED
*/
Status?: Status;
/**
* The UUID returned by CreateCloudFormationTemplate.Pattern: [0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}
*/
TemplateId?: __string;
/**
* A link to the template that can be used to deploy the application using
AWS CloudFormation.
*/
TemplateUrl?: __string;
}
export interface ListApplicationDependenciesRequest {
/**
* The Amazon Resource Name (ARN) of the application.
*/
ApplicationId: __string;
/**
* The total number of items to return.
*/
MaxItems?: MaxItems;
/**
* A token to specify where to start paginating.
*/
NextToken?: __string;
/**
* The semantic version of the application to get.
*/
SemanticVersion?: __string;
}
export interface ListApplicationDependenciesResponse {
/**
* An array of application summaries nested in the application.
*/
Dependencies?: __listOfApplicationDependencySummary;
/**
* The token to request the next page of results.
*/
NextToken?: __string;
}
export interface ListApplicationVersionsRequest {
/**
* The Amazon Resource Name (ARN) of the application.
*/
ApplicationId: __string;
/**
* The total number of items to return.
*/
MaxItems?: MaxItems;
/**
* A token to specify where to start paginating.
*/
NextToken?: __string;
}
export interface ListApplicationVersionsResponse {
/**
* The token to request the next page of results.
*/
NextToken?: __string;
/**
* An array of version summaries for the application.
*/
Versions?: __listOfVersionSummary;
}
export interface ListApplicationsRequest {
/**
* The total number of items to return.
*/
MaxItems?: MaxItems;
/**
* A token to specify where to start paginating.
*/
NextToken?: __string;
}
export interface ListApplicationsResponse {
/**
* An array of application summaries.
*/
Applications?: __listOfApplicationSummary;
/**
* The token to request the next page of results.
*/
NextToken?: __string;
}
export type MaxItems = number;
export interface ParameterDefinition {
/**
* A regular expression that represents the patterns to allow for String types.
*/
AllowedPattern?: __string;
/**
* An array containing the list of values allowed for the parameter.
*/
AllowedValues?: __listOf__string;
/**
* A string that explains a constraint when the constraint is violated. For example, without a constraint description,
a parameter that has an allowed pattern of [A-Za-z0-9]+ displays the following error message when the user
specifies an invalid value:
Malformed input-Parameter MyParameter must match pattern [A-Za-z0-9]+
By adding a constraint description, such as "must contain only uppercase and lowercase letters and numbers," you can display
the following customized error message:
Malformed input-Parameter MyParameter must contain only uppercase and lowercase letters and numbers.
*/
ConstraintDescription?: __string;
/**
* A value of the appropriate type for the template to use if no value is specified when a stack is created.
If you define constraints for the parameter, you must specify a value that adheres to those constraints.
*/
DefaultValue?: __string;
/**
* A string of up to 4,000 characters that describes the parameter.
*/
Description?: __string;
/**
* An integer value that determines the largest number of characters that you want to allow for String types.
*/
MaxLength?: __integer;
/**
* A numeric value that determines the largest numeric value that you want to allow for Number types.
*/
MaxValue?: __integer;
/**
* An integer value that determines the smallest number of characters that you want to allow for String types.
*/
MinLength?: __integer;
/**
* A numeric value that determines the smallest numeric value that you want to allow for Number types.
*/
MinValue?: __integer;
/**
* The name of the parameter.
*/
Name: __string;
/**
* Whether to mask the parameter value whenever anyone makes a call that describes the stack. If you set the
value to true, the parameter value is masked with asterisks (*****).
*/
NoEcho?: __boolean;
/**
* A list of AWS SAM resources that use this parameter.
*/
ReferencedByResources: __listOf__string;
/**
* The type of the parameter.Valid values: String | Number | List<Number> | CommaDelimitedList
String: A literal string.For example, users can specify "MyUserName".
Number: An integer or float. AWS CloudFormation validates the parameter value as a number. However, when you use the
parameter elsewhere in your template (for example, by using the Ref intrinsic function), the parameter value becomes a string.For example, users might specify "8888".
List<Number>: An array of integers or floats that are separated by commas. AWS CloudFormation validates the parameter value as numbers. However, when
you use the parameter elsewhere in your template (for example, by using the Ref intrinsic function), the parameter value becomes a list of strings.For example, users might specify "80,20", and then Ref results in ["80","20"].
CommaDelimitedList: An array of literal strings that are separated by commas. The total number of strings should be one more than the total number of commas.
Also, each member string is space-trimmed.For example, users might specify "test,dev,prod", and then Ref results in ["test","dev","prod"].
*/
Type?: __string;
}
export interface ParameterValue {
/**
* The key associated with the parameter. If you don't specify a key and value for a particular parameter, AWS CloudFormation
uses the default value that is specified in your template.
*/
Name: __string;
/**
* The input value associated with the parameter.
*/
Value: __string;
}
export interface PutApplicationPolicyRequest {
/**
* The Amazon Resource Name (ARN) of the application.
*/
ApplicationId: __string;
/**
* An array of policy statements applied to the application.
*/
Statements: __listOfApplicationPolicyStatement;
}
export interface PutApplicationPolicyResponse {
/**
* An array of policy statements applied to the application.
*/
Statements?: __listOfApplicationPolicyStatement;
}
export interface RollbackConfiguration {
/**
* This property corresponds to the content of the same name for the AWS CloudFormation RollbackConfiguration
Data Type.
*/
MonitoringTimeInMinutes?: __integer;
/**
* This property corresponds to the content of the same name for the AWS CloudFormation RollbackConfiguration
Data Type.
*/
RollbackTriggers?: __listOfRollbackTrigger;
}
export interface RollbackTrigger {
/**
* This property corresponds to the content of the same name for the AWS CloudFormation RollbackTrigger
Data Type.
*/
Arn: __string;
/**
* This property corresponds to the content of the same name for the AWS CloudFormation RollbackTrigger
Data Type.
*/
Type: __string;
}
export type Status = "PREPARING"|"ACTIVE"|"EXPIRED"|string;
export interface Tag {
/**
* This property corresponds to the content of the same name for the AWS CloudFormation Tag
Data Type.
*/
Key: __string;
/**
* This property corresponds to the content of the same name for the AWS CloudFormation
Tag
Data Type.
*/
Value: __string;
}
export interface UnshareApplicationRequest {
/**
* The Amazon Resource Name (ARN) of the application.
*/
ApplicationId: __string;
/**
* The AWS Organization ID to unshare the application from.
*/
OrganizationId: __string;
}
export interface UpdateApplicationRequest {
/**
* The Amazon Resource Name (ARN) of the application.
*/
ApplicationId: __string;
/**
* The name of the author publishing the app.Minimum length=1. Maximum length=127.Pattern "^[a-z0-9](([a-z0-9]|-(?!-))*[a-z0-9])?$";
*/
Author?: __string;
/**
* The description of the application.Minimum length=1. Maximum length=256
*/
Description?: __string;
/**
* A URL with more information about the application, for example the location of your GitHub repository for the application.
*/
HomePageUrl?: __string;
/**
* Labels to improve discovery of apps in search results.Minimum length=1. Maximum length=127. Maximum number of labels: 10Pattern: "^[a-zA-Z0-9+\\-_:\\/@]+$";
*/
Labels?: __listOf__string;
/**
* A text readme file in Markdown language that contains a more detailed description of the application and how it works.Maximum size 5 MB
*/
ReadmeBody?: __string;
/**
* A link to the readme file in Markdown language that contains a more detailed description of the application and how it works.Maximum size 5 MB
*/
ReadmeUrl?: __string;
}
export interface UpdateApplicationResponse {
/**
* The application Amazon Resource Name (ARN).
*/
ApplicationId?: __string;
/**
* The name of the author publishing the app.Minimum length=1. Maximum length=127.Pattern "^[a-z0-9](([a-z0-9]|-(?!-))*[a-z0-9])?$";
*/
Author?: __string;
/**
* The date and time this resource was created.
*/
CreationTime?: __string;
/**
* The description of the application.Minimum length=1. Maximum length=256
*/
Description?: __string;
/**
* A URL with more information about the application, for example the location of your GitHub repository for the application.
*/
HomePageUrl?: __string;
/**
* Whether the author of this application has been verified. This means means that AWS has made a good faith review, as a reasonable and prudent service provider, of the information provided by the requester and has confirmed that the requester's identity is as claimed.
*/
IsVerifiedAuthor?: __boolean;
/**
* Labels to improve discovery of apps in search results.Minimum length=1. Maximum length=127. Maximum number of labels: 10Pattern: "^[a-zA-Z0-9+\\-_:\\/@]+$";
*/
Labels?: __listOf__string;
/**
* A link to a license file of the app that matches the spdxLicenseID value of your application.Maximum size 5 MB
*/
LicenseUrl?: __string;
/**
* The name of the application.Minimum length=1. Maximum length=140Pattern: "[a-zA-Z0-9\\-]+";
*/
Name?: __string;
/**
* A link to the readme file in Markdown language that contains a more detailed description of the application and how it works.Maximum size 5 MB
*/
ReadmeUrl?: __string;
/**
* A valid identifier from https://spdx.org/licenses/.
*/
SpdxLicenseId?: __string;
/**
* The URL to the public profile of a verified author. This URL is submitted by the author.
*/
VerifiedAuthorUrl?: __string;
/**
* Version information about the application.
*/
Version?: Version;
}
export interface Version {
/**
* The application Amazon Resource Name (ARN).
*/
ApplicationId: __string;
/**
* The date and time this resource was created.
*/
CreationTime: __string;
/**
* An array of parameter types supported by the application.
*/
ParameterDefinitions: __listOfParameterDefinition;
/**
* A list of values that you must specify before you can deploy certain applications.
Some applications might include resources that can affect permissions in your AWS
account, for example, by creating new AWS Identity and Access Management (IAM) users.
For those applications, you must explicitly acknowledge their capabilities by
specifying this parameter.The only valid values are CAPABILITY_IAM, CAPABILITY_NAMED_IAM,
CAPABILITY_RESOURCE_POLICY, and CAPABILITY_AUTO_EXPAND.The following resources require you to specify CAPABILITY_IAM or
CAPABILITY_NAMED_IAM:
AWS::IAM::Group,
AWS::IAM::InstanceProfile,
AWS::IAM::Policy, and
AWS::IAM::Role.
If the application contains IAM resources, you can specify either CAPABILITY_IAM
or CAPABILITY_NAMED_IAM. If the application contains IAM resources
with custom names, you must specify CAPABILITY_NAMED_IAM.The following resources require you to specify CAPABILITY_RESOURCE_POLICY:
AWS::Lambda::Permission,
AWS::IAM:Policy,
AWS::ApplicationAutoScaling::ScalingPolicy,
AWS::S3::BucketPolicy,
AWS::SQS::QueuePolicy, and
AWS::SNS::TopicPolicy.Applications that contain one or more nested applications require you to specify
CAPABILITY_AUTO_EXPAND.If your application template contains any of the above resources, we recommend that you review
all permissions associated with the application before deploying. If you don't specify
this parameter for an application that requires capabilities, the call will fail.
*/
RequiredCapabilities: __listOfCapability;
/**
* Whether all of the AWS resources contained in this application are supported in the region
in which it is being retrieved.
*/
ResourcesSupported: __boolean;
/**
* The semantic version of the application:
https://semver.org/
*/
SemanticVersion: __string;
/**
* A link to the S3 object that contains the ZIP archive of the source code for this version of your application.Maximum size 50 MB
*/
SourceCodeArchiveUrl?: __string;
/**
* A link to a public repository for the source code of your application, for example the URL of a specific GitHub commit.
*/
SourceCodeUrl?: __string;
/**
* A link to the packaged AWS SAM template of your application.
*/
TemplateUrl: __string;
}
export interface VersionSummary {
/**
* The application Amazon Resource Name (ARN).
*/
ApplicationId: __string;
/**
* The date and time this resource was created.
*/
CreationTime: __string;
/**
* The semantic version of the application:
https://semver.org/
*/
SemanticVersion: __string;
/**
* A link to a public repository for the source code of your application, for example the URL of a specific GitHub commit.
*/
SourceCodeUrl?: __string;
}
export type __boolean = boolean;
export type __integer = number;
export type __listOfApplicationDependencySummary = ApplicationDependencySummary[];
export type __listOfApplicationPolicyStatement = ApplicationPolicyStatement[];
export type __listOfApplicationSummary = ApplicationSummary[];
export type __listOfCapability = Capability[];
export type __listOfParameterDefinition = ParameterDefinition[];
export type __listOfParameterValue = ParameterValue[];
export type __listOfRollbackTrigger = RollbackTrigger[];
export type __listOfTag = Tag[];
export type __listOfVersionSummary = VersionSummary[];
export type __listOf__string = __string[];
export type __string = string;
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
export type apiVersion = "2017-09-08"|"latest"|string;
export interface ClientApiVersions {
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
apiVersion?: apiVersion;
}
export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions;
/**
* Contains interfaces for use with the ServerlessApplicationRepository client.
*/
export import Types = ServerlessApplicationRepository;
}
export = ServerlessApplicationRepository; | the_stack |
import * as os from 'os';
import * as path from 'path';
import { Architecture, AssetCode, Code, Runtime } from '@aws-cdk/aws-lambda';
import * as cdk from '@aws-cdk/core';
import { PackageInstallation } from './package-installation';
import { PackageManager } from './package-manager';
import { BundlingOptions, SourceMapMode } from './types';
import { exec, extractDependencies, findUp } from './util';
const ESBUILD_MAJOR_VERSION = '0';
/**
* Bundling properties
*/
export interface BundlingProps extends BundlingOptions {
/**
* Path to lock file
*/
readonly depsLockFilePath: string;
/**
* Entry file
*/
readonly entry: string;
/**
* The runtime of the lambda function
*/
readonly runtime: Runtime;
/**
* The system architecture of the lambda function
*/
readonly architecture: Architecture;
/**
* Path to project root
*/
readonly projectRoot: string;
/**
* Run compilation using `tsc` before bundling
*/
readonly preCompilation?: boolean
}
/**
* Bundling with esbuild
*/
export class Bundling implements cdk.BundlingOptions {
/**
* esbuild bundled Lambda asset code
*/
public static bundle(options: BundlingProps): AssetCode {
return Code.fromAsset(options.projectRoot, {
assetHash: options.assetHash,
assetHashType: options.assetHash ? cdk.AssetHashType.CUSTOM : cdk.AssetHashType.OUTPUT,
bundling: new Bundling(options),
});
}
public static clearEsbuildInstallationCache(): void {
this.esbuildInstallation = undefined;
}
public static clearTscInstallationCache(): void {
this.tscInstallation = undefined;
}
public static clearTscCompilationCache(): void {
this.tscCompiled = false;
}
private static esbuildInstallation?: PackageInstallation;
private static tscInstallation?: PackageInstallation;
private static tscCompiled = false
// Core bundling options
public readonly image: cdk.DockerImage;
public readonly command: string[];
public readonly environment?: { [key: string]: string };
public readonly workingDirectory: string;
public readonly local?: cdk.ILocalBundling;
private readonly projectRoot: string;
private readonly relativeEntryPath: string;
private readonly relativeTsconfigPath?: string;
private readonly relativeDepsLockFilePath: string;
private readonly externals: string[];
private readonly packageManager: PackageManager;
constructor(private readonly props: BundlingProps) {
this.packageManager = PackageManager.fromLockFile(props.depsLockFilePath);
Bundling.esbuildInstallation = Bundling.esbuildInstallation ?? PackageInstallation.detect('esbuild');
Bundling.tscInstallation = Bundling.tscInstallation ?? PackageInstallation.detect('tsc');
this.projectRoot = props.projectRoot;
this.relativeEntryPath = path.relative(this.projectRoot, path.resolve(props.entry));
this.relativeDepsLockFilePath = path.relative(this.projectRoot, path.resolve(props.depsLockFilePath));
if (this.relativeDepsLockFilePath.includes('..')) {
throw new Error(`Expected depsLockFilePath: ${props.depsLockFilePath} to be under projectRoot: ${this.projectRoot} (${this.relativeDepsLockFilePath})`);
}
if (props.tsconfig) {
this.relativeTsconfigPath = path.relative(this.projectRoot, path.resolve(props.tsconfig));
}
if (props.preCompilation && !/\.tsx?$/.test(props.entry)) {
throw new Error('preCompilation can only be used with typescript files');
}
this.externals = [
...props.externalModules ?? ['aws-sdk'], // Mark aws-sdk as external by default (available in the runtime)
...props.nodeModules ?? [], // Mark the modules that we are going to install as externals also
];
// Docker bundling
const shouldBuildImage = props.forceDockerBundling || !Bundling.esbuildInstallation;
this.image = shouldBuildImage ? props.dockerImage ?? cdk.DockerImage.fromBuild(path.join(__dirname, '../lib'),
{
buildArgs: {
...props.buildArgs ?? {},
IMAGE: props.runtime.bundlingImage.image,
ESBUILD_VERSION: props.esbuildVersion ?? ESBUILD_MAJOR_VERSION,
},
platform: props.architecture.dockerPlatform,
})
: cdk.DockerImage.fromRegistry('dummy'); // Do not build if we don't need to
const bundlingCommand = this.createBundlingCommand({
inputDir: cdk.AssetStaging.BUNDLING_INPUT_DIR,
outputDir: cdk.AssetStaging.BUNDLING_OUTPUT_DIR,
esbuildRunner: 'esbuild', // esbuild is installed globally in the docker image
tscRunner: 'tsc', // tsc is installed globally in the docker image
osPlatform: 'linux', // linux docker image
});
this.command = ['bash', '-c', bundlingCommand];
this.environment = props.environment;
// Bundling sets the working directory to cdk.AssetStaging.BUNDLING_INPUT_DIR
// and we want to force npx to use the globally installed esbuild.
this.workingDirectory = '/';
// Local bundling
if (!props.forceDockerBundling) { // only if Docker is not forced
this.local = this.getLocalBundlingProvider();
}
}
private createBundlingCommand(options: BundlingCommandOptions): string {
const pathJoin = osPathJoin(options.osPlatform);
let tscCommand: string = '';
let relativeEntryPath = this.relativeEntryPath;
if (this.props.preCompilation) {
let tsconfig = this.relativeTsconfigPath;
if (!tsconfig) {
const findConfig = findUp('tsconfig.json', path.dirname(this.props.entry));
if (!findConfig) {
throw new Error('Cannot find a tsconfig.json, please specify the prop: tsconfig');
}
tsconfig = path.relative(this.projectRoot, findConfig);
}
relativeEntryPath = relativeEntryPath.replace(/\.ts(x?)$/, '.js$1');
if (!Bundling.tscCompiled) {
// Intentionally Setting rootDir and outDir, so that the compiled js file always end up next ts file.
tscCommand = `${options.tscRunner} --project ${pathJoin(options.inputDir, tsconfig)} --rootDir ./ --outDir ./`;
Bundling.tscCompiled = true;
}
}
const loaders = Object.entries(this.props.loader ?? {});
const defines = Object.entries(this.props.define ?? {});
if (this.props.sourceMap === false && this.props.sourceMapMode) {
throw new Error('sourceMapMode cannot be used when sourceMap is false');
}
const sourceMapEnabled = this.props.sourceMapMode ?? this.props.sourceMap;
const sourceMapMode = this.props.sourceMapMode ?? SourceMapMode.DEFAULT;
const sourceMapValue = sourceMapMode === SourceMapMode.DEFAULT ? '' : `=${this.props.sourceMapMode}`;
const sourcesContent = this.props.sourcesContent ?? true;
const esbuildCommand: string[] = [
options.esbuildRunner,
'--bundle', `"${pathJoin(options.inputDir, relativeEntryPath)}"`,
`--target=${this.props.target ?? toTarget(this.props.runtime)}`,
'--platform=node',
`--outfile="${pathJoin(options.outputDir, 'index.js')}"`,
...this.props.minify ? ['--minify'] : [],
...sourceMapEnabled ? [`--sourcemap${sourceMapValue}`] : [],
...sourcesContent ? [] : [`--sources-content=${sourcesContent}`],
...this.externals.map(external => `--external:${external}`),
...loaders.map(([ext, name]) => `--loader:${ext}=${name}`),
...defines.map(([key, value]) => `--define:${key}=${JSON.stringify(value)}`),
...this.props.logLevel ? [`--log-level=${this.props.logLevel}`] : [],
...this.props.keepNames ? ['--keep-names'] : [],
...this.relativeTsconfigPath ? [`--tsconfig=${pathJoin(options.inputDir, this.relativeTsconfigPath)}`] : [],
...this.props.metafile ? [`--metafile=${pathJoin(options.outputDir, 'index.meta.json')}`] : [],
...this.props.banner ? [`--banner:js=${JSON.stringify(this.props.banner)}`] : [],
...this.props.footer ? [`--footer:js=${JSON.stringify(this.props.footer)}`] : [],
...this.props.charset ? [`--charset=${this.props.charset}`] : [],
];
let depsCommand = '';
if (this.props.nodeModules) {
// Find 'package.json' closest to entry folder, we are going to extract the
// modules versions from it.
const pkgPath = findUp('package.json', path.dirname(this.props.entry));
if (!pkgPath) {
throw new Error('Cannot find a `package.json` in this project. Using `nodeModules` requires a `package.json`.');
}
// Determine dependencies versions, lock file and installer
const dependencies = extractDependencies(pkgPath, this.props.nodeModules);
const osCommand = new OsCommand(options.osPlatform);
const lockFilePath = pathJoin(options.inputDir, this.relativeDepsLockFilePath ?? this.packageManager.lockFile);
// Create dummy package.json, copy lock file if any and then install
depsCommand = chain([
osCommand.writeJson(pathJoin(options.outputDir, 'package.json'), { dependencies }),
osCommand.copy(lockFilePath, pathJoin(options.outputDir, this.packageManager.lockFile)),
osCommand.changeDirectory(options.outputDir),
this.packageManager.installCommand.join(' '),
]);
}
return chain([
...this.props.commandHooks?.beforeBundling(options.inputDir, options.outputDir) ?? [],
tscCommand,
esbuildCommand.join(' '),
...(this.props.nodeModules && this.props.commandHooks?.beforeInstall(options.inputDir, options.outputDir)) ?? [],
depsCommand,
...this.props.commandHooks?.afterBundling(options.inputDir, options.outputDir) ?? [],
]);
}
private getLocalBundlingProvider(): cdk.ILocalBundling {
const osPlatform = os.platform();
const createLocalCommand = (outputDir: string, esbuild: PackageInstallation, tsc?: PackageInstallation) => this.createBundlingCommand({
inputDir: this.projectRoot,
outputDir,
esbuildRunner: esbuild.isLocal ? this.packageManager.runBinCommand('esbuild') : 'esbuild',
tscRunner: tsc && (tsc.isLocal ? this.packageManager.runBinCommand('tsc') : 'tsc'),
osPlatform,
});
const environment = this.props.environment ?? {};
const cwd = this.projectRoot;
return {
tryBundle(outputDir: string) {
if (!Bundling.esbuildInstallation) {
process.stderr.write('esbuild cannot run locally. Switching to Docker bundling.\n');
return false;
}
if (!Bundling.esbuildInstallation.version.startsWith(`${ESBUILD_MAJOR_VERSION}.`)) {
throw new Error(`Expected esbuild version ${ESBUILD_MAJOR_VERSION}.x but got ${Bundling.esbuildInstallation.version}`);
}
const localCommand = createLocalCommand(outputDir, Bundling.esbuildInstallation, Bundling.tscInstallation);
exec(
osPlatform === 'win32' ? 'cmd' : 'bash',
[
osPlatform === 'win32' ? '/c' : '-c',
localCommand,
],
{
env: { ...process.env, ...environment },
stdio: [ // show output
'ignore', // ignore stdio
process.stderr, // redirect stdout to stderr
'inherit', // inherit stderr
],
cwd,
windowsVerbatimArguments: osPlatform === 'win32',
});
return true;
},
};
}
}
interface BundlingCommandOptions {
readonly inputDir: string;
readonly outputDir: string;
readonly esbuildRunner: string;
readonly tscRunner?: string;
readonly osPlatform: NodeJS.Platform;
}
/**
* OS agnostic command
*/
class OsCommand {
constructor(private readonly osPlatform: NodeJS.Platform) {}
public writeJson(filePath: string, data: any): string {
const stringifiedData = JSON.stringify(data);
if (this.osPlatform === 'win32') {
return `echo ^${stringifiedData}^ > "${filePath}"`;
}
return `echo '${stringifiedData}' > "${filePath}"`;
}
public copy(src: string, dest: string): string {
if (this.osPlatform === 'win32') {
return `copy "${src}" "${dest}"`;
}
return `cp "${src}" "${dest}"`;
}
public changeDirectory(dir: string): string {
return `cd "${dir}"`;
}
}
/**
* Chain commands
*/
function chain(commands: string[]): string {
return commands.filter(c => !!c).join(' && ');
}
/**
* Platform specific path join
*/
function osPathJoin(platform: NodeJS.Platform) {
return function(...paths: string[]): string {
const joined = path.join(...paths);
// If we are on win32 but need posix style paths
if (os.platform() === 'win32' && platform !== 'win32') {
return joined.replace(/\\/g, '/');
}
return joined;
};
}
/**
* Converts a runtime to an esbuild node target
*/
function toTarget(runtime: Runtime): string {
const match = runtime.name.match(/nodejs(\d+)/);
if (!match) {
throw new Error('Cannot extract version from runtime.');
}
return `node${match[1]}`;
} | the_stack |
import tempy from 'tempy'
/**
* this is not a real package and only used to utilize helper
* methods without having to ignore them for test coverage
*/
// eslint-disable-next-line
import { clean, getResults } from './helpers/wdio-allure-helper'
import AllureReporter from '../src/'
import { runnerEnd, runnerStart } from './__fixtures__/runner'
import * as cucumberHelper from './__fixtures__/cucumber'
import * as attachmentHelper from './__fixtures__/attachment'
import { commandStart, commandEnd } from './__fixtures__/command'
let processOn: any
beforeAll(() => {
processOn = process.on.bind(process)
process.on = jest.fn()
})
afterAll(() => {
process.on = processOn
})
describe('reporter option "useCucumberStepReporter" set to true', () => {
describe('reporter option "disableWebdriverStepsReporting" set to true', () => {
describe('Passing tests', () => {
const outputDir = tempy.directory()
let allureXml: any
beforeAll(() => {
const reporter = new AllureReporter({ outputDir, useCucumberStepReporter: true, disableWebdriverStepsReporting: true })
reporter.onRunnerStart(runnerStart())
reporter.onSuiteStart(cucumberHelper.featureStart())
reporter.onSuiteStart(cucumberHelper.scenarioStart())
reporter.onHookStart(cucumberHelper.hookStart())
reporter.onHookEnd(cucumberHelper.hookEnd())
reporter.onTestStart(cucumberHelper.testStart())
reporter.onBeforeCommand(commandStart())
reporter.onAfterCommand(commandEnd())
reporter.onTestPass()
reporter.onHookStart(cucumberHelper.hookStart())
reporter.addAttachment(attachmentHelper.xmlAttachment())
reporter.onHookEnd(cucumberHelper.hookEnd())
const suiteResults: any = { tests: [cucumberHelper.testPass()], hooks: new Array(2).fill(cucumberHelper.hookEnd()) }
reporter.onSuiteEnd(cucumberHelper.scenarioEnd(suiteResults))
reporter.onSuiteEnd(cucumberHelper.featureEnd(suiteResults))
reporter.onRunnerEnd(runnerEnd())
const results = getResults(outputDir)
expect(results).toHaveLength(2) // one for report, one for attachment
allureXml = results.find((xml: any) => xml('ns2\\:test-suite').length >= 1)
})
afterAll(() => {
clean(outputDir)
})
it('should report one suite', () => {
expect(allureXml('ns2\\:test-suite > name').text()).toEqual('MyFeature')
expect(allureXml('ns2\\:test-suite > title').text()).toEqual('MyFeature')
})
it('should detect passed test case', () => {
expect(allureXml('test-case > name').text()).toEqual('MyScenario')
expect(allureXml('test-case').attr('status')).toEqual('passed')
})
it('should not report passing hook', () => {
expect(allureXml('step > name').eq(0).text()).not.toContain('Hook')
expect(allureXml('step > title').eq(0).text()).not.toContain('Hook')
})
it('should report one passing step', () => {
expect(allureXml('step > name').eq(0).text()).toEqual('I do something')
expect(allureXml('step > title').eq(0).text()).toEqual('I do something')
expect(allureXml('step').eq(0).attr('status')).toEqual('passed')
expect(allureXml('step').length).toEqual(1)
})
it('should detect analytics labels in test case', () => {
expect(allureXml('test-case label[name="language"]').eq(0).attr('value')).toEqual('javascript')
expect(allureXml('test-case label[name="framework"]').eq(0).attr('value')).toEqual('wdio')
})
it('should add browser name as test argument', () => {
expect(allureXml('test-case parameter[kind="argument"]')).toHaveLength(1)
expect(allureXml('test-case parameter[name="browser"]').eq(0).attr('value')).toEqual('chrome-68')
})
it('should detect tags labels on top in test case', () => {
expect(allureXml('test-case label[name="severity"]').eq(0).attr('value')).toEqual('critical')
})
it('should detect description on top in test case', () => {
expect(allureXml('test-case > description').eq(0).text()).toEqual('My scenario description')
expect(allureXml('test-case description[type="text"]')).toHaveLength(1)
})
it('should move attachments from successful hook to test-case', () => {
expect(allureXml('test-case > attachments > attachment').length).toEqual(1)
})
})
})
describe('Passing tests', () => {
const outputDir = tempy.directory()
let allureXml: any
let reporter: any
beforeAll(() => {
reporter = new AllureReporter({ outputDir, useCucumberStepReporter: true })
reporter.onRunnerStart(runnerStart())
reporter.onSuiteStart(cucumberHelper.featureStart())
reporter.onSuiteStart(cucumberHelper.scenarioStart())
reporter.onHookStart(cucumberHelper.hookStart())
reporter.onHookEnd(cucumberHelper.hookEnd())
reporter.onTestStart(cucumberHelper.testStart())
reporter.onBeforeCommand(commandStart())
reporter.onAfterCommand(commandEnd())
reporter._consoleOutput = 'some console output'
reporter.onTestPass()
reporter.onHookStart(cucumberHelper.hookStart())
reporter.addAttachment(attachmentHelper.xmlAttachment())
reporter.onHookEnd(cucumberHelper.hookEnd())
const suiteResults: any = { tests: [cucumberHelper.testPass()], hooks: new Array(2).fill(cucumberHelper.hookEnd()) }
reporter.onSuiteEnd(cucumberHelper.scenarioEnd(suiteResults))
reporter.onSuiteEnd(cucumberHelper.featureEnd(suiteResults))
reporter.onRunnerEnd(runnerEnd())
const results = getResults(outputDir)
expect(results).toHaveLength(2) // one for report, one for attachment
allureXml = results.find((xml: any) => xml('ns2\\:test-suite').length >= 1)
})
afterAll(() => {
clean(outputDir)
jest.resetAllMocks()
})
it('should have the console log add', () => {
expect(allureXml('test-case > steps > step > attachments > attachment')).toHaveLength(1)
expect(allureXml('test-case > steps > step > attachments > attachment').eq(0).attr('title')).toBe('Console Logs')
})
it('should report one suite', () => {
expect(allureXml('ns2\\:test-suite > name').text()).toEqual('MyFeature')
expect(allureXml('ns2\\:test-suite > title').text()).toEqual('MyFeature')
})
it('should detect passed test case', () => {
expect(allureXml('test-case > name').text()).toEqual('MyScenario')
expect(allureXml('test-case').attr('status')).toEqual('passed')
})
it('should not report passing hook', () => {
expect(allureXml('step > name').eq(0).text()).not.toContain('Hook')
expect(allureXml('step > title').eq(0).text()).not.toContain('Hook')
})
describe('steps', () => {
it('should report two passing steps', () => {
expect(allureXml('step').length).toEqual(2)
})
it('should report one passing step for test', () => {
expect(allureXml('step > name').eq(0).text()).toEqual('I do something')
expect(allureXml('step > title').eq(0).text()).toEqual('I do something')
expect(allureXml('step').eq(0).attr('status')).toEqual('passed')
expect(allureXml('step').length).toEqual(2)
})
it('should add step from command', () => {
expect(allureXml('step > name').eq(1).text()).toEqual('GET /session/:sessionId/element')
expect(allureXml('step > title').eq(1).text()).toEqual('GET /session/:sessionId/element')
expect(allureXml('test-case attachment[title="Response"]')).toHaveLength(1)
expect(allureXml('step').eq(1).attr('status')).toEqual('passed')
})
})
it('should detect analytics labels in test case', () => {
expect(allureXml('test-case label[name="language"]').eq(0).attr('value')).toEqual('javascript')
expect(allureXml('test-case label[name="framework"]').eq(0).attr('value')).toEqual('wdio')
})
it('should add browser name as test argument', () => {
expect(allureXml('test-case parameter[kind="argument"]')).toHaveLength(1)
expect(allureXml('test-case parameter[name="browser"]').eq(0).attr('value')).toEqual('chrome-68')
})
it('should detect tags labels on top in test case', () => {
expect(allureXml('test-case label[name="severity"]').eq(0).attr('value')).toEqual('critical')
})
it('should detect description on top in test case', () => {
expect(allureXml('test-case > description').eq(0).text()).toEqual('My scenario description')
expect(allureXml('test-case description[type="text"]')).toHaveLength(1)
})
it('should move attachments from successful hook to test-case', () => {
expect(allureXml('test-case > attachments > attachment').length).toEqual(1)
})
it('should not call endStep if currentStep is not `Step` instance', () => {
reporter._allure.getCurrentSuite = jest.fn()
reporter._allure.endStep = jest.fn()
reporter._allure.endCase = jest.fn()
reporter._allure.addAttachment = jest.fn()
reporter.onTestPass()
expect(reporter._allure.endStep).not.toHaveBeenCalled()
expect(reporter._allure.endCase).toHaveBeenCalled()
})
})
describe('Skipped test', () => {
const outputDir = tempy.directory()
let allureXml: any
let reporter: any
beforeAll(() => {
reporter = new AllureReporter({ outputDir, useCucumberStepReporter: true })
reporter.onRunnerStart(runnerStart())
reporter.onSuiteStart(cucumberHelper.featureStart())
reporter.onSuiteStart(cucumberHelper.scenarioStart())
reporter.onTestStart(cucumberHelper.testStart())
reporter._consoleOutput = 'some console output'
reporter.onTestSkip(cucumberHelper.testSkipped())
const suiteResults: any = { tests: [cucumberHelper.testSkipped()] }
reporter.onSuiteEnd(cucumberHelper.scenarioEnd(suiteResults))
reporter.onSuiteEnd(cucumberHelper.featureEnd(suiteResults))
reporter.onRunnerEnd(runnerEnd())
const results = getResults(outputDir)
expect(results).toHaveLength(1)
allureXml = results[0]
})
afterAll(() => {
clean(outputDir)
jest.resetAllMocks()
})
it('should report one suite', () => {
expect(allureXml('ns2\\:test-suite > name').text()).toEqual('MyFeature')
expect(allureXml('ns2\\:test-suite > title').text()).toEqual('MyFeature')
})
it('should report scenario as pending', () => {
expect(allureXml('test-case').attr('status')).toEqual('pending')
})
it('should report one canceled step', () => {
expect(allureXml('step > name').eq(0).text()).toEqual('I do something')
expect(allureXml('step > title').eq(0).text()).toEqual('I do something')
expect(allureXml('step').eq(0).attr('status')).toEqual('canceled')
expect(allureXml('step').length).toEqual(1)
})
it('should have the console log add', () => {
expect(allureXml('test-case > steps > step > attachments > attachment')).toHaveLength(1)
expect(allureXml('test-case > steps > step > attachments > attachment').eq(0).attr('title')).toBe('Console Logs')
})
it('should not call endStep if currentStep is not `Step` instance', () => {
reporter._allure.getCurrentSuite = jest.fn()
reporter._allure.endStep = jest.fn()
reporter._allure.addAttachment = jest.fn()
reporter.onTestSkip(cucumberHelper.testSkipped())
expect(reporter._allure.endStep).not.toHaveBeenCalled()
})
})
describe('Skipped test after several steps passed', () => {
const outputDir = tempy.directory()
let allureXml: any
beforeAll(() => {
const reporter = new AllureReporter({ outputDir, useCucumberStepReporter: true })
reporter.onRunnerStart(runnerStart())
reporter.onSuiteStart(cucumberHelper.featureStart())
reporter.onSuiteStart(cucumberHelper.scenarioStart())
reporter.onTestStart(cucumberHelper.testStart())
reporter.onTestPass()
reporter.onTestStart(cucumberHelper.test2start())
reporter.onTestSkip(cucumberHelper.test2Skipped())
const suiteResults: any = { tests: [cucumberHelper.testPass()] }
reporter.onSuiteEnd(cucumberHelper.scenarioEnd(suiteResults))
reporter.onSuiteEnd(cucumberHelper.featureEnd(suiteResults))
reporter.onRunnerEnd(runnerEnd())
const results = getResults(outputDir)
expect(results).toHaveLength(1)
allureXml = results[0]
})
afterAll(() => {
clean(outputDir)
})
it('should report one suite', () => {
expect(allureXml('ns2\\:test-suite > name').text()).toEqual('MyFeature')
expect(allureXml('ns2\\:test-suite > title').text()).toEqual('MyFeature')
})
it('should report scenario as passed', () => {
expect(allureXml('test-case').attr('status')).toEqual('passed')
})
it('should report one passed step', () => {
expect(allureXml('step > name').eq(0).text()).toEqual('I do something')
expect(allureXml('step > title').eq(0).text()).toEqual('I do something')
expect(allureXml('step').eq(0).attr('status')).toEqual('passed')
})
it('should report one canceled step', () => {
expect(allureXml('step > name').eq(1).text()).toEqual('I check something')
expect(allureXml('step > title').eq(1).text()).toEqual('I check something')
expect(allureXml('step').eq(1).attr('status')).toEqual('canceled')
})
})
describe('Failed tests', () => {
let outputDir: any
let allureXml
let reporter: any
beforeEach(() => {
outputDir = tempy.directory()
})
afterEach(() => {
clean(outputDir)
jest.resetAllMocks()
})
it('should handle failed test', () => {
reporter = new AllureReporter({ outputDir, useCucumberStepReporter: true })
reporter.onRunnerStart(runnerStart())
reporter.onSuiteStart(cucumberHelper.featureStart())
reporter.onSuiteStart(cucumberHelper.scenarioStart())
reporter.onTestStart(cucumberHelper.testStart())
reporter.onBeforeCommand(commandStart())
reporter.onAfterCommand(commandEnd())
reporter._consoleOutput = 'some console output'
reporter.onTestFail(cucumberHelper.testFail())
const suiteResults: any = { tests: ['failed'] }
reporter.onSuiteEnd(cucumberHelper.scenarioEnd(suiteResults))
reporter.onSuiteEnd(cucumberHelper.featureEnd(suiteResults))
reporter.onRunnerEnd(runnerEnd())
const results = getResults(outputDir)
expect(results).toHaveLength(1)
allureXml = results[0]
expect(allureXml('ns2\\:test-suite > name').text()).toEqual('MyFeature')
expect(allureXml('test-case > name').text()).toEqual('MyScenario')
expect(allureXml('test-case').attr('status')).toEqual('failed')
expect(allureXml('step').attr('status')).toEqual('failed')
expect(allureXml('test-case parameter[kind="argument"]')).toHaveLength(1)
expect(allureXml('test-case parameter[name="browser"]').eq(0).attr('value')).toEqual('chrome-68')
expect(allureXml('test-case > steps > step > attachments > attachment')).toHaveLength(1)
expect(allureXml('test-case > steps > step > attachments > attachment').eq(0).attr('title')).toBe('Console Logs')
})
it('should handle failed hook', () => {
const reporter = new AllureReporter({ outputDir, useCucumberStepReporter: true })
reporter.onRunnerStart(runnerStart())
reporter.onSuiteStart(cucumberHelper.featureStart())
reporter.onSuiteStart(cucumberHelper.scenarioStart())
reporter.onHookStart(cucumberHelper.hookStart())
reporter.onHookEnd(cucumberHelper.hookFail())
reporter.onTestStart(cucumberHelper.testStart())
reporter.onTestSkip(cucumberHelper.testSkipped())
const suiteResults: any = { tests: [cucumberHelper.testSkipped()], hooks: [cucumberHelper.hookFail()] }
reporter.onSuiteEnd(cucumberHelper.scenarioEnd(suiteResults))
reporter.onSuiteEnd(cucumberHelper.featureEnd(suiteResults))
reporter.onRunnerEnd(runnerEnd())
const results = getResults(outputDir)
expect(results).toHaveLength(1)
allureXml = results[0]
expect(allureXml('ns2\\:test-suite > name').text()).toEqual('MyFeature')
expect(allureXml('test-case > name').text()).toEqual('MyScenario')
expect(allureXml('test-case').attr('status')).toEqual('failed')
expect(allureXml('step > name').eq(0).text()).toEqual('Hook')
expect(allureXml('step').eq(0).attr('status')).toEqual('failed')
expect(allureXml('step').eq(1).attr('status')).toEqual('canceled')
expect(allureXml('test-case parameter[kind="argument"]')).toHaveLength(1)
expect(allureXml('test-case parameter[name="browser"]').eq(0).attr('value')).toEqual('chrome-68')
})
it('should not call endStep if currentStep is not `Step` instance', () => {
reporter._allure.getCurrentSuite = jest.fn()
reporter._allure.endStep = jest.fn()
reporter._allure.endCase = jest.fn()
reporter._allure.addAttachment = jest.fn()
reporter.onTestFail(cucumberHelper.testSkipped())
expect(reporter._allure.endStep).not.toHaveBeenCalled()
expect(reporter._allure.endCase).toHaveBeenCalled()
})
})
describe('Data Table', () => {
const outputDir = tempy.directory()
let allureXml: any
beforeAll(() => {
const reporter = new AllureReporter({ outputDir, useCucumberStepReporter: true })
reporter.onRunnerStart(runnerStart())
reporter.onSuiteStart(cucumberHelper.featureStart())
reporter.onSuiteStart(cucumberHelper.scenarioStart())
reporter.onHookStart(cucumberHelper.hookStart())
reporter.onHookEnd(cucumberHelper.hookEnd())
reporter.onTestStart(cucumberHelper.test3Start())
reporter.onBeforeCommand(commandStart())
reporter.onAfterCommand(commandEnd())
reporter.onTestPass()
reporter.onHookStart(cucumberHelper.hookStart())
reporter.addAttachment(attachmentHelper.xmlAttachment())
reporter.onHookEnd(cucumberHelper.hookEnd())
const suiteResults: any = { tests: [cucumberHelper.testPass()], hooks: new Array(2).fill(cucumberHelper.hookEnd()) }
reporter.onSuiteEnd(cucumberHelper.scenarioEnd(suiteResults))
reporter.onSuiteEnd(cucumberHelper.featureEnd(suiteResults))
reporter.onRunnerEnd(runnerEnd())
const results = getResults(outputDir)
expect(results).toHaveLength(2) // one for report, one for attachment
allureXml = results.find((xml: any) => xml('ns2\\:test-suite').length >= 1)
})
afterAll(() => {
clean(outputDir)
})
it('should add data table as attachment to test-case', () => {
expect(allureXml('test-case > attachments > attachment').length).toEqual(1)
})
})
}) | the_stack |
import Interval from '@yavin/client/utils/classes/interval';
import Duration from '@yavin/client/utils/classes/duration';
import { module, test } from 'qunit';
import { getPeriodForGrain, Grain } from '@yavin/client/utils/date';
import moment, { Moment } from 'moment';
const FORMAT = 'YYYY-MM-DD';
module('Unit | Utils | Interval Class', function () {
test('Construction', function (assert) {
assert.expect(5);
//@ts-expect-error
assert.throws(() => new Interval(), 'error is thrown while constructing with an undefined start');
//@ts-expect-error
assert.throws(() => new Interval('current'), 'error is thrown while constructing with an undefined end');
assert.throws(
//@ts-expect-error
() => new Interval('current', { a: 23 }),
'error is thrown while constructing with an unaccepted object type'
);
assert.throws(
//@ts-expect-error
() => new Interval(new Duration('P1W'), new Duration('P12W')),
'error is thrown while constructing with an interval composed of two durations'
);
assert.ok(new Interval(new Duration('P7D'), moment()), 'proper interval can be built');
});
test('isEqual', function (assert) {
assert.expect(4);
let interval = new Interval(new Duration('P7D'), moment());
assert.notOk(interval.isEqual(), 'Interval does not equal undefined');
assert.notOk(
interval.isEqual(new Interval(new Duration('P14W'), moment().subtract(3, 'weeks'))),
'Interval does not equal interval with different start/end'
);
assert.notOk(
interval.isEqual(new Interval(moment().subtract(7, 'days'), 'current')),
'Interval does not equal interval with similar dates, but different types'
);
assert.ok(interval.isEqual(interval), 'Interval equals one with matching start/end');
});
test('diffForTimePeriod', function (assert) {
assert.expect(7);
assert.equal(
new Interval(new Duration('P1D'), moment.utc('2021-02-05')).diffForTimePeriod('day'),
1,
'Interval has 1 days for absolute day to 1 day ago'
);
assert.equal(
new Interval(new Duration('P7D'), 'current').diffForTimePeriod('day'),
7,
'Interval has 7 days for current til 7 days ago'
);
assert.equal(
new Interval(moment('2014-10-10'), moment('2015-10-10')).diffForTimePeriod('day'),
365,
'Interval has 365 days for a 1 year period'
);
assert.equal(
new Interval(moment('2015-11-09 00:00:00.000'), moment('2015-11-10 10:00:00.000')).diffForTimePeriod('hour'),
34,
'Interval has 34 hours for a 1 day 10 hour time period'
);
assert.equal(
new Interval(moment('2015-11-09'), moment('2015-11-10')).diffForTimePeriod('day'),
1,
'Interval has 1 day for a 1 day period'
);
assert.equal(
new Interval('current', 'next').diffForTimePeriod('day'),
1,
'Interval has 1 day for current til next'
);
assert.equal(
new Interval(moment('2015-11-10 10:00:00.000'), moment('2015-11-10 11:00:00.000')).diffForTimePeriod('hour'),
1,
'Interval has 1 hour for a 1 hour period'
);
});
test('getDatesForInterval', function (assert) {
assert.expect(1);
let testInterval = new Interval(moment('4-9-2017', 'D-M-Y'), moment('25-9-2017', 'D-M-Y')),
dates = testInterval.getDatesForInterval('isoWeek');
assert.deepEqual(
dates.map((date) => date.format('D-M-Y')),
['4-9-2017', '11-9-2017', '18-9-2017'],
'A moment for each isoWeek between Sep 4 and Sep 25 (exclusive) is returned'
);
});
test('_asMoments', function (assert) {
let moments = new Interval(new Duration('P7D'), 'current')['_asMoments']('day'),
current = moment(),
sevenDaysAgo = current.clone().subtract(7, 'days');
assert.ok(moments.start.isSame(sevenDaysAgo, 'day'), 'Duration is correctly subtracted from end (1)');
assert.ok(moments.end?.isSame(current, 'day'), 'Current macro is correctly substituted');
let start = moment('2014-10-10', FORMAT),
end = moment('2015-10-10', FORMAT);
moments = new Interval(start, end)['_asMoments']('day');
assert.ok(moments.start.isSame(start) && moments.end?.isSame(end), 'Given moments are correctly returned');
moments = new Interval(new Duration('P2M'), 'next')['_asMoments']('day');
let next = moment().add(1, 'days'),
twoMonthsBeforeNext = next.clone().subtract(2, 'months');
assert.ok(moments.start.isSame(twoMonthsBeforeNext, 'day'), 'Duration is correctly subtracted from end (2)');
assert.ok(moments.end?.isSame(next, 'day'), 'Next macro is correctly substituted');
});
test('asMomentsForTimePeriod', function (assert) {
assert.expect(2);
let start = moment('2014-10-10', FORMAT),
end = moment('2015-10-10', FORMAT),
moments = new Interval(start, end).asMomentsForTimePeriod('isoWeek');
assert.ok(moments.start.isSame(start.startOf('isoWeek')), 'Start moment is at start of isoWeek');
assert.ok(moments.end.isSame(end.startOf('isoWeek')), 'End moment is at start of isoWeek');
});
test('asMomentsForTimePeriod with current and next for time period', function (assert) {
assert.expect(1);
// end is next, which will be undefined as moment
let moments = new Interval('current', 'next').asMomentsForTimePeriod('isoWeek');
let expected = moments.end.startOf(getPeriodForGrain('isoWeek'));
assert.ok(moments.end.isSame(expected), 'Setting end to next will be computed correctly');
});
test('asMomentsForTimePeriod - same start and end date', function (assert) {
assert.expect(3);
let start = moment('2017-10-10', FORMAT),
end = moment('2017-10-10', FORMAT),
moments = new Interval(start, end).asMomentsForTimePeriod('isoWeek');
assert.equal(moments.start.format(FORMAT), '2017-10-09', 'Start moment is at start of isoWeek');
assert.equal(moments.end.format(FORMAT), '2017-10-16', 'End moment is at start of next isoWeek');
moments = new Interval(start, end).asMomentsForTimePeriod('isoWeek', false);
assert.ok(moments.start.isSame(moments.end), 'Start moment is same as end moment');
});
test('asMomentsInclusive', function (assert) {
assert.expect(8);
const toInclusive = (startStr: string, endStr: string, grain: Grain) => {
const { start, end } = Interval.parseFromStrings(startStr, endStr).asMomentsInclusive(grain);
return [start.toISOString(), end.toISOString()];
};
const startStr = '2014-01-01';
const endStr = '2015-01-01';
const startValue = `${startStr}T00:00:00.000Z`;
assert.deepEqual(
toInclusive(startStr, endStr, 'second'),
[startValue, '2014-12-31T23:59:59.000Z'],
'End moment is inclusive of the second'
);
assert.deepEqual(
toInclusive(startStr, endStr, 'minute'),
[startValue, '2014-12-31T23:59:00.000Z'],
'End moment is inclusive of the minute'
);
assert.deepEqual(
toInclusive(startStr, endStr, 'hour'),
[startValue, '2014-12-31T23:00:00.000Z'],
'End moment is inclusive of the hour'
);
assert.deepEqual(
toInclusive(startStr, endStr, 'day'),
[startValue, '2014-12-31T00:00:00.000Z'],
'End moment is inclusive of the day'
);
assert.deepEqual(
toInclusive(startStr, endStr, 'isoWeek'),
['2013-12-30T00:00:00.000Z', '2014-12-22T00:00:00.000Z'],
'End moment is inclusive of the isoWeek and aligned to isoWeek'
);
assert.deepEqual(
toInclusive(startStr, endStr, 'month'),
[startValue, '2014-12-01T00:00:00.000Z'],
'End moment is inclusive of the month'
);
assert.deepEqual(
toInclusive(startStr, endStr, 'quarter'),
[startValue, '2014-10-01T00:00:00.000Z'],
'End moment is inclusive of the quarter'
);
assert.deepEqual(
toInclusive(startStr, endStr, 'year'),
[startValue, '2014-01-01T00:00:00.000Z'],
'End moment is inclusive of the year'
);
});
test('makeEndExclusiveFor', function (assert) {
const start = moment('2017-10-10T00:00:00.000Z').utc();
const end = moment('2017-10-12T01:02:03.004Z').utc();
const interval = new Interval(start, end);
assert.equal(
interval.makeEndExclusiveFor('second')['_asMoments']('second').end?.toISOString(),
'2017-10-12T01:02:04.000Z',
'interval is inclusive of the second'
);
assert.equal(
interval.makeEndExclusiveFor('minute')['_asMoments']('minute').end?.toISOString(),
'2017-10-12T01:03:00.000Z',
'interval is inclusive of the minute'
);
assert.equal(
interval.makeEndExclusiveFor('hour')['_asMoments']('hour').end?.toISOString(),
'2017-10-12T02:00:00.000Z',
'interval is inclusive of the hour'
);
assert.equal(
interval.makeEndExclusiveFor('day')['_asMoments']('day').end?.toISOString(),
'2017-10-13T00:00:00.000Z',
'interval is inclusive of the day'
);
assert.equal(
interval.makeEndExclusiveFor('isoWeek')['_asMoments']('week').end?.toISOString(),
'2017-10-16T00:00:00.000Z',
'interval is inclusive of the isoWeek'
);
assert.equal(
interval.makeEndExclusiveFor('month')['_asMoments']('month').end?.toISOString(),
'2017-11-01T00:00:00.000Z',
'interval is inclusive of the month'
);
assert.equal(
interval.makeEndExclusiveFor('quarter')['_asMoments']('quarter').end?.toISOString(),
'2018-01-01T00:00:00.000Z',
'interval is inclusive of the quarter'
);
assert.equal(
interval.makeEndExclusiveFor('year')['_asMoments']('year').end?.toISOString(),
'2018-01-01T00:00:00.000Z',
'interval is inclusive of the year'
);
});
test('asIntervalForTimePeriod', function (assert) {
assert.expect(2);
let start = moment('2014-10-10', FORMAT),
end = moment('2015-10-10', FORMAT),
newInterval = new Interval(start, end).asIntervalForTimePeriod('isoWeek')['_asMoments']('week');
assert.ok(newInterval.start.isSame(start.startOf('isoWeek')), 'Start moment is at start of isoWeek');
assert.ok(newInterval.end?.isSame(end.startOf('isoWeek')), 'End moment is at start of isoWeek');
});
test('asIntervalForTimePeriod - same start and end date', function (assert) {
assert.expect(2);
let start = moment('2017-10-10', FORMAT),
end = moment('2017-10-10', FORMAT),
newInterval = new Interval(start, end).asIntervalForTimePeriod('isoWeek')['_asMoments']('week');
assert.equal(newInterval.start.format(FORMAT), '2017-10-09', 'Start moment is at start of isoWeek');
assert.equal(newInterval.end?.format(FORMAT), '2017-10-16', 'End moment is at start of isoWeek');
});
test('asStrings', function (assert) {
assert.expect(3);
let strings = new Interval(new Duration('P7D'), 'current').asStrings();
assert.equal(strings.start, 'P7D', 'Duration is converted to iso string');
assert.equal(strings.end, 'current', 'Macro keeps original value');
let start = moment('2014-10-10', FORMAT),
end = moment('2015-10-10', FORMAT);
strings = new Interval(start, end).asStrings();
assert.equal(strings.start, start.toISOString(), 'Moments are formatted for API');
});
test('elementToString', function (assert) {
assert.expect(3);
assert.equal(Interval.elementToString(new Duration('P7D')), 'P7D', 'Duration is converted to iso string');
assert.equal(Interval.elementToString('current'), 'current', 'Macro keeps original value');
let start = moment('2014-10-10', FORMAT);
assert.equal(Interval.elementToString(start), start.toISOString(), 'Moments are formatted for API');
});
test('fromString', function (assert) {
assert.expect(5);
assert.equal(Interval.fromString('current'), 'current', 'Macro can be parsed from string');
assert.ok(
(Interval.fromString('P7D') as Duration).isEqual(new Duration('P7D')),
'Duration can be parsed from iso string'
);
assert.ok(
(Interval.fromString('2014-10-10 00:00:00.000') as Moment).isSame(moment.utc('2014-10-10', FORMAT)),
'Moments can be parsed from API date string'
);
assert.throws(
() => {
Interval.fromString('not any valid date');
},
/Cannot parse string/,
'Unrecognized string throws error'
);
assert.throws(
() => {
//@ts-expect-error
Interval.fromString(123);
},
/Argument must be a string/,
'Throws error when not given a string'
);
});
test('_isAcceptedType', function (assert) {
assert.expect(4);
let interval = new Interval('current', 'current');
assert.ok(interval['_isAcceptedType'](new Duration('P7D')), 'Duration are accepted');
assert.ok(interval['_isAcceptedType']('current'), 'String macros are accepted');
assert.ok(interval['_isAcceptedType'](moment('2014-10-10', FORMAT)), 'Moments are accepted');
assert.notOk(interval['_isAcceptedType']({ random: 'object' }), 'Generic objects are not accepted');
});
test('isInterval', function (assert) {
assert.expect(2);
assert.ok(Interval.isInterval(new Interval('current', 'current')), 'isInterval returns true for intervals');
assert.notOk(Interval.isInterval({ random: 'object' }), 'isInterval returns false for anything else');
});
}); | the_stack |
import { GaxiosPromise } from 'gaxios';
import { Compute, JWT, OAuth2Client, UserRefreshClient } from 'google-auth-library';
import { APIRequestContext, BodyResponseCallback, GlobalOptions, GoogleConfigurable, MethodOptions } from 'googleapis-common';
export declare namespace games_v1 {
interface Options extends GlobalOptions {
version: 'v1';
}
interface StandardParameters {
/**
* Data format for the response.
*/
alt?: string;
/**
* Selector specifying which fields to include in a partial response.
*/
fields?: string;
/**
* API key. Your API key identifies your project and provides you with API
* access, quota, and reports. Required unless you provide an OAuth 2.0
* token.
*/
key?: string;
/**
* OAuth 2.0 token for the current user.
*/
oauth_token?: string;
/**
* Returns response with indentations and line breaks.
*/
prettyPrint?: boolean;
/**
* An opaque string that represents a user for quota purposes. Must not
* exceed 40 characters.
*/
quotaUser?: string;
/**
* Deprecated. Please use quotaUser instead.
*/
userIp?: string;
}
/**
* Google Play Game Services API
*
* The API for Google Play Game Services.
*
* @example
* const {google} = require('googleapis');
* const games = google.games('v1');
*
* @namespace games
* @type {Function}
* @version v1
* @variation v1
* @param {object=} options Options for Games
*/
class Games {
context: APIRequestContext;
achievementDefinitions: Resource$Achievementdefinitions;
achievements: Resource$Achievements;
applications: Resource$Applications;
events: Resource$Events;
leaderboards: Resource$Leaderboards;
metagame: Resource$Metagame;
players: Resource$Players;
pushtokens: Resource$Pushtokens;
questMilestones: Resource$Questmilestones;
quests: Resource$Quests;
revisions: Resource$Revisions;
rooms: Resource$Rooms;
scores: Resource$Scores;
snapshots: Resource$Snapshots;
turnBasedMatches: Resource$Turnbasedmatches;
constructor(options: GlobalOptions, google?: GoogleConfigurable);
}
/**
* This is a JSON template for an achievement definition object.
*/
interface Schema$AchievementDefinition {
/**
* The type of the achievement. Possible values are: -
* "STANDARD" - Achievement is either locked or unlocked. -
* "INCREMENTAL" - Achievement is incremental.
*/
achievementType?: string;
/**
* The description of the achievement.
*/
description?: string;
/**
* Experience points which will be earned when unlocking this achievement.
*/
experiencePoints?: string;
/**
* The total steps for an incremental achievement as a string.
*/
formattedTotalSteps?: string;
/**
* The ID of the achievement.
*/
id?: string;
/**
* The initial state of the achievement. Possible values are: -
* "HIDDEN" - Achievement is hidden. - "REVEALED" -
* Achievement is revealed. - "UNLOCKED" - Achievement is
* unlocked.
*/
initialState?: string;
/**
* Indicates whether the revealed icon image being returned is a default
* image, or is provided by the game.
*/
isRevealedIconUrlDefault?: boolean;
/**
* Indicates whether the unlocked icon image being returned is a default
* image, or is game-provided.
*/
isUnlockedIconUrlDefault?: boolean;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#achievementDefinition.
*/
kind?: string;
/**
* The name of the achievement.
*/
name?: string;
/**
* The image URL for the revealed achievement icon.
*/
revealedIconUrl?: string;
/**
* The total steps for an incremental achievement.
*/
totalSteps?: number;
/**
* The image URL for the unlocked achievement icon.
*/
unlockedIconUrl?: string;
}
/**
* This is a JSON template for a list of achievement definition objects.
*/
interface Schema$AchievementDefinitionsListResponse {
/**
* The achievement definitions.
*/
items?: Schema$AchievementDefinition[];
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#achievementDefinitionsListResponse.
*/
kind?: string;
/**
* Token corresponding to the next page of results.
*/
nextPageToken?: string;
}
/**
* This is a JSON template for an achievement increment response
*/
interface Schema$AchievementIncrementResponse {
/**
* The current steps recorded for this incremental achievement.
*/
currentSteps?: number;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#achievementIncrementResponse.
*/
kind?: string;
/**
* Whether the current steps for the achievement has reached the number of
* steps required to unlock.
*/
newlyUnlocked?: boolean;
}
/**
* This is a JSON template for an achievement reveal response
*/
interface Schema$AchievementRevealResponse {
/**
* The current state of the achievement for which a reveal was attempted.
* This might be UNLOCKED if the achievement was already unlocked. Possible
* values are: - "REVEALED" - Achievement is revealed. -
* "UNLOCKED" - Achievement is unlocked.
*/
currentState?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#achievementRevealResponse.
*/
kind?: string;
}
/**
* This is a JSON template for an achievement set steps at least response.
*/
interface Schema$AchievementSetStepsAtLeastResponse {
/**
* The current steps recorded for this incremental achievement.
*/
currentSteps?: number;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#achievementSetStepsAtLeastResponse.
*/
kind?: string;
/**
* Whether the the current steps for the achievement has reached the number
* of steps required to unlock.
*/
newlyUnlocked?: boolean;
}
/**
* This is a JSON template for an achievement unlock response
*/
interface Schema$AchievementUnlockResponse {
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#achievementUnlockResponse.
*/
kind?: string;
/**
* Whether this achievement was newly unlocked (that is, whether the unlock
* request for the achievement was the first for the player).
*/
newlyUnlocked?: boolean;
}
/**
* This is a JSON template for a list of achievement update requests.
*/
interface Schema$AchievementUpdateMultipleRequest {
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#achievementUpdateMultipleRequest.
*/
kind?: string;
/**
* The individual achievement update requests.
*/
updates?: Schema$AchievementUpdateRequest[];
}
/**
* This is a JSON template for an achievement unlock response.
*/
interface Schema$AchievementUpdateMultipleResponse {
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#achievementUpdateListResponse.
*/
kind?: string;
/**
* The updated state of the achievements.
*/
updatedAchievements?: Schema$AchievementUpdateResponse[];
}
/**
* This is a JSON template for a request to update an achievement.
*/
interface Schema$AchievementUpdateRequest {
/**
* The achievement this update is being applied to.
*/
achievementId?: string;
/**
* The payload if an update of type INCREMENT was requested for the
* achievement.
*/
incrementPayload?: Schema$GamesAchievementIncrement;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#achievementUpdateRequest.
*/
kind?: string;
/**
* The payload if an update of type SET_STEPS_AT_LEAST was requested for the
* achievement.
*/
setStepsAtLeastPayload?: Schema$GamesAchievementSetStepsAtLeast;
/**
* The type of update being applied. Possible values are: -
* "REVEAL" - Achievement is revealed. - "UNLOCK" -
* Achievement is unlocked. - "INCREMENT" - Achievement is
* incremented. - "SET_STEPS_AT_LEAST" - Achievement progress is
* set to at least the passed value.
*/
updateType?: string;
}
/**
* This is a JSON template for an achievement update response.
*/
interface Schema$AchievementUpdateResponse {
/**
* The achievement this update is was applied to.
*/
achievementId?: string;
/**
* The current state of the achievement. Possible values are: -
* "HIDDEN" - Achievement is hidden. - "REVEALED" -
* Achievement is revealed. - "UNLOCKED" - Achievement is
* unlocked.
*/
currentState?: string;
/**
* The current steps recorded for this achievement if it is incremental.
*/
currentSteps?: number;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#achievementUpdateResponse.
*/
kind?: string;
/**
* Whether this achievement was newly unlocked (that is, whether the unlock
* request for the achievement was the first for the player).
*/
newlyUnlocked?: boolean;
/**
* Whether the requested updates actually affected the achievement.
*/
updateOccurred?: boolean;
}
/**
* This is a JSON template for aggregate stats.
*/
interface Schema$AggregateStats {
/**
* The number of messages sent between a pair of peers.
*/
count?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#aggregateStats.
*/
kind?: string;
/**
* The maximum amount.
*/
max?: string;
/**
* The minimum amount.
*/
min?: string;
/**
* The total number of bytes sent for messages between a pair of peers.
*/
sum?: string;
}
/**
* This is a JSON template for an anonymous player
*/
interface Schema$AnonymousPlayer {
/**
* The base URL for the image to display for the anonymous player.
*/
avatarImageUrl?: string;
/**
* The name to display for the anonymous player.
*/
displayName?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#anonymousPlayer.
*/
kind?: string;
}
/**
* This is a JSON template for the Application resource.
*/
interface Schema$Application {
/**
* The number of achievements visible to the currently authenticated player.
*/
achievement_count?: number;
/**
* The assets of the application.
*/
assets?: Schema$ImageAsset[];
/**
* The author of the application.
*/
author?: string;
/**
* The category of the application.
*/
category?: Schema$ApplicationCategory;
/**
* The description of the application.
*/
description?: string;
/**
* A list of features that have been enabled for the application. Possible
* values are: - "SNAPSHOTS" - Snapshots has been enabled
*/
enabledFeatures?: string[];
/**
* The ID of the application.
*/
id?: string;
/**
* The instances of the application.
*/
instances?: Schema$Instance[];
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#application.
*/
kind?: string;
/**
* The last updated timestamp of the application.
*/
lastUpdatedTimestamp?: string;
/**
* The number of leaderboards visible to the currently authenticated player.
*/
leaderboard_count?: number;
/**
* The name of the application.
*/
name?: string;
/**
* A hint to the client UI for what color to use as an app-themed color. The
* color is given as an RGB triplet (e.g. "E0E0E0").
*/
themeColor?: string;
}
/**
* This is a JSON template for an application category object.
*/
interface Schema$ApplicationCategory {
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#applicationCategory.
*/
kind?: string;
/**
* The primary category.
*/
primary?: string;
/**
* The secondary category.
*/
secondary?: string;
}
/**
* This is a JSON template for a third party application verification response
* resource.
*/
interface Schema$ApplicationVerifyResponse {
/**
* An alternate ID that was once used for the player that was issued the
* auth token used in this request. (This field is not normally populated.)
*/
alternate_player_id?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#applicationVerifyResponse.
*/
kind?: string;
/**
* The ID of the player that was issued the auth token used in this request.
*/
player_id?: string;
}
/**
* This is a JSON template for data related to individual game categories.
*/
interface Schema$Category {
/**
* The category name.
*/
category?: string;
/**
* Experience points earned in this category.
*/
experiencePoints?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#category.
*/
kind?: string;
}
/**
* This is a JSON template for a list of category data objects.
*/
interface Schema$CategoryListResponse {
/**
* The list of categories with usage data.
*/
items?: Schema$Category[];
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#categoryListResponse.
*/
kind?: string;
/**
* Token corresponding to the next page of results.
*/
nextPageToken?: string;
}
/**
* This is a JSON template for a batch update failure resource.
*/
interface Schema$EventBatchRecordFailure {
/**
* The cause for the update failure. Possible values are: -
* "TOO_LARGE": A batch request was issued with more events than
* are allowed in a single batch. - "TIME_PERIOD_EXPIRED": A
* batch was sent with data too far in the past to record. -
* "TIME_PERIOD_SHORT": A batch was sent with a time range that
* was too short. - "TIME_PERIOD_LONG": A batch was sent with a
* time range that was too long. - "ALREADY_UPDATED": An attempt
* was made to record a batch of data which was already seen. -
* "RECORD_RATE_HIGH": An attempt was made to record data faster
* than the server will apply updates.
*/
failureCause?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#eventBatchRecordFailure.
*/
kind?: string;
/**
* The time range which was rejected; empty for a request-wide failure.
*/
range?: Schema$EventPeriodRange;
}
/**
* This is a JSON template for an event child relationship resource.
*/
interface Schema$EventChild {
/**
* The ID of the child event.
*/
childId?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#eventChild.
*/
kind?: string;
}
/**
* This is a JSON template for an event definition resource.
*/
interface Schema$EventDefinition {
/**
* A list of events that are a child of this event.
*/
childEvents?: Schema$EventChild[];
/**
* Description of what this event represents.
*/
description?: string;
/**
* The name to display for the event.
*/
displayName?: string;
/**
* The ID of the event.
*/
id?: string;
/**
* The base URL for the image that represents the event.
*/
imageUrl?: string;
/**
* Indicates whether the icon image being returned is a default image, or is
* game-provided.
*/
isDefaultImageUrl?: boolean;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#eventDefinition.
*/
kind?: string;
/**
* The visibility of event being tracked in this definition. Possible values
* are: - "REVEALED": This event should be visible to all users.
* - "HIDDEN": This event should only be shown to users that have
* recorded this event at least once.
*/
visibility?: string;
}
/**
* This is a JSON template for a ListDefinitions response.
*/
interface Schema$EventDefinitionListResponse {
/**
* The event definitions.
*/
items?: Schema$EventDefinition[];
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#eventDefinitionListResponse.
*/
kind?: string;
/**
* The pagination token for the next page of results.
*/
nextPageToken?: string;
}
/**
* This is a JSON template for an event period time range.
*/
interface Schema$EventPeriodRange {
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#eventPeriodRange.
*/
kind?: string;
/**
* The time when this update period ends, in millis, since 1970 UTC (Unix
* Epoch).
*/
periodEndMillis?: string;
/**
* The time when this update period begins, in millis, since 1970 UTC (Unix
* Epoch).
*/
periodStartMillis?: string;
}
/**
* This is a JSON template for an event period update resource.
*/
interface Schema$EventPeriodUpdate {
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#eventPeriodUpdate.
*/
kind?: string;
/**
* The time period being covered by this update.
*/
timePeriod?: Schema$EventPeriodRange;
/**
* The updates being made for this time period.
*/
updates?: Schema$EventUpdateRequest[];
}
/**
* This is a JSON template for an event update failure resource.
*/
interface Schema$EventRecordFailure {
/**
* The ID of the event that was not updated.
*/
eventId?: string;
/**
* The cause for the update failure. Possible values are: -
* "NOT_FOUND" - An attempt was made to set an event that was not
* defined. - "INVALID_UPDATE_VALUE" - An attempt was made to
* increment an event by a non-positive value.
*/
failureCause?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#eventRecordFailure.
*/
kind?: string;
}
/**
* This is a JSON template for an event period update resource.
*/
interface Schema$EventRecordRequest {
/**
* The current time when this update was sent, in milliseconds, since 1970
* UTC (Unix Epoch).
*/
currentTimeMillis?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#eventRecordRequest.
*/
kind?: string;
/**
* The request ID used to identify this attempt to record events.
*/
requestId?: string;
/**
* A list of the time period updates being made in this request.
*/
timePeriods?: Schema$EventPeriodUpdate[];
}
/**
* This is a JSON template for an event period update resource.
*/
interface Schema$EventUpdateRequest {
/**
* The ID of the event being modified in this update.
*/
definitionId?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#eventUpdateRequest.
*/
kind?: string;
/**
* The number of times this event occurred in this time period.
*/
updateCount?: string;
}
/**
* This is a JSON template for an event period update resource.
*/
interface Schema$EventUpdateResponse {
/**
* Any batch-wide failures which occurred applying updates.
*/
batchFailures?: Schema$EventBatchRecordFailure[];
/**
* Any failures updating a particular event.
*/
eventFailures?: Schema$EventRecordFailure[];
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#eventUpdateResponse.
*/
kind?: string;
/**
* The current status of any updated events
*/
playerEvents?: Schema$PlayerEvent[];
}
/**
* This is a JSON template for the payload to request to increment an
* achievement.
*/
interface Schema$GamesAchievementIncrement {
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#GamesAchievementIncrement.
*/
kind?: string;
/**
* The requestId associated with an increment to an achievement.
*/
requestId?: string;
/**
* The number of steps to be incremented.
*/
steps?: number;
}
/**
* This is a JSON template for the payload to request to increment an
* achievement.
*/
interface Schema$GamesAchievementSetStepsAtLeast {
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#GamesAchievementSetStepsAtLeast.
*/
kind?: string;
/**
* The minimum number of steps for the achievement to be set to.
*/
steps?: number;
}
/**
* This is a JSON template for an image asset object.
*/
interface Schema$ImageAsset {
/**
* The height of the asset.
*/
height?: number;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#imageAsset.
*/
kind?: string;
/**
* The name of the asset.
*/
name?: string;
/**
* The URL of the asset.
*/
url?: string;
/**
* The width of the asset.
*/
width?: number;
}
/**
* This is a JSON template for the Instance resource.
*/
interface Schema$Instance {
/**
* URI which shows where a user can acquire this instance.
*/
acquisitionUri?: string;
/**
* Platform dependent details for Android.
*/
androidInstance?: Schema$InstanceAndroidDetails;
/**
* Platform dependent details for iOS.
*/
iosInstance?: Schema$InstanceIosDetails;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#instance.
*/
kind?: string;
/**
* Localized display name.
*/
name?: string;
/**
* The platform type. Possible values are: - "ANDROID" -
* Instance is for Android. - "IOS" - Instance is for iOS -
* "WEB_APP" - Instance is for Web App.
*/
platformType?: string;
/**
* Flag to show if this game instance supports realtime play.
*/
realtimePlay?: boolean;
/**
* Flag to show if this game instance supports turn based play.
*/
turnBasedPlay?: boolean;
/**
* Platform dependent details for Web.
*/
webInstance?: Schema$InstanceWebDetails;
}
/**
* This is a JSON template for the Android instance details resource.
*/
interface Schema$InstanceAndroidDetails {
/**
* Flag indicating whether the anti-piracy check is enabled.
*/
enablePiracyCheck?: boolean;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#instanceAndroidDetails.
*/
kind?: string;
/**
* Android package name which maps to Google Play URL.
*/
packageName?: string;
/**
* Indicates that this instance is the default for new installations.
*/
preferred?: boolean;
}
/**
* This is a JSON template for the iOS details resource.
*/
interface Schema$InstanceIosDetails {
/**
* Bundle identifier.
*/
bundleIdentifier?: string;
/**
* iTunes App ID.
*/
itunesAppId?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#instanceIosDetails.
*/
kind?: string;
/**
* Indicates that this instance is the default for new installations on iPad
* devices.
*/
preferredForIpad?: boolean;
/**
* Indicates that this instance is the default for new installations on
* iPhone devices.
*/
preferredForIphone?: boolean;
/**
* Flag to indicate if this instance supports iPad.
*/
supportIpad?: boolean;
/**
* Flag to indicate if this instance supports iPhone.
*/
supportIphone?: boolean;
}
/**
* This is a JSON template for the Web details resource.
*/
interface Schema$InstanceWebDetails {
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#instanceWebDetails.
*/
kind?: string;
/**
* Launch URL for the game.
*/
launchUrl?: string;
/**
* Indicates that this instance is the default for new installations.
*/
preferred?: boolean;
}
/**
* This is a JSON template for the Leaderboard resource.
*/
interface Schema$Leaderboard {
/**
* The icon for the leaderboard.
*/
iconUrl?: string;
/**
* The leaderboard ID.
*/
id?: string;
/**
* Indicates whether the icon image being returned is a default image, or is
* game-provided.
*/
isIconUrlDefault?: boolean;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#leaderboard.
*/
kind?: string;
/**
* The name of the leaderboard.
*/
name?: string;
/**
* How scores are ordered. Possible values are: -
* "LARGER_IS_BETTER" - Larger values are better; scores are
* sorted in descending order. - "SMALLER_IS_BETTER" - Smaller
* values are better; scores are sorted in ascending order.
*/
order?: string;
}
/**
* This is a JSON template for the Leaderboard Entry resource.
*/
interface Schema$LeaderboardEntry {
/**
* The localized string for the numerical value of this score.
*/
formattedScore?: string;
/**
* The localized string for the rank of this score for this leaderboard.
*/
formattedScoreRank?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#leaderboardEntry.
*/
kind?: string;
/**
* The player who holds this score.
*/
player?: Schema$Player;
/**
* The rank of this score for this leaderboard.
*/
scoreRank?: string;
/**
* Additional information about the score. Values must contain no more than
* 64 URI-safe characters as defined by section 2.3 of RFC 3986.
*/
scoreTag?: string;
/**
* The numerical value of this score.
*/
scoreValue?: string;
/**
* The time span of this high score. Possible values are: -
* "ALL_TIME" - The score is an all-time high score. -
* "WEEKLY" - The score is a weekly high score. -
* "DAILY" - The score is a daily high score.
*/
timeSpan?: string;
/**
* The timestamp at which this score was recorded, in milliseconds since the
* epoch in UTC.
*/
writeTimestampMillis?: string;
}
/**
* This is a JSON template for a list of leaderboard objects.
*/
interface Schema$LeaderboardListResponse {
/**
* The leaderboards.
*/
items?: Schema$Leaderboard[];
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#leaderboardListResponse.
*/
kind?: string;
/**
* Token corresponding to the next page of results.
*/
nextPageToken?: string;
}
/**
* This is a JSON template for a score rank in a leaderboard.
*/
interface Schema$LeaderboardScoreRank {
/**
* The number of scores in the leaderboard as a string.
*/
formattedNumScores?: string;
/**
* The rank in the leaderboard as a string.
*/
formattedRank?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#leaderboardScoreRank.
*/
kind?: string;
/**
* The number of scores in the leaderboard.
*/
numScores?: string;
/**
* The rank in the leaderboard.
*/
rank?: string;
}
/**
* This is a JSON template for a ListScores response.
*/
interface Schema$LeaderboardScores {
/**
* The scores in the leaderboard.
*/
items?: Schema$LeaderboardEntry[];
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#leaderboardScores.
*/
kind?: string;
/**
* The pagination token for the next page of results.
*/
nextPageToken?: string;
/**
* The total number of scores in the leaderboard.
*/
numScores?: string;
/**
* The score of the requesting player on the leaderboard. The player's
* score may appear both here and in the list of scores above. If you are
* viewing a public leaderboard and the player is not sharing their gameplay
* information publicly, the scoreRank and formattedScoreRank values will
* not be present.
*/
playerScore?: Schema$LeaderboardEntry;
/**
* The pagination token for the previous page of results.
*/
prevPageToken?: string;
}
/**
* This is a JSON template for the metagame config resource
*/
interface Schema$MetagameConfig {
/**
* Current version of the metagame configuration data. When this data is
* updated, the version number will be increased by one.
*/
currentVersion?: number;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#metagameConfig.
*/
kind?: string;
/**
* The list of player levels.
*/
playerLevels?: Schema$PlayerLevel[];
}
/**
* This is a JSON template for network diagnostics reported for a client.
*/
interface Schema$NetworkDiagnostics {
/**
* The Android network subtype.
*/
androidNetworkSubtype?: number;
/**
* The Android network type.
*/
androidNetworkType?: number;
/**
* iOS network type as defined in Reachability.h.
*/
iosNetworkType?: number;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#networkDiagnostics.
*/
kind?: string;
/**
* The MCC+MNC code for the client's network connection. On Android:
* http://developer.android.com/reference/android/telephony/TelephonyManager.html#getNetworkOperator()
* On iOS, see:
* https://developer.apple.com/library/ios/documentation/NetworkingInternet/Reference/CTCarrier/Reference/Reference.html
*/
networkOperatorCode?: string;
/**
* The name of the carrier of the client's network connection. On
* Android:
* http://developer.android.com/reference/android/telephony/TelephonyManager.html#getNetworkOperatorName()
* On iOS:
* https://developer.apple.com/library/ios/documentation/NetworkingInternet/Reference/CTCarrier/Reference/Reference.html#//apple_ref/occ/instp/CTCarrier/carrierName
*/
networkOperatorName?: string;
/**
* The amount of time in milliseconds it took for the client to establish a
* connection with the XMPP server.
*/
registrationLatencyMillis?: number;
}
/**
* This is a JSON template for a result for a match participant.
*/
interface Schema$ParticipantResult {
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#participantResult.
*/
kind?: string;
/**
* The ID of the participant.
*/
participantId?: string;
/**
* The placement or ranking of the participant in the match results; a
* number from one to the number of participants in the match. Multiple
* participants may have the same placing value in case of a type.
*/
placing?: number;
/**
* The result of the participant for this match. Possible values are: -
* "MATCH_RESULT_WIN" - The participant won the match. -
* "MATCH_RESULT_LOSS" - The participant lost the match. -
* "MATCH_RESULT_TIE" - The participant tied the match. -
* "MATCH_RESULT_NONE" - There was no winner for the match (nobody
* wins or loses this kind of game.) - "MATCH_RESULT_DISCONNECT"
* - The participant disconnected / left during the match. -
* "MATCH_RESULT_DISAGREED" - Different clients reported different
* results for this participant.
*/
result?: string;
}
/**
* This is a JSON template for peer channel diagnostics.
*/
interface Schema$PeerChannelDiagnostics {
/**
* Number of bytes received.
*/
bytesReceived?: Schema$AggregateStats;
/**
* Number of bytes sent.
*/
bytesSent?: Schema$AggregateStats;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#peerChannelDiagnostics.
*/
kind?: string;
/**
* Number of messages lost.
*/
numMessagesLost?: number;
/**
* Number of messages received.
*/
numMessagesReceived?: number;
/**
* Number of messages sent.
*/
numMessagesSent?: number;
/**
* Number of send failures.
*/
numSendFailures?: number;
/**
* Roundtrip latency stats in milliseconds.
*/
roundtripLatencyMillis?: Schema$AggregateStats;
}
/**
* This is a JSON template for peer session diagnostics.
*/
interface Schema$PeerSessionDiagnostics {
/**
* Connected time in milliseconds.
*/
connectedTimestampMillis?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#peerSessionDiagnostics.
*/
kind?: string;
/**
* The participant ID of the peer.
*/
participantId?: string;
/**
* Reliable channel diagnostics.
*/
reliableChannel?: Schema$PeerChannelDiagnostics;
/**
* Unreliable channel diagnostics.
*/
unreliableChannel?: Schema$PeerChannelDiagnostics;
}
/**
* This is a JSON template for metadata about a player playing a game with the
* currently authenticated user.
*/
interface Schema$Played {
/**
* True if the player was auto-matched with the currently authenticated
* user.
*/
autoMatched?: boolean;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#played.
*/
kind?: string;
/**
* The last time the player played the game in milliseconds since the epoch
* in UTC.
*/
timeMillis?: string;
}
/**
* This is a JSON template for a Player resource.
*/
interface Schema$Player {
/**
* The base URL for the image that represents the player.
*/
avatarImageUrl?: string;
/**
* The url to the landscape mode player banner image.
*/
bannerUrlLandscape?: string;
/**
* The url to the portrait mode player banner image.
*/
bannerUrlPortrait?: string;
/**
* The name to display for the player.
*/
displayName?: string;
/**
* An object to represent Play Game experience information for the player.
*/
experienceInfo?: Schema$PlayerExperienceInfo;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#player.
*/
kind?: string;
/**
* Details about the last time this player played a multiplayer game with
* the currently authenticated player. Populated for PLAYED_WITH player
* collection members.
*/
lastPlayedWith?: Schema$Played;
/**
* An object representation of the individual components of the player's
* name. For some players, these fields may not be present.
*/
name?: {
familyName?: string;
givenName?: string;
};
/**
* The player ID that was used for this player the first time they signed
* into the game in question. This is only populated for calls to player.get
* for the requesting player, only if the player ID has subsequently
* changed, and only to clients that support remapping player IDs.
*/
originalPlayerId?: string;
/**
* The ID of the player.
*/
playerId?: string;
/**
* The player's profile settings. Controls whether or not the
* player's profile is visible to other players.
*/
profileSettings?: Schema$ProfileSettings;
/**
* The player's title rewarded for their game activities.
*/
title?: string;
}
/**
* This is a JSON template for an achievement object.
*/
interface Schema$PlayerAchievement {
/**
* The state of the achievement. Possible values are: - "HIDDEN"
* - Achievement is hidden. - "REVEALED" - Achievement is
* revealed. - "UNLOCKED" - Achievement is unlocked.
*/
achievementState?: string;
/**
* The current steps for an incremental achievement.
*/
currentSteps?: number;
/**
* Experience points earned for the achievement. This field is absent for
* achievements that have not yet been unlocked and 0 for achievements that
* have been unlocked by testers but that are unpublished.
*/
experiencePoints?: string;
/**
* The current steps for an incremental achievement as a string.
*/
formattedCurrentStepsString?: string;
/**
* The ID of the achievement.
*/
id?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#playerAchievement.
*/
kind?: string;
/**
* The timestamp of the last modification to this achievement's state.
*/
lastUpdatedTimestamp?: string;
}
/**
* This is a JSON template for a list of achievement objects.
*/
interface Schema$PlayerAchievementListResponse {
/**
* The achievements.
*/
items?: Schema$PlayerAchievement[];
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#playerAchievementListResponse.
*/
kind?: string;
/**
* Token corresponding to the next page of results.
*/
nextPageToken?: string;
}
/**
* This is a JSON template for an event status resource.
*/
interface Schema$PlayerEvent {
/**
* The ID of the event definition.
*/
definitionId?: string;
/**
* The current number of times this event has occurred, as a string. The
* formatting of this string depends on the configuration of your event in
* the Play Games Developer Console.
*/
formattedNumEvents?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#playerEvent.
*/
kind?: string;
/**
* The current number of times this event has occurred.
*/
numEvents?: string;
/**
* The ID of the player.
*/
playerId?: string;
}
/**
* This is a JSON template for a ListByPlayer response.
*/
interface Schema$PlayerEventListResponse {
/**
* The player events.
*/
items?: Schema$PlayerEvent[];
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#playerEventListResponse.
*/
kind?: string;
/**
* The pagination token for the next page of results.
*/
nextPageToken?: string;
}
/**
* This is a JSON template for 1P/3P metadata about the player's
* experience.
*/
interface Schema$PlayerExperienceInfo {
/**
* The current number of experience points for the player.
*/
currentExperiencePoints?: string;
/**
* The current level of the player.
*/
currentLevel?: Schema$PlayerLevel;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#playerExperienceInfo.
*/
kind?: string;
/**
* The timestamp when the player was leveled up, in millis since Unix epoch
* UTC.
*/
lastLevelUpTimestampMillis?: string;
/**
* The next level of the player. If the current level is the maximum level,
* this should be same as the current level.
*/
nextLevel?: Schema$PlayerLevel;
}
/**
* This is a JSON template for a player leaderboard score object.
*/
interface Schema$PlayerLeaderboardScore {
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#playerLeaderboardScore.
*/
kind?: string;
/**
* The ID of the leaderboard this score is in.
*/
leaderboard_id?: string;
/**
* The public rank of the score in this leaderboard. This object will not be
* present if the user is not sharing their scores publicly.
*/
publicRank?: Schema$LeaderboardScoreRank;
/**
* The formatted value of this score.
*/
scoreString?: string;
/**
* Additional information about the score. Values must contain no more than
* 64 URI-safe characters as defined by section 2.3 of RFC 3986.
*/
scoreTag?: string;
/**
* The numerical value of this score.
*/
scoreValue?: string;
/**
* The social rank of the score in this leaderboard.
*/
socialRank?: Schema$LeaderboardScoreRank;
/**
* The time span of this score. Possible values are: -
* "ALL_TIME" - The score is an all-time score. -
* "WEEKLY" - The score is a weekly score. - "DAILY" -
* The score is a daily score.
*/
timeSpan?: string;
/**
* The timestamp at which this score was recorded, in milliseconds since the
* epoch in UTC.
*/
writeTimestamp?: string;
}
/**
* This is a JSON template for a list of player leaderboard scores.
*/
interface Schema$PlayerLeaderboardScoreListResponse {
/**
* The leaderboard scores.
*/
items?: Schema$PlayerLeaderboardScore[];
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#playerLeaderboardScoreListResponse.
*/
kind?: string;
/**
* The pagination token for the next page of results.
*/
nextPageToken?: string;
/**
* The Player resources for the owner of this score.
*/
player?: Schema$Player;
}
/**
* This is a JSON template for 1P/3P metadata about a user's level.
*/
interface Schema$PlayerLevel {
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#playerLevel.
*/
kind?: string;
/**
* The level for the user.
*/
level?: number;
/**
* The maximum experience points for this level.
*/
maxExperiencePoints?: string;
/**
* The minimum experience points for this level.
*/
minExperiencePoints?: string;
}
/**
* This is a JSON template for a third party player list response.
*/
interface Schema$PlayerListResponse {
/**
* The players.
*/
items?: Schema$Player[];
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#playerListResponse.
*/
kind?: string;
/**
* Token corresponding to the next page of results.
*/
nextPageToken?: string;
}
/**
* This is a JSON template for a player score.
*/
interface Schema$PlayerScore {
/**
* The formatted score for this player score.
*/
formattedScore?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#playerScore.
*/
kind?: string;
/**
* The numerical value for this player score.
*/
score?: string;
/**
* Additional information about this score. Values will contain no more than
* 64 URI-safe characters as defined by section 2.3 of RFC 3986.
*/
scoreTag?: string;
/**
* The time span for this player score. Possible values are: -
* "ALL_TIME" - The score is an all-time score. -
* "WEEKLY" - The score is a weekly score. - "DAILY" -
* The score is a daily score.
*/
timeSpan?: string;
}
/**
* This is a JSON template for a list of score submission statuses.
*/
interface Schema$PlayerScoreListResponse {
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#playerScoreListResponse.
*/
kind?: string;
/**
* The score submissions statuses.
*/
submittedScores?: Schema$PlayerScoreResponse[];
}
/**
* This is a JSON template for a list of leaderboard entry resources.
*/
interface Schema$PlayerScoreResponse {
/**
* The time spans where the submitted score is better than the existing
* score for that time span. Possible values are: - "ALL_TIME" -
* The score is an all-time score. - "WEEKLY" - The score is a
* weekly score. - "DAILY" - The score is a daily score.
*/
beatenScoreTimeSpans?: string[];
/**
* The formatted value of the submitted score.
*/
formattedScore?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#playerScoreResponse.
*/
kind?: string;
/**
* The leaderboard ID that this score was submitted to.
*/
leaderboardId?: string;
/**
* Additional information about this score. Values will contain no more than
* 64 URI-safe characters as defined by section 2.3 of RFC 3986.
*/
scoreTag?: string;
/**
* The scores in time spans that have not been beaten. As an example, the
* submitted score may be better than the player's DAILY score, but not
* better than the player's scores for the WEEKLY or ALL_TIME time
* spans.
*/
unbeatenScores?: Schema$PlayerScore[];
}
/**
* This is a JSON template for a list of score submission requests
*/
interface Schema$PlayerScoreSubmissionList {
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#playerScoreSubmissionList.
*/
kind?: string;
/**
* The score submissions.
*/
scores?: Schema$ScoreSubmission[];
}
/**
* This is a JSON template for profile settings
*/
interface Schema$ProfileSettings {
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#profileSettings.
*/
kind?: string;
/**
* The player's current profile visibility. This field is visible to
* both 1P and 3P APIs.
*/
profileVisible?: boolean;
}
/**
* This is a JSON template for a push token resource.
*/
interface Schema$PushToken {
/**
* The revision of the client SDK used by your application, in the same
* format that's used by revisions.check. Used to send backward
* compatible messages. Format: [PLATFORM_TYPE]:[VERSION_NUMBER]. Possible
* values of PLATFORM_TYPE are: - IOS - Push token is for iOS
*/
clientRevision?: string;
/**
* Unique identifier for this push token.
*/
id?: Schema$PushTokenId;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#pushToken.
*/
kind?: string;
/**
* The preferred language for notifications that are sent using this token.
*/
language?: string;
}
/**
* This is a JSON template for a push token ID resource.
*/
interface Schema$PushTokenId {
/**
* A push token ID for iOS devices.
*/
ios?: {
apns_device_token?: string;
apns_environment?: string;
};
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#pushTokenId.
*/
kind?: string;
}
/**
* This is a JSON template for a Quest resource.
*/
interface Schema$Quest {
/**
* The timestamp at which the user accepted the quest in milliseconds since
* the epoch in UTC. Only present if the player has accepted the quest.
*/
acceptedTimestampMillis?: string;
/**
* The ID of the application this quest is part of.
*/
applicationId?: string;
/**
* The banner image URL for the quest.
*/
bannerUrl?: string;
/**
* The description of the quest.
*/
description?: string;
/**
* The timestamp at which the quest ceases to be active in milliseconds
* since the epoch in UTC.
*/
endTimestampMillis?: string;
/**
* The icon image URL for the quest.
*/
iconUrl?: string;
/**
* The ID of the quest.
*/
id?: string;
/**
* Indicates whether the banner image being returned is a default image, or
* is game-provided.
*/
isDefaultBannerUrl?: boolean;
/**
* Indicates whether the icon image being returned is a default image, or is
* game-provided.
*/
isDefaultIconUrl?: boolean;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#quest.
*/
kind?: string;
/**
* The timestamp at which the quest was last updated by the user in
* milliseconds since the epoch in UTC. Only present if the player has
* accepted the quest.
*/
lastUpdatedTimestampMillis?: string;
/**
* The quest milestones.
*/
milestones?: Schema$QuestMilestone[];
/**
* The name of the quest.
*/
name?: string;
/**
* The timestamp at which the user should be notified that the quest will
* end soon in milliseconds since the epoch in UTC.
*/
notifyTimestampMillis?: string;
/**
* The timestamp at which the quest becomes active in milliseconds since the
* epoch in UTC.
*/
startTimestampMillis?: string;
/**
* The state of the quest. Possible values are: - "UPCOMING":
* The quest is upcoming. The user can see the quest, but cannot accept it
* until it is open. - "OPEN": The quest is currently open and
* may be accepted at this time. - "ACCEPTED": The user is
* currently participating in this quest. - "COMPLETED": The user
* has completed the quest. - "FAILED": The quest was attempted
* but was not completed before the deadline expired. -
* "EXPIRED": The quest has expired and was not accepted. -
* "DELETED": The quest should be deleted from the local database.
*/
state?: string;
}
/**
* This is a JSON template for a Quest Criterion Contribution resource.
*/
interface Schema$QuestContribution {
/**
* The formatted value of the contribution as a string. Format depends on
* the configuration for the associated event definition in the Play Games
* Developer Console.
*/
formattedValue?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#questContribution.
*/
kind?: string;
/**
* The value of the contribution.
*/
value?: string;
}
/**
* This is a JSON template for a Quest Criterion resource.
*/
interface Schema$QuestCriterion {
/**
* The total number of times the associated event must be incremented for
* the player to complete this quest.
*/
completionContribution?: Schema$QuestContribution;
/**
* The number of increments the player has made toward the completion count
* event increments required to complete the quest. This value will not
* exceed the completion contribution. There will be no currentContribution
* until the player has accepted the quest.
*/
currentContribution?: Schema$QuestContribution;
/**
* The ID of the event the criterion corresponds to.
*/
eventId?: string;
/**
* The value of the event associated with this quest at the time that the
* quest was accepted. This value may change if event increments that took
* place before the start of quest are uploaded after the quest starts.
* There will be no initialPlayerProgress until the player has accepted the
* quest.
*/
initialPlayerProgress?: Schema$QuestContribution;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#questCriterion.
*/
kind?: string;
}
/**
* This is a JSON template for a list of quest objects.
*/
interface Schema$QuestListResponse {
/**
* The quests.
*/
items?: Schema$Quest[];
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#questListResponse.
*/
kind?: string;
/**
* Token corresponding to the next page of results.
*/
nextPageToken?: string;
}
/**
* This is a JSON template for a Quest Milestone resource.
*/
interface Schema$QuestMilestone {
/**
* The completion reward data of the milestone, represented as a
* Base64-encoded string. This is a developer-specified binary blob with
* size between 0 and 2 KB before encoding.
*/
completionRewardData?: string;
/**
* The criteria of the milestone.
*/
criteria?: Schema$QuestCriterion[];
/**
* The milestone ID.
*/
id?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#questMilestone.
*/
kind?: string;
/**
* The current state of the milestone. Possible values are: -
* "COMPLETED_NOT_CLAIMED" - The milestone is complete, but has
* not yet been claimed. - "CLAIMED" - The milestone is complete
* and has been claimed. - "NOT_COMPLETED" - The milestone has
* not yet been completed. - "NOT_STARTED" - The milestone is for
* a quest that has not yet been accepted.
*/
state?: string;
}
/**
* This is a JSON template for the result of checking a revision.
*/
interface Schema$RevisionCheckResponse {
/**
* The version of the API this client revision should use when calling API
* methods.
*/
apiVersion?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#revisionCheckResponse.
*/
kind?: string;
/**
* The result of the revision check. Possible values are: - "OK"
* - The revision being used is current. - "DEPRECATED" - There
* is currently a newer version available, but the revision being used still
* works. - "INVALID" - The revision being used is not supported
* in any released version.
*/
revisionStatus?: string;
}
/**
* This is a JSON template for a room resource object.
*/
interface Schema$Room {
/**
* The ID of the application being played.
*/
applicationId?: string;
/**
* Criteria for auto-matching players into this room.
*/
autoMatchingCriteria?: Schema$RoomAutoMatchingCriteria;
/**
* Auto-matching status for this room. Not set if the room is not currently
* in the auto-matching queue.
*/
autoMatchingStatus?: Schema$RoomAutoMatchStatus;
/**
* Details about the room creation.
*/
creationDetails?: Schema$RoomModification;
/**
* This short description is generated by our servers and worded relative to
* the player requesting the room. It is intended to be displayed when the
* room is shown in a list (that is, an invitation to a room.)
*/
description?: string;
/**
* The ID of the participant that invited the user to the room. Not set if
* the user was not invited to the room.
*/
inviterId?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#room.
*/
kind?: string;
/**
* Details about the last update to the room.
*/
lastUpdateDetails?: Schema$RoomModification;
/**
* The participants involved in the room, along with their statuses.
* Includes participants who have left or declined invitations.
*/
participants?: Schema$RoomParticipant[];
/**
* Globally unique ID for a room.
*/
roomId?: string;
/**
* The version of the room status: an increasing counter, used by the client
* to ignore out-of-order updates to room status.
*/
roomStatusVersion?: number;
/**
* The status of the room. Possible values are: -
* "ROOM_INVITING" - One or more players have been invited and not
* responded. - "ROOM_AUTO_MATCHING" - One or more slots need to
* be filled by auto-matching. - "ROOM_CONNECTING" - Players have
* joined and are connecting to each other (either before or after
* auto-matching). - "ROOM_ACTIVE" - All players have joined and
* connected to each other. - "ROOM_DELETED" - The room should no
* longer be shown on the client. Returned in sync calls when a player joins
* a room (as a tombstone), or for rooms where all joined participants have
* left.
*/
status?: string;
/**
* The variant / mode of the application being played; can be any integer
* value, or left blank.
*/
variant?: number;
}
/**
* This is a JSON template for a room auto-match criteria object.
*/
interface Schema$RoomAutoMatchingCriteria {
/**
* A bitmask indicating when auto-matches are valid. When ANDed with other
* exclusive bitmasks, the result must be zero. Can be used to support
* exclusive roles within a game.
*/
exclusiveBitmask?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#roomAutoMatchingCriteria.
*/
kind?: string;
/**
* The maximum number of players that should be added to the room by
* auto-matching.
*/
maxAutoMatchingPlayers?: number;
/**
* The minimum number of players that should be added to the room by
* auto-matching.
*/
minAutoMatchingPlayers?: number;
}
/**
* This is a JSON template for status of room automatching that is in
* progress.
*/
interface Schema$RoomAutoMatchStatus {
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#roomAutoMatchStatus.
*/
kind?: string;
/**
* An estimate for the amount of time (in seconds) that auto-matching is
* expected to take to complete.
*/
waitEstimateSeconds?: number;
}
/**
* This is a JSON template for the client address when setting up a room.
*/
interface Schema$RoomClientAddress {
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#roomClientAddress.
*/
kind?: string;
/**
* The XMPP address of the client on the Google Games XMPP network.
*/
xmppAddress?: string;
}
/**
* This is a JSON template for a room creation request.
*/
interface Schema$RoomCreateRequest {
/**
* Criteria for auto-matching players into this room.
*/
autoMatchingCriteria?: Schema$RoomAutoMatchingCriteria;
/**
* The capabilities that this client supports for realtime communication.
*/
capabilities?: string[];
/**
* Client address for the player creating the room.
*/
clientAddress?: Schema$RoomClientAddress;
/**
* The player IDs to invite to the room.
*/
invitedPlayerIds?: string[];
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#roomCreateRequest.
*/
kind?: string;
/**
* Network diagnostics for the client creating the room.
*/
networkDiagnostics?: Schema$NetworkDiagnostics;
/**
* A randomly generated numeric ID. This number is used at the server to
* ensure that the request is handled correctly across retries.
*/
requestId?: string;
/**
* The variant / mode of the application to be played. This can be any
* integer value, or left blank. You should use a small number of variants
* to keep the auto-matching pool as large as possible.
*/
variant?: number;
}
/**
* This is a JSON template for a join room request.
*/
interface Schema$RoomJoinRequest {
/**
* The capabilities that this client supports for realtime communication.
*/
capabilities?: string[];
/**
* Client address for the player joining the room.
*/
clientAddress?: Schema$RoomClientAddress;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#roomJoinRequest.
*/
kind?: string;
/**
* Network diagnostics for the client joining the room.
*/
networkDiagnostics?: Schema$NetworkDiagnostics;
}
/**
* This is a JSON template for room leave diagnostics.
*/
interface Schema$RoomLeaveDiagnostics {
/**
* Android network subtype.
* http://developer.android.com/reference/android/net/NetworkInfo.html#getSubtype()
*/
androidNetworkSubtype?: number;
/**
* Android network type.
* http://developer.android.com/reference/android/net/NetworkInfo.html#getType()
*/
androidNetworkType?: number;
/**
* iOS network type as defined in Reachability.h.
*/
iosNetworkType?: number;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#roomLeaveDiagnostics.
*/
kind?: string;
/**
* The MCC+MNC code for the client's network connection. On Android:
* http://developer.android.com/reference/android/telephony/TelephonyManager.html#getNetworkOperator()
* On iOS, see:
* https://developer.apple.com/library/ios/documentation/NetworkingInternet/Reference/CTCarrier/Reference/Reference.html
*/
networkOperatorCode?: string;
/**
* The name of the carrier of the client's network connection. On
* Android:
* http://developer.android.com/reference/android/telephony/TelephonyManager.html#getNetworkOperatorName()
* On iOS:
* https://developer.apple.com/library/ios/documentation/NetworkingInternet/Reference/CTCarrier/Reference/Reference.html#//apple_ref/occ/instp/CTCarrier/carrierName
*/
networkOperatorName?: string;
/**
* Diagnostics about all peer sessions.
*/
peerSession?: Schema$PeerSessionDiagnostics[];
/**
* Whether or not sockets were used.
*/
socketsUsed?: boolean;
}
/**
* This is a JSON template for a leave room request.
*/
interface Schema$RoomLeaveRequest {
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#roomLeaveRequest.
*/
kind?: string;
/**
* Diagnostics for a player leaving the room.
*/
leaveDiagnostics?: Schema$RoomLeaveDiagnostics;
/**
* Reason for leaving the match. Possible values are: -
* "PLAYER_LEFT" - The player chose to leave the room.. -
* "GAME_LEFT" - The game chose to remove the player from the
* room. - "REALTIME_ABANDONED" - The player switched to another
* application and abandoned the room. -
* "REALTIME_PEER_CONNECTION_FAILURE" - The client was unable to
* establish a connection to other peer(s). -
* "REALTIME_SERVER_CONNECTION_FAILURE" - The client was unable to
* communicate with the server. - "REALTIME_SERVER_ERROR" - The
* client received an error response when it tried to communicate with the
* server. - "REALTIME_TIMEOUT" - The client timed out while
* waiting for a room. - "REALTIME_CLIENT_DISCONNECTING" - The
* client disconnects without first calling Leave. -
* "REALTIME_SIGN_OUT" - The user signed out of G+ while in the
* room. - "REALTIME_GAME_CRASHED" - The game crashed. -
* "REALTIME_ROOM_SERVICE_CRASHED" - RoomAndroidService crashed.
* - "REALTIME_DIFFERENT_CLIENT_ROOM_OPERATION" - Another client
* is trying to enter a room. -
* "REALTIME_SAME_CLIENT_ROOM_OPERATION" - The same client is
* trying to enter a new room.
*/
reason?: string;
}
/**
* This is a JSON template for a list of rooms.
*/
interface Schema$RoomList {
/**
* The rooms.
*/
items?: Schema$Room[];
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#roomList.
*/
kind?: string;
/**
* The pagination token for the next page of results.
*/
nextPageToken?: string;
}
/**
* This is a JSON template for room modification metadata.
*/
interface Schema$RoomModification {
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#roomModification.
*/
kind?: string;
/**
* The timestamp at which they modified the room, in milliseconds since the
* epoch in UTC.
*/
modifiedTimestampMillis?: string;
/**
* The ID of the participant that modified the room.
*/
participantId?: string;
}
/**
* This is a JSON template for an update on the status of a peer in a room.
*/
interface Schema$RoomP2PStatus {
/**
* The amount of time in milliseconds it took to establish connections with
* this peer.
*/
connectionSetupLatencyMillis?: number;
/**
* The error code in event of a failure. Possible values are: -
* "P2P_FAILED" - The client failed to establish a P2P connection
* with the peer. - "PRESENCE_FAILED" - The client failed to
* register to receive P2P connections. - "RELAY_SERVER_FAILED" -
* The client received an error when trying to use the relay server to
* establish a P2P connection with the peer.
*/
error?: string;
/**
* More detailed diagnostic message returned in event of a failure.
*/
error_reason?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#roomP2PStatus.
*/
kind?: string;
/**
* The ID of the participant.
*/
participantId?: string;
/**
* The status of the peer in the room. Possible values are: -
* "CONNECTION_ESTABLISHED" - The client established a P2P
* connection with the peer. - "CONNECTION_FAILED" - The client
* failed to establish directed presence with the peer.
*/
status?: string;
/**
* The amount of time in milliseconds it took to send packets back and forth
* on the unreliable channel with this peer.
*/
unreliableRoundtripLatencyMillis?: number;
}
/**
* This is a JSON template for an update on the status of peers in a room.
*/
interface Schema$RoomP2PStatuses {
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#roomP2PStatuses.
*/
kind?: string;
/**
* The updates for the peers.
*/
updates?: Schema$RoomP2PStatus[];
}
/**
* This is a JSON template for a participant in a room.
*/
interface Schema$RoomParticipant {
/**
* True if this participant was auto-matched with the requesting player.
*/
autoMatched?: boolean;
/**
* Information about a player that has been anonymously auto-matched against
* the requesting player. (Either player or autoMatchedPlayer will be set.)
*/
autoMatchedPlayer?: Schema$AnonymousPlayer;
/**
* The capabilities which can be used when communicating with this
* participant.
*/
capabilities?: string[];
/**
* Client address for the participant.
*/
clientAddress?: Schema$RoomClientAddress;
/**
* True if this participant is in the fully connected set of peers in the
* room.
*/
connected?: boolean;
/**
* An identifier for the participant in the scope of the room. Cannot be
* used to identify a player across rooms or in other contexts.
*/
id?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#roomParticipant.
*/
kind?: string;
/**
* The reason the participant left the room; populated if the participant
* status is PARTICIPANT_LEFT. Possible values are: -
* "PLAYER_LEFT" - The player explicitly chose to leave the room.
* - "GAME_LEFT" - The game chose to remove the player from the
* room. - "ABANDONED" - The player switched to another
* application and abandoned the room. - "PEER_CONNECTION_FAILURE"
* - The client was unable to establish or maintain a connection to other
* peer(s) in the room. - "SERVER_ERROR" - The client received an
* error response when it tried to communicate with the server. -
* "TIMEOUT" - The client timed out while waiting for players to
* join and connect. - "PRESENCE_FAILURE" - The client's XMPP
* connection ended abruptly.
*/
leaveReason?: string;
/**
* Information about the player. Not populated if this player was
* anonymously auto-matched against the requesting player. (Either player or
* autoMatchedPlayer will be set.)
*/
player?: Schema$Player;
/**
* The status of the participant with respect to the room. Possible values
* are: - "PARTICIPANT_INVITED" - The participant has been
* invited to join the room, but has not yet responded. -
* "PARTICIPANT_JOINED" - The participant has joined the room
* (either after creating it or accepting an invitation.) -
* "PARTICIPANT_DECLINED" - The participant declined an invitation
* to join the room. - "PARTICIPANT_LEFT" - The participant
* joined the room and then left it.
*/
status?: string;
}
/**
* This is a JSON template for the status of a room that the player has
* joined.
*/
interface Schema$RoomStatus {
/**
* Auto-matching status for this room. Not set if the room is not currently
* in the automatching queue.
*/
autoMatchingStatus?: Schema$RoomAutoMatchStatus;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#roomStatus.
*/
kind?: string;
/**
* The participants involved in the room, along with their statuses.
* Includes participants who have left or declined invitations.
*/
participants?: Schema$RoomParticipant[];
/**
* Globally unique ID for a room.
*/
roomId?: string;
/**
* The status of the room. Possible values are: -
* "ROOM_INVITING" - One or more players have been invited and not
* responded. - "ROOM_AUTO_MATCHING" - One or more slots need to
* be filled by auto-matching. - "ROOM_CONNECTING" - Players have
* joined are connecting to each other (either before or after
* auto-matching). - "ROOM_ACTIVE" - All players have joined and
* connected to each other. - "ROOM_DELETED" - All joined players
* have left.
*/
status?: string;
/**
* The version of the status for the room: an increasing counter, used by
* the client to ignore out-of-order updates to room status.
*/
statusVersion?: number;
}
/**
* This is a JSON template for a request to submit a score to leaderboards.
*/
interface Schema$ScoreSubmission {
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#scoreSubmission.
*/
kind?: string;
/**
* The leaderboard this score is being submitted to.
*/
leaderboardId?: string;
/**
* The new score being submitted.
*/
score?: string;
/**
* Additional information about this score. Values will contain no more than
* 64 URI-safe characters as defined by section 2.3 of RFC 3986.
*/
scoreTag?: string;
/**
* Signature Values will contain URI-safe characters as defined by
* section 2.3 of RFC 3986.
*/
signature?: string;
}
/**
* This is a JSON template for an snapshot object.
*/
interface Schema$Snapshot {
/**
* The cover image of this snapshot. May be absent if there is no image.
*/
coverImage?: Schema$SnapshotImage;
/**
* The description of this snapshot.
*/
description?: string;
/**
* The ID of the file underlying this snapshot in the Drive API. Only
* present if the snapshot is a view on a Drive file and the file is owned
* by the caller.
*/
driveId?: string;
/**
* The duration associated with this snapshot, in millis.
*/
durationMillis?: string;
/**
* The ID of the snapshot.
*/
id?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#snapshot.
*/
kind?: string;
/**
* The timestamp (in millis since Unix epoch) of the last modification to
* this snapshot.
*/
lastModifiedMillis?: string;
/**
* The progress value (64-bit integer set by developer) associated with this
* snapshot.
*/
progressValue?: string;
/**
* The title of this snapshot.
*/
title?: string;
/**
* The type of this snapshot. Possible values are: - "SAVE_GAME"
* - A snapshot representing a save game.
*/
type?: string;
/**
* The unique name provided when the snapshot was created.
*/
uniqueName?: string;
}
/**
* This is a JSON template for an image of a snapshot.
*/
interface Schema$SnapshotImage {
/**
* The height of the image.
*/
height?: number;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#snapshotImage.
*/
kind?: string;
/**
* The MIME type of the image.
*/
mime_type?: string;
/**
* The URL of the image. This URL may be invalidated at any time and should
* not be cached.
*/
url?: string;
/**
* The width of the image.
*/
width?: number;
}
/**
* This is a JSON template for a list of snapshot objects.
*/
interface Schema$SnapshotListResponse {
/**
* The snapshots.
*/
items?: Schema$Snapshot[];
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#snapshotListResponse.
*/
kind?: string;
/**
* Token corresponding to the next page of results. If there are no more
* results, the token is omitted.
*/
nextPageToken?: string;
}
/**
* This is a JSON template for an turn-based auto-match criteria object.
*/
interface Schema$TurnBasedAutoMatchingCriteria {
/**
* A bitmask indicating when auto-matches are valid. When ANDed with other
* exclusive bitmasks, the result must be zero. Can be used to support
* exclusive roles within a game.
*/
exclusiveBitmask?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#turnBasedAutoMatchingCriteria.
*/
kind?: string;
/**
* The maximum number of players that should be added to the match by
* auto-matching.
*/
maxAutoMatchingPlayers?: number;
/**
* The minimum number of players that should be added to the match by
* auto-matching.
*/
minAutoMatchingPlayers?: number;
}
/**
* This is a JSON template for a turn-based match resource object.
*/
interface Schema$TurnBasedMatch {
/**
* The ID of the application being played.
*/
applicationId?: string;
/**
* Criteria for auto-matching players into this match.
*/
autoMatchingCriteria?: Schema$TurnBasedAutoMatchingCriteria;
/**
* Details about the match creation.
*/
creationDetails?: Schema$TurnBasedMatchModification;
/**
* The data / game state for this match.
*/
data?: Schema$TurnBasedMatchData;
/**
* This short description is generated by our servers based on turn state
* and is localized and worded relative to the player requesting the match.
* It is intended to be displayed when the match is shown in a list.
*/
description?: string;
/**
* The ID of the participant that invited the user to the match. Not set if
* the user was not invited to the match.
*/
inviterId?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#turnBasedMatch.
*/
kind?: string;
/**
* Details about the last update to the match.
*/
lastUpdateDetails?: Schema$TurnBasedMatchModification;
/**
* Globally unique ID for a turn-based match.
*/
matchId?: string;
/**
* The number of the match in a chain of rematches. Will be set to 1 for the
* first match and incremented by 1 for each rematch.
*/
matchNumber?: number;
/**
* The version of this match: an increasing counter, used to avoid
* out-of-date updates to the match.
*/
matchVersion?: number;
/**
* The participants involved in the match, along with their statuses.
* Includes participants who have left or declined invitations.
*/
participants?: Schema$TurnBasedMatchParticipant[];
/**
* The ID of the participant that is taking a turn.
*/
pendingParticipantId?: string;
/**
* The data / game state for the previous match; set for the first turn of
* rematches only.
*/
previousMatchData?: Schema$TurnBasedMatchData;
/**
* The ID of a rematch of this match. Only set for completed matches that
* have been rematched.
*/
rematchId?: string;
/**
* The results reported for this match.
*/
results?: Schema$ParticipantResult[];
/**
* The status of the match. Possible values are: -
* "MATCH_AUTO_MATCHING" - One or more slots need to be filled by
* auto-matching; the match cannot be established until they are filled. -
* "MATCH_ACTIVE" - The match has started. -
* "MATCH_COMPLETE" - The match has finished. -
* "MATCH_CANCELED" - The match was canceled. -
* "MATCH_EXPIRED" - The match expired due to inactivity. -
* "MATCH_DELETED" - The match should no longer be shown on the
* client. Returned only for tombstones for matches when sync is called.
*/
status?: string;
/**
* The status of the current user in the match. Derived from the match type,
* match status, the user's participant status, and the pending
* participant for the match. Possible values are: -
* "USER_INVITED" - The user has been invited to join the match
* and has not responded yet. - "USER_AWAITING_TURN" - The user
* is waiting for their turn. - "USER_TURN" - The user has an
* action to take in the match. - "USER_MATCH_COMPLETED" - The
* match has ended (it is completed, canceled, or expired.)
*/
userMatchStatus?: string;
/**
* The variant / mode of the application being played; can be any integer
* value, or left blank.
*/
variant?: number;
/**
* The ID of another participant in the match that can be used when
* describing the participants the user is playing with.
*/
withParticipantId?: string;
}
/**
* This is a JSON template for a turn-based match creation request.
*/
interface Schema$TurnBasedMatchCreateRequest {
/**
* Criteria for auto-matching players into this match.
*/
autoMatchingCriteria?: Schema$TurnBasedAutoMatchingCriteria;
/**
* The player ids to invite to the match.
*/
invitedPlayerIds?: string[];
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#turnBasedMatchCreateRequest.
*/
kind?: string;
/**
* A randomly generated numeric ID. This number is used at the server to
* ensure that the request is handled correctly across retries.
*/
requestId?: string;
/**
* The variant / mode of the application to be played. This can be any
* integer value, or left blank. You should use a small number of variants
* to keep the auto-matching pool as large as possible.
*/
variant?: number;
}
/**
* This is a JSON template for a turn-based match data object.
*/
interface Schema$TurnBasedMatchData {
/**
* The byte representation of the data (limited to 128 kB), as a
* Base64-encoded string with the URL_SAFE encoding option.
*/
data?: string;
/**
* True if this match has data available but it wasn't returned in a
* list response; fetching the match individually will retrieve this data.
*/
dataAvailable?: boolean;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#turnBasedMatchData.
*/
kind?: string;
}
/**
* This is a JSON template for sending a turn-based match data object.
*/
interface Schema$TurnBasedMatchDataRequest {
/**
* The byte representation of the data (limited to 128 kB), as a
* Base64-encoded string with the URL_SAFE encoding option.
*/
data?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#turnBasedMatchDataRequest.
*/
kind?: string;
}
/**
* This is a JSON template for a list of turn-based matches.
*/
interface Schema$TurnBasedMatchList {
/**
* The matches.
*/
items?: Schema$TurnBasedMatch[];
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#turnBasedMatchList.
*/
kind?: string;
/**
* The pagination token for the next page of results.
*/
nextPageToken?: string;
}
/**
* This is a JSON template for turn-based match modification metadata.
*/
interface Schema$TurnBasedMatchModification {
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#turnBasedMatchModification.
*/
kind?: string;
/**
* The timestamp at which they modified the match, in milliseconds since the
* epoch in UTC.
*/
modifiedTimestampMillis?: string;
/**
* The ID of the participant that modified the match.
*/
participantId?: string;
}
/**
* This is a JSON template for a participant in a turn-based match.
*/
interface Schema$TurnBasedMatchParticipant {
/**
* True if this participant was auto-matched with the requesting player.
*/
autoMatched?: boolean;
/**
* Information about a player that has been anonymously auto-matched against
* the requesting player. (Either player or autoMatchedPlayer will be set.)
*/
autoMatchedPlayer?: Schema$AnonymousPlayer;
/**
* An identifier for the participant in the scope of the match. Cannot be
* used to identify a player across matches or in other contexts.
*/
id?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#turnBasedMatchParticipant.
*/
kind?: string;
/**
* Information about the player. Not populated if this player was
* anonymously auto-matched against the requesting player. (Either player or
* autoMatchedPlayer will be set.)
*/
player?: Schema$Player;
/**
* The status of the participant with respect to the match. Possible values
* are: - "PARTICIPANT_NOT_INVITED_YET" - The participant is
* slated to be invited to the match, but the invitation has not been sent;
* the invite will be sent when it becomes their turn. -
* "PARTICIPANT_INVITED" - The participant has been invited to
* join the match, but has not yet responded. -
* "PARTICIPANT_JOINED" - The participant has joined the match
* (either after creating it or accepting an invitation.) -
* "PARTICIPANT_DECLINED" - The participant declined an invitation
* to join the match. - "PARTICIPANT_LEFT" - The participant
* joined the match and then left it. - "PARTICIPANT_FINISHED" -
* The participant finished playing in the match. -
* "PARTICIPANT_UNRESPONSIVE" - The participant did not take their
* turn in the allotted time.
*/
status?: string;
}
/**
* This is a JSON template for a rematch response.
*/
interface Schema$TurnBasedMatchRematch {
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#turnBasedMatchRematch.
*/
kind?: string;
/**
* The old match that the rematch was created from; will be updated such
* that the rematchId field will point at the new match.
*/
previousMatch?: Schema$TurnBasedMatch;
/**
* The newly created match; a rematch of the old match with the same
* participants.
*/
rematch?: Schema$TurnBasedMatch;
}
/**
* This is a JSON template for a turn-based match results object.
*/
interface Schema$TurnBasedMatchResults {
/**
* The final match data.
*/
data?: Schema$TurnBasedMatchDataRequest;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#turnBasedMatchResults.
*/
kind?: string;
/**
* The version of the match being updated.
*/
matchVersion?: number;
/**
* The match results for the participants in the match.
*/
results?: Schema$ParticipantResult[];
}
/**
* This is a JSON template for a list of turn-based matches returned from a
* sync.
*/
interface Schema$TurnBasedMatchSync {
/**
* The matches.
*/
items?: Schema$TurnBasedMatch[];
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#turnBasedMatchSync.
*/
kind?: string;
/**
* True if there were more matches available to fetch at the time the
* response was generated (which were not returned due to page size limits.)
*/
moreAvailable?: boolean;
/**
* The pagination token for the next page of results.
*/
nextPageToken?: string;
}
/**
* This is a JSON template for the object representing a turn.
*/
interface Schema$TurnBasedMatchTurn {
/**
* The shared game state data after the turn is over.
*/
data?: Schema$TurnBasedMatchDataRequest;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string games#turnBasedMatchTurn.
*/
kind?: string;
/**
* The version of this match: an increasing counter, used to avoid
* out-of-date updates to the match.
*/
matchVersion?: number;
/**
* The ID of the participant who should take their turn next. May be set to
* the current player's participant ID to update match state without
* changing the turn. If not set, the match will wait for other player(s) to
* join via automatching; this is only valid if automatch criteria is set on
* the match with remaining slots for automatched players.
*/
pendingParticipantId?: string;
/**
* The match results for the participants in the match.
*/
results?: Schema$ParticipantResult[];
}
class Resource$Achievementdefinitions {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* games.achievementDefinitions.list
* @desc Lists all the achievement definitions for your application.
* @alias games.achievementDefinitions.list
* @memberOf! ()
*
* @param {object=} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {integer=} params.maxResults The maximum number of achievement resources to return in the response, used for paging. For any response, the actual number of achievement resources returned may be less than the specified maxResults.
* @param {string=} params.pageToken The token returned by the previous request.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list(params?: Params$Resource$Achievementdefinitions$List, options?: MethodOptions): GaxiosPromise<Schema$AchievementDefinitionsListResponse>;
list(params: Params$Resource$Achievementdefinitions$List, options: MethodOptions | BodyResponseCallback<Schema$AchievementDefinitionsListResponse>, callback: BodyResponseCallback<Schema$AchievementDefinitionsListResponse>): void;
list(params: Params$Resource$Achievementdefinitions$List, callback: BodyResponseCallback<Schema$AchievementDefinitionsListResponse>): void;
list(callback: BodyResponseCallback<Schema$AchievementDefinitionsListResponse>): void;
}
interface Params$Resource$Achievementdefinitions$List extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The maximum number of achievement resources to return in the response,
* used for paging. For any response, the actual number of achievement
* resources returned may be less than the specified maxResults.
*/
maxResults?: number;
/**
* The token returned by the previous request.
*/
pageToken?: string;
}
class Resource$Achievements {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* games.achievements.increment
* @desc Increments the steps of the achievement with the given ID for the
* currently authenticated player.
* @alias games.achievements.increment
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.achievementId The ID of the achievement used by this method.
* @param {string=} params.requestId A randomly generated numeric ID for each request specified by the caller. This number is used at the server to ensure that the request is handled correctly across retries.
* @param {integer} params.stepsToIncrement The number of steps to increment.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
increment(params?: Params$Resource$Achievements$Increment, options?: MethodOptions): GaxiosPromise<Schema$AchievementIncrementResponse>;
increment(params: Params$Resource$Achievements$Increment, options: MethodOptions | BodyResponseCallback<Schema$AchievementIncrementResponse>, callback: BodyResponseCallback<Schema$AchievementIncrementResponse>): void;
increment(params: Params$Resource$Achievements$Increment, callback: BodyResponseCallback<Schema$AchievementIncrementResponse>): void;
increment(callback: BodyResponseCallback<Schema$AchievementIncrementResponse>): void;
/**
* games.achievements.list
* @desc Lists the progress for all your application's achievements for the
* currently authenticated player.
* @alias games.achievements.list
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {integer=} params.maxResults The maximum number of achievement resources to return in the response, used for paging. For any response, the actual number of achievement resources returned may be less than the specified maxResults.
* @param {string=} params.pageToken The token returned by the previous request.
* @param {string} params.playerId A player ID. A value of me may be used in place of the authenticated player's ID.
* @param {string=} params.state Tells the server to return only achievements with the specified state. If this parameter isn't specified, all achievements are returned.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list(params?: Params$Resource$Achievements$List, options?: MethodOptions): GaxiosPromise<Schema$PlayerAchievementListResponse>;
list(params: Params$Resource$Achievements$List, options: MethodOptions | BodyResponseCallback<Schema$PlayerAchievementListResponse>, callback: BodyResponseCallback<Schema$PlayerAchievementListResponse>): void;
list(params: Params$Resource$Achievements$List, callback: BodyResponseCallback<Schema$PlayerAchievementListResponse>): void;
list(callback: BodyResponseCallback<Schema$PlayerAchievementListResponse>): void;
/**
* games.achievements.reveal
* @desc Sets the state of the achievement with the given ID to REVEALED for
* the currently authenticated player.
* @alias games.achievements.reveal
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.achievementId The ID of the achievement used by this method.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
reveal(params?: Params$Resource$Achievements$Reveal, options?: MethodOptions): GaxiosPromise<Schema$AchievementRevealResponse>;
reveal(params: Params$Resource$Achievements$Reveal, options: MethodOptions | BodyResponseCallback<Schema$AchievementRevealResponse>, callback: BodyResponseCallback<Schema$AchievementRevealResponse>): void;
reveal(params: Params$Resource$Achievements$Reveal, callback: BodyResponseCallback<Schema$AchievementRevealResponse>): void;
reveal(callback: BodyResponseCallback<Schema$AchievementRevealResponse>): void;
/**
* games.achievements.setStepsAtLeast
* @desc Sets the steps for the currently authenticated player towards
* unlocking an achievement. If the steps parameter is less than the current
* number of steps that the player already gained for the achievement, the
* achievement is not modified.
* @alias games.achievements.setStepsAtLeast
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.achievementId The ID of the achievement used by this method.
* @param {integer} params.steps The minimum value to set the steps to.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
setStepsAtLeast(params?: Params$Resource$Achievements$Setstepsatleast, options?: MethodOptions): GaxiosPromise<Schema$AchievementSetStepsAtLeastResponse>;
setStepsAtLeast(params: Params$Resource$Achievements$Setstepsatleast, options: MethodOptions | BodyResponseCallback<Schema$AchievementSetStepsAtLeastResponse>, callback: BodyResponseCallback<Schema$AchievementSetStepsAtLeastResponse>): void;
setStepsAtLeast(params: Params$Resource$Achievements$Setstepsatleast, callback: BodyResponseCallback<Schema$AchievementSetStepsAtLeastResponse>): void;
setStepsAtLeast(callback: BodyResponseCallback<Schema$AchievementSetStepsAtLeastResponse>): void;
/**
* games.achievements.unlock
* @desc Unlocks this achievement for the currently authenticated player.
* @alias games.achievements.unlock
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.achievementId The ID of the achievement used by this method.
* @param {string=} params.builtinGameId Override used only by built-in games in Play Games application.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
unlock(params?: Params$Resource$Achievements$Unlock, options?: MethodOptions): GaxiosPromise<Schema$AchievementUnlockResponse>;
unlock(params: Params$Resource$Achievements$Unlock, options: MethodOptions | BodyResponseCallback<Schema$AchievementUnlockResponse>, callback: BodyResponseCallback<Schema$AchievementUnlockResponse>): void;
unlock(params: Params$Resource$Achievements$Unlock, callback: BodyResponseCallback<Schema$AchievementUnlockResponse>): void;
unlock(callback: BodyResponseCallback<Schema$AchievementUnlockResponse>): void;
/**
* games.achievements.updateMultiple
* @desc Updates multiple achievements for the currently authenticated
* player.
* @alias games.achievements.updateMultiple
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.builtinGameId Override used only by built-in games in Play Games application.
* @param {().AchievementUpdateMultipleRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
updateMultiple(params?: Params$Resource$Achievements$Updatemultiple, options?: MethodOptions): GaxiosPromise<Schema$AchievementUpdateMultipleResponse>;
updateMultiple(params: Params$Resource$Achievements$Updatemultiple, options: MethodOptions | BodyResponseCallback<Schema$AchievementUpdateMultipleResponse>, callback: BodyResponseCallback<Schema$AchievementUpdateMultipleResponse>): void;
updateMultiple(params: Params$Resource$Achievements$Updatemultiple, callback: BodyResponseCallback<Schema$AchievementUpdateMultipleResponse>): void;
updateMultiple(callback: BodyResponseCallback<Schema$AchievementUpdateMultipleResponse>): void;
}
interface Params$Resource$Achievements$Increment extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The ID of the achievement used by this method.
*/
achievementId?: string;
/**
* A randomly generated numeric ID for each request specified by the caller.
* This number is used at the server to ensure that the request is handled
* correctly across retries.
*/
requestId?: string;
/**
* The number of steps to increment.
*/
stepsToIncrement?: number;
}
interface Params$Resource$Achievements$List extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The maximum number of achievement resources to return in the response,
* used for paging. For any response, the actual number of achievement
* resources returned may be less than the specified maxResults.
*/
maxResults?: number;
/**
* The token returned by the previous request.
*/
pageToken?: string;
/**
* A player ID. A value of me may be used in place of the authenticated
* player's ID.
*/
playerId?: string;
/**
* Tells the server to return only achievements with the specified state. If
* this parameter isn't specified, all achievements are returned.
*/
state?: string;
}
interface Params$Resource$Achievements$Reveal extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The ID of the achievement used by this method.
*/
achievementId?: string;
}
interface Params$Resource$Achievements$Setstepsatleast extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The ID of the achievement used by this method.
*/
achievementId?: string;
/**
* The minimum value to set the steps to.
*/
steps?: number;
}
interface Params$Resource$Achievements$Unlock extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The ID of the achievement used by this method.
*/
achievementId?: string;
/**
* Override used only by built-in games in Play Games application.
*/
builtinGameId?: string;
}
interface Params$Resource$Achievements$Updatemultiple extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* Override used only by built-in games in Play Games application.
*/
builtinGameId?: string;
/**
* Request body metadata
*/
requestBody?: Schema$AchievementUpdateMultipleRequest;
}
class Resource$Applications {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* games.applications.get
* @desc Retrieves the metadata of the application with the given ID. If the
* requested application is not available for the specified platformType,
* the returned response will not include any instance data.
* @alias games.applications.get
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.applicationId The application ID from the Google Play developer console.
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {string=} params.platformType Restrict application details returned to the specific platform.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get(params?: Params$Resource$Applications$Get, options?: MethodOptions): GaxiosPromise<Schema$Application>;
get(params: Params$Resource$Applications$Get, options: MethodOptions | BodyResponseCallback<Schema$Application>, callback: BodyResponseCallback<Schema$Application>): void;
get(params: Params$Resource$Applications$Get, callback: BodyResponseCallback<Schema$Application>): void;
get(callback: BodyResponseCallback<Schema$Application>): void;
/**
* games.applications.played
* @desc Indicate that the the currently authenticated user is playing your
* application.
* @alias games.applications.played
* @memberOf! ()
*
* @param {object=} params Parameters for request
* @param {string=} params.builtinGameId Override used only by built-in games in Play Games application.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
played(params?: Params$Resource$Applications$Played, options?: MethodOptions): GaxiosPromise<void>;
played(params: Params$Resource$Applications$Played, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void;
played(params: Params$Resource$Applications$Played, callback: BodyResponseCallback<void>): void;
played(callback: BodyResponseCallback<void>): void;
/**
* games.applications.verify
* @desc Verifies the auth token provided with this request is for the
* application with the specified ID, and returns the ID of the player it
* was granted for.
* @alias games.applications.verify
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.applicationId The application ID from the Google Play developer console.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
verify(params?: Params$Resource$Applications$Verify, options?: MethodOptions): GaxiosPromise<Schema$ApplicationVerifyResponse>;
verify(params: Params$Resource$Applications$Verify, options: MethodOptions | BodyResponseCallback<Schema$ApplicationVerifyResponse>, callback: BodyResponseCallback<Schema$ApplicationVerifyResponse>): void;
verify(params: Params$Resource$Applications$Verify, callback: BodyResponseCallback<Schema$ApplicationVerifyResponse>): void;
verify(callback: BodyResponseCallback<Schema$ApplicationVerifyResponse>): void;
}
interface Params$Resource$Applications$Get extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The application ID from the Google Play developer console.
*/
applicationId?: string;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* Restrict application details returned to the specific platform.
*/
platformType?: string;
}
interface Params$Resource$Applications$Played extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* Override used only by built-in games in Play Games application.
*/
builtinGameId?: string;
}
interface Params$Resource$Applications$Verify extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The application ID from the Google Play developer console.
*/
applicationId?: string;
}
class Resource$Events {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* games.events.listByPlayer
* @desc Returns a list showing the current progress on events in this
* application for the currently authenticated user.
* @alias games.events.listByPlayer
* @memberOf! ()
*
* @param {object=} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {integer=} params.maxResults The maximum number of events to return in the response, used for paging. For any response, the actual number of events to return may be less than the specified maxResults.
* @param {string=} params.pageToken The token returned by the previous request.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
listByPlayer(params?: Params$Resource$Events$Listbyplayer, options?: MethodOptions): GaxiosPromise<Schema$PlayerEventListResponse>;
listByPlayer(params: Params$Resource$Events$Listbyplayer, options: MethodOptions | BodyResponseCallback<Schema$PlayerEventListResponse>, callback: BodyResponseCallback<Schema$PlayerEventListResponse>): void;
listByPlayer(params: Params$Resource$Events$Listbyplayer, callback: BodyResponseCallback<Schema$PlayerEventListResponse>): void;
listByPlayer(callback: BodyResponseCallback<Schema$PlayerEventListResponse>): void;
/**
* games.events.listDefinitions
* @desc Returns a list of the event definitions in this application.
* @alias games.events.listDefinitions
* @memberOf! ()
*
* @param {object=} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {integer=} params.maxResults The maximum number of event definitions to return in the response, used for paging. For any response, the actual number of event definitions to return may be less than the specified maxResults.
* @param {string=} params.pageToken The token returned by the previous request.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
listDefinitions(params?: Params$Resource$Events$Listdefinitions, options?: MethodOptions): GaxiosPromise<Schema$EventDefinitionListResponse>;
listDefinitions(params: Params$Resource$Events$Listdefinitions, options: MethodOptions | BodyResponseCallback<Schema$EventDefinitionListResponse>, callback: BodyResponseCallback<Schema$EventDefinitionListResponse>): void;
listDefinitions(params: Params$Resource$Events$Listdefinitions, callback: BodyResponseCallback<Schema$EventDefinitionListResponse>): void;
listDefinitions(callback: BodyResponseCallback<Schema$EventDefinitionListResponse>): void;
/**
* games.events.record
* @desc Records a batch of changes to the number of times events have
* occurred for the currently authenticated user of this application.
* @alias games.events.record
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {().EventRecordRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
record(params?: Params$Resource$Events$Record, options?: MethodOptions): GaxiosPromise<Schema$EventUpdateResponse>;
record(params: Params$Resource$Events$Record, options: MethodOptions | BodyResponseCallback<Schema$EventUpdateResponse>, callback: BodyResponseCallback<Schema$EventUpdateResponse>): void;
record(params: Params$Resource$Events$Record, callback: BodyResponseCallback<Schema$EventUpdateResponse>): void;
record(callback: BodyResponseCallback<Schema$EventUpdateResponse>): void;
}
interface Params$Resource$Events$Listbyplayer extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The maximum number of events to return in the response, used for paging.
* For any response, the actual number of events to return may be less than
* the specified maxResults.
*/
maxResults?: number;
/**
* The token returned by the previous request.
*/
pageToken?: string;
}
interface Params$Resource$Events$Listdefinitions extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The maximum number of event definitions to return in the response, used
* for paging. For any response, the actual number of event definitions to
* return may be less than the specified maxResults.
*/
maxResults?: number;
/**
* The token returned by the previous request.
*/
pageToken?: string;
}
interface Params$Resource$Events$Record extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* Request body metadata
*/
requestBody?: Schema$EventRecordRequest;
}
class Resource$Leaderboards {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* games.leaderboards.get
* @desc Retrieves the metadata of the leaderboard with the given ID.
* @alias games.leaderboards.get
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {string} params.leaderboardId The ID of the leaderboard.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get(params?: Params$Resource$Leaderboards$Get, options?: MethodOptions): GaxiosPromise<Schema$Leaderboard>;
get(params: Params$Resource$Leaderboards$Get, options: MethodOptions | BodyResponseCallback<Schema$Leaderboard>, callback: BodyResponseCallback<Schema$Leaderboard>): void;
get(params: Params$Resource$Leaderboards$Get, callback: BodyResponseCallback<Schema$Leaderboard>): void;
get(callback: BodyResponseCallback<Schema$Leaderboard>): void;
/**
* games.leaderboards.list
* @desc Lists all the leaderboard metadata for your application.
* @alias games.leaderboards.list
* @memberOf! ()
*
* @param {object=} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {integer=} params.maxResults The maximum number of leaderboards to return in the response. For any response, the actual number of leaderboards returned may be less than the specified maxResults.
* @param {string=} params.pageToken The token returned by the previous request.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list(params?: Params$Resource$Leaderboards$List, options?: MethodOptions): GaxiosPromise<Schema$LeaderboardListResponse>;
list(params: Params$Resource$Leaderboards$List, options: MethodOptions | BodyResponseCallback<Schema$LeaderboardListResponse>, callback: BodyResponseCallback<Schema$LeaderboardListResponse>): void;
list(params: Params$Resource$Leaderboards$List, callback: BodyResponseCallback<Schema$LeaderboardListResponse>): void;
list(callback: BodyResponseCallback<Schema$LeaderboardListResponse>): void;
}
interface Params$Resource$Leaderboards$Get extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The ID of the leaderboard.
*/
leaderboardId?: string;
}
interface Params$Resource$Leaderboards$List extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The maximum number of leaderboards to return in the response. For any
* response, the actual number of leaderboards returned may be less than the
* specified maxResults.
*/
maxResults?: number;
/**
* The token returned by the previous request.
*/
pageToken?: string;
}
class Resource$Metagame {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* games.metagame.getMetagameConfig
* @desc Return the metagame configuration data for the calling application.
* @alias games.metagame.getMetagameConfig
* @memberOf! ()
*
* @param {object=} params Parameters for request
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
getMetagameConfig(params?: Params$Resource$Metagame$Getmetagameconfig, options?: MethodOptions): GaxiosPromise<Schema$MetagameConfig>;
getMetagameConfig(params: Params$Resource$Metagame$Getmetagameconfig, options: MethodOptions | BodyResponseCallback<Schema$MetagameConfig>, callback: BodyResponseCallback<Schema$MetagameConfig>): void;
getMetagameConfig(params: Params$Resource$Metagame$Getmetagameconfig, callback: BodyResponseCallback<Schema$MetagameConfig>): void;
getMetagameConfig(callback: BodyResponseCallback<Schema$MetagameConfig>): void;
/**
* games.metagame.listCategoriesByPlayer
* @desc List play data aggregated per category for the player corresponding
* to playerId.
* @alias games.metagame.listCategoriesByPlayer
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.collection The collection of categories for which data will be returned.
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {integer=} params.maxResults The maximum number of category resources to return in the response, used for paging. For any response, the actual number of category resources returned may be less than the specified maxResults.
* @param {string=} params.pageToken The token returned by the previous request.
* @param {string} params.playerId A player ID. A value of me may be used in place of the authenticated player's ID.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
listCategoriesByPlayer(params?: Params$Resource$Metagame$Listcategoriesbyplayer, options?: MethodOptions): GaxiosPromise<Schema$CategoryListResponse>;
listCategoriesByPlayer(params: Params$Resource$Metagame$Listcategoriesbyplayer, options: MethodOptions | BodyResponseCallback<Schema$CategoryListResponse>, callback: BodyResponseCallback<Schema$CategoryListResponse>): void;
listCategoriesByPlayer(params: Params$Resource$Metagame$Listcategoriesbyplayer, callback: BodyResponseCallback<Schema$CategoryListResponse>): void;
listCategoriesByPlayer(callback: BodyResponseCallback<Schema$CategoryListResponse>): void;
}
interface Params$Resource$Metagame$Getmetagameconfig extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
}
interface Params$Resource$Metagame$Listcategoriesbyplayer extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The collection of categories for which data will be returned.
*/
collection?: string;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The maximum number of category resources to return in the response, used
* for paging. For any response, the actual number of category resources
* returned may be less than the specified maxResults.
*/
maxResults?: number;
/**
* The token returned by the previous request.
*/
pageToken?: string;
/**
* A player ID. A value of me may be used in place of the authenticated
* player's ID.
*/
playerId?: string;
}
class Resource$Players {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* games.players.get
* @desc Retrieves the Player resource with the given ID. To retrieve the
* player for the currently authenticated user, set playerId to me.
* @alias games.players.get
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {string} params.playerId A player ID. A value of me may be used in place of the authenticated player's ID.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get(params?: Params$Resource$Players$Get, options?: MethodOptions): GaxiosPromise<Schema$Player>;
get(params: Params$Resource$Players$Get, options: MethodOptions | BodyResponseCallback<Schema$Player>, callback: BodyResponseCallback<Schema$Player>): void;
get(params: Params$Resource$Players$Get, callback: BodyResponseCallback<Schema$Player>): void;
get(callback: BodyResponseCallback<Schema$Player>): void;
/**
* games.players.list
* @desc Get the collection of players for the currently authenticated user.
* @alias games.players.list
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.collection Collection of players being retrieved
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {integer=} params.maxResults The maximum number of player resources to return in the response, used for paging. For any response, the actual number of player resources returned may be less than the specified maxResults.
* @param {string=} params.pageToken The token returned by the previous request.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list(params?: Params$Resource$Players$List, options?: MethodOptions): GaxiosPromise<Schema$PlayerListResponse>;
list(params: Params$Resource$Players$List, options: MethodOptions | BodyResponseCallback<Schema$PlayerListResponse>, callback: BodyResponseCallback<Schema$PlayerListResponse>): void;
list(params: Params$Resource$Players$List, callback: BodyResponseCallback<Schema$PlayerListResponse>): void;
list(callback: BodyResponseCallback<Schema$PlayerListResponse>): void;
}
interface Params$Resource$Players$Get extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* A player ID. A value of me may be used in place of the authenticated
* player's ID.
*/
playerId?: string;
}
interface Params$Resource$Players$List extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* Collection of players being retrieved
*/
collection?: string;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The maximum number of player resources to return in the response, used
* for paging. For any response, the actual number of player resources
* returned may be less than the specified maxResults.
*/
maxResults?: number;
/**
* The token returned by the previous request.
*/
pageToken?: string;
}
class Resource$Pushtokens {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* games.pushtokens.remove
* @desc Removes a push token for the current user and application. Removing
* a non-existent push token will report success.
* @alias games.pushtokens.remove
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {().PushTokenId} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
remove(params?: Params$Resource$Pushtokens$Remove, options?: MethodOptions): GaxiosPromise<void>;
remove(params: Params$Resource$Pushtokens$Remove, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void;
remove(params: Params$Resource$Pushtokens$Remove, callback: BodyResponseCallback<void>): void;
remove(callback: BodyResponseCallback<void>): void;
/**
* games.pushtokens.update
* @desc Registers a push token for the current user and application.
* @alias games.pushtokens.update
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {().PushToken} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
update(params?: Params$Resource$Pushtokens$Update, options?: MethodOptions): GaxiosPromise<void>;
update(params: Params$Resource$Pushtokens$Update, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void;
update(params: Params$Resource$Pushtokens$Update, callback: BodyResponseCallback<void>): void;
update(callback: BodyResponseCallback<void>): void;
}
interface Params$Resource$Pushtokens$Remove extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* Request body metadata
*/
requestBody?: Schema$PushTokenId;
}
interface Params$Resource$Pushtokens$Update extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* Request body metadata
*/
requestBody?: Schema$PushToken;
}
class Resource$Questmilestones {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* games.questMilestones.claim
* @desc Report that a reward for the milestone corresponding to milestoneId
* for the quest corresponding to questId has been claimed by the currently
* authorized user.
* @alias games.questMilestones.claim
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.milestoneId The ID of the milestone.
* @param {string} params.questId The ID of the quest.
* @param {string} params.requestId A numeric ID to ensure that the request is handled correctly across retries. Your client application must generate this ID randomly.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
claim(params?: Params$Resource$Questmilestones$Claim, options?: MethodOptions): GaxiosPromise<void>;
claim(params: Params$Resource$Questmilestones$Claim, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void;
claim(params: Params$Resource$Questmilestones$Claim, callback: BodyResponseCallback<void>): void;
claim(callback: BodyResponseCallback<void>): void;
}
interface Params$Resource$Questmilestones$Claim extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The ID of the milestone.
*/
milestoneId?: string;
/**
* The ID of the quest.
*/
questId?: string;
/**
* A numeric ID to ensure that the request is handled correctly across
* retries. Your client application must generate this ID randomly.
*/
requestId?: string;
}
class Resource$Quests {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* games.quests.accept
* @desc Indicates that the currently authorized user will participate in
* the quest.
* @alias games.quests.accept
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {string} params.questId The ID of the quest.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
accept(params?: Params$Resource$Quests$Accept, options?: MethodOptions): GaxiosPromise<Schema$Quest>;
accept(params: Params$Resource$Quests$Accept, options: MethodOptions | BodyResponseCallback<Schema$Quest>, callback: BodyResponseCallback<Schema$Quest>): void;
accept(params: Params$Resource$Quests$Accept, callback: BodyResponseCallback<Schema$Quest>): void;
accept(callback: BodyResponseCallback<Schema$Quest>): void;
/**
* games.quests.list
* @desc Get a list of quests for your application and the currently
* authenticated player.
* @alias games.quests.list
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {integer=} params.maxResults The maximum number of quest resources to return in the response, used for paging. For any response, the actual number of quest resources returned may be less than the specified maxResults. Acceptable values are 1 to 50, inclusive. (Default: 50).
* @param {string=} params.pageToken The token returned by the previous request.
* @param {string} params.playerId A player ID. A value of me may be used in place of the authenticated player's ID.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list(params?: Params$Resource$Quests$List, options?: MethodOptions): GaxiosPromise<Schema$QuestListResponse>;
list(params: Params$Resource$Quests$List, options: MethodOptions | BodyResponseCallback<Schema$QuestListResponse>, callback: BodyResponseCallback<Schema$QuestListResponse>): void;
list(params: Params$Resource$Quests$List, callback: BodyResponseCallback<Schema$QuestListResponse>): void;
list(callback: BodyResponseCallback<Schema$QuestListResponse>): void;
}
interface Params$Resource$Quests$Accept extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The ID of the quest.
*/
questId?: string;
}
interface Params$Resource$Quests$List extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The maximum number of quest resources to return in the response, used for
* paging. For any response, the actual number of quest resources returned
* may be less than the specified maxResults. Acceptable values are 1 to 50,
* inclusive. (Default: 50).
*/
maxResults?: number;
/**
* The token returned by the previous request.
*/
pageToken?: string;
/**
* A player ID. A value of me may be used in place of the authenticated
* player's ID.
*/
playerId?: string;
}
class Resource$Revisions {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* games.revisions.check
* @desc Checks whether the games client is out of date.
* @alias games.revisions.check
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.clientRevision The revision of the client SDK used by your application. Format: [PLATFORM_TYPE]:[VERSION_NUMBER]. Possible values of PLATFORM_TYPE are: - "ANDROID" - Client is running the Android SDK. - "IOS" - Client is running the iOS SDK. - "WEB_APP" - Client is running as a Web App.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
check(params?: Params$Resource$Revisions$Check, options?: MethodOptions): GaxiosPromise<Schema$RevisionCheckResponse>;
check(params: Params$Resource$Revisions$Check, options: MethodOptions | BodyResponseCallback<Schema$RevisionCheckResponse>, callback: BodyResponseCallback<Schema$RevisionCheckResponse>): void;
check(params: Params$Resource$Revisions$Check, callback: BodyResponseCallback<Schema$RevisionCheckResponse>): void;
check(callback: BodyResponseCallback<Schema$RevisionCheckResponse>): void;
}
interface Params$Resource$Revisions$Check extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The revision of the client SDK used by your application. Format:
* [PLATFORM_TYPE]:[VERSION_NUMBER]. Possible values of PLATFORM_TYPE are:
* - "ANDROID" - Client is running the Android SDK. - "IOS" - Client is
* running the iOS SDK. - "WEB_APP" - Client is running as a Web App.
*/
clientRevision?: string;
}
class Resource$Rooms {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* games.rooms.create
* @desc Create a room. For internal use by the Games SDK only. Calling this
* method directly is unsupported.
* @alias games.rooms.create
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {().RoomCreateRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
create(params?: Params$Resource$Rooms$Create, options?: MethodOptions): GaxiosPromise<Schema$Room>;
create(params: Params$Resource$Rooms$Create, options: MethodOptions | BodyResponseCallback<Schema$Room>, callback: BodyResponseCallback<Schema$Room>): void;
create(params: Params$Resource$Rooms$Create, callback: BodyResponseCallback<Schema$Room>): void;
create(callback: BodyResponseCallback<Schema$Room>): void;
/**
* games.rooms.decline
* @desc Decline an invitation to join a room. For internal use by the Games
* SDK only. Calling this method directly is unsupported.
* @alias games.rooms.decline
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {string} params.roomId The ID of the room.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
decline(params?: Params$Resource$Rooms$Decline, options?: MethodOptions): GaxiosPromise<Schema$Room>;
decline(params: Params$Resource$Rooms$Decline, options: MethodOptions | BodyResponseCallback<Schema$Room>, callback: BodyResponseCallback<Schema$Room>): void;
decline(params: Params$Resource$Rooms$Decline, callback: BodyResponseCallback<Schema$Room>): void;
decline(callback: BodyResponseCallback<Schema$Room>): void;
/**
* games.rooms.dismiss
* @desc Dismiss an invitation to join a room. For internal use by the Games
* SDK only. Calling this method directly is unsupported.
* @alias games.rooms.dismiss
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.roomId The ID of the room.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
dismiss(params?: Params$Resource$Rooms$Dismiss, options?: MethodOptions): GaxiosPromise<void>;
dismiss(params: Params$Resource$Rooms$Dismiss, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void;
dismiss(params: Params$Resource$Rooms$Dismiss, callback: BodyResponseCallback<void>): void;
dismiss(callback: BodyResponseCallback<void>): void;
/**
* games.rooms.get
* @desc Get the data for a room.
* @alias games.rooms.get
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {string} params.roomId The ID of the room.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get(params?: Params$Resource$Rooms$Get, options?: MethodOptions): GaxiosPromise<Schema$Room>;
get(params: Params$Resource$Rooms$Get, options: MethodOptions | BodyResponseCallback<Schema$Room>, callback: BodyResponseCallback<Schema$Room>): void;
get(params: Params$Resource$Rooms$Get, callback: BodyResponseCallback<Schema$Room>): void;
get(callback: BodyResponseCallback<Schema$Room>): void;
/**
* games.rooms.join
* @desc Join a room. For internal use by the Games SDK only. Calling this
* method directly is unsupported.
* @alias games.rooms.join
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {string} params.roomId The ID of the room.
* @param {().RoomJoinRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
join(params?: Params$Resource$Rooms$Join, options?: MethodOptions): GaxiosPromise<Schema$Room>;
join(params: Params$Resource$Rooms$Join, options: MethodOptions | BodyResponseCallback<Schema$Room>, callback: BodyResponseCallback<Schema$Room>): void;
join(params: Params$Resource$Rooms$Join, callback: BodyResponseCallback<Schema$Room>): void;
join(callback: BodyResponseCallback<Schema$Room>): void;
/**
* games.rooms.leave
* @desc Leave a room. For internal use by the Games SDK only. Calling this
* method directly is unsupported.
* @alias games.rooms.leave
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {string} params.roomId The ID of the room.
* @param {().RoomLeaveRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
leave(params?: Params$Resource$Rooms$Leave, options?: MethodOptions): GaxiosPromise<Schema$Room>;
leave(params: Params$Resource$Rooms$Leave, options: MethodOptions | BodyResponseCallback<Schema$Room>, callback: BodyResponseCallback<Schema$Room>): void;
leave(params: Params$Resource$Rooms$Leave, callback: BodyResponseCallback<Schema$Room>): void;
leave(callback: BodyResponseCallback<Schema$Room>): void;
/**
* games.rooms.list
* @desc Returns invitations to join rooms.
* @alias games.rooms.list
* @memberOf! ()
*
* @param {object=} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {integer=} params.maxResults The maximum number of rooms to return in the response, used for paging. For any response, the actual number of rooms to return may be less than the specified maxResults.
* @param {string=} params.pageToken The token returned by the previous request.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list(params?: Params$Resource$Rooms$List, options?: MethodOptions): GaxiosPromise<Schema$RoomList>;
list(params: Params$Resource$Rooms$List, options: MethodOptions | BodyResponseCallback<Schema$RoomList>, callback: BodyResponseCallback<Schema$RoomList>): void;
list(params: Params$Resource$Rooms$List, callback: BodyResponseCallback<Schema$RoomList>): void;
list(callback: BodyResponseCallback<Schema$RoomList>): void;
/**
* games.rooms.reportStatus
* @desc Updates sent by a client reporting the status of peers in a room.
* For internal use by the Games SDK only. Calling this method directly is
* unsupported.
* @alias games.rooms.reportStatus
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {string} params.roomId The ID of the room.
* @param {().RoomP2PStatuses} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
reportStatus(params?: Params$Resource$Rooms$Reportstatus, options?: MethodOptions): GaxiosPromise<Schema$RoomStatus>;
reportStatus(params: Params$Resource$Rooms$Reportstatus, options: MethodOptions | BodyResponseCallback<Schema$RoomStatus>, callback: BodyResponseCallback<Schema$RoomStatus>): void;
reportStatus(params: Params$Resource$Rooms$Reportstatus, callback: BodyResponseCallback<Schema$RoomStatus>): void;
reportStatus(callback: BodyResponseCallback<Schema$RoomStatus>): void;
}
interface Params$Resource$Rooms$Create extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* Request body metadata
*/
requestBody?: Schema$RoomCreateRequest;
}
interface Params$Resource$Rooms$Decline extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The ID of the room.
*/
roomId?: string;
}
interface Params$Resource$Rooms$Dismiss extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The ID of the room.
*/
roomId?: string;
}
interface Params$Resource$Rooms$Get extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The ID of the room.
*/
roomId?: string;
}
interface Params$Resource$Rooms$Join extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The ID of the room.
*/
roomId?: string;
/**
* Request body metadata
*/
requestBody?: Schema$RoomJoinRequest;
}
interface Params$Resource$Rooms$Leave extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The ID of the room.
*/
roomId?: string;
/**
* Request body metadata
*/
requestBody?: Schema$RoomLeaveRequest;
}
interface Params$Resource$Rooms$List extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The maximum number of rooms to return in the response, used for paging.
* For any response, the actual number of rooms to return may be less than
* the specified maxResults.
*/
maxResults?: number;
/**
* The token returned by the previous request.
*/
pageToken?: string;
}
interface Params$Resource$Rooms$Reportstatus extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The ID of the room.
*/
roomId?: string;
/**
* Request body metadata
*/
requestBody?: Schema$RoomP2PStatuses;
}
class Resource$Scores {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* games.scores.get
* @desc Get high scores, and optionally ranks, in leaderboards for the
* currently authenticated player. For a specific time span, leaderboardId
* can be set to ALL to retrieve data for all leaderboards in a given time
* span. NOTE: You cannot ask for 'ALL' leaderboards and 'ALL' timeSpans in
* the same request; only one parameter may be set to 'ALL'.
* @alias games.scores.get
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.includeRankType The types of ranks to return. If the parameter is omitted, no ranks will be returned.
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {string} params.leaderboardId The ID of the leaderboard. Can be set to 'ALL' to retrieve data for all leaderboards for this application.
* @param {integer=} params.maxResults The maximum number of leaderboard scores to return in the response. For any response, the actual number of leaderboard scores returned may be less than the specified maxResults.
* @param {string=} params.pageToken The token returned by the previous request.
* @param {string} params.playerId A player ID. A value of me may be used in place of the authenticated player's ID.
* @param {string} params.timeSpan The time span for the scores and ranks you're requesting.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get(params?: Params$Resource$Scores$Get, options?: MethodOptions): GaxiosPromise<Schema$PlayerLeaderboardScoreListResponse>;
get(params: Params$Resource$Scores$Get, options: MethodOptions | BodyResponseCallback<Schema$PlayerLeaderboardScoreListResponse>, callback: BodyResponseCallback<Schema$PlayerLeaderboardScoreListResponse>): void;
get(params: Params$Resource$Scores$Get, callback: BodyResponseCallback<Schema$PlayerLeaderboardScoreListResponse>): void;
get(callback: BodyResponseCallback<Schema$PlayerLeaderboardScoreListResponse>): void;
/**
* games.scores.list
* @desc Lists the scores in a leaderboard, starting from the top.
* @alias games.scores.list
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.collection The collection of scores you're requesting.
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {string} params.leaderboardId The ID of the leaderboard.
* @param {integer=} params.maxResults The maximum number of leaderboard scores to return in the response. For any response, the actual number of leaderboard scores returned may be less than the specified maxResults.
* @param {string=} params.pageToken The token returned by the previous request.
* @param {string} params.timeSpan The time span for the scores and ranks you're requesting.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list(params?: Params$Resource$Scores$List, options?: MethodOptions): GaxiosPromise<Schema$LeaderboardScores>;
list(params: Params$Resource$Scores$List, options: MethodOptions | BodyResponseCallback<Schema$LeaderboardScores>, callback: BodyResponseCallback<Schema$LeaderboardScores>): void;
list(params: Params$Resource$Scores$List, callback: BodyResponseCallback<Schema$LeaderboardScores>): void;
list(callback: BodyResponseCallback<Schema$LeaderboardScores>): void;
/**
* games.scores.listWindow
* @desc Lists the scores in a leaderboard around (and including) a player's
* score.
* @alias games.scores.listWindow
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.collection The collection of scores you're requesting.
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {string} params.leaderboardId The ID of the leaderboard.
* @param {integer=} params.maxResults The maximum number of leaderboard scores to return in the response. For any response, the actual number of leaderboard scores returned may be less than the specified maxResults.
* @param {string=} params.pageToken The token returned by the previous request.
* @param {integer=} params.resultsAbove The preferred number of scores to return above the player's score. More scores may be returned if the player is at the bottom of the leaderboard; fewer may be returned if the player is at the top. Must be less than or equal to maxResults.
* @param {boolean=} params.returnTopIfAbsent True if the top scores should be returned when the player is not in the leaderboard. Defaults to true.
* @param {string} params.timeSpan The time span for the scores and ranks you're requesting.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
listWindow(params?: Params$Resource$Scores$Listwindow, options?: MethodOptions): GaxiosPromise<Schema$LeaderboardScores>;
listWindow(params: Params$Resource$Scores$Listwindow, options: MethodOptions | BodyResponseCallback<Schema$LeaderboardScores>, callback: BodyResponseCallback<Schema$LeaderboardScores>): void;
listWindow(params: Params$Resource$Scores$Listwindow, callback: BodyResponseCallback<Schema$LeaderboardScores>): void;
listWindow(callback: BodyResponseCallback<Schema$LeaderboardScores>): void;
/**
* games.scores.submit
* @desc Submits a score to the specified leaderboard.
* @alias games.scores.submit
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {string} params.leaderboardId The ID of the leaderboard.
* @param {string} params.score The score you're submitting. The submitted score is ignored if it is worse than a previously submitted score, where worse depends on the leaderboard sort order. The meaning of the score value depends on the leaderboard format type. For fixed-point, the score represents the raw value. For time, the score represents elapsed time in milliseconds. For currency, the score represents a value in micro units.
* @param {string=} params.scoreTag Additional information about the score you're submitting. Values must contain no more than 64 URI-safe characters as defined by section 2.3 of RFC 3986.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
submit(params?: Params$Resource$Scores$Submit, options?: MethodOptions): GaxiosPromise<Schema$PlayerScoreResponse>;
submit(params: Params$Resource$Scores$Submit, options: MethodOptions | BodyResponseCallback<Schema$PlayerScoreResponse>, callback: BodyResponseCallback<Schema$PlayerScoreResponse>): void;
submit(params: Params$Resource$Scores$Submit, callback: BodyResponseCallback<Schema$PlayerScoreResponse>): void;
submit(callback: BodyResponseCallback<Schema$PlayerScoreResponse>): void;
/**
* games.scores.submitMultiple
* @desc Submits multiple scores to leaderboards.
* @alias games.scores.submitMultiple
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {().PlayerScoreSubmissionList} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
submitMultiple(params?: Params$Resource$Scores$Submitmultiple, options?: MethodOptions): GaxiosPromise<Schema$PlayerScoreListResponse>;
submitMultiple(params: Params$Resource$Scores$Submitmultiple, options: MethodOptions | BodyResponseCallback<Schema$PlayerScoreListResponse>, callback: BodyResponseCallback<Schema$PlayerScoreListResponse>): void;
submitMultiple(params: Params$Resource$Scores$Submitmultiple, callback: BodyResponseCallback<Schema$PlayerScoreListResponse>): void;
submitMultiple(callback: BodyResponseCallback<Schema$PlayerScoreListResponse>): void;
}
interface Params$Resource$Scores$Get extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The types of ranks to return. If the parameter is omitted, no ranks will
* be returned.
*/
includeRankType?: string;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The ID of the leaderboard. Can be set to 'ALL' to retrieve data for all
* leaderboards for this application.
*/
leaderboardId?: string;
/**
* The maximum number of leaderboard scores to return in the response. For
* any response, the actual number of leaderboard scores returned may be
* less than the specified maxResults.
*/
maxResults?: number;
/**
* The token returned by the previous request.
*/
pageToken?: string;
/**
* A player ID. A value of me may be used in place of the authenticated
* player's ID.
*/
playerId?: string;
/**
* The time span for the scores and ranks you're requesting.
*/
timeSpan?: string;
}
interface Params$Resource$Scores$List extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The collection of scores you're requesting.
*/
collection?: string;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The ID of the leaderboard.
*/
leaderboardId?: string;
/**
* The maximum number of leaderboard scores to return in the response. For
* any response, the actual number of leaderboard scores returned may be
* less than the specified maxResults.
*/
maxResults?: number;
/**
* The token returned by the previous request.
*/
pageToken?: string;
/**
* The time span for the scores and ranks you're requesting.
*/
timeSpan?: string;
}
interface Params$Resource$Scores$Listwindow extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The collection of scores you're requesting.
*/
collection?: string;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The ID of the leaderboard.
*/
leaderboardId?: string;
/**
* The maximum number of leaderboard scores to return in the response. For
* any response, the actual number of leaderboard scores returned may be
* less than the specified maxResults.
*/
maxResults?: number;
/**
* The token returned by the previous request.
*/
pageToken?: string;
/**
* The preferred number of scores to return above the player's score. More
* scores may be returned if the player is at the bottom of the leaderboard;
* fewer may be returned if the player is at the top. Must be less than or
* equal to maxResults.
*/
resultsAbove?: number;
/**
* True if the top scores should be returned when the player is not in the
* leaderboard. Defaults to true.
*/
returnTopIfAbsent?: boolean;
/**
* The time span for the scores and ranks you're requesting.
*/
timeSpan?: string;
}
interface Params$Resource$Scores$Submit extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The ID of the leaderboard.
*/
leaderboardId?: string;
/**
* The score you're submitting. The submitted score is ignored if it is
* worse than a previously submitted score, where worse depends on the
* leaderboard sort order. The meaning of the score value depends on the
* leaderboard format type. For fixed-point, the score represents the raw
* value. For time, the score represents elapsed time in milliseconds. For
* currency, the score represents a value in micro units.
*/
score?: string;
/**
* Additional information about the score you're submitting. Values must
* contain no more than 64 URI-safe characters as defined by section 2.3 of
* RFC 3986.
*/
scoreTag?: string;
}
interface Params$Resource$Scores$Submitmultiple extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* Request body metadata
*/
requestBody?: Schema$PlayerScoreSubmissionList;
}
class Resource$Snapshots {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* games.snapshots.get
* @desc Retrieves the metadata for a given snapshot ID.
* @alias games.snapshots.get
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {string} params.snapshotId The ID of the snapshot.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get(params?: Params$Resource$Snapshots$Get, options?: MethodOptions): GaxiosPromise<Schema$Snapshot>;
get(params: Params$Resource$Snapshots$Get, options: MethodOptions | BodyResponseCallback<Schema$Snapshot>, callback: BodyResponseCallback<Schema$Snapshot>): void;
get(params: Params$Resource$Snapshots$Get, callback: BodyResponseCallback<Schema$Snapshot>): void;
get(callback: BodyResponseCallback<Schema$Snapshot>): void;
/**
* games.snapshots.list
* @desc Retrieves a list of snapshots created by your application for the
* player corresponding to the player ID.
* @alias games.snapshots.list
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {integer=} params.maxResults The maximum number of snapshot resources to return in the response, used for paging. For any response, the actual number of snapshot resources returned may be less than the specified maxResults.
* @param {string=} params.pageToken The token returned by the previous request.
* @param {string} params.playerId A player ID. A value of me may be used in place of the authenticated player's ID.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list(params?: Params$Resource$Snapshots$List, options?: MethodOptions): GaxiosPromise<Schema$SnapshotListResponse>;
list(params: Params$Resource$Snapshots$List, options: MethodOptions | BodyResponseCallback<Schema$SnapshotListResponse>, callback: BodyResponseCallback<Schema$SnapshotListResponse>): void;
list(params: Params$Resource$Snapshots$List, callback: BodyResponseCallback<Schema$SnapshotListResponse>): void;
list(callback: BodyResponseCallback<Schema$SnapshotListResponse>): void;
}
interface Params$Resource$Snapshots$Get extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The ID of the snapshot.
*/
snapshotId?: string;
}
interface Params$Resource$Snapshots$List extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The maximum number of snapshot resources to return in the response, used
* for paging. For any response, the actual number of snapshot resources
* returned may be less than the specified maxResults.
*/
maxResults?: number;
/**
* The token returned by the previous request.
*/
pageToken?: string;
/**
* A player ID. A value of me may be used in place of the authenticated
* player's ID.
*/
playerId?: string;
}
class Resource$Turnbasedmatches {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* games.turnBasedMatches.cancel
* @desc Cancel a turn-based match.
* @alias games.turnBasedMatches.cancel
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.matchId The ID of the match.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
cancel(params?: Params$Resource$Turnbasedmatches$Cancel, options?: MethodOptions): GaxiosPromise<void>;
cancel(params: Params$Resource$Turnbasedmatches$Cancel, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void;
cancel(params: Params$Resource$Turnbasedmatches$Cancel, callback: BodyResponseCallback<void>): void;
cancel(callback: BodyResponseCallback<void>): void;
/**
* games.turnBasedMatches.create
* @desc Create a turn-based match.
* @alias games.turnBasedMatches.create
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {().TurnBasedMatchCreateRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
create(params?: Params$Resource$Turnbasedmatches$Create, options?: MethodOptions): GaxiosPromise<Schema$TurnBasedMatch>;
create(params: Params$Resource$Turnbasedmatches$Create, options: MethodOptions | BodyResponseCallback<Schema$TurnBasedMatch>, callback: BodyResponseCallback<Schema$TurnBasedMatch>): void;
create(params: Params$Resource$Turnbasedmatches$Create, callback: BodyResponseCallback<Schema$TurnBasedMatch>): void;
create(callback: BodyResponseCallback<Schema$TurnBasedMatch>): void;
/**
* games.turnBasedMatches.decline
* @desc Decline an invitation to play a turn-based match.
* @alias games.turnBasedMatches.decline
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {string} params.matchId The ID of the match.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
decline(params?: Params$Resource$Turnbasedmatches$Decline, options?: MethodOptions): GaxiosPromise<Schema$TurnBasedMatch>;
decline(params: Params$Resource$Turnbasedmatches$Decline, options: MethodOptions | BodyResponseCallback<Schema$TurnBasedMatch>, callback: BodyResponseCallback<Schema$TurnBasedMatch>): void;
decline(params: Params$Resource$Turnbasedmatches$Decline, callback: BodyResponseCallback<Schema$TurnBasedMatch>): void;
decline(callback: BodyResponseCallback<Schema$TurnBasedMatch>): void;
/**
* games.turnBasedMatches.dismiss
* @desc Dismiss a turn-based match from the match list. The match will no
* longer show up in the list and will not generate notifications.
* @alias games.turnBasedMatches.dismiss
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.matchId The ID of the match.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
dismiss(params?: Params$Resource$Turnbasedmatches$Dismiss, options?: MethodOptions): GaxiosPromise<void>;
dismiss(params: Params$Resource$Turnbasedmatches$Dismiss, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void;
dismiss(params: Params$Resource$Turnbasedmatches$Dismiss, callback: BodyResponseCallback<void>): void;
dismiss(callback: BodyResponseCallback<void>): void;
/**
* games.turnBasedMatches.finish
* @desc Finish a turn-based match. Each player should make this call once,
* after all results are in. Only the player whose turn it is may make the
* first call to Finish, and can pass in the final match state.
* @alias games.turnBasedMatches.finish
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {string} params.matchId The ID of the match.
* @param {().TurnBasedMatchResults} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
finish(params?: Params$Resource$Turnbasedmatches$Finish, options?: MethodOptions): GaxiosPromise<Schema$TurnBasedMatch>;
finish(params: Params$Resource$Turnbasedmatches$Finish, options: MethodOptions | BodyResponseCallback<Schema$TurnBasedMatch>, callback: BodyResponseCallback<Schema$TurnBasedMatch>): void;
finish(params: Params$Resource$Turnbasedmatches$Finish, callback: BodyResponseCallback<Schema$TurnBasedMatch>): void;
finish(callback: BodyResponseCallback<Schema$TurnBasedMatch>): void;
/**
* games.turnBasedMatches.get
* @desc Get the data for a turn-based match.
* @alias games.turnBasedMatches.get
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {boolean=} params.includeMatchData Get match data along with metadata.
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {string} params.matchId The ID of the match.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get(params?: Params$Resource$Turnbasedmatches$Get, options?: MethodOptions): GaxiosPromise<Schema$TurnBasedMatch>;
get(params: Params$Resource$Turnbasedmatches$Get, options: MethodOptions | BodyResponseCallback<Schema$TurnBasedMatch>, callback: BodyResponseCallback<Schema$TurnBasedMatch>): void;
get(params: Params$Resource$Turnbasedmatches$Get, callback: BodyResponseCallback<Schema$TurnBasedMatch>): void;
get(callback: BodyResponseCallback<Schema$TurnBasedMatch>): void;
/**
* games.turnBasedMatches.join
* @desc Join a turn-based match.
* @alias games.turnBasedMatches.join
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {string} params.matchId The ID of the match.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
join(params?: Params$Resource$Turnbasedmatches$Join, options?: MethodOptions): GaxiosPromise<Schema$TurnBasedMatch>;
join(params: Params$Resource$Turnbasedmatches$Join, options: MethodOptions | BodyResponseCallback<Schema$TurnBasedMatch>, callback: BodyResponseCallback<Schema$TurnBasedMatch>): void;
join(params: Params$Resource$Turnbasedmatches$Join, callback: BodyResponseCallback<Schema$TurnBasedMatch>): void;
join(callback: BodyResponseCallback<Schema$TurnBasedMatch>): void;
/**
* games.turnBasedMatches.leave
* @desc Leave a turn-based match when it is not the current player's turn,
* without canceling the match.
* @alias games.turnBasedMatches.leave
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {string} params.matchId The ID of the match.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
leave(params?: Params$Resource$Turnbasedmatches$Leave, options?: MethodOptions): GaxiosPromise<Schema$TurnBasedMatch>;
leave(params: Params$Resource$Turnbasedmatches$Leave, options: MethodOptions | BodyResponseCallback<Schema$TurnBasedMatch>, callback: BodyResponseCallback<Schema$TurnBasedMatch>): void;
leave(params: Params$Resource$Turnbasedmatches$Leave, callback: BodyResponseCallback<Schema$TurnBasedMatch>): void;
leave(callback: BodyResponseCallback<Schema$TurnBasedMatch>): void;
/**
* games.turnBasedMatches.leaveTurn
* @desc Leave a turn-based match during the current player's turn, without
* canceling the match.
* @alias games.turnBasedMatches.leaveTurn
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {string} params.matchId The ID of the match.
* @param {integer} params.matchVersion The version of the match being updated.
* @param {string=} params.pendingParticipantId The ID of another participant who should take their turn next. If not set, the match will wait for other player(s) to join via automatching; this is only valid if automatch criteria is set on the match with remaining slots for automatched players.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
leaveTurn(params?: Params$Resource$Turnbasedmatches$Leaveturn, options?: MethodOptions): GaxiosPromise<Schema$TurnBasedMatch>;
leaveTurn(params: Params$Resource$Turnbasedmatches$Leaveturn, options: MethodOptions | BodyResponseCallback<Schema$TurnBasedMatch>, callback: BodyResponseCallback<Schema$TurnBasedMatch>): void;
leaveTurn(params: Params$Resource$Turnbasedmatches$Leaveturn, callback: BodyResponseCallback<Schema$TurnBasedMatch>): void;
leaveTurn(callback: BodyResponseCallback<Schema$TurnBasedMatch>): void;
/**
* games.turnBasedMatches.list
* @desc Returns turn-based matches the player is or was involved in.
* @alias games.turnBasedMatches.list
* @memberOf! ()
*
* @param {object=} params Parameters for request
* @param {boolean=} params.includeMatchData True if match data should be returned in the response. Note that not all data will necessarily be returned if include_match_data is true; the server may decide to only return data for some of the matches to limit download size for the client. The remainder of the data for these matches will be retrievable on request.
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {integer=} params.maxCompletedMatches The maximum number of completed or canceled matches to return in the response. If not set, all matches returned could be completed or canceled.
* @param {integer=} params.maxResults The maximum number of matches to return in the response, used for paging. For any response, the actual number of matches to return may be less than the specified maxResults.
* @param {string=} params.pageToken The token returned by the previous request.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list(params?: Params$Resource$Turnbasedmatches$List, options?: MethodOptions): GaxiosPromise<Schema$TurnBasedMatchList>;
list(params: Params$Resource$Turnbasedmatches$List, options: MethodOptions | BodyResponseCallback<Schema$TurnBasedMatchList>, callback: BodyResponseCallback<Schema$TurnBasedMatchList>): void;
list(params: Params$Resource$Turnbasedmatches$List, callback: BodyResponseCallback<Schema$TurnBasedMatchList>): void;
list(callback: BodyResponseCallback<Schema$TurnBasedMatchList>): void;
/**
* games.turnBasedMatches.rematch
* @desc Create a rematch of a match that was previously completed, with the
* same participants. This can be called by only one player on a match still
* in their list; the player must have called Finish first. Returns the
* newly created match; it will be the caller's turn.
* @alias games.turnBasedMatches.rematch
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {string} params.matchId The ID of the match.
* @param {string=} params.requestId A randomly generated numeric ID for each request specified by the caller. This number is used at the server to ensure that the request is handled correctly across retries.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
rematch(params?: Params$Resource$Turnbasedmatches$Rematch, options?: MethodOptions): GaxiosPromise<Schema$TurnBasedMatchRematch>;
rematch(params: Params$Resource$Turnbasedmatches$Rematch, options: MethodOptions | BodyResponseCallback<Schema$TurnBasedMatchRematch>, callback: BodyResponseCallback<Schema$TurnBasedMatchRematch>): void;
rematch(params: Params$Resource$Turnbasedmatches$Rematch, callback: BodyResponseCallback<Schema$TurnBasedMatchRematch>): void;
rematch(callback: BodyResponseCallback<Schema$TurnBasedMatchRematch>): void;
/**
* games.turnBasedMatches.sync
* @desc Returns turn-based matches the player is or was involved in that
* changed since the last sync call, with the least recent changes coming
* first. Matches that should be removed from the local cache will have a
* status of MATCH_DELETED.
* @alias games.turnBasedMatches.sync
* @memberOf! ()
*
* @param {object=} params Parameters for request
* @param {boolean=} params.includeMatchData True if match data should be returned in the response. Note that not all data will necessarily be returned if include_match_data is true; the server may decide to only return data for some of the matches to limit download size for the client. The remainder of the data for these matches will be retrievable on request.
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {integer=} params.maxCompletedMatches The maximum number of completed or canceled matches to return in the response. If not set, all matches returned could be completed or canceled.
* @param {integer=} params.maxResults The maximum number of matches to return in the response, used for paging. For any response, the actual number of matches to return may be less than the specified maxResults.
* @param {string=} params.pageToken The token returned by the previous request.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
sync(params?: Params$Resource$Turnbasedmatches$Sync, options?: MethodOptions): GaxiosPromise<Schema$TurnBasedMatchSync>;
sync(params: Params$Resource$Turnbasedmatches$Sync, options: MethodOptions | BodyResponseCallback<Schema$TurnBasedMatchSync>, callback: BodyResponseCallback<Schema$TurnBasedMatchSync>): void;
sync(params: Params$Resource$Turnbasedmatches$Sync, callback: BodyResponseCallback<Schema$TurnBasedMatchSync>): void;
sync(callback: BodyResponseCallback<Schema$TurnBasedMatchSync>): void;
/**
* games.turnBasedMatches.takeTurn
* @desc Commit the results of a player turn.
* @alias games.turnBasedMatches.takeTurn
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.language The preferred language to use for strings returned by this method.
* @param {string} params.matchId The ID of the match.
* @param {().TurnBasedMatchTurn} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
takeTurn(params?: Params$Resource$Turnbasedmatches$Taketurn, options?: MethodOptions): GaxiosPromise<Schema$TurnBasedMatch>;
takeTurn(params: Params$Resource$Turnbasedmatches$Taketurn, options: MethodOptions | BodyResponseCallback<Schema$TurnBasedMatch>, callback: BodyResponseCallback<Schema$TurnBasedMatch>): void;
takeTurn(params: Params$Resource$Turnbasedmatches$Taketurn, callback: BodyResponseCallback<Schema$TurnBasedMatch>): void;
takeTurn(callback: BodyResponseCallback<Schema$TurnBasedMatch>): void;
}
interface Params$Resource$Turnbasedmatches$Cancel extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The ID of the match.
*/
matchId?: string;
}
interface Params$Resource$Turnbasedmatches$Create extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* Request body metadata
*/
requestBody?: Schema$TurnBasedMatchCreateRequest;
}
interface Params$Resource$Turnbasedmatches$Decline extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The ID of the match.
*/
matchId?: string;
}
interface Params$Resource$Turnbasedmatches$Dismiss extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The ID of the match.
*/
matchId?: string;
}
interface Params$Resource$Turnbasedmatches$Finish extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The ID of the match.
*/
matchId?: string;
/**
* Request body metadata
*/
requestBody?: Schema$TurnBasedMatchResults;
}
interface Params$Resource$Turnbasedmatches$Get extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* Get match data along with metadata.
*/
includeMatchData?: boolean;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The ID of the match.
*/
matchId?: string;
}
interface Params$Resource$Turnbasedmatches$Join extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The ID of the match.
*/
matchId?: string;
}
interface Params$Resource$Turnbasedmatches$Leave extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The ID of the match.
*/
matchId?: string;
}
interface Params$Resource$Turnbasedmatches$Leaveturn extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The ID of the match.
*/
matchId?: string;
/**
* The version of the match being updated.
*/
matchVersion?: number;
/**
* The ID of another participant who should take their turn next. If not
* set, the match will wait for other player(s) to join via automatching;
* this is only valid if automatch criteria is set on the match with
* remaining slots for automatched players.
*/
pendingParticipantId?: string;
}
interface Params$Resource$Turnbasedmatches$List extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* True if match data should be returned in the response. Note that not all
* data will necessarily be returned if include_match_data is true; the
* server may decide to only return data for some of the matches to limit
* download size for the client. The remainder of the data for these matches
* will be retrievable on request.
*/
includeMatchData?: boolean;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The maximum number of completed or canceled matches to return in the
* response. If not set, all matches returned could be completed or
* canceled.
*/
maxCompletedMatches?: number;
/**
* The maximum number of matches to return in the response, used for paging.
* For any response, the actual number of matches to return may be less than
* the specified maxResults.
*/
maxResults?: number;
/**
* The token returned by the previous request.
*/
pageToken?: string;
}
interface Params$Resource$Turnbasedmatches$Rematch extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The ID of the match.
*/
matchId?: string;
/**
* A randomly generated numeric ID for each request specified by the caller.
* This number is used at the server to ensure that the request is handled
* correctly across retries.
*/
requestId?: string;
}
interface Params$Resource$Turnbasedmatches$Sync extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* True if match data should be returned in the response. Note that not all
* data will necessarily be returned if include_match_data is true; the
* server may decide to only return data for some of the matches to limit
* download size for the client. The remainder of the data for these matches
* will be retrievable on request.
*/
includeMatchData?: boolean;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The maximum number of completed or canceled matches to return in the
* response. If not set, all matches returned could be completed or
* canceled.
*/
maxCompletedMatches?: number;
/**
* The maximum number of matches to return in the response, used for paging.
* For any response, the actual number of matches to return may be less than
* the specified maxResults.
*/
maxResults?: number;
/**
* The token returned by the previous request.
*/
pageToken?: string;
}
interface Params$Resource$Turnbasedmatches$Taketurn extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The preferred language to use for strings returned by this method.
*/
language?: string;
/**
* The ID of the match.
*/
matchId?: string;
/**
* Request body metadata
*/
requestBody?: Schema$TurnBasedMatchTurn;
}
} | the_stack |
import {IuploadfileList, IattributeList, stringToNum} from "../ICommon";
import {indexedColors} from "../common/constant";
import {LightenDarkenColor} from "../common/method";
class xmloperation {
/**
* @param tag Search xml tag name , div,title etc.
* @param file Xml string
* @return Xml element string
*/
protected getElementsByOneTag(tag:string, file:string):string[]{
//<a:[^/>: ]+?>.*?</a:[^/>: ]+?>
let readTagReg;
if(tag.indexOf("|")>-1){
let tags = tag.split("|"), tagsRegTxt="";
for(let i=0;i<tags.length;i++){
let t = tags[i];
tagsRegTxt += "|<"+ t +" [^>]+?[^/]>[\\s\\S]*?</"+ t +">|<"+ t +" [^>]+?/>|<"+ t +">[\\s\\S]*?</"+ t +">|<"+ t +"/>";
}
tagsRegTxt = tagsRegTxt.substr(1, tagsRegTxt.length);
readTagReg = new RegExp(tagsRegTxt, "g");
}
else{
readTagReg = new RegExp("<"+ tag +" [^>]+?[^/]>[\\s\\S]*?</"+ tag +">|<"+ tag +" [^>]+?/>|<"+ tag +">[\\s\\S]*?</"+ tag +">|<"+ tag +"/>", "g");
}
let ret = file.match(readTagReg);
if(ret==null){
return [];
}
else{
return ret;
}
}
}
export class ReadXml extends xmloperation{
originFile:IuploadfileList
constructor(files:IuploadfileList){
super();
this.originFile = files;
}
/**
* @param path Search xml tag group , div,title etc.
* @param fileName One of uploadfileList, uploadfileList is file group, {key:value}
* @return Xml element calss
*/
getElementsByTagName(path:string, fileName:string): Element[]{
let file = this.getFileByName(fileName);
let pathArr = path.split("/"), ret:string[] | string;
for(let key in pathArr){
let path = pathArr[key];
if(ret==undefined){
ret = this.getElementsByOneTag(path,file);
}
else{
if(ret instanceof Array){
let items:string[]=[];
for(let key in ret){
let item = ret[key];
items = items.concat(this.getElementsByOneTag(path,item));
}
ret = items;
}
else{
ret = this.getElementsByOneTag(path,ret);
}
}
}
let elements:Element[] = [];
for(let i=0;i<ret.length;i++){
let ele = new Element(ret[i]);
elements.push(ele);
}
return elements;
}
/**
* @param name One of uploadfileList's name, search for file by this parameter
* @retrun Select a file from uploadfileList
*/
private getFileByName(name:string):string{
for(let fileKey in this.originFile){
if(fileKey.indexOf(name)>-1){
return this.originFile[fileKey];
}
}
return "";
}
}
export class Element extends xmloperation {
elementString:string
attributeList:IattributeList
value:string
container:string
constructor(str:string){
super();
this.elementString = str;
this.setValue();
const readAttrReg = new RegExp('[a-zA-Z0-9_:]*?=".*?"', "g");
let attrList = this.container.match(readAttrReg);
this.attributeList = {};
if(attrList!=null){
for(let key in attrList){
let attrFull = attrList[key];
// let al= attrFull.split("=");
if(attrFull.length==0){
continue;
}
let attrKey = attrFull.substr(0, attrFull.indexOf('='));
let attrValue = attrFull.substr(attrFull.indexOf('=') + 1);
if(attrKey==null || attrValue==null ||attrKey.length==0 || attrValue.length==0){
continue;
}
this.attributeList[attrKey] = attrValue.substr(1, attrValue.length-2);
}
}
}
/**
* @param name Get attribute by key in element
* @return Single attribute
*/
get(name:string):string|number|boolean{
return this.attributeList[name];
}
/**
* @param tag Get elements by tag in elementString
* @return Element group
*/
getInnerElements(tag:string):Element[]{
let ret = this.getElementsByOneTag(tag,this.elementString);
let elements:Element[] = [];
for(let i=0;i<ret.length;i++){
let ele = new Element(ret[i]);
elements.push(ele);
}
if(elements.length==0){
return null;
}
return elements;
}
/**
* @desc get xml dom value and container, <container>value</container>
*/
private setValue(){
let str = this.elementString;
if(str.substr(str.length-2, 2)=="/>"){
this.value = "";
this.container = str;
}
else{
let firstTag = this.getFirstTag();
const firstTagReg = new RegExp("(<"+ firstTag +" [^>]+?[^/]>)([\\s\\S]*?)</"+ firstTag +">|(<"+ firstTag +">)([\\s\\S]*?)</"+ firstTag +">", "g");
let result = firstTagReg.exec(str);
if (result != null) {
if(result[1]!=null){
this.container = result[1];
this.value = result[2];
}
else{
this.container = result[3];
this.value = result[4];
}
}
}
}
/**
* @desc get xml dom first tag, <a><b></b></a>, get a
*/
private getFirstTag(){
let str = this.elementString;
let firstTag = str.substr(0, str.indexOf(' '));
if(firstTag=="" || firstTag.indexOf(">")>-1){
firstTag = str.substr(0, str.indexOf('>'));
}
firstTag = firstTag.substr(1,firstTag.length);
return firstTag;
}
}
export interface IStyleCollections {
[index:string]:Element[] | IattributeList
}
function combineIndexedColor(indexedColorsInner:Element[], indexedColors:IattributeList):IattributeList{
let ret:IattributeList = {};
if(indexedColorsInner==null || indexedColorsInner.length==0){
return indexedColors;
}
for(let key in indexedColors){
let value = indexedColors[key], kn = parseInt(key);
let inner = indexedColorsInner[kn];
if(inner==null){
ret[key] = value;
}
else{
let rgb = inner.attributeList.rgb;
ret[key] = rgb;
}
}
return ret;
}
//clrScheme:Element[]
export function getColor(color:Element, styles:IStyleCollections , type:string="g"){
let attrList = color.attributeList;
let clrScheme = styles["clrScheme"] as Element[];
let indexedColorsInner = styles["indexedColors"] as Element[];
let mruColorsInner = styles["mruColors"];
let indexedColorsList = combineIndexedColor(indexedColorsInner, indexedColors);
let indexed = attrList.indexed, rgb = attrList.rgb, theme = attrList.theme, tint = attrList.tint;
let bg;
if(indexed!=null){
let indexedNum = parseInt(indexed);
bg = indexedColorsList[indexedNum];
if(bg!=null){
bg = bg.substring(bg.length-6, bg.length);
bg = "#"+bg;
}
}
else if(rgb!=null){
rgb = rgb.substring(rgb.length-6, rgb.length);
bg = "#"+rgb;
}
else if(theme!=null){
let themeNum = parseInt(theme);
if(themeNum==0){
themeNum = 1;
}
else if(themeNum==1){
themeNum = 0;
}
else if(themeNum==2){
themeNum = 3;
}
else if(themeNum==3){
themeNum = 2;
}
let clrSchemeElement = clrScheme[themeNum];
if(clrSchemeElement!=null){
let clrs = clrSchemeElement.getInnerElements("a:sysClr|a:srgbClr");
if(clrs!=null){
let clr = clrs[0];
let clrAttrList = clr.attributeList;
// console.log(clr.container, );
if(clr.container.indexOf("sysClr")>-1){
// if(type=="g" && clrAttrList.val=="windowText"){
// bg = null;
// }
// else if((type=="t" || type=="b") && clrAttrList.val=="window"){
// bg = null;
// }
// else
if(clrAttrList.lastClr!=null){
bg = "#" + clrAttrList.lastClr;
}
else if(clrAttrList.val!=null){
bg = "#" + clrAttrList.val;
}
}
else if(clr.container.indexOf("srgbClr")>-1){
// console.log(clrAttrList.val);
bg = "#" + clrAttrList.val;
}
}
}
}
if(tint!=null){
let tintNum = parseFloat(tint);
if(bg!=null){
bg = LightenDarkenColor(bg, tintNum);
}
}
return bg;
}
/**
* @dom xml attribute object
* @attr attribute name
* @d if attribute is null, return default value
* @return attribute value
*/
export function getlineStringAttr(frpr:Element, attr:string):string{
let attrEle = frpr.getInnerElements(attr), value;
if(attrEle!=null && attrEle.length>0){
if(attr=="b" || attr=="i" || attr=="strike"){
value = "1";
}
else if(attr=="u"){
let v = attrEle[0].attributeList.val;
if(v=="double"){
value = "2";
}
else if(v=="singleAccounting"){
value = "3";
}
else if(v=="doubleAccounting"){
value = "4";
}
else{
value = "1";
}
}
else if(attr=="vertAlign"){
let v = attrEle[0].attributeList.val;
if(v=="subscript"){
value = "1";
}
else if(v=="superscript"){
value = "2";
}
}
else{
value = attrEle[0].attributeList.val;
}
}
return value;
} | the_stack |
// Pulled from https://github.com/facebook/react/blob/master/packages/react-dom/src/shared/possibleStandardNames.js
const possibleStandardNames = {
// HTML
accept: 'accept',
acceptcharset: 'acceptCharset',
'accept-charset': 'acceptCharset',
accesskey: 'accessKey',
action: 'action',
allowfullscreen: 'allowFullScreen',
alt: 'alt',
as: 'as',
async: 'async',
autocapitalize: 'autoCapitalize',
autocomplete: 'autoComplete',
autocorrect: 'autoCorrect',
autofocus: 'autoFocus',
autoplay: 'autoPlay',
autosave: 'autoSave',
capture: 'capture',
cellpadding: 'cellPadding',
cellspacing: 'cellSpacing',
challenge: 'challenge',
charset: 'charSet',
checked: 'checked',
children: 'children',
cite: 'cite',
class: 'className',
classid: 'classID',
classname: 'className',
cols: 'cols',
colspan: 'colSpan',
content: 'content',
contenteditable: 'contentEditable',
contextmenu: 'contextMenu',
controls: 'controls',
controlslist: 'controlsList',
coords: 'coords',
crossorigin: 'crossOrigin',
dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',
data: 'data',
datetime: 'dateTime',
default: 'default',
defaultchecked: 'defaultChecked',
defaultvalue: 'defaultValue',
defer: 'defer',
dir: 'dir',
disabled: 'disabled',
disablepictureinpicture: 'disablePictureInPicture',
disableremoteplayback: 'disableRemotePlayback',
download: 'download',
draggable: 'draggable',
enctype: 'encType',
enterkeyhint: 'enterKeyHint',
for: 'htmlFor',
form: 'form',
formmethod: 'formMethod',
formaction: 'formAction',
formenctype: 'formEncType',
formnovalidate: 'formNoValidate',
formtarget: 'formTarget',
frameborder: 'frameBorder',
headers: 'headers',
height: 'height',
hidden: 'hidden',
high: 'high',
href: 'href',
hreflang: 'hrefLang',
htmlfor: 'htmlFor',
httpequiv: 'httpEquiv',
'http-equiv': 'httpEquiv',
icon: 'icon',
id: 'id',
innerhtml: 'innerHTML',
inputmode: 'inputMode',
integrity: 'integrity',
is: 'is',
itemid: 'itemID',
itemprop: 'itemProp',
itemref: 'itemRef',
itemscope: 'itemScope',
itemtype: 'itemType',
keyparams: 'keyParams',
keytype: 'keyType',
kind: 'kind',
label: 'label',
lang: 'lang',
list: 'list',
loop: 'loop',
low: 'low',
manifest: 'manifest',
marginwidth: 'marginWidth',
marginheight: 'marginHeight',
max: 'max',
maxlength: 'maxLength',
media: 'media',
mediagroup: 'mediaGroup',
method: 'method',
min: 'min',
minlength: 'minLength',
multiple: 'multiple',
muted: 'muted',
name: 'name',
nomodule: 'noModule',
nonce: 'nonce',
novalidate: 'noValidate',
open: 'open',
optimum: 'optimum',
pattern: 'pattern',
placeholder: 'placeholder',
playsinline: 'playsInline',
poster: 'poster',
preload: 'preload',
profile: 'profile',
radiogroup: 'radioGroup',
readonly: 'readOnly',
referrerpolicy: 'referrerPolicy',
rel: 'rel',
required: 'required',
reversed: 'reversed',
role: 'role',
rows: 'rows',
rowspan: 'rowSpan',
sandbox: 'sandbox',
scope: 'scope',
scoped: 'scoped',
scrolling: 'scrolling',
seamless: 'seamless',
selected: 'selected',
shape: 'shape',
size: 'size',
sizes: 'sizes',
span: 'span',
spellcheck: 'spellCheck',
src: 'src',
srcdoc: 'srcDoc',
srclang: 'srcLang',
srcset: 'srcSet',
start: 'start',
step: 'step',
style: 'style',
summary: 'summary',
tabindex: 'tabIndex',
target: 'target',
title: 'title',
type: 'type',
usemap: 'useMap',
value: 'value',
width: 'width',
wmode: 'wmode',
wrap: 'wrap',
// SVG
about: 'about',
accentheight: 'accentHeight',
'accent-height': 'accentHeight',
accumulate: 'accumulate',
additive: 'additive',
alignmentbaseline: 'alignmentBaseline',
'alignment-baseline': 'alignmentBaseline',
allowreorder: 'allowReorder',
alphabetic: 'alphabetic',
amplitude: 'amplitude',
arabicform: 'arabicForm',
'arabic-form': 'arabicForm',
ascent: 'ascent',
attributename: 'attributeName',
attributetype: 'attributeType',
autoreverse: 'autoReverse',
azimuth: 'azimuth',
basefrequency: 'baseFrequency',
baselineshift: 'baselineShift',
'baseline-shift': 'baselineShift',
baseprofile: 'baseProfile',
bbox: 'bbox',
begin: 'begin',
bias: 'bias',
by: 'by',
calcmode: 'calcMode',
capheight: 'capHeight',
'cap-height': 'capHeight',
clip: 'clip',
clippath: 'clipPath',
'clip-path': 'clipPath',
clippathunits: 'clipPathUnits',
cliprule: 'clipRule',
'clip-rule': 'clipRule',
color: 'color',
colorinterpolation: 'colorInterpolation',
'color-interpolation': 'colorInterpolation',
colorinterpolationfilters: 'colorInterpolationFilters',
'color-interpolation-filters': 'colorInterpolationFilters',
colorprofile: 'colorProfile',
'color-profile': 'colorProfile',
colorrendering: 'colorRendering',
'color-rendering': 'colorRendering',
contentscripttype: 'contentScriptType',
contentstyletype: 'contentStyleType',
cursor: 'cursor',
cx: 'cx',
cy: 'cy',
d: 'd',
datatype: 'datatype',
decelerate: 'decelerate',
descent: 'descent',
diffuseconstant: 'diffuseConstant',
direction: 'direction',
display: 'display',
divisor: 'divisor',
dominantbaseline: 'dominantBaseline',
'dominant-baseline': 'dominantBaseline',
dur: 'dur',
dx: 'dx',
dy: 'dy',
edgemode: 'edgeMode',
elevation: 'elevation',
enablebackground: 'enableBackground',
'enable-background': 'enableBackground',
end: 'end',
exponent: 'exponent',
externalresourcesrequired: 'externalResourcesRequired',
fill: 'fill',
fillopacity: 'fillOpacity',
'fill-opacity': 'fillOpacity',
fillrule: 'fillRule',
'fill-rule': 'fillRule',
filter: 'filter',
filterres: 'filterRes',
filterunits: 'filterUnits',
floodopacity: 'floodOpacity',
'flood-opacity': 'floodOpacity',
floodcolor: 'floodColor',
'flood-color': 'floodColor',
focusable: 'focusable',
fontfamily: 'fontFamily',
'font-family': 'fontFamily',
fontsize: 'fontSize',
'font-size': 'fontSize',
fontsizeadjust: 'fontSizeAdjust',
'font-size-adjust': 'fontSizeAdjust',
fontstretch: 'fontStretch',
'font-stretch': 'fontStretch',
fontstyle: 'fontStyle',
'font-style': 'fontStyle',
fontvariant: 'fontVariant',
'font-variant': 'fontVariant',
fontweight: 'fontWeight',
'font-weight': 'fontWeight',
format: 'format',
from: 'from',
fx: 'fx',
fy: 'fy',
g1: 'g1',
g2: 'g2',
glyphname: 'glyphName',
'glyph-name': 'glyphName',
glyphorientationhorizontal: 'glyphOrientationHorizontal',
'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
glyphorientationvertical: 'glyphOrientationVertical',
'glyph-orientation-vertical': 'glyphOrientationVertical',
glyphref: 'glyphRef',
gradienttransform: 'gradientTransform',
gradientunits: 'gradientUnits',
hanging: 'hanging',
horizadvx: 'horizAdvX',
'horiz-adv-x': 'horizAdvX',
horizoriginx: 'horizOriginX',
'horiz-origin-x': 'horizOriginX',
ideographic: 'ideographic',
imagerendering: 'imageRendering',
'image-rendering': 'imageRendering',
in2: 'in2',
in: 'in',
inlist: 'inlist',
intercept: 'intercept',
k1: 'k1',
k2: 'k2',
k3: 'k3',
k4: 'k4',
k: 'k',
kernelmatrix: 'kernelMatrix',
kernelunitlength: 'kernelUnitLength',
kerning: 'kerning',
keypoints: 'keyPoints',
keysplines: 'keySplines',
keytimes: 'keyTimes',
lengthadjust: 'lengthAdjust',
letterspacing: 'letterSpacing',
'letter-spacing': 'letterSpacing',
lightingcolor: 'lightingColor',
'lighting-color': 'lightingColor',
limitingconeangle: 'limitingConeAngle',
local: 'local',
markerend: 'markerEnd',
'marker-end': 'markerEnd',
markerheight: 'markerHeight',
markermid: 'markerMid',
'marker-mid': 'markerMid',
markerstart: 'markerStart',
'marker-start': 'markerStart',
markerunits: 'markerUnits',
markerwidth: 'markerWidth',
mask: 'mask',
maskcontentunits: 'maskContentUnits',
maskunits: 'maskUnits',
mathematical: 'mathematical',
mode: 'mode',
numoctaves: 'numOctaves',
offset: 'offset',
opacity: 'opacity',
operator: 'operator',
order: 'order',
orient: 'orient',
orientation: 'orientation',
origin: 'origin',
overflow: 'overflow',
overlineposition: 'overlinePosition',
'overline-position': 'overlinePosition',
overlinethickness: 'overlineThickness',
'overline-thickness': 'overlineThickness',
paintorder: 'paintOrder',
'paint-order': 'paintOrder',
panose1: 'panose1',
'panose-1': 'panose1',
pathlength: 'pathLength',
patterncontentunits: 'patternContentUnits',
patterntransform: 'patternTransform',
patternunits: 'patternUnits',
pointerevents: 'pointerEvents',
'pointer-events': 'pointerEvents',
points: 'points',
pointsatx: 'pointsAtX',
pointsaty: 'pointsAtY',
pointsatz: 'pointsAtZ',
prefix: 'prefix',
preservealpha: 'preserveAlpha',
preserveaspectratio: 'preserveAspectRatio',
primitiveunits: 'primitiveUnits',
property: 'property',
r: 'r',
radius: 'radius',
refx: 'refX',
refy: 'refY',
renderingintent: 'renderingIntent',
'rendering-intent': 'renderingIntent',
repeatcount: 'repeatCount',
repeatdur: 'repeatDur',
requiredextensions: 'requiredExtensions',
requiredfeatures: 'requiredFeatures',
resource: 'resource',
restart: 'restart',
result: 'result',
results: 'results',
rotate: 'rotate',
rx: 'rx',
ry: 'ry',
scale: 'scale',
security: 'security',
seed: 'seed',
shaperendering: 'shapeRendering',
'shape-rendering': 'shapeRendering',
slope: 'slope',
spacing: 'spacing',
specularconstant: 'specularConstant',
specularexponent: 'specularExponent',
speed: 'speed',
spreadmethod: 'spreadMethod',
startoffset: 'startOffset',
stddeviation: 'stdDeviation',
stemh: 'stemh',
stemv: 'stemv',
stitchtiles: 'stitchTiles',
stopcolor: 'stopColor',
'stop-color': 'stopColor',
stopopacity: 'stopOpacity',
'stop-opacity': 'stopOpacity',
strikethroughposition: 'strikethroughPosition',
'strikethrough-position': 'strikethroughPosition',
strikethroughthickness: 'strikethroughThickness',
'strikethrough-thickness': 'strikethroughThickness',
string: 'string',
stroke: 'stroke',
strokedasharray: 'strokeDasharray',
'stroke-dasharray': 'strokeDasharray',
strokedashoffset: 'strokeDashoffset',
'stroke-dashoffset': 'strokeDashoffset',
strokelinecap: 'strokeLinecap',
'stroke-linecap': 'strokeLinecap',
strokelinejoin: 'strokeLinejoin',
'stroke-linejoin': 'strokeLinejoin',
strokemiterlimit: 'strokeMiterlimit',
'stroke-miterlimit': 'strokeMiterlimit',
strokewidth: 'strokeWidth',
'stroke-width': 'strokeWidth',
strokeopacity: 'strokeOpacity',
'stroke-opacity': 'strokeOpacity',
suppresscontenteditablewarning: 'suppressContentEditableWarning',
suppresshydrationwarning: 'suppressHydrationWarning',
surfacescale: 'surfaceScale',
systemlanguage: 'systemLanguage',
tablevalues: 'tableValues',
targetx: 'targetX',
targety: 'targetY',
textanchor: 'textAnchor',
'text-anchor': 'textAnchor',
textdecoration: 'textDecoration',
'text-decoration': 'textDecoration',
textlength: 'textLength',
textrendering: 'textRendering',
'text-rendering': 'textRendering',
to: 'to',
transform: 'transform',
typeof: 'typeof',
u1: 'u1',
u2: 'u2',
underlineposition: 'underlinePosition',
'underline-position': 'underlinePosition',
underlinethickness: 'underlineThickness',
'underline-thickness': 'underlineThickness',
unicode: 'unicode',
unicodebidi: 'unicodeBidi',
'unicode-bidi': 'unicodeBidi',
unicoderange: 'unicodeRange',
'unicode-range': 'unicodeRange',
unitsperem: 'unitsPerEm',
'units-per-em': 'unitsPerEm',
unselectable: 'unselectable',
valphabetic: 'vAlphabetic',
'v-alphabetic': 'vAlphabetic',
values: 'values',
vectoreffect: 'vectorEffect',
'vector-effect': 'vectorEffect',
version: 'version',
vertadvy: 'vertAdvY',
'vert-adv-y': 'vertAdvY',
vertoriginx: 'vertOriginX',
'vert-origin-x': 'vertOriginX',
vertoriginy: 'vertOriginY',
'vert-origin-y': 'vertOriginY',
vhanging: 'vHanging',
'v-hanging': 'vHanging',
videographic: 'vIdeographic',
'v-ideographic': 'vIdeographic',
viewbox: 'viewBox',
viewtarget: 'viewTarget',
visibility: 'visibility',
vmathematical: 'vMathematical',
'v-mathematical': 'vMathematical',
vocab: 'vocab',
widths: 'widths',
wordspacing: 'wordSpacing',
'word-spacing': 'wordSpacing',
writingmode: 'writingMode',
'writing-mode': 'writingMode',
x1: 'x1',
x2: 'x2',
x: 'x',
xchannelselector: 'xChannelSelector',
xheight: 'xHeight',
'x-height': 'xHeight',
xlinkactuate: 'xlinkActuate',
'xlink:actuate': 'xlinkActuate',
xlinkarcrole: 'xlinkArcrole',
'xlink:arcrole': 'xlinkArcrole',
xlinkhref: 'xlinkHref',
'xlink:href': 'xlinkHref',
xlinkrole: 'xlinkRole',
'xlink:role': 'xlinkRole',
xlinkshow: 'xlinkShow',
'xlink:show': 'xlinkShow',
xlinktitle: 'xlinkTitle',
'xlink:title': 'xlinkTitle',
xlinktype: 'xlinkType',
'xlink:type': 'xlinkType',
xmlbase: 'xmlBase',
'xml:base': 'xmlBase',
xmllang: 'xmlLang',
'xml:lang': 'xmlLang',
xmlns: 'xmlns',
'xml:space': 'xmlSpace',
xmlnsxlink: 'xmlnsXlink',
'xmlns:xlink': 'xmlnsXlink',
xmlspace: 'xmlSpace',
y1: 'y1',
y2: 'y2',
y: 'y',
ychannelselector: 'yChannelSelector',
z: 'z',
zoomandpan: 'zoomAndPan',
}
export default possibleStandardNames | the_stack |
import { AbortController, AbortError, AbortSignal } from "../src";
import { assert } from "chai";
describe("AbortController", () => {
function doAsyncOperation(aborter: AbortSignal, runningTimeinMs: number = 100): Promise<void> {
const s = Date.now();
return new Promise((resolve, reject) => {
// check status every 10 ms.
const handle = setInterval(() => {
// check if we're aborted.
if (aborter.aborted) {
clearInterval(handle);
return reject(new AbortError());
}
// if we're completed, resolve.
if (Date.now() - s > runningTimeinMs) {
clearInterval(handle);
return resolve();
}
// else, continue trying.
}, 10);
});
}
it("should not abort without calling abort()", async () => {
await doAsyncOperation(AbortSignal.none);
});
it("should abort when calling abort() before request finishes", async () => {
const controller = new AbortController();
const aborter = controller.signal;
const response = doAsyncOperation(aborter);
controller.abort();
try {
const rs = await response;
console.log("got result", rs);
assert.fail();
} catch (err) {
assert.strictEqual(err.name, "AbortError");
}
});
it("should abort when calling abort() after creation but before request finishes", async () => {
const controller = new AbortController();
const aborter = controller.signal;
const response = doAsyncOperation(aborter, 500);
setTimeout(() => controller.abort(), 50);
try {
const r = await response;
console.log("got, r", r);
assert.fail();
} catch (err) {
assert.strictEqual(err.name, "AbortError");
}
});
it("should not abort when calling abort() after request finishes", async () => {
const controller = new AbortController();
const aborter = controller.signal;
await doAsyncOperation(aborter);
controller.abort();
});
it("should invoke onabort callback when aborting", async () => {
const controller = new AbortController();
const aborter = controller.signal;
let s = undefined;
try {
aborter.onabort = () => {
s = "aborted";
};
const response = doAsyncOperation(aborter);
controller.abort();
await response;
assert.fail();
} catch (err) {
assert.strictEqual(s, "aborted");
}
});
it("should invoke abort listener callbacks when aborting", async () => {
const controller = new AbortController();
const aborter = controller.signal;
const s: string[] = [];
try {
aborter.addEventListener("abort", () => {
s.push("aborted");
});
aborter.addEventListener("abort", () => {
s.push("aborted");
});
const response = doAsyncOperation(aborter);
controller.abort();
await response;
assert.fail();
} catch (err) {
assert.deepEqual(s, ["aborted", "aborted"]);
}
});
// Test for the issue reported in https://github.com/Azure/azure-sdk-for-js/issues/13985
it("should invoke all abort listener callbacks when aborting even when listeners self-remove", async () => {
const controller = new AbortController();
const signal = controller.signal;
const acks: string[] = [];
try {
const onAbortFoo = () => {
acks.push("foo");
signal.removeEventListener("abort", onAbortFoo);
};
const onAbortBar = () => {
acks.push("bar");
signal.removeEventListener("abort", onAbortBar);
};
signal.addEventListener("abort", onAbortFoo);
signal.addEventListener("abort", onAbortBar);
const response = doAsyncOperation(signal);
controller.abort();
await response;
assert.fail();
} catch (err) {
assert.deepEqual(acks, ["foo", "bar"]);
}
});
it("should abort after timeout when using created using timeout()", async () => {
const aborter = AbortController.timeout(50);
let s = undefined;
try {
aborter.onabort = () => {
s = "aborted";
};
await doAsyncOperation(aborter, 200);
assert.fail();
} catch (err) {
assert.deepEqual(s, "aborted");
}
});
it("should propagate aborted state to child signals", async () => {
const parentController = new AbortController();
const parentSignal = parentController.signal;
let s = undefined;
parentSignal.addEventListener("abort", () => {
s = "parent";
});
parentController.abort();
const childController = new AbortController(parentSignal);
assert.strictEqual(true, childController.signal.aborted);
assert.strictEqual(s, "parent");
});
it("should propagate 'true' aborted state from any parent to child signals", async () => {
const parent1 = new AbortController();
const parent2 = new AbortController();
const parent3 = new AbortController();
let s = undefined;
parent1.signal.addEventListener("abort", () => {
s = "parent1";
});
parent2.signal.addEventListener("abort", () => {
s = "parent2";
});
parent3.signal.addEventListener("abort", () => {
s = "parent3";
});
parent1.abort();
const childController = new AbortController(parent1.signal, parent2.signal, parent3.signal);
assert.strictEqual(true, childController.signal.aborted);
assert.strictEqual(true, parent1.signal.aborted);
assert.strictEqual(false, parent2.signal.aborted);
assert.strictEqual(false, parent3.signal.aborted);
assert.strictEqual(s, "parent1");
});
it("should propagate 'true' aborted state from any parent to child signals (arrays)", async () => {
const parent1 = new AbortController();
const parent2 = new AbortController();
const parent3 = new AbortController();
let s = undefined;
parent1.signal.addEventListener("abort", () => {
s = "parent1";
});
parent2.signal.addEventListener("abort", () => {
s = "parent2";
});
parent3.signal.addEventListener("abort", () => {
s = "parent3";
});
parent1.abort();
const childController = new AbortController([parent1.signal, parent2.signal, parent3.signal]);
assert.strictEqual(true, childController.signal.aborted);
assert.strictEqual(true, parent1.signal.aborted);
assert.strictEqual(false, parent2.signal.aborted);
assert.strictEqual(false, parent3.signal.aborted);
assert.strictEqual(s, "parent1");
});
it("should call abort() on child signals that were created before parent abort() call", async function () {
const parentController = new AbortController();
const parentSignal = parentController.signal;
const child1 = new AbortController(parentSignal);
const child2 = new AbortController(parentSignal);
const values: string[] = [];
parentSignal.addEventListener("abort", () => {
values.push("parent");
});
child1.signal.addEventListener("abort", () => {
values.push("child1");
});
child2.signal.addEventListener("abort", () => {
values.push("child2");
});
// trigger abort() on parentSignal, event listeners should trigger on children
parentController.abort();
assert.strictEqual(3, values.length);
assert.strictEqual(true, parentSignal.aborted);
assert.strictEqual(true, child1.signal.aborted);
assert.strictEqual(true, child2.signal.aborted);
assert.strictEqual(true, values.includes("parent"));
assert.strictEqual(true, values.includes("child1"));
assert.strictEqual(true, values.includes("child2"));
});
it("should call abort() on child signal that was created before any parent's abort() call", async () => {
const parent1 = new AbortController();
const parent2 = new AbortController();
const parent3 = new AbortController();
const child = new AbortController(parent1.signal, parent2.signal, parent3.signal);
const values: string[] = [];
parent1.signal.addEventListener("abort", () => {
values.push("parent1");
});
parent2.signal.addEventListener("abort", () => {
values.push("parent2");
});
parent3.signal.addEventListener("abort", () => {
values.push("parent3");
});
child.signal.addEventListener("abort", () => {
values.push("child");
});
// trigger abort() on a parent, event listeners should trigger on child
parent2.abort();
assert.strictEqual(true, child.signal.aborted);
assert.strictEqual(false, parent1.signal.aborted);
assert.strictEqual(true, parent2.signal.aborted);
assert.strictEqual(false, parent3.signal.aborted);
assert.strictEqual(2, values.length);
assert.strictEqual(true, values.includes("parent2"));
assert.strictEqual(true, values.includes("child"));
});
it("should call abort() on child signal that was created before any parent's abort() call (arrays)", async () => {
const parent1 = new AbortController();
const parent2 = new AbortController();
const parent3 = new AbortController();
const child = new AbortController([parent1.signal, parent2.signal, parent3.signal]);
const values: string[] = [];
parent1.signal.addEventListener("abort", () => {
values.push("parent1");
});
parent2.signal.addEventListener("abort", () => {
values.push("parent2");
});
parent3.signal.addEventListener("abort", () => {
values.push("parent3");
});
child.signal.addEventListener("abort", () => {
values.push("child");
});
// trigger abort() on a parent, event listeners should trigger on child
parent2.abort();
assert.strictEqual(true, child.signal.aborted);
assert.strictEqual(false, parent1.signal.aborted);
assert.strictEqual(true, parent2.signal.aborted);
assert.strictEqual(false, parent3.signal.aborted);
assert.strictEqual(2, values.length);
assert.strictEqual(true, values.includes("parent2"));
assert.strictEqual(true, values.includes("child"));
});
it("should call abort() on deeply nested child signals that were created before parent abort() call", async function () {
const parentController = new AbortController();
const parentSignal = parentController.signal;
const child1 = new AbortController(parentSignal);
const child2 = new AbortController(child1.signal);
const values: string[] = [];
parentSignal.addEventListener("abort", () => {
values.push("parent");
});
child1.signal.addEventListener("abort", () => {
values.push("child1");
});
child2.signal.addEventListener("abort", () => {
values.push("child2");
});
// trigger abort() on parentSignal, event listeners should trigger on children
parentController.abort();
assert.strictEqual(3, values.length);
assert.strictEqual(true, parentSignal.aborted);
assert.strictEqual(true, child1.signal.aborted);
assert.strictEqual(true, child2.signal.aborted);
assert.strictEqual(true, values.includes("parent"));
assert.strictEqual(true, values.includes("child1"));
assert.strictEqual(true, values.includes("child2"));
});
it("should not call abort() on parent signals when child calls abort()", async function () {
const parentController = new AbortController();
const parentSignal = parentController.signal;
const child1 = new AbortController(parentSignal);
const child2 = new AbortController(child1.signal);
const values: string[] = [];
parentSignal.addEventListener("abort", () => {
values.push("parent");
});
child1.signal.addEventListener("abort", () => {
values.push("child1");
});
child2.signal.addEventListener("abort", () => {
values.push("child2");
});
// trigger abort() on child, event listeners should not trigger on parent
child1.abort();
assert.strictEqual(2, values.length);
assert.strictEqual(false, parentSignal.aborted);
assert.strictEqual(true, child1.signal.aborted);
assert.strictEqual(true, child2.signal.aborted);
assert.strictEqual(true, values.includes("child1"));
assert.strictEqual(true, values.includes("child2"));
// trigger abort() on parent, children should not invoke listeners again
parentController.abort();
assert.strictEqual(3, values.length);
assert.strictEqual(true, parentSignal.aborted);
assert.strictEqual(true, child1.signal.aborted);
assert.strictEqual(true, child2.signal.aborted);
assert.strictEqual(true, values.includes("parent"));
assert.strictEqual(true, values.includes("child1"));
assert.strictEqual(true, values.includes("child2"));
});
}); | the_stack |
import { Header } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { HeaderClient } from "../headerClient";
import {
HeaderParamExistingKeyOptionalParams,
HeaderResponseExistingKeyOptionalParams,
HeaderResponseExistingKeyResponse,
HeaderParamProtectedKeyOptionalParams,
HeaderResponseProtectedKeyOptionalParams,
HeaderResponseProtectedKeyResponse,
HeaderParamIntegerOptionalParams,
HeaderResponseIntegerOptionalParams,
HeaderResponseIntegerResponse,
HeaderParamLongOptionalParams,
HeaderResponseLongOptionalParams,
HeaderResponseLongResponse,
HeaderParamFloatOptionalParams,
HeaderResponseFloatOptionalParams,
HeaderResponseFloatResponse,
HeaderParamDoubleOptionalParams,
HeaderResponseDoubleOptionalParams,
HeaderResponseDoubleResponse,
HeaderParamBoolOptionalParams,
HeaderResponseBoolOptionalParams,
HeaderResponseBoolResponse,
HeaderParamStringOptionalParams,
HeaderResponseStringOptionalParams,
HeaderResponseStringResponse,
HeaderParamDateOptionalParams,
HeaderResponseDateOptionalParams,
HeaderResponseDateResponse,
HeaderParamDatetimeOptionalParams,
HeaderResponseDatetimeOptionalParams,
HeaderResponseDatetimeResponse,
HeaderParamDatetimeRfc1123OptionalParams,
HeaderResponseDatetimeRfc1123OptionalParams,
HeaderResponseDatetimeRfc1123Response,
HeaderParamDurationOptionalParams,
HeaderResponseDurationOptionalParams,
HeaderResponseDurationResponse,
HeaderParamByteOptionalParams,
HeaderResponseByteOptionalParams,
HeaderResponseByteResponse,
HeaderParamEnumOptionalParams,
HeaderResponseEnumOptionalParams,
HeaderResponseEnumResponse,
HeaderCustomRequestIdOptionalParams
} from "../models";
/** Class containing Header operations. */
export class HeaderImpl implements Header {
private readonly client: HeaderClient;
/**
* Initialize a new instance of the class Header class.
* @param client Reference to the service client
*/
constructor(client: HeaderClient) {
this.client = client;
}
/**
* Send a post request with header value "User-Agent": "overwrite"
* @param userAgent Send a post request with header value "User-Agent": "overwrite"
* @param options The options parameters.
*/
paramExistingKey(
userAgent: string,
options?: HeaderParamExistingKeyOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ userAgent, options },
paramExistingKeyOperationSpec
);
}
/**
* Get a response with header value "User-Agent": "overwrite"
* @param options The options parameters.
*/
responseExistingKey(
options?: HeaderResponseExistingKeyOptionalParams
): Promise<HeaderResponseExistingKeyResponse> {
return this.client.sendOperationRequest(
{ options },
responseExistingKeyOperationSpec
);
}
/**
* Send a post request with header value "Content-Type": "text/html"
* @param contentType Send a post request with header value "Content-Type": "text/html"
* @param options The options parameters.
*/
paramProtectedKey(
contentType: string,
options?: HeaderParamProtectedKeyOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ contentType, options },
paramProtectedKeyOperationSpec
);
}
/**
* Get a response with header value "Content-Type": "text/html"
* @param options The options parameters.
*/
responseProtectedKey(
options?: HeaderResponseProtectedKeyOptionalParams
): Promise<HeaderResponseProtectedKeyResponse> {
return this.client.sendOperationRequest(
{ options },
responseProtectedKeyOperationSpec
);
}
/**
* Send a post request with header values "scenario": "positive", "value": 1 or "scenario": "negative",
* "value": -2
* @param scenario Send a post request with header values "scenario": "positive" or "negative"
* @param value Send a post request with header values 1 or -2
* @param options The options parameters.
*/
paramInteger(
scenario: string,
value: number,
options?: HeaderParamIntegerOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ scenario, value, options },
paramIntegerOperationSpec
);
}
/**
* Get a response with header value "value": 1 or -2
* @param scenario Send a post request with header values "scenario": "positive" or "negative"
* @param options The options parameters.
*/
responseInteger(
scenario: string,
options?: HeaderResponseIntegerOptionalParams
): Promise<HeaderResponseIntegerResponse> {
return this.client.sendOperationRequest(
{ scenario, options },
responseIntegerOperationSpec
);
}
/**
* Send a post request with header values "scenario": "positive", "value": 105 or "scenario":
* "negative", "value": -2
* @param scenario Send a post request with header values "scenario": "positive" or "negative"
* @param value Send a post request with header values 105 or -2
* @param options The options parameters.
*/
paramLong(
scenario: string,
value: number,
options?: HeaderParamLongOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ scenario, value, options },
paramLongOperationSpec
);
}
/**
* Get a response with header value "value": 105 or -2
* @param scenario Send a post request with header values "scenario": "positive" or "negative"
* @param options The options parameters.
*/
responseLong(
scenario: string,
options?: HeaderResponseLongOptionalParams
): Promise<HeaderResponseLongResponse> {
return this.client.sendOperationRequest(
{ scenario, options },
responseLongOperationSpec
);
}
/**
* Send a post request with header values "scenario": "positive", "value": 0.07 or "scenario":
* "negative", "value": -3.0
* @param scenario Send a post request with header values "scenario": "positive" or "negative"
* @param value Send a post request with header values 0.07 or -3.0
* @param options The options parameters.
*/
paramFloat(
scenario: string,
value: number,
options?: HeaderParamFloatOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ scenario, value, options },
paramFloatOperationSpec
);
}
/**
* Get a response with header value "value": 0.07 or -3.0
* @param scenario Send a post request with header values "scenario": "positive" or "negative"
* @param options The options parameters.
*/
responseFloat(
scenario: string,
options?: HeaderResponseFloatOptionalParams
): Promise<HeaderResponseFloatResponse> {
return this.client.sendOperationRequest(
{ scenario, options },
responseFloatOperationSpec
);
}
/**
* Send a post request with header values "scenario": "positive", "value": 7e120 or "scenario":
* "negative", "value": -3.0
* @param scenario Send a post request with header values "scenario": "positive" or "negative"
* @param value Send a post request with header values 7e120 or -3.0
* @param options The options parameters.
*/
paramDouble(
scenario: string,
value: number,
options?: HeaderParamDoubleOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ scenario, value, options },
paramDoubleOperationSpec
);
}
/**
* Get a response with header value "value": 7e120 or -3.0
* @param scenario Send a post request with header values "scenario": "positive" or "negative"
* @param options The options parameters.
*/
responseDouble(
scenario: string,
options?: HeaderResponseDoubleOptionalParams
): Promise<HeaderResponseDoubleResponse> {
return this.client.sendOperationRequest(
{ scenario, options },
responseDoubleOperationSpec
);
}
/**
* Send a post request with header values "scenario": "true", "value": true or "scenario": "false",
* "value": false
* @param scenario Send a post request with header values "scenario": "true" or "false"
* @param value Send a post request with header values true or false
* @param options The options parameters.
*/
paramBool(
scenario: string,
value: boolean,
options?: HeaderParamBoolOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ scenario, value, options },
paramBoolOperationSpec
);
}
/**
* Get a response with header value "value": true or false
* @param scenario Send a post request with header values "scenario": "true" or "false"
* @param options The options parameters.
*/
responseBool(
scenario: string,
options?: HeaderResponseBoolOptionalParams
): Promise<HeaderResponseBoolResponse> {
return this.client.sendOperationRequest(
{ scenario, options },
responseBoolOperationSpec
);
}
/**
* Send a post request with header values "scenario": "valid", "value": "The quick brown fox jumps over
* the lazy dog" or "scenario": "null", "value": null or "scenario": "empty", "value": ""
* @param scenario Send a post request with header values "scenario": "valid" or "null" or "empty"
* @param options The options parameters.
*/
paramString(
scenario: string,
options?: HeaderParamStringOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ scenario, options },
paramStringOperationSpec
);
}
/**
* Get a response with header values "The quick brown fox jumps over the lazy dog" or null or ""
* @param scenario Send a post request with header values "scenario": "valid" or "null" or "empty"
* @param options The options parameters.
*/
responseString(
scenario: string,
options?: HeaderResponseStringOptionalParams
): Promise<HeaderResponseStringResponse> {
return this.client.sendOperationRequest(
{ scenario, options },
responseStringOperationSpec
);
}
/**
* Send a post request with header values "scenario": "valid", "value": "2010-01-01" or "scenario":
* "min", "value": "0001-01-01"
* @param scenario Send a post request with header values "scenario": "valid" or "min"
* @param value Send a post request with header values "2010-01-01" or "0001-01-01"
* @param options The options parameters.
*/
paramDate(
scenario: string,
value: Date,
options?: HeaderParamDateOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ scenario, value, options },
paramDateOperationSpec
);
}
/**
* Get a response with header values "2010-01-01" or "0001-01-01"
* @param scenario Send a post request with header values "scenario": "valid" or "min"
* @param options The options parameters.
*/
responseDate(
scenario: string,
options?: HeaderResponseDateOptionalParams
): Promise<HeaderResponseDateResponse> {
return this.client.sendOperationRequest(
{ scenario, options },
responseDateOperationSpec
);
}
/**
* Send a post request with header values "scenario": "valid", "value": "2010-01-01T12:34:56Z" or
* "scenario": "min", "value": "0001-01-01T00:00:00Z"
* @param scenario Send a post request with header values "scenario": "valid" or "min"
* @param value Send a post request with header values "2010-01-01T12:34:56Z" or "0001-01-01T00:00:00Z"
* @param options The options parameters.
*/
paramDatetime(
scenario: string,
value: Date,
options?: HeaderParamDatetimeOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ scenario, value, options },
paramDatetimeOperationSpec
);
}
/**
* Get a response with header values "2010-01-01T12:34:56Z" or "0001-01-01T00:00:00Z"
* @param scenario Send a post request with header values "scenario": "valid" or "min"
* @param options The options parameters.
*/
responseDatetime(
scenario: string,
options?: HeaderResponseDatetimeOptionalParams
): Promise<HeaderResponseDatetimeResponse> {
return this.client.sendOperationRequest(
{ scenario, options },
responseDatetimeOperationSpec
);
}
/**
* Send a post request with header values "scenario": "valid", "value": "Wed, 01 Jan 2010 12:34:56 GMT"
* or "scenario": "min", "value": "Mon, 01 Jan 0001 00:00:00 GMT"
* @param scenario Send a post request with header values "scenario": "valid" or "min"
* @param options The options parameters.
*/
paramDatetimeRfc1123(
scenario: string,
options?: HeaderParamDatetimeRfc1123OptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ scenario, options },
paramDatetimeRfc1123OperationSpec
);
}
/**
* Get a response with header values "Wed, 01 Jan 2010 12:34:56 GMT" or "Mon, 01 Jan 0001 00:00:00 GMT"
* @param scenario Send a post request with header values "scenario": "valid" or "min"
* @param options The options parameters.
*/
responseDatetimeRfc1123(
scenario: string,
options?: HeaderResponseDatetimeRfc1123OptionalParams
): Promise<HeaderResponseDatetimeRfc1123Response> {
return this.client.sendOperationRequest(
{ scenario, options },
responseDatetimeRfc1123OperationSpec
);
}
/**
* Send a post request with header values "scenario": "valid", "value": "P123DT22H14M12.011S"
* @param scenario Send a post request with header values "scenario": "valid"
* @param value Send a post request with header values "P123DT22H14M12.011S"
* @param options The options parameters.
*/
paramDuration(
scenario: string,
value: string,
options?: HeaderParamDurationOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ scenario, value, options },
paramDurationOperationSpec
);
}
/**
* Get a response with header values "P123DT22H14M12.011S"
* @param scenario Send a post request with header values "scenario": "valid"
* @param options The options parameters.
*/
responseDuration(
scenario: string,
options?: HeaderResponseDurationOptionalParams
): Promise<HeaderResponseDurationResponse> {
return this.client.sendOperationRequest(
{ scenario, options },
responseDurationOperationSpec
);
}
/**
* Send a post request with header values "scenario": "valid", "value": "啊齄丂狛狜隣郎隣兀﨩"
* @param scenario Send a post request with header values "scenario": "valid"
* @param value Send a post request with header values "啊齄丂狛狜隣郎隣兀﨩"
* @param options The options parameters.
*/
paramByte(
scenario: string,
value: Uint8Array,
options?: HeaderParamByteOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ scenario, value, options },
paramByteOperationSpec
);
}
/**
* Get a response with header values "啊齄丂狛狜隣郎隣兀﨩"
* @param scenario Send a post request with header values "scenario": "valid"
* @param options The options parameters.
*/
responseByte(
scenario: string,
options?: HeaderResponseByteOptionalParams
): Promise<HeaderResponseByteResponse> {
return this.client.sendOperationRequest(
{ scenario, options },
responseByteOperationSpec
);
}
/**
* Send a post request with header values "scenario": "valid", "value": "GREY" or "scenario": "null",
* "value": null
* @param scenario Send a post request with header values "scenario": "valid" or "null" or "empty"
* @param options The options parameters.
*/
paramEnum(
scenario: string,
options?: HeaderParamEnumOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ scenario, options },
paramEnumOperationSpec
);
}
/**
* Get a response with header values "GREY" or null
* @param scenario Send a post request with header values "scenario": "valid" or "null" or "empty"
* @param options The options parameters.
*/
responseEnum(
scenario: string,
options?: HeaderResponseEnumOptionalParams
): Promise<HeaderResponseEnumResponse> {
return this.client.sendOperationRequest(
{ scenario, options },
responseEnumOperationSpec
);
}
/**
* Send x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the header of the request
* @param options The options parameters.
*/
customRequestId(
options?: HeaderCustomRequestIdOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ options },
customRequestIdOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const paramExistingKeyOperationSpec: coreClient.OperationSpec = {
path: "/header/param/existingkey",
httpMethod: "POST",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.userAgent],
serializer
};
const responseExistingKeyOperationSpec: coreClient.OperationSpec = {
path: "/header/response/existingkey",
httpMethod: "POST",
responses: {
200: {
headersMapper: Mappers.HeaderResponseExistingKeyHeaders
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const paramProtectedKeyOperationSpec: coreClient.OperationSpec = {
path: "/header/param/protectedkey",
httpMethod: "POST",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.contentType],
serializer
};
const responseProtectedKeyOperationSpec: coreClient.OperationSpec = {
path: "/header/response/protectedkey",
httpMethod: "POST",
responses: {
200: {
headersMapper: Mappers.HeaderResponseProtectedKeyHeaders
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const paramIntegerOperationSpec: coreClient.OperationSpec = {
path: "/header/param/prim/integer",
httpMethod: "POST",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.scenario, Parameters.value],
serializer
};
const responseIntegerOperationSpec: coreClient.OperationSpec = {
path: "/header/response/prim/integer",
httpMethod: "POST",
responses: {
200: {
headersMapper: Mappers.HeaderResponseIntegerHeaders
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.scenario],
serializer
};
const paramLongOperationSpec: coreClient.OperationSpec = {
path: "/header/param/prim/long",
httpMethod: "POST",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.scenario, Parameters.value],
serializer
};
const responseLongOperationSpec: coreClient.OperationSpec = {
path: "/header/response/prim/long",
httpMethod: "POST",
responses: {
200: {
headersMapper: Mappers.HeaderResponseLongHeaders
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.scenario],
serializer
};
const paramFloatOperationSpec: coreClient.OperationSpec = {
path: "/header/param/prim/float",
httpMethod: "POST",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.scenario, Parameters.value1],
serializer
};
const responseFloatOperationSpec: coreClient.OperationSpec = {
path: "/header/response/prim/float",
httpMethod: "POST",
responses: {
200: {
headersMapper: Mappers.HeaderResponseFloatHeaders
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.scenario],
serializer
};
const paramDoubleOperationSpec: coreClient.OperationSpec = {
path: "/header/param/prim/double",
httpMethod: "POST",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.scenario, Parameters.value1],
serializer
};
const responseDoubleOperationSpec: coreClient.OperationSpec = {
path: "/header/response/prim/double",
httpMethod: "POST",
responses: {
200: {
headersMapper: Mappers.HeaderResponseDoubleHeaders
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.scenario],
serializer
};
const paramBoolOperationSpec: coreClient.OperationSpec = {
path: "/header/param/prim/bool",
httpMethod: "POST",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.scenario, Parameters.value2],
serializer
};
const responseBoolOperationSpec: coreClient.OperationSpec = {
path: "/header/response/prim/bool",
httpMethod: "POST",
responses: {
200: {
headersMapper: Mappers.HeaderResponseBoolHeaders
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.scenario],
serializer
};
const paramStringOperationSpec: coreClient.OperationSpec = {
path: "/header/param/prim/string",
httpMethod: "POST",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.scenario, Parameters.value3],
serializer
};
const responseStringOperationSpec: coreClient.OperationSpec = {
path: "/header/response/prim/string",
httpMethod: "POST",
responses: {
200: {
headersMapper: Mappers.HeaderResponseStringHeaders
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.scenario],
serializer
};
const paramDateOperationSpec: coreClient.OperationSpec = {
path: "/header/param/prim/date",
httpMethod: "POST",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.scenario, Parameters.value4],
serializer
};
const responseDateOperationSpec: coreClient.OperationSpec = {
path: "/header/response/prim/date",
httpMethod: "POST",
responses: {
200: {
headersMapper: Mappers.HeaderResponseDateHeaders
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.scenario],
serializer
};
const paramDatetimeOperationSpec: coreClient.OperationSpec = {
path: "/header/param/prim/datetime",
httpMethod: "POST",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.scenario, Parameters.value5],
serializer
};
const responseDatetimeOperationSpec: coreClient.OperationSpec = {
path: "/header/response/prim/datetime",
httpMethod: "POST",
responses: {
200: {
headersMapper: Mappers.HeaderResponseDatetimeHeaders
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.scenario],
serializer
};
const paramDatetimeRfc1123OperationSpec: coreClient.OperationSpec = {
path: "/header/param/prim/datetimerfc1123",
httpMethod: "POST",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.scenario, Parameters.value6],
serializer
};
const responseDatetimeRfc1123OperationSpec: coreClient.OperationSpec = {
path: "/header/response/prim/datetimerfc1123",
httpMethod: "POST",
responses: {
200: {
headersMapper: Mappers.HeaderResponseDatetimeRfc1123Headers
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.scenario],
serializer
};
const paramDurationOperationSpec: coreClient.OperationSpec = {
path: "/header/param/prim/duration",
httpMethod: "POST",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.scenario, Parameters.value7],
serializer
};
const responseDurationOperationSpec: coreClient.OperationSpec = {
path: "/header/response/prim/duration",
httpMethod: "POST",
responses: {
200: {
headersMapper: Mappers.HeaderResponseDurationHeaders
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.scenario],
serializer
};
const paramByteOperationSpec: coreClient.OperationSpec = {
path: "/header/param/prim/byte",
httpMethod: "POST",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.scenario, Parameters.value8],
serializer
};
const responseByteOperationSpec: coreClient.OperationSpec = {
path: "/header/response/prim/byte",
httpMethod: "POST",
responses: {
200: {
headersMapper: Mappers.HeaderResponseByteHeaders
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.scenario],
serializer
};
const paramEnumOperationSpec: coreClient.OperationSpec = {
path: "/header/param/prim/enum",
httpMethod: "POST",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.scenario, Parameters.value9],
serializer
};
const responseEnumOperationSpec: coreClient.OperationSpec = {
path: "/header/response/prim/enum",
httpMethod: "POST",
responses: {
200: {
headersMapper: Mappers.HeaderResponseEnumHeaders
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.scenario],
serializer
};
const customRequestIdOperationSpec: coreClient.OperationSpec = {
path:
"/header/custom/x-ms-client-request-id/9C4D50EE-2D56-4CD3-8152-34347DC9F2B0",
httpMethod: "POST",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import { Injectable } from '@angular/core';
import { AwesomeCordovaNativePlugin, Cordova, Plugin } from '@awesome-cordova-plugins/core';
const hypertrackIonicPluginVersion = "0.2.0"
// Minimal cordova-plugin-hypertrack-v3 version: 0.5.0
@Plugin({
pluginName: 'cordova-plugin-hypertrack-v3',
plugin: 'cordova-plugin-hypertrack-v3',
pluginRef: 'hypertrack',
repo: 'https://github.com/hypertrack/cordova-plugin-hypertrack.git',
platforms: ['Android, iOS'],
})
@Injectable()
export class HyperTrackPlugin extends AwesomeCordovaNativePlugin {
@Cordova()
initialize(publishableKey: string): Promise<HyperTrackCordova> {
return;
}
@Cordova()
getBlockers(): Promise<Set<Blocker>> {
return;
}
@Cordova()
enableDebugLogging(): Promise<any> {
return;
}
}
// Interfaces for Cordova Plugin callbacks
interface DeviceIdReceiver {
(deviceId: string): any;
}
interface TrackingStateReceiver {
(isRunning: boolean): any;
}
interface FailureHandler {
(error: Error): any;
}
interface SuccessHandler {
(): any;
}
interface LocationReceiver {
(location: CordovaLatestLocationResult): any;
}
// SDK instance that exposed from Cordova utilizes usage of callbacks, so we
// wrap it with adapter to avoid mix of callbacks and Promises
interface HyperTrackCordova {
getDeviceId(success: DeviceIdReceiver, error: FailureHandler): void;
isRunning(success: TrackingStateReceiver, error: FailureHandler): void;
setDeviceName(name: string, success: SuccessHandler, error: FailureHandler): void;
setDeviceMetadata(metadata: Object, success: SuccessHandler, error: FailureHandler): void;
setTrackingNotificationProperties(
title: string,
message: string,
success: SuccessHandler,
error: FailureHandler
): void;
addGeoTag(
geotagData: Object,
expectedLocation: Coordinates | undefined,
success: SuccessHandler,
error: FailureHandler
): void;
requestPermissionsIfNecessary(success: SuccessHandler, error: FailureHandler): void;
allowMockLocations(success: SuccessHandler, error: FailureHandler): void;
syncDeviceSettings(success: SuccessHandler, error: FailureHandler): void;
start(success: SuccessHandler, error: FailureHandler): void;
stop(success: SuccessHandler, error: FailureHandler): void;
getLatestLocation(success: LocationReceiver, error: FailureHandler): void;
getCurrentLocation(success: LocationReceiver, error: FailureHandler): void;
}
export class CoordinatesValidationError extends Error {}
/** Wrapper class for passing spatial geoposition as a geotag's expected location */
export class Coordinates {
constructor(public latitude: number, public longitude: number) {
if (latitude < -90.0 || latitude > 90.0 || longitude < -180.0 || longitude > 180.0) {
throw new CoordinatesValidationError('latitude and longitude should be of correct values');
}
}
public toString = (): string => {
return JSON.stringify(this);
}
}
/** A blocker is an obstacle that needs to be resolved to achieve reliable tracking. */
export interface Blocker {
/** Recommended name for a user action, that needs to be performed to resolve the blocker. */
userActionTitle: string;
/** Recommended name for a button, that will navigate user to the place where he can resolve the blocker */
userActionCTA: string;
/** User action explanation */
userActionExplanation: string;
/** An action that navigates user to the dedicated settings menu. */
resolve: () => void;
}
export type CordovaLatestLocationResult = {
type: "location",
location: Coordinates,
} | {
type: "outage",
outage: {
code: number,
name: keyof typeof Outage
}
}
export type LocationResult = {
type: LocationResultType.LOCATION,
value: Coordinates
} |
{
type: LocationResultType.OUTAGE,
value: Outage
}
export enum LocationResultType {
LOCATION, OUTAGE
}
export enum Outage {
MISSING_LOCATION_PERMISSION,
MISSING_ACTIVITY_PERMISSION,
LOCATION_SERVICE_DISABLED,
NOT_TRACKING,
START_HAS_NOT_FINISHED,
NO_GPS_SIGNAL,
RESTART_REQUIRED
}
/**
* @usage
* ```typescript
* import { HyperTrack } from '@awesome-cordova-plugins/hyper-track';
*
* initializeHypertrack() {
* HyperTrack.enableDebugLogging();
* HyperTrack.initialize('YOUR_PUBLISHING_KEY')
* .then( this.onSdkInstanceReceived )
* .catch( (err) => console.error("HyperTrack init failed with error " + err) );
* }
* onSdkInstanceReceived(sdkInstance: HyperTrack) {
* sdkInstance.getDeviceId()
* .then((id) => console.log("Got device id " + id))
* .then(() => sdkInstance.setDeviceName("Elvis Ionic"))
* .then(() => console.log("Device name was changed"))
* .then(() => sdkInstance.setDeviceMetadata({platform: "Ionic Android"}))
* .then(() => console.log("Device metadata was changed"))
* .then(() => sdkInstance.setTrackingNotificationProperties("Tracking On", "Ionic SDK is tracking"))
* .then(() => console.log("Notification properties were changed"))
* .catch((err) => console.error("Got error in HyperTrack " + err));
* }
*
* ```
*/
export class HyperTrack {
/** Enables debug log in native HyperTrack SDK. */
static enableDebugLogging(): void {
new HyperTrackPlugin().enableDebugLogging();
}
/**
* Entry point into SDK.
*
* Initializes SDK. Also resolves SDK instance that could be used to query deviceId or set
* various data.
*
* @param publishableKey account-specific secret from the HyperTrack dashborad.
* @see {@link https://dashboard.hypertrack.com/setup}.
*/
static initialize(publishableKey: string): Promise<HyperTrack> {
console.log(`Hypertrack Ionic plugin version ${hypertrackIonicPluginVersion}`)
return new Promise((resolve, reject) => {
new HyperTrackPlugin()
.initialize(publishableKey)
.then((cordovaInstance: HyperTrackCordova) => {
resolve(new HyperTrack(cordovaInstance));
})
.catch((err: Error) => reject(err));
});
}
/**
* Get the list of blockers that needs to be resolved for reliable tracking.
*
* @see {Blocker}
*/
static getBlockers(): Promise<Set<Blocker>> {
return new HyperTrackPlugin().getBlockers();
}
/** Resolves device ID that could be used to identify the device. */
getDeviceId(): Promise<string> {
return new Promise((resolve, reject) => {
this.cordovaInstanceHandle.getDeviceId(
(deviceId) => resolve(deviceId),
(err) => reject(err)
);
});
}
/** Resolves to true if tracking service is running and false otherwise */
isRunning(): Promise<boolean> {
return new Promise((resolve, reject) => {
this.cordovaInstanceHandle.isRunning(
(isRunning) => resolve(isRunning),
(err) => reject(err)
);
});
}
/**
* Sets device name that could be used to identify the device in HyperTrack dashboard
*
* @param name
*/
setDeviceName(name: string): Promise<void> {
return new Promise((resolve, reject) => {
this.cordovaInstanceHandle.setDeviceName(
name,
() => resolve(),
(err) => reject(err)
);
});
}
/**
* Use this to set additional properties, like segments, teams etc.
*
* @param metadata key-value pais of properties.
*/
setDeviceMetadata(metadata: Object): Promise<void> {
return new Promise((resolve, reject) => {
this.cordovaInstanceHandle.setDeviceMetadata(
metadata,
() => resolve(),
(err) => reject(err)
);
});
}
/**
* Updates title and text in persistent notification, that appears when tracking is active.
*
* @param title
* @param message
*/
setTrackingNotificationProperties(title: string, message: string): Promise<void> {
return new Promise((resolve, reject) => {
this.cordovaInstanceHandle.setTrackingNotificationProperties(
title,
message,
() => resolve(),
(err) => reject(err)
);
});
}
/**
* Adds special marker-like object to device timeline.
*
* @param geotagData
* @param expectedLocation
*/
addGeotag(geotagData: Object, expectedLocation?: Coordinates): Promise<void> {
return new Promise((resolve, reject) => {
this.cordovaInstanceHandle.addGeoTag(
geotagData,
expectedLocation,
() => resolve(),
(err) => reject(err)
);
});
}
/** Pops up permission request dialog, if permissions weren't granted before or does nothing otherwise. */
requestPermissionsIfNecessary(): Promise<void> {
return new Promise((resolve, reject) => {
this.cordovaInstanceHandle.requestPermissionsIfNecessary(
() => resolve(),
(err) => reject(err)
);
});
}
/** Allows injecting false locations into the SDK, which ignores them by default. */
allowMockLocations(): Promise<void> {
return new Promise((resolve, reject) => {
this.cordovaInstanceHandle.allowMockLocations(
() => resolve(),
(err) => reject(err)
);
});
}
/**
* Synchronizes tracking state with platform model. This method is used to
* harden platform2device communication channel.
*/
syncDeviceSettings(): Promise<void> {
return new Promise((resolve, reject) => {
this.cordovaInstanceHandle.syncDeviceSettings(
() => resolve(),
(err) => reject(err)
);
});
}
/** Start tracking. */
start(): Promise<void> {
return new Promise((resolve, reject) => {
this.cordovaInstanceHandle.start(
() => resolve(),
(err) => reject(err)
);
});
}
/** Stop tracking. */
stop(): Promise<void> {
return new Promise((resolve, reject) => {
this.cordovaInstanceHandle.stop(
() => resolve(),
(err) => reject(err)
);
});
}
/**
* Resolves latest device location that was sent by the SDK.
* Only available for Android platform.
* */
getLatestLocation(): Promise<LocationResult> {
return new Promise((resolve, reject) => {
this.cordovaInstanceHandle.getLatestLocation(
locationResult => resolve(this.handleLocationResult(locationResult)),
err => reject(err)
);
});
}
/**
* Resolves latest device location from system location provider.
* Only available for Android platform.
* */
getCurrentLocation(): Promise<LocationResult> {
return new Promise((resolve, reject) => {
this.cordovaInstanceHandle.getCurrentLocation(
locationResult => resolve(this.handleLocationResult(locationResult)),
err => reject(err)
);
});
}
private handleLocationResult(locationResult: CordovaLatestLocationResult): LocationResult {
switch (locationResult.type) {
case "location": {
return {
type: LocationResultType.LOCATION,
value: locationResult.location
}
}
case "outage": {
const outage = Outage[locationResult.outage.name]
return {
type: LocationResultType.OUTAGE,
value: outage
}
}
}
}
private constructor(private cordovaInstanceHandle: HyperTrackCordova) {}
} | the_stack |
import { createElement, isBlazor, isNullOrUndefined } from '@syncfusion/ej2-base';
import { ClickEventArgs } from '@syncfusion/ej2-buttons';
import { MenuEventArgs, Toolbar as Tool } from '@syncfusion/ej2-navigations';
import { PdfViewer, PdfViewerBase, Toolbar } from '../index';
import { DropDownButton, BeforeOpenCloseMenuEventArgs, OpenCloseMenuEventArgs, ItemModel, DropDownButtonModel } from '@syncfusion/ej2-splitbuttons';
/* eslint-disable */
/**
* @hidden
*/
export class FormDesignerToolbar {
private pdfViewer: PdfViewer;
private pdfViewerBase: PdfViewerBase;
/**
* @private
*/
public primaryToolbar: Toolbar;
public toolbarElement: HTMLElement;
private textboxItem: HTMLElement;
private passwordItem: HTMLElement;
private checkboxItem: HTMLElement;
private radioButtonItem: HTMLElement;
private dropdownItem: HTMLElement;
private listboxItem: HTMLElement;
private signatureItem: HTMLElement;
private deleteItem: HTMLElement;
private closeItem: HTMLElement;
/**
* @private
*/
public toolbar: Tool;
/**
* @private
*/
public isToolbarHidden: boolean = false;
private isTextboxBtnVisible: boolean = true;
private isPasswordBtnVisible: boolean = true;
private isCheckboxBtnVisible: boolean = true;
private isRadiobuttonBtnVisible: boolean = true;
private isDropdownBtnVisible: boolean = true;
private isListboxBtnVisible: boolean = true;
private isSignatureBtnVisible: boolean = true;
private isDeleteBtnVisible: boolean = true;
private toolbarBorderHeight: number = 1;
/**
* @private
*/
public handWrittenSignatureItem: HTMLElement;
constructor(viewer: PdfViewer, viewerBase: PdfViewerBase, toolbar: Toolbar) {
this.pdfViewer = viewer;
this.pdfViewerBase = viewerBase;
this.primaryToolbar = toolbar;
}
public initializeFormDesignerToolbar(): void {
// eslint-disable-next-line max-len
this.toolbarElement = createElement('div', { id: this.pdfViewer.element.id + '_formdesigner_toolbar', className: 'e-pv-formdesigner-toolbar' });
this.pdfViewerBase.viewerMainContainer.appendChild(this.toolbarElement);
this.toolbar = new Tool({
width: '', height: '', overflowMode: 'Popup',
items: this.createToolbarItems(), clicked: this.onToolbarClicked.bind(this),
created: () => {
this.createDropDowns();
}
});
//this.toolbar.isStringTemplate = true;
if (this.pdfViewer.enableRtl) {
this.toolbar.enableRtl = true;
}
this.toolbar.appendTo(this.toolbarElement);
this.afterToolbarCreation();
this.createSignContainer();
this.applyFormDesignerToolbarSettings();
//this.updateToolbarItems();
this.showFormDesignerToolbar(null, true);
}
/**
* @param element
* @param isInitialLoading
* @param element
* @param isInitialLoading
* @private
*/
public showFormDesignerToolbar(element?: HTMLElement, isInitialLoading?: boolean): void {
if (!this.isToolbarHidden) {
// eslint-disable-next-line
let formDesignerModule: any = this.pdfViewer.formDesignerModule;
if (element) {
this.primaryToolbar.deSelectItem(element);
} else {
if (this.pdfViewer.enableToolbar) {
this.primaryToolbar.deSelectItem(this.primaryToolbar.formDesignerItem);
}
}
this.adjustViewer(false);
// eslint-disable-next-line max-len
//this.deselectAllItems();
this.toolbarElement.style.display = 'none';
this.pdfViewer.formDesignerModule.setMode("edit");
this.pdfViewer.designerMode = false;
if (!isInitialLoading) {
this.pdfViewer.isFormDesignerToolbarVisible = false;
}
} else {
const toolBarInitialStatus: string = this.toolbarElement.style.display;
this.toolbarElement.style.display = 'block';
this.pdfViewer.designerMode =true;
this.pdfViewer.formDesignerModule.setMode("designer");
if (!isInitialLoading) {
this.pdfViewer.isFormDesignerToolbarVisible = true;
}
if (element) {
this.primaryToolbar.selectItem(element);
} else {
if (this.pdfViewer.enableToolbar) {
this.primaryToolbar.selectItem(this.primaryToolbar.formDesignerItem);
}
}
if (toolBarInitialStatus === 'none') {
this.adjustViewer(true);
}
}
// eslint-disable-next-line max-len
if (this.pdfViewer.magnification && this.pdfViewer.magnification.fitType === 'fitToPage') {
this.pdfViewer.magnification.fitToPage();
}
//this.enableAnnotationAddTools(true);
this.isToolbarHidden = !this.isToolbarHidden;
}
/**
* @param isAdjust
* @private
*/
public adjustViewer(isAdjust: boolean): void {
let splitterElement: HTMLElement;
let toolbarContainer: HTMLElement;
let formDesignerToolbarHeight: number;
if (isBlazor()) {
splitterElement = this.pdfViewer.element.querySelector('.e-pv-sidebar-toolbar-splitter');
toolbarContainer = this.pdfViewer.element.querySelector('.e-pv-toolbar');
const formDesignerToolbarContainer: HTMLElement = this.pdfViewer.element.querySelector('.e-pv-formDesigner-toolbar');
formDesignerToolbarHeight = this.getToolbarHeight(formDesignerToolbarContainer);
} else {
splitterElement = this.pdfViewerBase.getElement('_sideBarToolbarSplitter');
toolbarContainer = this.pdfViewerBase.getElement('_toolbarContainer');
formDesignerToolbarHeight = this.getToolbarHeight(this.toolbarElement);
}
let toolbarHeight: number = this.getToolbarHeight(toolbarContainer);
const sideBarToolbar: HTMLElement = this.pdfViewerBase.navigationPane.sideBarToolbar;
const sideBarContentContainer: HTMLElement = this.pdfViewerBase.navigationPane.sideBarContentContainer;
const commentsContainer: HTMLElement = this.pdfViewerBase.navigationPane.commentPanelContainer;
const commentPanelResizer: HTMLElement = this.pdfViewerBase.navigationPane.commentPanelResizer;
if (isAdjust) {
if (this.pdfViewer.enableToolbar) {
sideBarToolbar.style.top = (toolbarHeight + formDesignerToolbarHeight) + 'px';
sideBarContentContainer.style.top = (toolbarHeight + formDesignerToolbarHeight) + 'px';
splitterElement.style.top = (toolbarHeight + formDesignerToolbarHeight) + 'px';
commentsContainer.style.top = (toolbarHeight + formDesignerToolbarHeight) + 'px';
commentPanelResizer.style.top = (toolbarHeight + formDesignerToolbarHeight) + 'px';
} else {
sideBarToolbar.style.top = (formDesignerToolbarHeight) + 'px';
sideBarContentContainer.style.top = (formDesignerToolbarHeight) + 'px';
splitterElement.style.top = (formDesignerToolbarHeight) + 'px';
commentsContainer.style.top = (formDesignerToolbarHeight) + 'px';
commentPanelResizer.style.top = (toolbarHeight + formDesignerToolbarHeight) + 'px';
}
if (!this.pdfViewer.enableToolbar) {
toolbarHeight = 0;
}
// eslint-disable-next-line max-len
this.pdfViewerBase.viewerContainer.style.height = this.updateViewerHeight(this.getElementHeight(this.pdfViewerBase.viewerContainer), (formDesignerToolbarHeight + toolbarHeight)) + 'px';
sideBarToolbar.style.height = this.getNavigationToolbarHeight(formDesignerToolbarHeight + toolbarHeight) + 'px';
splitterElement.style.height = this.getNavigationToolbarHeight(formDesignerToolbarHeight + toolbarHeight) + 'px';
} else {
if (this.pdfViewer.enableToolbar) {
// eslint-disable-next-line max-len
sideBarToolbar.style.top = toolbarHeight + 'px';
sideBarContentContainer.style.top = toolbarHeight + 'px';
splitterElement.style.top = toolbarHeight + 'px';
commentsContainer.style.top = toolbarHeight + 'px';
commentPanelResizer.style.top = toolbarHeight + 'px';
} else {
sideBarToolbar.style.top = 1 + 'px';
sideBarToolbar.style.height = '100%';
sideBarContentContainer.style.top = 1 + 'px';
sideBarContentContainer.style.height = '100%';
splitterElement.style.top = 1 + 'px';
splitterElement.style.height = '100%';
commentsContainer.style.top = 1 + 'px';
commentsContainer.style.height = '100%';
commentPanelResizer.style.top = 1 + 'px';
commentPanelResizer.style.height = '100%';
}
if (!this.pdfViewer.enableToolbar) {
toolbarHeight = 0;
}
// eslint-disable-next-line max-len
this.pdfViewerBase.viewerContainer.style.height = this.resetViewerHeight(this.getElementHeight(this.pdfViewerBase.viewerContainer), formDesignerToolbarHeight) + 'px';
sideBarToolbar.style.height = this.getNavigationToolbarHeight(toolbarHeight);
splitterElement.style.height = this.getNavigationToolbarHeight(toolbarHeight);
if (this.pdfViewerBase.viewerContainer.style.height === '0px') {
// eslint-disable-next-line
this.pdfViewerBase.viewerContainer.style.height = (parseInt(this.pdfViewer.element.style.height) - parseInt(sideBarToolbar.style.top)) + 'px';
}
}
if (isBlazor()) {
this.updateContentContainerHeight(isAdjust, true);
} else {
this.updateContentContainerHeight(isAdjust);
}
}
private getElementHeight(element: HTMLElement): number {
try {
return element.getBoundingClientRect().height;
} catch (error) {
return 0;
}
}
private updateViewerHeight(viewerHeight: number, toolbarHeight: number): number {
return this.getElementHeight(this.pdfViewer.element) - toolbarHeight;
}
private resetViewerHeight(viewerHeight: number, toolbarHeight: number): number {
return viewerHeight + toolbarHeight;
}
private getNavigationToolbarHeight(toolbarHeight: number): string {
const height: number = this.pdfViewer.element.getBoundingClientRect().height;
return (height !== 0) ? height - toolbarHeight + 'px' : '';
}
private updateContentContainerHeight(isAdjust: boolean, isBlazor?: boolean): void {
let formDesignerToolbarHeight: number;
if (isBlazor) {
const formDesignerToolbarContainer: HTMLElement = this.pdfViewer.element.querySelector('.e-pv-formDesigner-toolbar');
formDesignerToolbarHeight = this.getToolbarHeight(formDesignerToolbarContainer);
} else {
formDesignerToolbarHeight = this.getToolbarHeight(this.toolbarElement);
}
const sideBarClientRect: ClientRect = this.pdfViewerBase.navigationPane.sideBarContentContainer.getBoundingClientRect();
if (sideBarClientRect.height !== 0) {
if (isAdjust) {
// eslint-disable-next-line max-len
this.pdfViewerBase.navigationPane.sideBarContentContainer.style.height = sideBarClientRect.height - formDesignerToolbarHeight + 'px';
} else {
// eslint-disable-next-line max-len
this.pdfViewerBase.navigationPane.sideBarContentContainer.style.height = sideBarClientRect.height + formDesignerToolbarHeight + 'px';
}
}
}
private getToolbarHeight(element: HTMLElement): number {
let toolbarHeight: number = element.getBoundingClientRect().height;
if (toolbarHeight === 0 && element === this.pdfViewerBase.getElement('_toolbarContainer')) {
// getComputedStyle gets the value from style and toolbar border height is added to it.
// eslint-disable-next-line
toolbarHeight = parseFloat(window.getComputedStyle(element)['height']) + this.toolbarBorderHeight;
}
return toolbarHeight;
}
// eslint-disable-next-line
private createToolbarItems(): any[] {
const signTemplate: string = this.getTemplate('span', '_formfield_signature', 'e-pv-annotation-handwritten-container');
// eslint-disable-next-line
let items: any[] = [];
// eslint-disable-next-line max-len
items.push({ prefixIcon: 'e-pv-textbox-icon e-pv-icon', className: 'e-pv-annotation-shapes-container', id: this.pdfViewer.element.id + '_formdesigner_textbox', align: 'Left' });
items.push({ prefixIcon: 'e-pv-password-icon e-pv-icon', className: 'e-pv-annotation-shapes-container', id: this.pdfViewer.element.id + '_formdesigner_passwordfield', align: 'Left' });
items.push({ prefixIcon: 'e-pv-checkbox-icon e-pv-icon', className: 'e-pv-annotation-shapes-container', id: this.pdfViewer.element.id + '_formdesigner_checkbox', align: 'Left' });
items.push({ prefixIcon: 'e-pv-radiobutton-icon e-pv-icon', className: 'e-pv-annotation-shapes-container', id: this.pdfViewer.element.id + '_formdesigner_radiobutton', align: 'Left' });
items.push({ prefixIcon: 'e-pv-dropdown-icon e-pv-icon', className: 'e-pv-annotation-shapes-container', id: this.pdfViewer.element.id + '_formdesigner_dropdown', align: 'Left' });
items.push({ prefixIcon: 'e-pv-listbox-icon e-pv-icon', className: 'e-pv-annotation-shapes-container', id: this.pdfViewer.element.id + '_formdesigner_listbox', align: 'Left' });
items.push({ template: signTemplate, align: 'Left' });
items.push({ type: 'Separator', align: 'Left' });
// eslint-disable-next-line max-len
items.push({ prefixIcon: 'e-pv-annotation-delete-icon e-pv-icon', className: 'e-pv-annotation-delete-container', id: this.pdfViewer.element.id + '_formdesigner_delete', align: 'Left' });
items.push({ prefixIcon: 'e-pv-annotation-tools-close-icon e-pv-icon', className: 'e-pv-annotation-tools-close-container', id: this.pdfViewer.element.id + '_formdesigner_close', align: 'Right' });
return items;
}
private createSignContainer(): void {
this.handWrittenSignatureItem = this.pdfViewerBase.getElement('_formfield_signature');
// eslint-disable-next-line max-len
this.primaryToolbar.createTooltip(this.pdfViewerBase.getElement('_formfield_signature'), this.pdfViewer.localeObj.getConstant('HandwrittenSignatureDialogHeaderText'));
// eslint-disable-next-line
let proxy: any = this;
let items: ItemModel[] =[];
items=[
{
text: 'ADD SIGNATURE'
},
{
separator: true
},
{
text: 'ADD INITIAL'
}];
const saveOptions: DropDownButtonModel = {
items: items,
iconCss: 'e-pv-handwritten-icon e-pv-icon',
cssClass: 'e-pv-handwritten-popup',
beforeItemRender: (args: MenuEventArgs): void => {
this.pdfViewer.clearSelection(this.pdfViewerBase.currentPageNumber - 1);
if(args.element && args.element.className.indexOf("e-separator")!==-1) {
args.element.style.margin = "8px 0";
}
if (args.item.text === 'ADD SIGNATURE') {
args.element.innerHTML = '';
let addInitialSpan: HTMLElement = createElement('button');
addInitialSpan.classList.add("e-control", "e-btn", "e-lib", "e-outline", "e-primary");
addInitialSpan.textContent = this.pdfViewer.localeObj.getConstant('SignatureFieldDialogHeaderText');
addInitialSpan.style.width = "130px";
addInitialSpan.style.height = "36px";
addInitialSpan.addEventListener('click', this.clickSignature.bind(this));
args.element.appendChild(addInitialSpan);
args.element.addEventListener('mouseover', this.hoverInitialBtn.bind(this));
args.element.style.width = '206px';
args.element.style.display = 'flex';
args.element.style.flexDirection = 'column';
args.element.style.height = 'auto';
args.element.style.alignItems = 'center';
}
if (args.item.text === 'ADD INITIAL') {
args.element.innerHTML = '';
let addInitialSpan: HTMLElement = createElement('button');
addInitialSpan.classList.add("e-control", "e-btn", "e-lib", "e-outline", "e-primary");
addInitialSpan.textContent = this.pdfViewer.localeObj.getConstant('InitialFieldDialogHeaderText');
addInitialSpan.style.width = "130px";
addInitialSpan.style.height = "36px";
addInitialSpan.addEventListener('click', this.clickInitial.bind(this));
args.element.appendChild(addInitialSpan);
args.element.addEventListener('mouseover', this.hoverInitialBtn.bind(this));
args.element.style.width = '206px';
args.element.style.display = 'flex';
args.element.style.flexDirection = 'column';
args.element.style.height = 'auto';
args.element.style.alignItems = 'center';
}
},
};
const drpDownBtn: DropDownButton = new DropDownButton(saveOptions);
if (this.pdfViewer.enableRtl) {
drpDownBtn.enableRtl = this.pdfViewer.enableRtl;
}
drpDownBtn.appendTo(this.handWrittenSignatureItem);
}
private hoverInitialBtn(event:any): void {
const eventTarget: HTMLElement = event.target as HTMLElement;
let currentFieldID: string = isNullOrUndefined(event.path) ? event.composedPath()[0].id : event.path[0].id;
if(currentFieldID!=='sign_'+currentFieldID.split("_")[1] && currentFieldID!=='delete_'+currentFieldID.split("_")[1]){
let liElement: HTMLElement = document.getElementById(eventTarget.id);
if (isNullOrUndefined(liElement)) {
liElement = document.getElementById(eventTarget.parentElement.id);
}
if ((liElement as HTMLLIElement) != null && (eventTarget.id !== 'sign_' + eventTarget.id.split('_')[1] || eventTarget.id !== 'sign_border_' + eventTarget.id.split('_')[2])) {
liElement.style.background = 'transparent';
liElement.style.cursor = 'default';
} else if ((liElement.parentElement as HTMLLIElement) != null && (eventTarget.id !== 'sign_' + eventTarget.id.split('_')[1] || eventTarget.id !== 'sign_border_' + eventTarget.id.split('_')[2])) {
liElement.parentElement.style.background = 'transparent';
liElement.parentElement.style.cursor='default';
}
}
}
private getTemplate(elementName: string, id: string, className: string): string {
const element: HTMLElement = createElement(elementName, { id: this.pdfViewer.element.id + id });
if (className) {
element.className = className;
}
return element.outerHTML;
}
private onToolbarClicked(args: ClickEventArgs): void {
// eslint-disable-next-line
if(args && (args as IToolbarClick).item) {
if((args as IToolbarClick).item.id.indexOf("textbox")!==-1) {
this.pdfViewer.formDesignerModule.setFormFieldMode('Textbox');
} else if((args as IToolbarClick).item.id.indexOf("passwordfield")!==-1) {
this.pdfViewer.formDesignerModule.setFormFieldMode('Password');
} else if((args as IToolbarClick).item.id.indexOf("checkbox")!==-1) {
this.pdfViewer.formDesignerModule.setFormFieldMode('CheckBox');
} else if((args as IToolbarClick).item.id.indexOf("radiobutton")!==-1) {
this.pdfViewer.formDesignerModule.setFormFieldMode('RadioButton');
} else if((args as IToolbarClick).item.id.indexOf("dropdown")!==-1) {
this.pdfViewer.formDesignerModule.setFormFieldMode('DropDown');
} else if((args as IToolbarClick).item.id.indexOf("listbox")!==-1) {
this.pdfViewer.formDesignerModule.setFormFieldMode('ListBox');
} else if((args as IToolbarClick).item.id.indexOf("signature")!==-1) {
this.pdfViewer.formDesignerModule.setFormFieldMode('SignatureField');
} else if((args as IToolbarClick).item.id.indexOf("close")!==-1) {
this.pdfViewer.toolbarModule.formDesignerToolbarModule.showFormDesignerToolbar(this.pdfViewer.toolbarModule.formDesignerItem);
} else if((args as IToolbarClick).item.id.indexOf("delete")!==-1) {
this.pdfViewer.formDesignerModule.deleteFormField(this.pdfViewer.selectedItems.formFields[0]);
this.showHideDeleteIcon(false);
}
if (this.pdfViewer.selectedItems.formFields.length > 0) {
this.pdfViewer.clearSelection(this.pdfViewer.selectedItems.formFields[0].pageIndex);
}
}
}
private clickSignature(args: any): void {
this.pdfViewer.formDesignerModule.setFormFieldMode('SignatureField');
}
private clickInitial(args: any): void {
this.pdfViewer.isInitialFieldToolbarSelection = true;
this.pdfViewer.formDesignerModule.setFormFieldMode('InitialField');
this.pdfViewer.isInitialFieldToolbarSelection = false;
}
private afterToolbarCreation(): void {
// eslint-disable-next-line max-len
this.textboxItem = this.primaryToolbar.addClassToolbarItem('_formdesigner_textbox', 'e-pv-formdesigner-textbox', this.pdfViewer.localeObj.getConstant('Textbox'));
this.passwordItem = this.primaryToolbar.addClassToolbarItem('_formdesigner_passwordfield', 'e-pv-formdesigner-passwordfield', this.pdfViewer.localeObj.getConstant('Password'));
this.checkboxItem = this.primaryToolbar.addClassToolbarItem('_formdesigner_checkbox', 'e-pv-formdesigner-checkbox', this.pdfViewer.localeObj.getConstant('Check Box'));
this.radioButtonItem = this.primaryToolbar.addClassToolbarItem('_formdesigner_radiobutton', 'e-pv-formdesigner-radiobutton', this.pdfViewer.localeObj.getConstant('Radio Button'));
this.dropdownItem = this.primaryToolbar.addClassToolbarItem('_formdesigner_dropdown', 'e-pv-formdesigner-dropdown', this.pdfViewer.localeObj.getConstant('Dropdown'));
this.listboxItem = this.primaryToolbar.addClassToolbarItem('_formdesigner_listbox', 'e-pv-formdesigner-listbox', this.pdfViewer.localeObj.getConstant('List Box'));
//this.signatureItem = this.primaryToolbar.addClassToolbarItem('_formdesigner_signature', 'e-pv-formdesigner-signature', this.pdfViewer.localeObj.getConstant('Signature'));
this.deleteItem = this.primaryToolbar.addClassToolbarItem('_formdesigner_delete', 'e-pv-formdesigner-delete', this.pdfViewer.localeObj.getConstant('Delete FormField'));
this.closeItem = this.primaryToolbar.addClassToolbarItem('_formdesigner_close', 'e-pv-annotation-tools-close', null);
this.showHideDeleteIcon(false);
//this.enableTextMarkupAnnotationPropertiesTools(false);
}
public showHideDeleteIcon(isEnable: boolean): void {
if (this.toolbar)
this.toolbar.enableItems(this.deleteItem.parentElement, isEnable);
}
private applyFormDesignerToolbarSettings(): void {
if (this.pdfViewer.toolbarSettings.formDesignerToolbarItems) {
if (this.pdfViewer.toolbarSettings.formDesignerToolbarItems.indexOf('TextboxTool') !== -1) {
this.showTextboxTool(true);
} else {
this.showTextboxTool(false);
}
if (this.pdfViewer.toolbarSettings.formDesignerToolbarItems.indexOf('PasswordTool') !== -1) {
this.showPasswordTool(true);
} else {
this.showPasswordTool(false);
}
if (this.pdfViewer.toolbarSettings.formDesignerToolbarItems.indexOf('CheckBoxTool') !== -1) {
this.showCheckboxTool(true);
} else {
this.showCheckboxTool(false);
}
if (this.pdfViewer.toolbarSettings.formDesignerToolbarItems.indexOf('RadioButtonTool') !== -1) {
this.showRadioButtonTool(true);
} else {
this.showRadioButtonTool(false);
}
if (this.pdfViewer.toolbarSettings.formDesignerToolbarItems.indexOf('DropdownTool') !== -1) {
this.showDropdownTool(true);
} else {
this.showDropdownTool(false);
}
if (this.pdfViewer.toolbarSettings.formDesignerToolbarItems.indexOf('ListboxTool') !== -1) {
this.showListboxTool(true);
} else {
this.showListboxTool(false);
}
if (this.pdfViewer.toolbarSettings.formDesignerToolbarItems.indexOf('DrawSignatureTool') !== -1) {
this.showDrawSignatureTool(true);
} else {
this.showDrawSignatureTool(false);
}
if (this.pdfViewer.toolbarSettings.formDesignerToolbarItems.indexOf('DeleteTool') !== -1) {
this.showDeleteTool(true);
} else {
this.showDeleteTool(false);
}
this.showSeparator();
}
}
private showTextboxTool(isShow: boolean): void {
this.isTextboxBtnVisible = isShow;
this.applyHideToToolbar(isShow, 0, 0);
}
private showPasswordTool(isShow: boolean): void {
this.isPasswordBtnVisible = isShow;
this.applyHideToToolbar(isShow, 1, 1);
}
private showCheckboxTool(isShow: boolean): void {
this.isCheckboxBtnVisible = isShow;
this.applyHideToToolbar(isShow, 2, 2);
}
private showRadioButtonTool(isShow: boolean): void {
this.isRadiobuttonBtnVisible = isShow;
this.applyHideToToolbar(isShow, 3, 3);
}
private showDropdownTool(isShow: boolean): void {
this.isDropdownBtnVisible = isShow;
this.applyHideToToolbar(isShow, 4, 4);
}
private showListboxTool(isShow: boolean): void {
this.isListboxBtnVisible = isShow;
this.applyHideToToolbar(isShow, 5, 5);
}
private showDrawSignatureTool(isShow: boolean): void {
this.isSignatureBtnVisible = isShow;
this.applyHideToToolbar(isShow, 6, 6);
}
private showDeleteTool(isShow: boolean): void {
this.isDeleteBtnVisible = isShow;
this.applyHideToToolbar(isShow, 8, 8);
}
private showSeparator(): void {
if(!this.isSignatureBtnVisible && !this.isDeleteBtnVisible)
this.applyHideToToolbar(false, 7, 7);
}
private applyHideToToolbar(show: boolean, startIndex: number, endIndex: number): void {
const isHide: boolean = !show;
for (let index: number = startIndex; index <= endIndex; index++) {
this.toolbar.hideItem(index, isHide);
}
}
private createDropDowns(): void {
}
/**
* @private
*/
public destroy(): void {
let componentElement: any = [this.textboxItem, this.passwordItem, this.checkboxItem, this.radioButtonItem,
this.listboxItem, this.dropdownItem, this.handWrittenSignatureItem, this.deleteItem];
for (let i: number = 0; i < componentElement.length; i++) {
if (componentElement[i]) {
this.destroyDependentComponent(componentElement[i]);
}
}
}
private destroyDependentComponent(component: any): void {
if (component.ej2_instances) {
for (let i: number = component.ej2_instances.length - 1; i >=0; i--) {
component.ej2_instances[i].destroy();
}
}
}
}
interface IToolbarClick extends ClickEventArgs {
item: any
} | the_stack |
import { DebugElement } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DropdownSitesComponent, Relations } from './sites-dropdown.component';
import { SitesService, setupTestBed } from '@alfresco/adf-core';
import { of } from 'rxjs';
import { getFakeSitePaging,
getFakeSitePagingNoMoreItems,
getFakeSitePagingFirstPage,
getFakeSitePagingLastPage,
getFakeSitePagingWithMembers
} from '../mock';
import { ContentTestingModule } from '../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
const customSiteList = {
'list': {
'entries': [
{
'entry': {
'guid': '-my-',
'title': 'PERSONAL_FILES'
}
},
{
'entry': {
'guid': '-mysites-',
'title': 'FILE_LIBRARIES'
}
}
]
}
};
describe('DropdownSitesComponent', () => {
let component: any;
let fixture: ComponentFixture<DropdownSitesComponent>;
let debug: DebugElement;
let element: HTMLElement;
let siteService: SitesService;
setupTestBed({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
]
});
describe('Rendering tests', () => {
describe('Infinite Loading', () => {
beforeEach(() => {
siteService = TestBed.inject(SitesService);
fixture = TestBed.createComponent(DropdownSitesComponent);
debug = fixture.debugElement;
element = fixture.nativeElement;
component = fixture.componentInstance;
spyOn(siteService, 'getSites').and.returnValue(of(getFakeSitePaging()));
});
it('Should show loading item if there are more itemes', async () => {
fixture.detectChanges();
await fixture.whenStable();
expect(element.querySelector('[data-automation-id="site-loading"]')).toBeDefined();
});
it('Should not show loading item if there are more itemes', async () => {
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
expect(element.querySelector('[data-automation-id="site-loading"]')).toBeNull();
});
});
describe('Sites', () => {
beforeEach(() => {
siteService = TestBed.inject(SitesService);
spyOn(siteService, 'getSites').and.returnValue(of(getFakeSitePagingNoMoreItems()));
fixture = TestBed.createComponent(DropdownSitesComponent);
debug = fixture.debugElement;
element = fixture.nativeElement;
component = fixture.componentInstance;
});
function openSelectBox() {
const selectBox = debug.query(By.css(('[data-automation-id="site-my-files-option"] .mat-select-trigger')));
selectBox.triggerEventHandler('click', null);
}
it('Dropdown sites should be rendered', async () => {
fixture.detectChanges();
await fixture.whenStable();
expect(element.querySelector('#site-dropdown-container')).toBeDefined();
expect(element.querySelector('#site-dropdown')).toBeDefined();
expect(element.querySelector('#site-dropdown-container')).not.toBeNull();
expect(element.querySelector('#site-dropdown')).not.toBeNull();
});
it('should show the "My files" option by default', async () => {
component.hideMyFiles = false;
fixture.detectChanges();
await fixture.whenStable();
debug.query(By.css('.mat-select-trigger')).triggerEventHandler('click', null);
fixture.detectChanges();
await fixture.whenStable();
const options: any = debug.queryAll(By.css('mat-option'));
expect(options[0].nativeElement.innerText).toContain('DROPDOWN.MY_FILES_OPTION');
});
it('should hide the "My files" option if the developer desires that way', async () => {
component.hideMyFiles = true;
fixture.detectChanges();
await fixture.whenStable();
debug.query(By.css('.mat-select-trigger')).triggerEventHandler('click', null);
fixture.detectChanges();
await fixture.whenStable();
const options: any = debug.queryAll(By.css('mat-option'));
expect(options[0].nativeElement.innerText).not.toContain('DROPDOWN.MY_FILES_OPTION');
});
it('should show the default placeholder label by default', async () => {
fixture.detectChanges();
await fixture.whenStable();
openSelectBox();
fixture.detectChanges();
await fixture.whenStable();
expect(fixture.nativeElement.innerText.trim()).toContain('DROPDOWN.PLACEHOLDER_LABEL');
});
it('should show custom placeholder label when the "placeholder" input property is given a value', async () => {
component.placeholder = 'NODE_SELECTOR.SELECT_LOCATION';
fixture.detectChanges();
await fixture.whenStable();
openSelectBox();
fixture.detectChanges();
await fixture.whenStable();
expect(fixture.nativeElement.innerText.trim()).toContain('NODE_SELECTOR.SELECT_LOCATION');
});
it('should load custom sites when the "siteList" input property is given a value', async () => {
component.siteList = customSiteList;
fixture.detectChanges();
await fixture.whenStable();
openSelectBox();
fixture.detectChanges();
await fixture.whenStable();
const options = debug.queryAll(By.css('mat-option'));
options[0].triggerEventHandler('click', null);
fixture.detectChanges();
await fixture.whenStable();
expect(options[0].nativeElement.innerText).toContain('PERSONAL_FILES');
expect(options[1].nativeElement.innerText).toContain('FILE_LIBRARIES');
});
it('should load sites by default', async () => {
fixture.detectChanges();
await fixture.whenStable();
debug.query(By.css('.mat-select-trigger')).triggerEventHandler('click', null);
fixture.detectChanges();
await fixture.whenStable();
const options: any = debug.queryAll(By.css('mat-option'));
expect(options[1].nativeElement.innerText).toContain('fake-test-site');
expect(options[2].nativeElement.innerText).toContain('fake-test-2');
});
it('should raise an event when a site is selected', (done) => {
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
debug.query(By.css('.mat-select-trigger')).triggerEventHandler('click', null);
fixture.detectChanges();
const options: any = debug.queryAll(By.css('mat-option'));
options[1].nativeElement.click();
fixture.detectChanges();
});
component.change.subscribe((site) => {
expect(site.entry.guid).toBe('fake-1');
done();
});
});
it('should be possible to select the default value', async () => {
component.value = 'swsdp';
fixture.detectChanges();
await fixture.whenStable();
expect(component.selected.entry.title).toBe('fake-test-2');
});
});
describe('Default value', () => {
beforeEach(() => {
siteService = TestBed.inject(SitesService);
spyOn(siteService, 'getSites').and.returnValues(of(getFakeSitePagingFirstPage()), of(getFakeSitePagingLastPage()));
fixture = TestBed.createComponent(DropdownSitesComponent);
component = fixture.componentInstance;
});
it('should load new sites if default value is not in the first page', (done) => {
component.value = 'fake-test-4';
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(component.selected.entry.title).toBe('fake-test-4');
done();
});
});
it('should NOT reload infinitely if default value is NOT found after all sites are loaded', (done) => {
component.value = 'nonexistent-site';
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(component.selected).toBeUndefined();
expect(component.loading).toBeFalsy();
done();
});
});
});
describe('Sites with members', () => {
beforeEach(() => {
siteService = TestBed.inject(SitesService);
spyOn(siteService, 'getSites').and.returnValue(of(getFakeSitePagingWithMembers()));
fixture = TestBed.createComponent(DropdownSitesComponent);
debug = fixture.debugElement;
element = fixture.nativeElement;
component = fixture.componentInstance;
});
afterEach(() => {
fixture.destroy();
});
describe('No relations', () => {
beforeEach(() => {
component.relations = Relations.Members;
});
it('should show only sites which logged user is member of when member relation is set', (done) => {
spyOn(siteService, 'getEcmCurrentLoggedUserName').and.returnValue('test');
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
debug.query(By.css('.mat-select-trigger')).triggerEventHandler('click', null);
fixture.detectChanges();
fixture.whenStable().then(() => {
const options: any = debug.queryAll(By.css('mat-option'));
expect(options[1].nativeElement.innerText).toContain('FAKE-SITE-PUBLIC');
expect(options[2].nativeElement.innerText).toContain('FAKE-PRIVATE-SITE-MEMBER');
expect(options[3]).toBeUndefined();
done();
});
});
});
});
describe('No relations', () => {
beforeEach(() => {
component.relations = [];
});
it('should show all the sites if no relation is set', (done) => {
spyOn(siteService, 'getEcmCurrentLoggedUserName').and.returnValue('test');
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
debug.query(By.css('.mat-select-trigger')).triggerEventHandler('click', null);
fixture.detectChanges();
fixture.whenStable().then(() => {
const options: any = debug.queryAll(By.css('mat-option'));
expect(options[1].nativeElement.innerText).toContain('FAKE-MODERATED-SITE');
expect(options[2].nativeElement.innerText).toContain('FAKE-SITE-PUBLIC');
expect(options[3].nativeElement.innerText).toContain('FAKE-PRIVATE-SITE-MEMBER');
done();
});
});
});
});
});
});
}); | the_stack |
import * as assert from 'assert'
import * as sinon from 'sinon'
import * as vscode from 'vscode'
import * as path from 'path'
import * as codeLensUtils from '../../../shared/codelens/codeLensUtils'
import * as Picker from '../../../shared/ui/picker'
import {
API_TARGET_TYPE,
CODE_TARGET_TYPE,
TEMPLATE_TARGET_TYPE,
} from '../../../shared/sam/debugger/awsSamDebugConfiguration'
import * as AddSamDebugConfiguration from '../../../shared/sam/debugger/commands/addSamDebugConfiguration'
describe('codeLensUtils', async function () {
let sandbox: sinon.SinonSandbox
beforeEach(function () {
sandbox = sinon.createSandbox()
})
afterEach(function () {
sandbox.restore()
})
describe('invokeCodeLensCommandPalette', async function () {
const range1: vscode.Range = new vscode.Range(new vscode.Position(0, 0), new vscode.Position(0, 1))
const range2: vscode.Range = new vscode.Range(new vscode.Position(1, 0), new vscode.Position(1, 1))
const doc: Pick<vscode.TextDocument, 'getText'> = {
getText: (range: vscode.Range) => {
if (range.start.line === 0) {
return 'one'
} else if (range.start.line === 1) {
return 'two'
}
return 'other'
},
}
it('filters out launch configs leading to the invoker UI', async function () {
sandbox.stub(Picker, 'promptUser').resolves(undefined)
const spy = sandbox.spy(Picker, 'createQuickPick')
await codeLensUtils.invokeCodeLensCommandPalette(doc, [
{
isResolved: true,
range: range1,
command: {
command: 'foo',
title: 'hasUI',
arguments: ['foo', 'bar', true],
},
},
{
isResolved: true,
range: range2,
command: {
command: 'foo',
title: 'noUI',
arguments: ['foo', 'bar', false],
},
},
])
assert.ok(spy.calledOnce, 'Spy called more than once')
assert.strictEqual(spy.args[0][0].items?.length, 1, 'createQuickPick called with multiple items')
assert.deepStrictEqual(
spy.args[0][0].items![0],
{
label: 'two',
detail: 'Function on line 2',
lens: {
command: {
title: 'noUI',
arguments: ['foo', 'bar', false],
command: 'foo',
},
range: range2,
isResolved: true,
},
},
'createQuickPick called with incorrect item'
)
})
it('provides a single quick pick item with no codelens if no codelenses are provided', async function () {
sandbox.stub(Picker, 'promptUser').resolves(undefined)
const spy = sandbox.spy(Picker, 'createQuickPick')
await codeLensUtils.invokeCodeLensCommandPalette(doc, [])
assert.ok(spy.calledOnce, 'Spy called more than once')
assert.strictEqual(spy.args[0][0].items?.length, 1, 'createQuickPick called with multiple items')
assert.deepStrictEqual(
spy.args[0][0].items![0],
{
label: 'No handlers found in current file',
detail: 'Ensure your language extension is working',
description: 'Click here to go back',
},
'createQuickPick called with incorrect item'
)
})
it('returns undefined if no value or an invalid value is chosen', async function () {
sandbox
.stub(Picker, 'promptUser')
.onFirstCall()
.resolves(undefined)
.onSecondCall()
.resolves([
{
label: 'noLens',
detail: 'noLens',
},
])
.onThirdCall()
.resolves([
{
label: 'noCommand',
detail: 'noCommand',
},
])
const createSpy = sandbox.spy(Picker, 'createQuickPick')
const finalSpy = sandbox.spy(codeLensUtils, 'pickAddSamDebugConfiguration')
await codeLensUtils.invokeCodeLensCommandPalette(
doc,
[
/* stub handles all pick logic */
],
finalSpy
)
await codeLensUtils.invokeCodeLensCommandPalette(
doc,
[
/* stub handles all pick logic */
],
finalSpy
)
await codeLensUtils.invokeCodeLensCommandPalette(
doc,
[
/* stub handles all pick logic */
],
finalSpy
)
assert.ok(createSpy.calledThrice, 'Not all test payloads run')
assert.ok(finalSpy.notCalled, 'pickAddSamDebugConfiguration called; function did not return undefined')
})
it('can pass valid codelens contents to pickAddSamDebugConfiguration', async function () {
const arg0: AddSamDebugConfiguration.AddSamDebugConfigurationInput = {
resourceName: 'foo',
rootUri: vscode.Uri.parse('file:///asdf'),
}
const arg1: AddSamDebugConfiguration.AddSamDebugConfigurationInput[] = []
const arg2 = false
const target = {
label: 'two',
detail: 'Function on line 2',
lens: {
command: {
title: 'noUI',
arguments: [arg0, arg1, arg2],
command: 'foo',
},
range: range2,
isResolved: true,
},
}
sandbox
.stub(Picker, 'promptUser')
.onFirstCall()
.resolves([target as any])
const finalStub = sandbox
.stub(codeLensUtils, 'pickAddSamDebugConfiguration')
.onFirstCall()
.resolves(undefined)
await codeLensUtils.invokeCodeLensCommandPalette(
doc,
[
/* stub handles all pick logic */
],
finalStub
)
assert.ok(finalStub.calledOnce, 'pickAddSamDebugConfiguration not called once and only once')
assert.ok(finalStub.calledWith(arg0, arg1, arg2), 'pickAddSamDebugConfiguration called with incorrect args')
})
})
describe('pickAddSamDebugConfiguration', function () {
it('should use CODE_TARGET_TYPE with no templateConfigs', function () {
const addSamStub = sandbox.stub(AddSamDebugConfiguration, 'addSamDebugConfiguration')
const codeConfig: AddSamDebugConfiguration.AddSamDebugConfigurationInput = {
resourceName: 'codeResource',
rootUri: vscode.Uri.file('path'),
}
const templateConfigs: AddSamDebugConfiguration.AddSamDebugConfigurationInput[] = []
codeLensUtils.pickAddSamDebugConfiguration(codeConfig, templateConfigs, false)
assert.strictEqual(addSamStub.calledOnceWith(codeConfig, CODE_TARGET_TYPE, false), true)
})
it('should use CODE_TARGET_TYPE when no template option is chosen', async function () {
sandbox.stub(Picker, 'promptUser').resolves(undefined)
sandbox.stub(Picker, 'verifySinglePickerOutput').returns({ label: 'No Template' })
const addSamStub = sandbox.stub(AddSamDebugConfiguration, 'addSamDebugConfiguration').resolves()
const codeConfig: AddSamDebugConfiguration.AddSamDebugConfigurationInput = {
resourceName: 'codeResource',
rootUri: vscode.Uri.file('path'),
}
const templateConfigs: AddSamDebugConfiguration.AddSamDebugConfigurationInput[] = [
{ resourceName: 'templateNoApi', rootUri: vscode.Uri.file('path') },
]
await codeLensUtils.pickAddSamDebugConfiguration(codeConfig, templateConfigs, false)
assert.strictEqual(addSamStub.calledOnceWith(codeConfig, CODE_TARGET_TYPE, false), true)
})
it('should use API_TARGET_TYPE when API template option is chosen', async function () {
sandbox.stub(Picker, 'promptUser').resolves(undefined)
sandbox
.stub(Picker, 'verifySinglePickerOutput')
.returns({ label: `${path.sep}path:templateWithApi (API Event: eventName)` })
const addSamStub = sandbox.stub(AddSamDebugConfiguration, 'addSamDebugConfiguration').resolves()
const codeConfig: AddSamDebugConfiguration.AddSamDebugConfigurationInput = {
resourceName: 'codeResource',
rootUri: vscode.Uri.file('path'),
}
const templateConfigs: AddSamDebugConfiguration.AddSamDebugConfigurationInput[] = [
{
resourceName: 'templateWithApi',
rootUri: vscode.Uri.file('path'),
apiEvent: { name: 'eventName', event: { Type: 'Api' } },
},
]
await codeLensUtils.pickAddSamDebugConfiguration(codeConfig, templateConfigs, false)
assert.strictEqual(addSamStub.args[0][1], API_TARGET_TYPE)
})
it('should use TEMPLATE_TARGET_TYPE when non API template option is chosen', async function () {
sandbox.stub(Picker, 'promptUser').resolves(undefined)
sandbox.stub(Picker, 'verifySinglePickerOutput').returns({ label: `${path.sep}path:templateNoApi` })
const addSamStub = sandbox.stub(AddSamDebugConfiguration, 'addSamDebugConfiguration').resolves()
const codeConfig: AddSamDebugConfiguration.AddSamDebugConfigurationInput = {
resourceName: 'codeResource',
rootUri: vscode.Uri.file('path'),
}
const templateConfigs: AddSamDebugConfiguration.AddSamDebugConfigurationInput[] = [
{ resourceName: 'templateNoApi', rootUri: vscode.Uri.file('path') },
]
await codeLensUtils.pickAddSamDebugConfiguration(codeConfig, templateConfigs, false)
assert.strictEqual(addSamStub.args[0][1], TEMPLATE_TARGET_TYPE)
})
})
}) | the_stack |
import * as coreClient from "@azure/core-client";
/** The container for solution. */
export interface Solution {
/**
* Resource ID.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly id?: string;
/**
* Resource name.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/**
* Resource type.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: string;
/** Resource location */
location?: string;
/** Resource tags */
tags?: { [propertyName: string]: string };
/** Plan for solution object supported by the OperationsManagement resource provider. */
plan?: SolutionPlan;
/** Properties for solution object supported by the OperationsManagement resource provider. */
properties?: SolutionProperties;
}
/** Plan for solution object supported by the OperationsManagement resource provider. */
export interface SolutionPlan {
/** name of the solution to be created. For Microsoft published solution it should be in the format of solutionType(workspaceName). SolutionType part is case sensitive. For third party solution, it can be anything. */
name?: string;
/** Publisher name. For gallery solution, it is Microsoft. */
publisher?: string;
/** promotionCode, Not really used now, can you left as empty */
promotionCode?: string;
/** name of the solution to enabled/add. For Microsoft published gallery solution it should be in the format of OMSGallery/<solutionType>. This is case sensitive */
product?: string;
}
/** Solution properties supported by the OperationsManagement resource provider. */
export interface SolutionProperties {
/** The azure resourceId for the workspace where the solution will be deployed/enabled. */
workspaceResourceId: string;
/**
* The provisioning state for the solution.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly provisioningState?: string;
/** The azure resources that will be contained within the solutions. They will be locked and gets deleted automatically when the solution is deleted. */
containedResources?: string[];
/** The resources that will be referenced from this solution. Deleting any of those solution out of band will break the solution. */
referencedResources?: string[];
}
/** The error body contract. */
export interface CodeMessageError {
/** The error details for a failed request. */
error?: CodeMessageErrorError;
}
/** The error details for a failed request. */
export interface CodeMessageErrorError {
/** The error type. */
code?: string;
/** The error message. */
message?: string;
}
/** The properties of a Solution that can be patched. */
export interface SolutionPatch {
/** Resource tags */
tags?: { [propertyName: string]: string };
}
/** the list of solution response */
export interface SolutionPropertiesList {
/** List of solution properties within the subscription. */
value?: Solution[];
}
/** the list of ManagementAssociation response */
export interface ManagementAssociationPropertiesList {
/** List of Management Association properties within the subscription. */
value?: ManagementAssociation[];
}
/** The container for solution. */
export interface ManagementAssociation {
/**
* Resource ID.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly id?: string;
/**
* Resource name.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/**
* Resource type.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: string;
/** Resource location */
location?: string;
/** Properties for ManagementAssociation object supported by the OperationsManagement resource provider. */
properties?: ManagementAssociationProperties;
}
/** ManagementAssociation properties supported by the OperationsManagement resource provider. */
export interface ManagementAssociationProperties {
/** The applicationId of the appliance for this association. */
applicationId: string;
}
/** the list of ManagementConfiguration response */
export interface ManagementConfigurationPropertiesList {
/** List of Management Configuration properties within the subscription. */
value?: ManagementConfiguration[];
}
/** The container for solution. */
export interface ManagementConfiguration {
/**
* Resource ID.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly id?: string;
/**
* Resource name.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/**
* Resource type.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: string;
/** Resource location */
location?: string;
/** Properties for ManagementConfiguration object supported by the OperationsManagement resource provider. */
properties?: ManagementConfigurationProperties;
}
/** ManagementConfiguration properties supported by the OperationsManagement resource provider. */
export interface ManagementConfigurationProperties {
/** The applicationId of the appliance for this Management. */
applicationId?: string;
/** The type of the parent resource. */
parentResourceType: string;
/** Parameters to run the ARM template */
parameters: ArmTemplateParameter[];
/**
* The provisioning state for the ManagementConfiguration.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly provisioningState?: string;
/** The Json object containing the ARM template to deploy */
template: Record<string, unknown>;
}
/** Parameter to pass to ARM template */
export interface ArmTemplateParameter {
/** name of the parameter. */
name?: string;
/** value for the parameter. In Jtoken */
value?: string;
}
/** Result of the request to list solution operations. */
export interface OperationListResult {
/** List of solution operations supported by the OperationsManagement resource provider. */
value?: Operation[];
}
/** Supported operation of OperationsManagement resource provider. */
export interface Operation {
/** Operation name: {provider}/{resource}/{operation} */
name?: string;
/** Display metadata associated with the operation. */
display?: OperationDisplay;
}
/** Display metadata associated with the operation. */
export interface OperationDisplay {
/** Service provider: Microsoft OperationsManagement. */
provider?: string;
/** Resource on which the operation is performed etc. */
resource?: string;
/** Type of operation: get, read, delete, etc. */
operation?: string;
}
/** Optional parameters. */
export interface SolutionsCreateOrUpdateOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Contains response data for the createOrUpdate operation. */
export type SolutionsCreateOrUpdateResponse = Solution;
/** Optional parameters. */
export interface SolutionsUpdateOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Contains response data for the update operation. */
export type SolutionsUpdateResponse = Solution;
/** Optional parameters. */
export interface SolutionsDeleteOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Optional parameters. */
export interface SolutionsGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type SolutionsGetResponse = Solution;
/** Optional parameters. */
export interface SolutionsListByResourceGroupOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listByResourceGroup operation. */
export type SolutionsListByResourceGroupResponse = SolutionPropertiesList;
/** Optional parameters. */
export interface SolutionsListBySubscriptionOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listBySubscription operation. */
export type SolutionsListBySubscriptionResponse = SolutionPropertiesList;
/** Optional parameters. */
export interface ManagementAssociationsListBySubscriptionOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listBySubscription operation. */
export type ManagementAssociationsListBySubscriptionResponse = ManagementAssociationPropertiesList;
/** Optional parameters. */
export interface ManagementAssociationsCreateOrUpdateOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the createOrUpdate operation. */
export type ManagementAssociationsCreateOrUpdateResponse = ManagementAssociation;
/** Optional parameters. */
export interface ManagementAssociationsDeleteOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface ManagementAssociationsGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type ManagementAssociationsGetResponse = ManagementAssociation;
/** Optional parameters. */
export interface ManagementConfigurationsListBySubscriptionOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listBySubscription operation. */
export type ManagementConfigurationsListBySubscriptionResponse = ManagementConfigurationPropertiesList;
/** Optional parameters. */
export interface ManagementConfigurationsCreateOrUpdateOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the createOrUpdate operation. */
export type ManagementConfigurationsCreateOrUpdateResponse = ManagementConfiguration;
/** Optional parameters. */
export interface ManagementConfigurationsDeleteOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface ManagementConfigurationsGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type ManagementConfigurationsGetResponse = ManagementConfiguration;
/** Optional parameters. */
export interface OperationsListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type OperationsListResponse = OperationListResult;
/** Optional parameters. */
export interface OperationsManagementClientOptionalParams
extends coreClient.ServiceClientOptions {
/** server parameter */
$host?: string;
/** Api Version */
apiVersion?: string;
/** Overrides client endpoint. */
endpoint?: string;
} | the_stack |
import {
clearNode,
createEvent,
createDomain,
forward,
createStore,
sample,
combine,
createEffect,
split,
} from 'effector'
import {argumentHistory} from 'effector/fixtures'
it('will deactivate event', () => {
const fn = jest.fn()
const event = createEvent<number>()
event.watch(x => fn(x))
clearNode(event)
event(1)
expect(fn).toBeCalledTimes(0)
})
it('will deactivate store', () => {
const fn = jest.fn()
const store = createStore(0)
store.watch(x => fn(x))
expect(fn).toBeCalledTimes(1)
clearNode(store)
//@ts-expect-error
store.setState(1)
expect(fn).toBeCalledTimes(1)
})
it('will not broke subscribers', () => {
const fn = jest.fn()
const eventA = createEvent<number>()
const eventB = createEvent<number>()
eventB.watch(e => fn(e))
forward({
from: eventA,
to: eventB,
})
eventA(0)
expect(fn).toBeCalledTimes(1)
clearNode(eventA)
eventA(1) //nothing happens
expect(fn).toBeCalledTimes(1)
eventB(2) //work as expected
expect(fn).toBeCalledTimes(2)
})
test('deep cleaning', () => {
const fn1 = jest.fn()
const fn2 = jest.fn()
const source = createStore(0)
const target = source.map(x => {
fn1(x)
return x
})
target.watch(x => fn2(x))
expect(fn1).toBeCalledTimes(1)
expect(fn2).toBeCalledTimes(1)
//please be careful with {deep: true}
//it will destroy everything related to that node
clearNode(source, {deep: true})
//@ts-expect-error
source.setState(1) //nothing happens
expect(fn1).toBeCalledTimes(1)
expect(fn2).toBeCalledTimes(1)
//@ts-expect-error
target.setState(2) //dead as well
expect(fn2).toBeCalledTimes(1)
})
describe('itermediate steps should not stay', () => {
it('support store.map', () => {
const fn = jest.fn()
const source = createStore(0)
const target = source.map(x => {
fn(x)
return x
})
//@ts-expect-error
source.setState(1)
expect(fn).toBeCalledTimes(2)
clearNode(target)
//@ts-expect-error
source.setState(2)
expect(fn).toBeCalledTimes(2)
})
it('support event.map', () => {
const fn = jest.fn()
const source = createEvent<number>()
const target = source.map(x => {
fn(x)
return x
})
source(1)
expect(fn).toBeCalledTimes(1)
clearNode(target)
source(2)
expect(fn).toBeCalledTimes(1)
})
it('support store.on', () => {
const fn = jest.fn()
const trigger = createEvent()
const store = createStore(0).on(trigger, x => {
fn(x)
return x + 1
})
trigger()
expect(fn).toBeCalledTimes(1)
clearNode(store)
trigger()
expect(fn).toBeCalledTimes(1)
})
it('support sample result', () => {
const fn = jest.fn()
const trigger = createEvent()
const store = createStore(null)
const result = sample({
source: store,
clock: trigger,
fn,
})
trigger()
expect(fn).toBeCalledTimes(1)
clearNode(result)
trigger()
expect(fn).toBeCalledTimes(1)
})
it('support sample source', () => {
const fn = jest.fn()
const trigger = createEvent()
const store = createStore(null)
sample({
source: store,
clock: trigger,
fn,
})
trigger()
expect(fn).toBeCalledTimes(1)
clearNode(store)
trigger()
expect(fn).toBeCalledTimes(1)
})
})
describe('based on clearNode', () => {
it('will not clear store after event will be destroyed', () => {
const fn = jest.fn()
const store = createStore(0)
const eventA = createEvent()
const eventB = createEvent()
store.on(eventA, x => x + 1).on(eventB, x => x + 1)
store.watch(fn)
eventA()
clearNode(eventA)
eventB()
expect(argumentHistory(fn)).toMatchInlineSnapshot(`
Array [
0,
1,
2,
]
`)
})
it('will not clear connected units after forward will be destroyed', () => {
const fn = jest.fn()
const eventA = createEvent<number>()
const eventB = createEvent<number>()
const unsub = forward({
from: eventA,
to: eventB,
})
eventA.watch(fn)
eventA(0)
unsub()
eventA(1)
expect(argumentHistory(fn)).toMatchInlineSnapshot(`
Array [
0,
1,
]
`)
})
it('will not clear unit after .watch will be destroyed', () => {
const fn = jest.fn()
const event = createEvent<number>()
const unsub = event.watch(() => {})
event.watch(fn)
event(0)
unsub()
event(1)
expect(argumentHistory(fn)).toMatchInlineSnapshot(`
Array [
0,
1,
]
`)
})
it('will not clear store after store.updates.watch will be destroyed', () => {
const fn = jest.fn()
const event = createEvent()
const store = createStore(0).on(event, x => x + 1)
const unsub = store.updates.watch(() => {})
store.updates.watch(fn)
event()
unsub()
event()
expect(argumentHistory(fn)).toMatchInlineSnapshot(`
Array [
1,
2,
]
`)
})
it('will not clear node, connected via forward to destroyed one', () => {
const fn = jest.fn()
const store = createStore(0)
const event = createEvent<number>()
event.watch(fn)
forward({
from: store.updates,
to: event,
})
//@ts-expect-error
store.setState(1)
event(2)
clearNode(store)
event(3)
expect(argumentHistory(fn)).toMatchInlineSnapshot(`
Array [
1,
2,
3,
]
`)
})
it('will not clear node, which forwarded to destroyed one', () => {
const fn = jest.fn()
const store = createStore(0)
const event = createEvent()
store.updates.watch(fn)
forward({
from: store.updates,
to: event,
})
//@ts-expect-error
store.setState(1)
clearNode(event)
//@ts-expect-error
store.setState(2)
expect(argumentHistory(fn)).toMatchInlineSnapshot(`
Array [
1,
2,
]
`)
})
})
describe('domain support', () => {
it('will not clear domain.createStore after event will be destroyed', () => {
const fn = jest.fn()
const domain = createDomain()
const store = domain.createStore(0)
const eventA = domain.createEvent()
const eventB = domain.createEvent()
store.on(eventA, x => x + 1).on(eventB, x => x + 1)
store.watch(fn)
eventA()
clearNode(eventA)
eventB()
expect(argumentHistory(fn)).toMatchInlineSnapshot(`
Array [
0,
1,
2,
]
`)
})
it('will not clear connected units after forward will be destroyed', () => {
const fn = jest.fn()
const domain = createDomain()
const eventA = domain.createEvent<number>()
const eventB = domain.createEvent<number>()
const unsub = forward({
from: eventA,
to: eventB,
})
eventA.watch(fn)
eventA(0)
unsub()
eventA(1)
expect(argumentHistory(fn)).toMatchInlineSnapshot(`
Array [
0,
1,
]
`)
})
it('will not clear unit after .watch will be destroyed', () => {
const fn = jest.fn()
const domain = createDomain()
const event = domain.createEvent<number>()
const unsub = event.watch(() => {})
event.watch(fn)
event(0)
unsub()
event(1)
expect(argumentHistory(fn)).toMatchInlineSnapshot(`
Array [
0,
1,
]
`)
})
it('will not clear store after store.updates.watch will be destroyed', () => {
const fn = jest.fn()
const domain = createDomain()
const event = domain.createEvent()
const store = domain.createStore(0).on(event, x => x + 1)
const unsub = store.updates.watch(() => {})
store.updates.watch(fn)
event()
unsub()
event()
expect(argumentHistory(fn)).toMatchInlineSnapshot(`
Array [
1,
2,
]
`)
})
it('will not clear node, connected via forward to destroyed one', () => {
const fn = jest.fn()
const domain = createDomain()
const store = domain.createStore(0)
const event = domain.createEvent<number>()
event.watch(fn)
forward({
from: store.updates,
to: event,
})
//@ts-expect-error
store.setState(1)
event(2)
clearNode(store)
event(3)
expect(argumentHistory(fn)).toMatchInlineSnapshot(`
Array [
1,
2,
3,
]
`)
})
it('will not clear node, which forwarded to destroyed one', () => {
const fn = jest.fn()
const domain = createDomain()
const store = domain.createStore(0)
const event = domain.createEvent()
store.updates.watch(fn)
forward({
from: store.updates,
to: event,
})
//@ts-expect-error
store.setState(1)
clearNode(event)
//@ts-expect-error
store.setState(2)
expect(argumentHistory(fn)).toMatchInlineSnapshot(`
Array [
1,
2,
]
`)
})
it('will not clear event after clearNode call at its prepended event', () => {
const fn = jest.fn()
const domain = createDomain()
const event = domain.createEvent<number>()
const prepended = event.prepend<number>(_ => _)
event.watch(fn)
clearNode(prepended)
event(1)
expect(argumentHistory(fn)).toEqual([1])
})
test('child should not survive clearNode(domain) call', () => {
const fn = jest.fn()
const domain = createDomain()
const event = domain.createEvent<number>()
event.watch(fn)
event(1)
clearNode(domain)
event(2)
expect(argumentHistory(fn)).toEqual([1])
})
describe('clearNode(domain) should not affect sibling nodes', () => {
describe('with forward', () => {
test('from', () => {
const fn = jest.fn()
const domain = createDomain()
const event = createEvent<number>()
const event2 = domain.createEvent<number>()
forward({
from: event,
to: event2,
})
event.watch(fn)
event(0)
clearNode(domain)
event(1)
expect(argumentHistory(fn)).toEqual([0, 1])
})
test('from array', () => {
const fn = jest.fn()
const domain = createDomain()
const event = createEvent<number>()
const event2 = domain.createEvent<number>()
const event3 = domain.createEvent<number>()
forward({
from: [event, event2],
to: event3,
})
event.watch(fn)
event(0)
clearNode(domain)
event(1)
expect(argumentHistory(fn)).toEqual([0, 1])
})
test('to', () => {
const fn = jest.fn()
const domain = createDomain()
const event = createEvent<number>()
const event2 = domain.createEvent<number>()
forward({
from: event2,
to: event,
})
event.watch(fn)
event(0)
event2(1)
clearNode(domain)
event(2)
event2(3)
expect(argumentHistory(fn)).toEqual([0, 1, 2])
})
test('to array', () => {
const fn = jest.fn()
const domain = createDomain()
const event = createEvent<number>()
const event2 = domain.createEvent<number>()
const event3 = domain.createEvent<number>()
forward({
from: event2,
to: [event, event3],
})
event.watch(fn)
event(0)
event2(1)
clearNode(domain)
event(2)
event2(3)
expect(argumentHistory(fn)).toEqual([0, 1, 2])
})
})
test('with sample', () => {
const fn = jest.fn()
const fn2 = jest.fn()
const store = createStore<number | null>(null)
const event = createEvent<number>()
store.on(event, (_, e) => e)
store.watch(fn)
const domain = createDomain()
const eventInDomain = domain.createEvent<number>()
eventInDomain.watch(fn2)
sample({
source: store,
clock: eventInDomain,
})
event(1)
eventInDomain(-1)
clearNode(domain)
event(2)
eventInDomain(-2)
expect(argumentHistory(fn2)).toEqual([-1])
expect(argumentHistory(fn)).toEqual([null, 1, 2])
})
test('with combine', () => {
const fn = jest.fn()
const fn2 = jest.fn()
const store = createStore<number | null>(null)
const event = createEvent<number>()
store.on(event, (_, e) => e)
store.watch(fn)
const domain = createDomain()
const storeInDomain = domain.createStore<number | null>(null)
storeInDomain.on(event, (_, e) => e)
storeInDomain.watch(fn2)
combine({store, storeInDomain})
event(1)
clearNode(domain)
event(2)
expect(argumentHistory(fn2)).toEqual([null, 1])
expect(argumentHistory(fn)).toEqual([null, 1, 2])
})
describe('with split', () => {
test('from domain source to non-domain target', () => {
const fn = jest.fn()
const domain = createDomain()
const source = domain.createEvent<number>()
const target = createEvent<number>()
split({
source,
match: {even: x => x % 2 === 0},
cases: {even: target},
})
target.watch(fn)
clearNode(domain)
source(2)
target(4)
expect(argumentHistory(fn)).toEqual([4])
})
test('from non-domain source to domain target', () => {
const fn = jest.fn()
const domain = createDomain()
const source = createEvent<number>()
const target = domain.createEvent<number>()
split({
source,
match: {even: x => x % 2 === 0},
cases: {even: target},
})
source.watch(fn)
clearNode(domain)
source(2)
target(4)
expect(argumentHistory(fn)).toEqual([2])
})
test('from domain source to domain target', () => {
const fn = jest.fn()
const domain1 = createDomain()
const domain2 = createDomain()
const source = domain1.createEvent<number>()
const target = domain2.createEvent<number>()
split({
source,
match: {even: x => x % 2 === 0},
cases: {even: target},
})
target.watch(fn)
clearNode(domain1)
source(2)
target(4)
expect(argumentHistory(fn)).toEqual([4])
})
})
})
describe('clearNode(domain) should not affect sample targets', () => {
test('with store as source', () => {
const fn = jest.fn()
const fn2 = jest.fn()
const event1 = createEvent<number>()
const event2 = createEvent<number>()
const storeA = createStore(0).on(event1, (_, v) => v)
const storeB = createStore(0).on(event2, (_, v) => v)
storeA.watch(fn)
storeB.watch(fn2)
const domain = createDomain()
const storeInDomain = domain.createStore(0)
sample({
source: storeInDomain,
clock: createEvent(),
target: storeA,
})
sample({
source: storeA,
clock: createEvent(),
target: storeB,
})
event1(1)
event2(100)
clearNode(domain)
event1(2)
event2(200)
expect(argumentHistory(fn2)).toEqual([0, 100, 200])
expect(argumentHistory(fn)).toEqual([0, 1, 2])
})
test('with event as source', () => {
const fn = jest.fn()
const fn2 = jest.fn()
const store = createStore(0)
const source = createEvent<number>()
const clock = createEvent()
source.watch(fn)
store.watch(fn2)
const domain = createDomain()
const eventInDomain = domain.createEvent<number>()
sample({
source: eventInDomain,
clock: createEvent(),
target: store,
})
sample({
source,
clock,
target: store,
})
source(1)
clock()
clearNode(domain)
source(2)
clock()
expect(argumentHistory(fn2)).toEqual([0, 1, 2])
expect(argumentHistory(fn)).toEqual([1, 2])
})
})
describe('clearNode(domain) should not propagate through .on', () => {
test('to store without domain', async () => {
const fn1 = jest.fn()
const fn2 = jest.fn()
const domain1 = createDomain()
const inc = createEffect(() => 1)
const dec = createEvent()
const store1 = domain1.createStore(0).on(inc.doneData, x => x + 1)
const store2 = createStore(0)
.on(inc.doneData, x => x + 1)
.on(dec, x => x - 1)
store2.watch(fn1)
inc.doneData.watch(fn2)
clearNode(domain1)
await inc()
await inc()
dec()
expect(argumentHistory(fn1)).toMatchInlineSnapshot(`
Array [
0,
1,
2,
1,
]
`)
expect(fn2).toBeCalledTimes(2)
})
describe('to sibling domain', () => {
test('through effect without domain', async () => {
const fn1 = jest.fn()
const fn2 = jest.fn()
const domain1 = createDomain()
const domain2 = createDomain()
const inc = createEffect(() => 1)
const dec = createEvent()
const store1 = domain1.createStore(0).on(inc.doneData, x => x + 1)
const store2 = domain2
.createStore(0)
.on(inc.doneData, x => x + 1)
.on(dec, x => x - 1)
store2.watch(fn1)
inc.doneData.watch(fn2)
clearNode(domain1)
await inc()
await inc()
dec()
expect(argumentHistory(fn1)).toMatchInlineSnapshot(`
Array [
0,
1,
2,
1,
]
`)
expect(fn2).toBeCalledTimes(2)
})
test('through effect in sibling domain', async () => {
const fn1 = jest.fn()
const fn2 = jest.fn()
const domain1 = createDomain()
const domain2 = createDomain()
const inc = domain2.createEffect(() => 1)
const dec = createEvent()
const store1 = domain1.createStore(0).on(inc.doneData, x => x + 1)
const store2 = domain2
.createStore(0)
.on(inc.doneData, x => x + 1)
.on(dec, x => x - 1)
store2.watch(fn1)
inc.doneData.watch(fn2)
clearNode(domain1)
await inc()
await inc()
dec()
expect(argumentHistory(fn1)).toMatchInlineSnapshot(`
Array [
0,
1,
2,
1,
]
`)
expect(fn2).toBeCalledTimes(2)
})
test('through effect in target domain', async () => {
const fn1 = jest.fn()
const fn2 = jest.fn()
const domain1 = createDomain()
const domain2 = createDomain()
const inc = domain1.createEffect(() => 1)
const dec = createEvent()
const store1 = domain1.createStore(0).on(inc.doneData, x => x + 1)
const store2 = domain2
.createStore(0)
.on(inc.doneData, x => x + 1)
.on(dec, x => x - 1)
store2.watch(fn1)
inc.doneData.watch(fn2)
clearNode(domain1)
inc()
inc()
dec()
expect(argumentHistory(fn1)).toMatchInlineSnapshot(`
Array [
0,
-1,
]
`)
expect(fn2).toBeCalledTimes(0)
})
})
describe('to parent domain', () => {
test('through effect without domain', async () => {
const fn1 = jest.fn()
const fn2 = jest.fn()
const rootDomain = createDomain()
const domain1 = rootDomain.createDomain()
const inc = createEffect(() => 1)
const dec = createEvent()
const store1 = domain1.createStore(0).on(inc.doneData, x => x + 1)
const store2 = rootDomain
.createStore(0)
.on(inc.doneData, x => x + 1)
.on(dec, x => x - 1)
store2.watch(fn1)
inc.doneData.watch(fn2)
clearNode(domain1)
await inc()
await inc()
dec()
expect(argumentHistory(fn1)).toMatchInlineSnapshot(`
Array [
0,
1,
2,
1,
]
`)
expect(fn2).toBeCalledTimes(2)
})
test('through effect in root domain', async () => {
const fn1 = jest.fn()
const fn2 = jest.fn()
const rootDomain = createDomain()
const domain1 = rootDomain.createDomain()
const inc = rootDomain.createEffect(() => 1)
const dec = createEvent()
const store1 = domain1.createStore(0).on(inc.doneData, x => x + 1)
const store2 = rootDomain
.createStore(0)
.on(inc.doneData, x => x + 1)
.on(dec, x => x - 1)
store2.watch(fn1)
inc.doneData.watch(fn2)
clearNode(domain1)
await inc()
await inc()
dec()
expect(argumentHistory(fn1)).toMatchInlineSnapshot(`
Array [
0,
1,
2,
1,
]
`)
expect(fn2).toBeCalledTimes(2)
})
test('through effect in target domain', async () => {
const fn1 = jest.fn()
const fn2 = jest.fn()
const rootDomain = createDomain()
const domain1 = rootDomain.createDomain()
const inc = domain1.createEffect(() => 1)
const dec = createEvent()
const store1 = domain1.createStore(0).on(inc.doneData, x => x + 1)
const store2 = rootDomain
.createStore(0)
.on(inc.doneData, x => x + 1)
.on(dec, x => x - 1)
store2.watch(fn1)
inc.doneData.watch(fn2)
clearNode(domain1)
inc()
inc()
dec()
expect(argumentHistory(fn1)).toMatchInlineSnapshot(`
Array [
0,
-1,
]
`)
expect(fn2).toBeCalledTimes(0)
})
})
})
it('should remove erased units from domain hooks', () => {
const fn = jest.fn()
const domain = createDomain()
const event = domain.createEvent()
clearNode(event)
domain.onCreateEvent(fn)
expect(domain.history.events.size).toBe(0)
expect(fn).not.toHaveBeenCalled()
})
}) | the_stack |
/// <reference path="../typings/jquery/jquery.d.ts"/>
/// <reference path="../typings/qunit/qunit.d.ts"/>
/// <reference path="../ClientApi/WebApiCoreJQClientAuto.ts"/>
// Make sure chutzpah.json is updated with reference to the jQuery lib when the lib is upgraded.
// Sometimes the test cases are not appearing in Test Explorer, then claring %temp% may help.
// To launch IIS Express, use something like this: C:\VsProjects\webapiclientgen>"C:\Program Files (x86)\IIS Express\iisexpress.exe" /site:DemoWebApi /apppool:Clr4IntegratedAppPool /config:c:\vsprojects\webapiclientgen\.vs\config\applicationhost.config
// The post build events will copy the JS file of this test to wwwroot and bin\debug\...\wwwroot\
/*
And make sure the testApi credential exists through
POST to http://localhost:10965/api/Account/Register
Content-Type: application/json
{
Email: 'testapi@test.com',
Password: 'Tttttttt_8',
ConfirmPassword: 'Tttttttt_8'
}
*/
module CommonCases {
QUnit.config.testTimeout = 30000;
const baseUri = HttpClient.locationOrigin;
let authHttpClient = new AuthHttpClient();
let entitiesApi = new DemoWebApi_Controllers_Client.Entities(baseUri, authHttpClient);
let valuesApi = new DemoWebApi_Controllers_Client.Values(baseUri, authHttpClient);
let superDemoApi = new DemoWebApi_Controllers_Client.SuperDemo(baseUri);
let tupleApi = new DemoWebApi_Controllers_Client.Tuple(baseUri);
let heroesApi = new DemoWebApi_Controllers_Client.Heroes(baseUri);
//This should always work since it is a simple unit test.
QUnit.test("data compare", function (assert) {
let person: DemoWebApi_DemoData_Client.Person = {
name: "someone",
surname: "my",
givenName: "something",
};
let person2: DemoWebApi_DemoData_Client.Person = {
name: "someone",
surname: "my",
givenName: "something",
};
assert.equal(JSON.stringify(person), JSON.stringify(person2));
});
QUnit.module("Heroes", function () {
QUnit.test("GetAll", function (assert) {
let done = assert.async();
heroesApi.getHeros(data => {
assert.ok(data.length > 0);
done();
});
});
QUnit.test("Get", function (assert) {
let done = assert.async();
heroesApi.getHero(20, data => {
assert.equal(data.name, "Tornado");
done();
});
});
QUnit.test("Add", function (assert) {
let done = assert.async();
heroesApi.post("somebody", data => {
assert.equal(data.name, "somebody");
done();
});
});
QUnit.test("Search", function (assert) {
let done = assert.async();
heroesApi.search("Torn", data => {
assert.equal(data.length, 1);
assert.equal(data[0].name, "Tornado");
done();
});
});
});
QUnit.module('Entities', function () {
QUnit.test('GetMimsString', function (assert) {
const c: DemoWebApi_DemoData_Client.MimsPackage = {
tag: 'Hello',
result: {
result: 123.45
}
};
let done = assert.async();
entitiesApi.getMims(c, data => {
assert.strictEqual(data.message, 'Hello');
assert.equal(data.result, 123.45);
done();
});
});
QUnit.test('myGenericPerson', function (assert) {
const newPerson: DemoWebApi_DemoData_Client.Person = {
name: 'John Smith',
givenName: 'John',
surname: 'Smith',
dob: new Date('1977-12-28')
};
const c: DemoWebApi_DemoData_Client.MyGeneric<string, number, DemoWebApi_DemoData_Client.Person> = {
myK: 123.456,
myT: 'abc',
myU: newPerson,
status: 'OK',
};
let done = assert.async();
entitiesApi.getMyGenericPerson(c, data => {
assert.strictEqual(data.status, 'OK');
assert.equal(data.myU.name, 'John Smith');
done();
});
});
});
QUnit.module("TupleTests", function () {
QUnit.test("GetTuple2", function (assert) {
let done = assert.async();
tupleApi.getTuple2((data) => {
assert.equal(data["item1"], "Two");
assert.equal(data["item2"], 2);
done();
});
});
QUnit.test("PostTuple2", function (assert) {
let done = assert.async();
tupleApi.postTuple2({ item1: "One", item2: 2 }, (data) => {
assert.equal(data, "One");
done();
});
});
QUnit.test("GetTuple7", function (assert) {
let done = assert.async();
tupleApi.getTuple7((data) => {
assert.equal(data["item1"], "Seven");
assert.equal(data["item7"], 7);
done();
});
});
//Visual Studio IDE may give some
QUnit.test("PostTuple7", function (assert) {
let done = assert.async();
tupleApi.postTuple7({ item1: "One", item2: "", item3: "", item4: "", item5: "", item6: 33333, item7: 9 }, (data) => {
assert.equal(data, "One");
done();
});
});
QUnit.test("GetTuple8", function (assert) {
let done = assert.async();
tupleApi.getTuple8((data) => {
assert.equal(data["item1"], "Nested");
assert.equal(data["rest"].item1, "nine");
done();
});
});
//Visual Studio IDE may give some
QUnit.test("PostTuple8", function (assert) {
let done = assert.async();
tupleApi.postTuple8({ item1: "One", item2: "", item3: "", item4: "", item5: "", item6: "", item7: "", rest: { item1: "a", item2: "b", item3: "c" } }, (data) => {
assert.equal(data, "a");
done();
});
});
QUnit.test("LinkPersonCompany", function (assert) {
let done = assert.async();
tupleApi.linkPersonCompany1({
item1: {
name: "someone",
surname: "my",
givenName: "something",
},
item2: {
name: "Super",
addresses: [{ city: "New York", street1: "Somewhere st" }]
}
}, (data) => {
assert.equal(data.name, "someone");
done();
});
}
);
});
QUnit.module("SuperDemoTests", function () {
QUnit.test("JsZeroNotGood", function (assert) {
assert.notEqual(0.1 + 0.2 - 0.3, 0, "Zero, Zero; equal succeeds");
});
//if the WebAPI built with VS 2015 update 2 is hosted in IIS 10, this test pass.
//If the WebAPI built with VS 2015 update 2 is hosted in IIS 7.5, the test will failed.
// with .net core, equal is OK again.
QUnit.test("JsZeroNotGoodWithFloat", function (assert) {
let done = assert.async();
superDemoApi.getFloatZero((data) => {
// assert.equal(data, 0);
assert.ok(data < 0.0000001);
done();
});
});
QUnit.test("JsZeroNotGoodWithDouble", function (assert) {
let done = assert.async();
superDemoApi.getDoubleZero((data) => {
assert.notEqual(data, 0);
done();
});
});
QUnit.test("JsZeroGoodWithDecimal", function (assert) {
let done = assert.async();
superDemoApi.getDecimalZero((data) => {
assert.equal(data, 0);
done();
});
});
//QUnit.test("GetNextHour", function (assert) { the runner of chutzpah apparently intepret toISOString() as toString()
// let done = assert.async();
// let dt = new Date(Date.now());
// let h = dt.getHours();
// superDemoApi.getNextHour(dt, (data) => {
// assert.equal(data.getHours(), h + 1);
// done();
// });
//});
QUnit.test("GetIntSquare", function (assert) {
let done = assert.async();
superDemoApi.getIntSquare(100, (data) => {
assert.equal(data, 10000);
done();
});
});
QUnit.test("GetDecimalSquare", function (assert) {
let done = assert.async();
superDemoApi.getDecimalSquare(100, (data) => {
assert.equal(data, 10000);
done();
});
});
QUnit.test("GetDateTime", function (assert) {
let done = assert.async();
superDemoApi.getDateTime(true, (data) => {
assert.ok(data);
done();
});
});
QUnit.test("GetDateTimeNull", function (assert) {
let done = assert.async();
superDemoApi.getDateTime(false, (data) => {
assert.ok(data == undefined);
done();
});
});
QUnit.test("GetNullableDecimal", function (assert) {
let done = assert.async();
superDemoApi.getNullableDecimal(true, (data) => {
assert.ok(data > 10);
done();
});
});
QUnit.test("GetNullableDecimalNull", function (assert) {
let done = assert.async();
superDemoApi.getNullableDecimal(false, (data) => {
assert.ok(data == undefined);
done();
});
});
QUnit.test("GetNullString", function (assert) {
let done = assert.async();
superDemoApi.getNullString((data) => {
assert.ok(data == null);
done();
});
});
QUnit.test("GetNullPerson", function (assert) {
let done = assert.async();
superDemoApi.getNullPerson((data) => {
assert.ok(data == null);
done();
});
});
QUnit.test("GetByteArray", function (assert) {
let done = assert.async();
superDemoApi.getByteArray((data) => {
assert.ok(data.length > 0);
done();
});
});
QUnit.test("GetTextStream", function (assert) {
let done = assert.async();
superDemoApi.getTextStream((data) => {
assert.ok(data);
done();
});
});
QUnit.test("GetActionResult", function (assert) {
let done = assert.async();
superDemoApi.getActionResult((data) => {
assert.ok(data);
done();
});
});
QUnit.test("GetActionStringResult", function (assert) {
let done = assert.async();
superDemoApi.getActionResult((data) => {
assert.equal(data, "abcdefg");
done();
});
});
QUnit.test("Getbyte", function (assert) {
let done = assert.async();
superDemoApi.getbyte((data) => {
assert.equal(data, 255);
done();
});
});
QUnit.test("GetBool", function (assert) {
let done = assert.async();
superDemoApi.getBool((data) => {
assert.equal(data, true);
done();
});
});
QUnit.test("Getsbyte", function (assert) {
let done = assert.async();
superDemoApi.getsbyte((data) => {
assert.equal(data, -127);
done();
});
});
QUnit.test("GetChar", function (assert) {
let done = assert.async();
superDemoApi.getChar((data) => {
assert.equal(data, "A");
done();
});
});
QUnit.test("GetDecimal", function (assert) {
let done = assert.async();
superDemoApi.getDecimal((data) => {
assert.equal(data, 79228162514264337593543950335);
done();
});
});
QUnit.test("Getdouble", function (assert) {
let done = assert.async();
superDemoApi.getdouble((data) => {
assert.equal(data, -1.7976931348623e308);
done();
});
});
QUnit.test("GetUint", function (assert) {
let done = assert.async();
superDemoApi.getUint((data) => {
assert.equal(data, 4294967295);
done();
});
});
QUnit.test("Getulong", function (assert) {
let done = assert.async();
superDemoApi.getulong((data) => {
assert.equal(data, 18446744073709551615);
done();
});
});
QUnit.test("GetInt2d", function (assert) {
let done = assert.async();
superDemoApi.getInt2D((data) => {
assert.equal(data[0][0], 1);
assert.equal(data[0][3], 4);
assert.equal(data[1][0], 5);
assert.equal(data[1][3], 8);
done();
});
});
QUnit.test("GetInt2dJagged", function (assert) {
let done = assert.async();
superDemoApi.getInt2DJagged((data) => {
assert.equal(data[0][0], 1);
assert.equal(data[0][3], 4);
assert.equal(data[1][0], 5);
assert.equal(data[1][3], 8);
done();
});
});
QUnit.test("PostInt2d", function (assert) {
let done = assert.async();
superDemoApi.postInt2D([[1, 2, 3, 4], [5, 6, 7, 8]], (data) => {
assert.ok(data);
done();
});
});
QUnit.test("PostInt2dExpectedFalse", function (assert) {
let done = assert.async();
superDemoApi.postInt2D([[1, 2, 3, 4], [5, 6, 7, 9]], (data) => {
assert.ok(data == false);
done();
});
});
QUnit.test("PostIntArray", function (assert) {
let done = assert.async();
superDemoApi.postIntArray([1, 2, 3, 4, 5, 6, 7, 8], (data) => {
assert.ok(data);
done();
});
});
QUnit.test("getIntArrayQ", function (assert) {
let done = assert.async();
superDemoApi.getIntArrayQ([6, 7, 8], (data) => {
assert.equal(data.length, 3);
assert.equal(data[2], 8);
done();
});
});
QUnit.test("postDay", function (assert) {
let done = assert.async();
superDemoApi.postDay(DemoWebApi_DemoData_Client.Days.Fri, DemoWebApi_DemoData_Client.Days.Mon, (data) => {
assert.equal(data.length, 2);
assert.equal(data[1], DemoWebApi_DemoData_Client.Days.Mon);
done();
});
});
QUnit.test("PostWithQueryButEmptyBody", function (assert) {
let done = assert.async();
superDemoApi.postWithQueryButEmptyBody("abc", 123, (data) => {
assert.equal(data.item1, "abc");
assert.equal(data.item2, 123);
done();
});
});
QUnit.test("GetIntArray", function (assert) {
let done = assert.async();
superDemoApi.getIntArray((data) => {
assert.equal(data[7], 8);
done();
});
});
QUnit.test("PostInt2dJagged", function (assert) {
let done = assert.async();
superDemoApi.postInt2DJagged([[1, 2, 3, 4], [5, 6, 7, 8]], (data) => {
assert.ok(data);
done();
});
});
QUnit.test("PostInt2dJaggedExpectedFalse", function (assert) {
let done = assert.async();
superDemoApi.postInt2DJagged([[1, 2, 3, 4], [5, 6, 7, 9]], (data) => {
assert.ok(data == false);
done();
});
});
QUnit.test("GetDictionaryOfPeople", function (assert) {
let done = assert.async();
superDemoApi.getDictionaryOfPeople((data) => {
assert.equal(data["Spider Man"].name, "Peter Parker");
assert.equal(data["Spider Man"].addresses[0].city, "New York");
done();
});
});
QUnit.test("PostDictionaryOfPeople", function (assert) {
let done = assert.async();
superDemoApi.postDictionary({
"Iron Man": {
"surname": "Stark",
"givenName": "Tony",
"dob": null,
"id": "00000000-0000-0000-0000-000000000000",
"name": "Tony Stark",
"addresses": []
},
"Spider Man": {
"name": "Peter Parker",
"addresses": [
{
"id": "00000000-0000-0000-0000-000000000000",
"city": "New York",
state: "Somewhere",
"postalCode": null,
"country": null,
"type": 0,
location: { x: 100, y: 200 }
}
]
}
}, (data) => {
assert.equal(data, 2);
done();
});
});
QUnit.test("GetKeyValuePair", function (assert) {
let done = assert.async();
superDemoApi.getKeyhValuePair((data) => {
assert.equal(data.key, "Spider Man");
assert.equal(data.value.addresses[0].city, "New York");
done();
});
});
QUnit.module("ValuesTests", function () {
QUnit.test("Get", function (assert) {
let done = assert.async();
valuesApi.get((data) => {
assert.equal(data[1], "value2");
done();
});
});
QUnit.test("GetByIdAndName", function (assert) {
let done = assert.async();
valuesApi.getByIdAndName(1, "something to say中文\\`-=|~!@#$%^&*()_+/|?[]{},.';<>:\"", (data) => {
assert.equal(data, "something to say中文\\`-=|~!@#$%^&*()_+/|?[]{},.';<>:\"1");
done();
});
});
QUnit.test("GetByName", function (assert) {
let done = assert.async();
valuesApi.getByName("something", (data) => {
assert.equal(data, "SOMETHING");
done();
});
});
QUnit.test("PostValue", function (assert) {
let done = assert.async();
valuesApi.post('value', (data) => {
assert.equal(data, "VALUE");
done();
});
});
QUnit.test("Put", function (assert) {
let done = assert.async();
valuesApi.put(1, 'value', (data) => {
assert.expect(0);
done();
});
});
QUnit.test("Delete", function (assert) {
let done = assert.async();
valuesApi.delete(1, (data) => {
assert.expect(0);
done();
});
});
});
});
} | the_stack |
import assert from "assert";
import fs from "fs/promises";
import path from "path";
import {
Awaitable,
Context,
Mount,
Option,
OptionType,
Plugin,
PluginContext,
RequestContext,
SetupResult,
getRequestContext,
viewToBuffer,
} from "@miniflare/shared";
import dotenv from "dotenv";
import { MiniflareCoreError } from "../error";
import { Request, RequestInfo, RequestInit, Response } from "../standards";
const kWranglerBindings = Symbol("kWranglerBindings");
/** @internal */
export type _CoreMount = Mount<Request, Response>; // yuck :(
// Instead of binding to a service, use this function to handle `fetch`es
// some other custom way (e.g. Cloudflare Pages' `env.PAGES` asset handler)
export type FetcherFetch = (request: Request) => Awaitable<Response>;
export type ServiceBindingsOptions = Record<
string,
| string // Just service name, environment defaults to "production"
| { service: string; environment?: string } // TODO (someday): respect environment, currently ignored
| FetcherFetch
>;
interface ProcessedServiceBinding {
name: string;
service: string | FetcherFetch;
environment: string;
}
export interface BindingsOptions {
envPath?: boolean | string;
envPathDefaultFallback?: boolean;
bindings?: Record<string, any>;
globals?: Record<string, any>;
wasmBindings?: Record<string, string>;
textBlobBindings?: Record<string, string>;
dataBlobBindings?: Record<string, string>;
serviceBindings?: ServiceBindingsOptions;
}
export class Fetcher {
readonly #service: string | FetcherFetch;
readonly #getServiceFetch: (name: string) => Promise<FetcherFetch>;
constructor(
service: string | FetcherFetch,
getServiceFetch: (name: string) => Promise<FetcherFetch>
) {
this.#service = service;
this.#getServiceFetch = getServiceFetch;
}
async fetch(input: RequestInfo, init?: RequestInit): Promise<Response> {
// Check we're not too deep, should throw in the caller and NOT return a
// 500 Internal Server Error Response from this function
const parentCtx = getRequestContext();
const requestDepth = parentCtx?.requestDepth ?? 1;
const pipelineDepth = (parentCtx?.pipelineDepth ?? 0) + 1;
// NOTE: `new RequestContext` throws if too deep
const ctx = new RequestContext({ requestDepth, pipelineDepth });
// Always create new Request instance, so clean object passed to services
const req = new Request(input, init);
// If we're using a custom fetch handler, call that or wait for the service
// fetch handler to be available
const fetch =
typeof this.#service === "function"
? this.#service
: await this.#getServiceFetch(this.#service);
// Cloudflare Workers currently don't propagate errors thrown by the service
// when handling the request. Instead a 500 Internal Server Error Response
// is returned with the CF-Worker-Status header set to "exception". We
// could do this, but I think for Miniflare, we get a better developer
// experience if we don't (e.g. the pretty error page will only be shown
// if the error reaches the HTTP request listener). We already do this for
// Durable Objects. If user's want this behaviour, they can explicitly catch
// the error in their service.
// TODO: maybe add (debug/verbose) logging here?
return ctx.runWith(() => fetch(req));
}
}
export class BindingsPlugin
extends Plugin<BindingsOptions>
implements BindingsOptions
{
@Option({
type: OptionType.STRING,
name: "env",
alias: "e",
description: "Path to .env file",
logValue(value: boolean | string) {
if (value === true) return ".env";
if (value === false) return undefined;
return path.relative("", value);
},
fromWrangler: ({ miniflare }) => miniflare?.env_path,
})
envPath?: boolean | string;
// We want custom bindings to override Wrangler bindings, so we can't put
// fromWrangler in `bindings`. Using a symbol, means these low-priority
// bindings can only be loaded from a Wrangler config.
@Option({
type: OptionType.OBJECT,
logName: "Wrangler Variables",
fromWrangler: ({ vars }) => {
if (!vars) return;
// Wrangler stringifies all environment variables
return Object.fromEntries(
Object.entries(vars).map(([key, value]) => [key, String(value)])
);
},
})
[kWranglerBindings]?: Record<string, any>;
// This is another hack. When using the CLI, we'd like to load .env files
// by default if they exist. However, we'd also like to be able to customise
// the .env path in wrangler.toml files. Previously, we just set `envPath` to
// `true` if it wasn't specified via a CLI flag, but API options have a higher
// priority than wrangler.toml's, so `[miniflare] env_path` was always
// ignored. When this option is set to `true`, and `envPath` is undefined,
// we'll treat is as if it were `true`.
//
// See https://discord.com/channels/595317990191398933/891052295410835476/923265884095647844
@Option({ type: OptionType.NONE })
envPathDefaultFallback?: boolean;
@Option({
type: OptionType.OBJECT,
alias: "b",
description: "Binds variable/secret to environment",
logName: "Custom Bindings",
})
bindings?: Record<string, any>;
@Option({
type: OptionType.OBJECT,
description: "Binds variable/secret to global scope",
logName: "Custom Globals",
fromWrangler: ({ miniflare }) => miniflare?.globals,
})
globals?: Record<string, any>;
@Option({
type: OptionType.OBJECT,
typeFormat: "NAME=PATH",
name: "wasm",
description: "WASM module to bind",
logName: "WASM Bindings",
fromWrangler: ({ wasm_modules }) => wasm_modules,
})
wasmBindings?: Record<string, string>;
@Option({
type: OptionType.OBJECT,
typeFormat: "NAME=PATH",
name: "text-blob",
description: "Text blob to bind",
logName: "Text Blob Bindings",
fromWrangler: ({ text_blobs }) => text_blobs,
})
textBlobBindings?: Record<string, string>;
@Option({
type: OptionType.OBJECT,
typeFormat: "NAME=PATH",
name: "data-blob",
description: "Data blob to bind",
logName: "Data Blob Bindings",
fromWrangler: ({ data_blobs }) => data_blobs,
})
dataBlobBindings?: Record<string, string>;
@Option({
type: OptionType.OBJECT,
typeFormat: "NAME=MOUNT[@ENV]",
name: "service",
alias: "S",
description: "Mounted service to bind",
fromEntries: (entries) =>
Object.fromEntries(
// Allow specifying the environment on the CLI, e.g.
// --service AUTH_SERVICE=auth@development
entries.map(([name, serviceEnvironment]) => {
const atIndex = serviceEnvironment.indexOf("@");
if (atIndex === -1) {
return [name, serviceEnvironment];
} else {
const service = serviceEnvironment.substring(0, atIndex);
const environment = serviceEnvironment.substring(atIndex + 1);
return [name, { service, environment }];
}
})
),
fromWrangler: ({ experimental_services }) =>
experimental_services?.reduce(
(services, { name, service, environment }) => {
services[name] = { service, environment };
return services;
},
{} as ServiceBindingsOptions
),
})
serviceBindings?: ServiceBindingsOptions;
readonly #processedServiceBindings: ProcessedServiceBinding[];
#contextPromise?: Promise<void>;
#contextResolve?: () => void;
#mounts?: Map<string, _CoreMount>;
constructor(ctx: PluginContext, options?: BindingsOptions) {
super(ctx);
this.assignOptions(options);
if (this.envPathDefaultFallback && this.envPath === undefined) {
this.envPath = true;
}
this.#processedServiceBindings = Object.entries(
this.serviceBindings ?? {}
).map(([name, options]) => {
const service = typeof options === "object" ? options.service : options;
const environment =
(typeof options === "object" && options.environment) || "production";
return { name, service, environment };
});
if (this.#processedServiceBindings.length) {
ctx.log.warn(
"Service bindings are experimental and primarily meant for internal " +
"testing at the moment. There may be breaking changes in the future."
);
}
}
#getServiceFetch = async (service: string): Promise<FetcherFetch> => {
// Wait for mounts
assert(
this.#contextPromise,
"beforeReload() must be called before #getServiceFetch()"
);
await this.#contextPromise;
// Should've thrown error earlier in reload if service not found and
// dispatchFetch should always be set, it's optional to make testing easier.
const fetch = this.#mounts?.get(service)?.dispatchFetch;
assert(fetch);
return fetch;
};
async setup(): Promise<SetupResult> {
// Bindings should be loaded in this order, from lowest to highest priority:
// 1) Wrangler [vars]
// 2) .env Variables
// 3) WASM Module Bindings
// 4) Text blob Bindings
// 5) Data blob Bindings
// 6) Service Bindings
// 7) Custom Bindings
const bindings: Context = {};
const watch: string[] = [];
// 1) Copy Wrangler bindings first
Object.assign(bindings, this[kWranglerBindings]);
// 2) Load bindings from .env file
let envPath = this.envPath === true ? ".env" : this.envPath;
if (envPath) {
envPath = path.resolve(this.ctx.rootPath, envPath);
try {
Object.assign(
bindings,
dotenv.parse(await fs.readFile(envPath, "utf8"))
);
} catch (e: any) {
// Ignore ENOENT (file not found) errors for default path
if (!(e.code === "ENOENT" && this.envPath === true)) throw e;
}
watch.push(envPath);
}
// 3) Load WebAssembly module bindings from files
if (this.wasmBindings) {
// eslint-disable-next-line prefer-const
for (let [name, wasmPath] of Object.entries(this.wasmBindings)) {
wasmPath = path.resolve(this.ctx.rootPath, wasmPath);
bindings[name] = new WebAssembly.Module(await fs.readFile(wasmPath));
watch.push(wasmPath);
}
}
// 4) Load text blobs from files
if (this.textBlobBindings) {
// eslint-disable-next-line prefer-const
for (let [name, textPath] of Object.entries(this.textBlobBindings)) {
textPath = path.resolve(this.ctx.rootPath, textPath);
bindings[name] = await fs.readFile(textPath, "utf-8");
watch.push(textPath);
}
}
// 5) Load data blobs from files
if (this.dataBlobBindings) {
// eslint-disable-next-line prefer-const
for (let [name, dataPath] of Object.entries(this.dataBlobBindings)) {
dataPath = path.resolve(this.ctx.rootPath, dataPath);
const fileContent = await fs.readFile(dataPath);
bindings[name] = viewToBuffer(fileContent);
watch.push(dataPath);
}
}
// 6) Load service bindings
for (const { name, service } of this.#processedServiceBindings) {
bindings[name] = new Fetcher(service, this.#getServiceFetch);
}
// 7) Copy user's arbitrary bindings
Object.assign(bindings, this.bindings);
return { globals: this.globals, bindings, watch };
}
beforeReload(): void {
// Clear reference to old mounts map, wait for reload() to be called
// before allowing service binding `fetch`es again
this.#mounts = undefined;
this.#contextPromise = new Promise(
(resolve) => (this.#contextResolve = resolve)
);
}
reload(
bindings: Context,
moduleExports: Context,
mounts: Map<string, Mount>
): void {
// Check all services are mounted
for (const { name, service } of this.#processedServiceBindings) {
if (typeof service === "string" && !mounts.has(service)) {
throw new MiniflareCoreError(
"ERR_SERVICE_NOT_MOUNTED",
`Service "${service}" for binding "${name}" not found.
Make sure "${service}" is mounted so Miniflare knows where to find it.`
);
}
}
this.#mounts = mounts;
assert(
this.#contextResolve,
"beforeReload() must be called before reload()"
);
this.#contextResolve();
}
dispose(): void {
return this.beforeReload();
}
} | the_stack |
export = () => {
it("should support element access", () => {
const arr = [1, 2, 3];
expect(arr[0]).to.equal(1);
expect(arr[1]).to.equal(2);
expect(arr[2]).to.equal(3);
expect([1, 2, 3][0]).to.equal(1);
expect([1, 2, 3][1]).to.equal(2);
expect([1, 2, 3][2]).to.equal(3);
function foo() {
const result = [1, 2, 3];
return result;
}
expect(foo()[0]).to.equal(1);
expect(foo()[1]).to.equal(2);
expect(foo()[2]).to.equal(3);
let i = 2;
let a = arr[i];
let b = arr[2];
let { [i]: c } = arr;
let { [2]: d } = arr;
expect(a).to.equal(3);
expect(b).to.equal(3);
expect(c).to.equal(3);
expect(d).to.equal(3);
a = arr[i];
b = arr[2];
({ [i]: c } = arr);
({ [2]: d } = arr);
expect(a).to.equal(3);
expect(b).to.equal(3);
expect(c).to.equal(3);
expect(d).to.equal(3);
function f<T extends 0 | 1 | 2 | number>(v: T) {
let a = [];
a[v] = 3; // shouldn't make a compiler error
}
enum Foo {
A,
B,
C,
}
function g<T extends Foo>(v: T) {
const a = [];
a[v] = 3; // shouldn't make a compiler error
}
});
it("should support.size()", () => {
expect([].size()).to.equal(0);
expect([1].size()).to.equal(1);
expect([1, 2].size()).to.equal(2);
expect([1, 2, 3].size()).to.equal(3);
});
it("should support push", () => {
const a = new Array<number>();
a.push(123);
expect(a[0]).to.equal(123);
class Noodle {
public strings = new Array<string>();
}
const noodle = new Noodle();
noodle.strings.push("Rigatoni");
const strings = noodle.strings;
strings.push("Spaghetti");
if (strings.push("Lasagna")) {
}
expect(noodle.strings.push("Penne")).to.equal(4);
expect(noodle.strings[0]).to.equal("Rigatoni");
expect(noodle.strings[1]).to.equal("Spaghetti");
expect(noodle.strings[2]).to.equal("Lasagna");
expect(noodle.strings[3]).to.equal("Penne");
let arr = [0];
arr.push(1, 2, arr[1]);
expect(arr[0]).to.equal(0);
expect(arr[1]).to.equal(1);
expect(arr[2]).to.equal(2);
expect(arr[3]).to.equal(undefined);
expect([1, 2].push()).to.equal(2);
});
it("should support pop", () => {
const a = [456];
const b = a.pop();
expect(b).to.equal(456);
expect(a.size()).to.equal(0);
expect(a[0]).never.to.be.ok();
});
it("should support join", () => {
const a = [1, 2, 3];
const b = [true, false, true];
expect(a.join(", ")).to.equal("1, 2, 3");
expect([1, 2, 3].join(", ")).to.equal("1, 2, 3");
expect(b.join(", ")).to.equal("true, false, true");
expect([true, false, true].join(", ")).to.equal("true, false, true");
expect([1, "a", true].join(", ")).to.equal("1, a, true");
});
it("should support move", () => {
const a = [1, 2, 3];
let b = [0];
a.move(1, 2, 0);
expect(a.join(", ")).to.equal("2, 3, 3");
a.move(0, 2, 1, b);
expect(b.join(", ")).to.equal("0, 2, 3, 3");
b.move(0, 1, 2);
expect(b.join(", ")).to.equal("0, 2, 0, 2");
})
it("should support shift", () => {
const a = [1, 2, 3];
const b = a.shift();
expect(b).to.equal(1);
expect(a.size()).to.equal(2);
expect(a[0]).to.equal(2);
expect(a[1]).to.equal(3);
});
it("should support sort", () => {
const x = [4, 2, 6, 2, 1];
x.sort();
expect(x[0]).to.equal(1);
expect(x[1]).to.equal(2);
expect(x[2]).to.equal(2);
expect(x[3]).to.equal(4);
expect(x[4]).to.equal(6);
expect(x.sort((a, b) => a < b)).to.equal(x);
expect(x[0]).to.equal(1);
expect(x[1]).to.equal(2);
expect(x[2]).to.equal(2);
expect(x[3]).to.equal(4);
expect(x[4]).to.equal(6);
expect(x.sort((a, b) => a > b)).to.equal(x);
expect(x[0]).to.equal(6);
expect(x[1]).to.equal(4);
expect(x[2]).to.equal(2);
expect(x[3]).to.equal(2);
expect(x[4]).to.equal(1);
});
it("should support unshift", () => {
const a = [1, 2, 3];
const b = a.unshift(4);
a.unshift(5);
expect(a[0]).to.equal(5);
expect(a[1]).to.equal(4);
expect(a[2]).to.equal(1);
expect(a[3]).to.equal(2);
expect(a[4]).to.equal(3);
expect(b).to.equal(4);
});
it("should support indexOf", () => {
const a = [7, 1, 8, 1, 9];
expect(a.indexOf(1)).to.equal(1);
expect(a.indexOf(2)).to.equal(-1);
});
it("should support every", () => {
function even(value: number) {
return value % 2 === 0;
}
function odd(value: number) {
return !even(value);
}
const a = [1, 2, 3, 4, 5, 6];
expect(a.every(even)).to.equal(false);
expect(a.every(odd)).to.equal(false);
const b = [1, 3, 5];
expect(b.every(even)).to.equal(false);
expect(b.every(odd)).to.equal(true);
const c = [2, 4, 6];
expect(c.every(even)).to.equal(true);
expect(c.every(odd)).to.equal(false);
});
it("should support some", () => {
const a = [1, 2, 3];
expect(a.some(v => v === 2)).to.equal(true);
expect(a.some(v => v === 4)).to.equal(false);
});
it("should support forEach", () => {
const bin = [1, 2, 3];
let str = "";
bin.forEach(v => (str += v));
expect(str).to.equal("123");
});
it("should support map", () => {
const a = [1, 2, 3];
const b = a.map(v => v + 1);
expect(b).never.to.equal(a);
expect(b[0]).to.equal(2);
expect(b[1]).to.equal(3);
expect(b[2]).to.equal(4);
});
it("should support filter", () => {
const a = [1, 2, 3, 4, 5];
const b = a.filter(v => v % 2 === 0);
expect(b).never.to.equal(a);
expect(b.size()).to.equal(2);
expect(b[0]).to.equal(2);
expect(b[1]).to.equal(4);
});
it("should support reduce", () => {
function reducer(accum: Array<number>, value: Array<number>) {
return [...accum, ...value];
}
const a = [
[0, 1],
[2, 3],
[4, 5],
].reduce(reducer);
expect(a[0]).to.equal(0);
expect(a[1]).to.equal(1);
expect(a[2]).to.equal(2);
expect(a[3]).to.equal(3);
expect(a[4]).to.equal(4);
expect(a[5]).to.equal(5);
});
it("should support reducing empty arrays only with a initialValue parameter", () => {
expect(() => new Array<string>().reduce((previous, current, index, arr) => previous + current)).to.throw();
expect(
new Array<string>().reduce((previous, current, index, arr) => {
throw "This should never run! [1]";
}, "a"),
).to.equal("a");
});
it("should support reducing arrays with an undefined initialValue", () => {
expect(
[..."😂😄😃😊😉😍"].reduce(
(previous: undefined | number, current, index, arr) => index + (previous || index),
undefined,
),
).to.equal(16);
expect(
[].reduce(() => {
throw "Should not call the reducer function on an empty array! [1]";
}, undefined),
).to.equal(undefined);
});
it("should support reducing single-element arrays without calling a reducer when no initialValue is passed in", () => {
expect(
[4].reduce(() => {
throw "Should not call the reducer function on a single-element array with no initialValue! [1]";
}),
).to.equal(4);
});
it("should support reducing forwards or backwards", () => {
expect([..."abcdef"].reduce((previous, current) => previous + current)).to.equal("abcdef");
expect([..."abcdef"].reduce((previous, current) => previous + current, " ")).to.equal(" " + "abcdef");
});
it("should support Array.find", () => {
const a = [1, 2, 3, 4, 5];
const b = a.find(v => v % 2 === 0);
expect(b).to.equal(2);
const c = a.find(v => v === 6);
expect(c).never.to.be.ok();
const d = a.find(v => v % 2 !== 0);
expect(d).to.equal(1);
});
it("should allow spread 1", () => {
const a = [1, 2, 3];
const b = [...a, 4, 5, 6];
expect(b[0]).to.equal(1);
expect(b[1]).to.equal(2);
expect(b[2]).to.equal(3);
expect(b[3]).to.equal(4);
expect(b[4]).to.equal(5);
expect(b[5]).to.equal(6);
expect(b.size()).to.equal(6);
});
it("should allow spread 2", () => {
const c = [...[1], ...[2]];
expect(c[0]).to.equal(1);
expect(c[1]).to.equal(2);
});
it("should allow spread 3", () => {
const oldArr = [2]
let counter = 0
const newArr = [++counter, ...oldArr]
expect(newArr[0]).to.equal(1);
expect(newArr[1]).to.equal(2);
});
it("should allow spread 4", () => {
let counter = 0
const newArr = [++counter, ..."abc"];
expect(newArr[0]).to.equal(1);
expect(newArr[1]).to.equal("a");
expect(newArr[2]).to.equal("b");
expect(newArr[3]).to.equal("c");
});
it("should allow spread 5", () => {
let counter = 0
const newArr = [++counter, ...new Set([2])];
expect(newArr[0]).to.equal(1);
expect(newArr[1]).to.equal(2);
});
it("should allow spread 6", () => {
let counter = 0
const newArr = [["a", ++counter], ...new Map([["b", 2]])];
expect(newArr[0][0]).to.equal("a");
expect(newArr[0][1]).to.equal(1);
expect(newArr[1][0]).to.equal("b");
expect(newArr[1][1]).to.equal(2);
});
it("should allow spread 7", () => {
function* foo() {
yield 2;
}
let counter = 0
const newArr = [++counter, ...foo()];
expect(newArr[0]).to.equal(1);
expect(newArr[1]).to.equal(2);
});
it("should copy on spread", () => {
const a = [1, 2, 3];
const b = [...a];
expect(a).never.to.equal(b);
expect(a.size()).to.equal(b.size());
for (let i = 0; i < a.size(); i++) {
expect(b[i]).to.equal(a[i]);
}
});
it("should unpack spread into function calls", () => {
function foo(...args: Array<number>) {
expect(args[0]).to.equal(1);
expect(args[1]).to.equal(2);
expect(args[2]).to.equal(3);
}
foo(...[1, 2, 3]);
});
it("should support Array.sort", () => {
const months = ["March", "Jan", "Feb", "Dec"].sort();
expect(months[0]).to.equal("Dec");
expect(months[1]).to.equal("Feb");
expect(months[2]).to.equal("Jan");
expect(months[3]).to.equal("March");
const array1 = [1, 30, 4, 21, 100000].sort();
expect(array1[0]).to.equal(1);
expect(array1[1]).to.equal(4);
expect(array1[2]).to.equal(21);
expect(array1[3]).to.equal(30);
expect(array1[4]).to.equal(100000);
});
it("should support Array.isEmpty", () => {
new Array<string>().isEmpty();
const v = new Array<string>().isEmpty();
const arr = new Array<string>();
arr.isEmpty();
const x = arr.isEmpty();
expect(v).to.equal(true);
arr.push("Nope");
expect(arr.isEmpty()).to.equal(false);
});
it("should support Array.unorderedRemove", () => {
const arr = [0, 1, 2, 3, 4, 5, 6, 7];
let i = 2;
let value: number;
expect(arr.unorderedRemove((i *= 2))).to.equal(4);
expect(arr.size()).to.equal(7);
expect(arr[4]).to.equal(7);
expect(arr[6]).to.equal(6);
});
it("should support spreading non-apparent types", () => {
type TypeGuard<T> = (value: unknown) => value is T;
type StaticArguments<T> = T extends [TypeGuard<infer A>]
? [A]
: T extends [TypeGuard<infer A>, TypeGuard<infer B>]
? [A, B]
: T extends [TypeGuard<infer A>, TypeGuard<infer B>, TypeGuard<infer C>]
? [A, B, C]
: T extends [TypeGuard<infer A>, TypeGuard<infer B>, TypeGuard<infer C>, TypeGuard<infer D>]
? [A, B, C, D]
: T extends [
TypeGuard<infer A>,
TypeGuard<infer B>,
TypeGuard<infer C>,
TypeGuard<infer D>,
TypeGuard<infer E>,
]
? [A, B, C, D, E]
: T extends [
TypeGuard<infer A>,
TypeGuard<infer B>,
TypeGuard<infer C>,
TypeGuard<infer D>,
TypeGuard<infer E>,
TypeGuard<infer F>,
]
? [A, B, C, D, E, F]
: T extends [
TypeGuard<infer A>,
TypeGuard<infer B>,
TypeGuard<infer C>,
TypeGuard<infer D>,
TypeGuard<infer E>,
TypeGuard<infer F>,
TypeGuard<infer G>,
]
? [A, B, C, D, E, F, G]
: T extends [
TypeGuard<infer A>,
TypeGuard<infer B>,
TypeGuard<infer C>,
TypeGuard<infer D>,
TypeGuard<infer E>,
TypeGuard<infer F>,
TypeGuard<infer G>,
TypeGuard<infer H>,
]
? [A, B, C, D, E, F, G, H]
: Array<unknown>; // default, if user has more than 8 args then wtf they doing with their lives?!?
function f<C extends Array<unknown>>(arr: StaticArguments<C>) {
return [...arr];
}
f([0, 1]);
});
it("should support Array constructor", () => {
expect(new Array(10, undefined).isEmpty()).to.equal(true);
});
it("should support Array.mapFiltered", () => {
class A {
static i = 0;
f() {
return ++A.i > 5 ? { x: A.i } : undefined;
}
}
const arr = [new A(), new A(), new A(), new A(), new A(), new A(), new A(), new A()];
expect(arr.mapFiltered(a => a.f()).reduce((a, c) => a + c.x, 0)).to.equal(21);
});
it("should support Array.filterUndefined", () => {
function foo(...args: Array<unknown>) {
const safeArgs = args.filterUndefined();
expect(safeArgs[0]).to.equal("A");
expect(safeArgs[1]).to.equal("B");
expect(safeArgs[2]).to.equal("C");
}
foo(undefined, "A", undefined, "B", undefined, "C", undefined);
});
}; | the_stack |
* @module @morgan-stanley/desktopjs
*/
import { Container, WebContainerBase } from "../container";
import { ContainerWindow, PersistedWindowLayout, Rectangle, WindowEventArgs } from "../window";
import { ScreenManager, Display, Point } from "../screen";
import { NotificationOptions } from "../notification";
import { ObjectTransform, PropertyMap } from "../propertymapping";
import { Guid } from "../guid";
import { MessageBus, MessageBusSubscription, MessageBusOptions } from "../ipc";
import { EventArgs } from "../events";
declare let Notification: any;
// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace Default {
const windowEventMap = {
close: "unload"
};
/**
* @augments ContainerWindow
*/
export class DefaultContainerWindow extends ContainerWindow {
public get id(): string {
return this.innerWindow[DefaultContainer.windowUuidPropertyKey];
}
public get name(): string {
return this.innerWindow[DefaultContainer.windowNamePropertyKey];
}
public async load(url: string, options?: any) {
this.innerWindow.location.replace(url);
}
public async focus() {
this.innerWindow.focus();
}
public async show() {
// no implementation in a browser
}
public async hide() {
// no implementation in a browser
}
public async close() {
this.innerWindow.close();
}
public async minimize() {
this.innerWindow.minimize();
}
public async maximize() {
this.innerWindow.maximize();
}
public async restore() {
this.innerWindow.restore();
}
public async isShowing() {
// https://github.com/ai/visibilityjs ?
return true;
}
public async getSnapshot(): Promise<string> {
throw new Error("getSnapshot requires an implementation.");
}
public async flash(enable: boolean, options?: any) {
throw new Error("Not supported");
}
public async getParent(): Promise<ContainerWindow> {
// on the web, there's no parent
return null;
}
public async setParent(parent: ContainerWindow) {
// no implementation in a browser
}
public async getBounds() {
return new Rectangle(this.innerWindow.screenX, this.innerWindow.screenY, this.innerWindow.outerWidth, this.innerWindow.outerHeight);
}
public async setBounds(bounds: Rectangle) {
this.innerWindow.moveTo(bounds.x, bounds.y);
this.innerWindow.resizeTo(bounds.width, bounds.height);
}
public async getOptions() {
return this.innerWindow[Container.windowOptionsPropertyKey];
}
public async getState() {
return this.nativeWindow?.['getState']?.();
}
public async setState(state: any) {
const promise = this.nativeWindow?.['setState']?.(state);
this.emit("state-changed", <EventArgs> { name: "state-changed", sender: this, state });
ContainerWindow.emit("state-changed", <WindowEventArgs> { name: "state-changed", windowId: this.id, state } );
await promise;
}
protected attachListener(eventName: string, listener: (...args: any[]) => void): void {
this.innerWindow.addEventListener(windowEventMap[eventName] || eventName, listener);
}
protected detachListener(eventName: string, listener: (...args: any[]) => void): void {
this.innerWindow.removeEventListener(windowEventMap[eventName] || eventName, listener);
}
public get nativeWindow(): Window {
return this.innerWindow;
}
}
/**
* @augments MessageBus
*/
export class DefaultMessageBus implements MessageBus {
private container: DefaultContainer;
private static readonly messageSource: string = "desktopJS";
constructor(container: DefaultContainer) {
this.container = container;
}
async subscribe<T>(topic: string, listener: (event: any, message: T) => void, options?: MessageBusOptions) {
const subscription: MessageBusSubscription = new MessageBusSubscription(topic, (event: any) => {
// Only allow same origin
if (event.origin !== this.container.globalWindow.location.origin) {
return;
}
// Make sure topic received matches the one that was subscribed
const { source, "topic": receivedTopic, message } = event.data;
if (source === DefaultMessageBus.messageSource && topic === receivedTopic) {
listener({ topic }, message);
}
});
this.container.globalWindow?.addEventListener?.("message", subscription.listener);
return subscription;
}
async unsubscribe(subscription: MessageBusSubscription) {
return this.container.globalWindow.removeEventListener("message", subscription.listener);
}
async publish<T>(topic: string, message: T, options?: MessageBusOptions) {
// Get list of windows from global (set by opener on creation) or fallback to opener global in case
// there is a race condition of getting here before the opener set the global for us
const windows: Window[] = (this.container.globalWindow)
? this.container.globalWindow[DefaultContainer.windowsPropertyKey]
|| this.container.globalWindow.opener?.[DefaultContainer.windowsPropertyKey]
: [];
if (windows) {
for (const key in windows) {
const win = windows[key];
if (options?.name && options.name !== win[DefaultContainer.windowNamePropertyKey]) {
continue;
}
const targetOrigin = options?.targetOrigin || this.container.globalWindow.location.origin;
win.postMessage({ source: DefaultMessageBus.messageSource, topic, message }, targetOrigin);
}
}
}
}
/**
* @augments WebContainerBase
*/
export class DefaultContainer extends WebContainerBase {
private mainWindow: ContainerWindow;
public static readonly windowsPropertyKey: string = "desktopJS-windows";
public static readonly windowUuidPropertyKey: string = "desktopJS-uuid";
public static readonly windowNamePropertyKey: string = "desktopJS-name";
private static readonly rootWindowUuid: string = "root";
public static readonly defaultWindowOptionsMap: PropertyMap = {
x: { target: "left" },
y: { target: "top" }
};
public windowOptionsMap: PropertyMap = DefaultContainer.defaultWindowOptionsMap;
public constructor(win?: Window) {
super(win);
this.hostType = "Default";
this.ipc = this.createMessageBus();
// Create a global windows object for tracking all windows and add the current global window for current
if (this.globalWindow && !(DefaultContainer.windowsPropertyKey in this.globalWindow)) {
this.globalWindow[DefaultContainer.windowsPropertyKey] = { root: this.globalWindow };
this.globalWindow[DefaultContainer.windowNamePropertyKey] = this.globalWindow[DefaultContainer.windowUuidPropertyKey] = DefaultContainer.rootWindowUuid;
}
this.screen = new DefaultDisplayManager(this.globalWindow);
}
protected createMessageBus(): MessageBus {
return new DefaultMessageBus(this);
}
public setOptions(options: any) {
// noop. Any override to be done in overriding containers.
}
public async getOptions(): Promise<any> {
// noop. Any override to be done in overriding containers.
return {};
}
public async getInfo(): Promise<string | undefined> {
return this.globalWindow.navigator.appVersion;
}
public getMainWindow(): ContainerWindow {
if (!this.mainWindow) {
const win = this.globalWindow[DefaultContainer.windowsPropertyKey].root;
this.mainWindow = win ? this.wrapWindow(win) : null;
}
return this.mainWindow;
}
public getCurrentWindow(): ContainerWindow {
return this.wrapWindow(this.globalWindow);
}
protected getWindowOptions(options?: any): any {
return ObjectTransform.transformProperties(options, this.windowOptionsMap);
}
public wrapWindow(containerWindow: any) {
return new DefaultContainerWindow(containerWindow);
}
protected onOpen(open: (...args: any[]) => Window, ...args: any[]): Window {
const window = open.apply(this.globalWindow, args);
const uuid = Guid.newGuid();
try {
const windows = this.globalWindow[DefaultContainer.windowsPropertyKey];
windows[uuid] = window;
window[DefaultContainer.windowUuidPropertyKey] = uuid;
// Attach event handlers on window to cleanup reference on global windows object. beforeunload -> unload to prevent
// unload being called on open within Chrome.
window.addEventListener("beforeunload", () => {
window.addEventListener("unload", () => {
delete windows[uuid];
});
});
// Propagate the global windows object to the new window
window[DefaultContainer.windowsPropertyKey] = windows;
} catch (e) {
this.log("warn", `Error tracking new window, '${e.message}'`);
}
Container.emit("window-created", { name: "window-created", windowId: uuid });
ContainerWindow.emit("window-created", { name: "window-created", windowId: uuid });
return window;
}
public async createWindow(url: string, options?: any): Promise<ContainerWindow> {
let features: string;
let target = "_blank";
const newOptions = this.getWindowOptions(options);
if (newOptions) {
for (const prop in newOptions) {
features = (features ? features : "") + prop + "=" + newOptions[prop] + ",";
}
if (newOptions && "target" in newOptions) {
target = newOptions.target;
}
}
const window = this.globalWindow.open(url, target, features);
let windowReachable = true;
try {
window[Container.windowOptionsPropertyKey] = options; // Store the original options
// Set name as a unique desktopJS name property instead of overloading window.name
window[DefaultContainer.windowNamePropertyKey] = newOptions.name;
} catch (e) {
windowReachable = false;
this.log("warn",`Error proprogating properties to new window, '${e.message}'`);
}
const newWindow = this.wrapWindow(window);
this.emit("window-created", { sender: this, name: "window-created", window: newWindow, windowId: windowReachable ? newWindow.id : undefined, windowName: newOptions.name });
return newWindow;
}
public showNotification(title: string, options?: NotificationOptions) {
if (!("Notification" in this.globalWindow)) {
this.log("warn", "Notifications not supported");
return;
}
(<any>this.globalWindow).Notification.requestPermission(permission => {
if (permission === "denied") {
this.log("warn", "Notifications not permitted");
} else if (permission === "granted") {
new (<any>this.globalWindow).Notification(title, options);
}
});
}
protected async closeAllWindows(excludeSelf = false) {
const windows = this.globalWindow[DefaultContainer.windowsPropertyKey];
for (const key in windows) {
const win = windows[key];
if (!excludeSelf || this.globalWindow !== win) {
win.close();
}
}
}
public async getAllWindows() {
const windows: ContainerWindow[] = [];
const trackedWindows = this.globalWindow[DefaultContainer.windowsPropertyKey];
for (const key in trackedWindows) {
windows.push(this.wrapWindow(trackedWindows[key]));
}
return windows;
}
public async getWindowById(id: string): Promise<ContainerWindow | null> {
const win = this.globalWindow[DefaultContainer.windowsPropertyKey][id];
return win ? this.wrapWindow(win) : null;
}
public async getWindowByName(name: string): Promise<ContainerWindow | null> {
const trackedWindows = this.globalWindow[DefaultContainer.windowsPropertyKey];
for (const key in trackedWindows) {
if (trackedWindows[key][DefaultContainer.windowNamePropertyKey] === name) {
return this.wrapWindow(trackedWindows[key]);
}
}
return null;
}
public async buildLayout() {
const layout = new PersistedWindowLayout();
const promises: Promise<void>[] = [];
const windows = await this.getAllWindows();
windows.forEach(window => {
const nativeWin = window.nativeWindow;
try {
const options = nativeWin[Container.windowOptionsPropertyKey];
if (options && "persist" in options && !options.persist) {
return;
}
promises.push((async () => {
if (this.globalWindow !== nativeWin) {
layout.windows.push(
{
name: window.name,
url: (nativeWin && nativeWin.location) ? nativeWin.location.toString() : undefined,
id: window.id,
bounds: { x: nativeWin.screenX, y: nativeWin.screenY, width: nativeWin.innerWidth, height: nativeWin.innerHeight },
options: options,
state: await window.getState()
}
);
}
})());
} catch (e) {
// An error can happen if the window is not same origin and due to async loading we were able to
// add tracking to it before the content was loaded so we have a window with tracking in which we
// can't access properties any more so we will skip it with warning
this.log('warn', `Error while accessing window so skipping, '${e.message}'`);
}
});
await Promise.all(promises);
return layout;
}
}
/** @private */
class DefaultDisplayManager implements ScreenManager {
public readonly window: Window;
public constructor(window: Window) {
this.window = window;
}
public async getPrimaryDisplay() {
const display = new Display();
display.scaleFactor = this.window.devicePixelRatio;
display.id = "Current";
display.bounds = new Rectangle((<any>this.window.screen).availLeft,
(<any>this.window.screen).availTop,
this.window.screen.width,
this.window.screen.height);
display.workArea = new Rectangle((<any>this.window.screen).availLeft,
(<any>this.window.screen).availTop,
this.window.screen.availWidth,
this.window.screen.availHeight);
return display;
}
public async getAllDisplays() {
return [await this.getPrimaryDisplay()];
}
public async getMousePosition() {
return <Point>{ x: (<any>this.window.event).screenX, y: (<any>this.window.event).screenY };
}
}
} | the_stack |
import * as React from "react";
import {
StyleSheet,
View,
Animated,
BackHandler,
Dimensions,
} from "react-native";
import { PanGestureHandler, State } from "react-native-gesture-handler";
import {
enableScreens,
screensEnabled,
ScreenContainer,
Screen,
} from "react-native-screens";
import { SharedElementTransition } from "react-native-shared-element";
import { fromRight } from "../transitions";
import type { TransitionConfig } from "../transitions";
import { SharedElementsConfig, SharedElementsStrictConfig } from "../types";
import { normalizeSharedElementsConfig } from "../types/SharedElement";
import {
ScreenTransitionContext,
ScreenTransitionContextOnSharedElementsUpdatedEvent,
} from "./RouterScreenTransitionContext";
import { NavBarHeight } from "./navBar/constants";
enableScreens();
const styles = StyleSheet.create({
container: {
flex: 1,
},
node: {
...StyleSheet.absoluteFillObject,
//backfaceVisibility: "hidden"
},
swipeBackOverlay: {
position: "absolute",
left: 0,
top: NavBarHeight,
bottom: 0,
width: 30,
// backgroundColor: "green",
// opacity: 0.2
},
sharedElements: {
...StyleSheet.absoluteFillObject,
zIndex: 1000,
},
});
interface RouterProps {
initialNode: React.ReactNode;
transitionConfig: TransitionConfig;
}
type RouterAction = {
action: "push" | "pop";
config?: RouterConfig;
node?: React.ReactNode;
};
interface RouterState {
stack: React.ReactNode[];
prevIndex: number;
nextIndex: number;
animValue: Animated.AnimatedInterpolation;
transitionConfig: TransitionConfig | void;
sharedElementsConfig: SharedElementsStrictConfig | void;
sharedElementScreens: (ScreenTransitionContextOnSharedElementsUpdatedEvent | void)[];
actionsQueue: RouterAction[];
width: number;
height: number;
}
type RouterConfig = {
sharedElements?: SharedElementsConfig;
transitionConfig?: TransitionConfig;
};
let router: Router;
let AnimatedScreen: any;
const MaybeScreenContainer = (props: any) => {
if (screensEnabled()) {
return <ScreenContainer {...props} />;
}
return <View {...props} />;
};
const AnimatedRouterScreen = (props: any) => {
const { active, ...otherProps } = props;
if (screensEnabled()) {
AnimatedScreen = AnimatedScreen || Animated.createAnimatedComponent(Screen);
return <AnimatedScreen activityState={active ? 2 : 0} {...otherProps} />;
}
return <Animated.View {...otherProps} />;
};
export class Router extends React.Component<RouterProps, RouterState> {
_animValue = new Animated.Value(0);
_swipeBackAnimValue = new Animated.Value(0);
_onSwipeBackGestureEvent = Animated.event(
[{ nativeEvent: { translationX: this._swipeBackAnimValue } }],
{ useNativeDriver: true }
);
_backHandler: any;
static defaultProps = {
transitionConfig: fromRight(),
};
constructor(props: RouterProps) {
super(props);
router = this; //eslint-disable-line consistent-this
this.state = {
stack: [props.initialNode],
actionsQueue: [],
prevIndex: 0,
nextIndex: 0,
animValue: Animated.subtract(
this._animValue,
this._swipeBackAnimValue.interpolate({
inputRange: [0, Dimensions.get("window").width],
outputRange: [0, 1],
extrapolate: "clamp",
})
),
sharedElementScreens: [],
sharedElementsConfig: undefined,
transitionConfig: undefined,
width: Dimensions.get("window").width,
height: Dimensions.get("window").height,
};
}
componentDidMount() {
this._backHandler = BackHandler.addEventListener(
"hardwareBackPress",
this.onHardwareBackPress
);
}
componentWillUnmount() {
this._backHandler.remove();
}
renderSharedElementTransitions() {
const {
prevIndex,
nextIndex,
stack,
sharedElementScreens,
sharedElementsConfig,
transitionConfig,
animValue,
} = this.state;
//if (!sharedElementConfig) return;
if (prevIndex === nextIndex && nextIndex === stack.length - 1) {
// console.log('renderSharedElementTransitions: null');
return null;
}
const startIndex = Math.min(prevIndex, nextIndex);
const endIndex = startIndex + 1;
if (!sharedElementsConfig || !transitionConfig) {
return;
}
const { debug } = transitionConfig;
const startScreen = sharedElementScreens[startIndex];
const endScreen = sharedElementScreens[endIndex];
const nodes = sharedElementsConfig.map((sharedElementConfig) => {
const { id, otherId, ...other } = sharedElementConfig;
const node: any = {
id,
start: {
node: startScreen ? startScreen.nodes[id] : undefined,
ancestor: startScreen ? startScreen.ancestor : undefined,
},
end: {
node: endScreen ? endScreen.nodes[id] : undefined,
ancestor: endScreen ? endScreen.ancestor : undefined,
},
...other,
debug: sharedElementConfig.debug || debug,
};
return node;
});
// console.log('renderSharedElementTransitions: ', nodes);
const position = Animated.subtract(animValue, startIndex);
return (
<View style={styles.sharedElements} pointerEvents="none">
{nodes.map(({ id, ...other }) => (
<SharedElementTransition
key={`SharedElementTransition.${id}`}
{...other}
position={position}
/>
))}
</View>
);
}
renderBackSwiper() {
const { nextIndex, prevIndex, stack } = this.state;
if (!nextIndex && !prevIndex && stack.length <= 1) {
return;
}
return (
<PanGestureHandler
minDist={5}
onGestureEvent={this._onSwipeBackGestureEvent}
onHandlerStateChange={this._onSwipeBackStateChange}
>
<Animated.View style={styles.swipeBackOverlay} collapsable={false} />
</PanGestureHandler>
);
}
_onSwipeBackStateChange = (event: any) => {
const { width, nextIndex, prevIndex } = this.state;
const { nativeEvent } = event;
switch (nativeEvent.state) {
case State.ACTIVE:
// console.log("SWIPE ACTIVE: ", nativeEvent);
this.setState({
nextIndex: Math.max(nextIndex - 1, 0),
});
break;
case State.CANCELLED:
// console.log("SWIPE CANCEL: ", nativeEvent);
this.setState({
nextIndex: prevIndex,
});
break;
case State.END:
// console.log("SWIPE END: ", nativeEvent);
if (
nativeEvent.velocityX >= 1000 ||
(nativeEvent.velocityX > -1000 &&
nativeEvent.translationX >= width / 2)
) {
Animated.timing(this._swipeBackAnimValue, {
toValue: width,
duration: 100,
useNativeDriver: true,
}).start(({ finished }) => {
if (finished) {
this.pruneStack(this.state.nextIndex + 1);
this._swipeBackAnimValue.setValue(0);
this._animValue.setValue(this.state.nextIndex);
}
});
} else {
Animated.timing(this._swipeBackAnimValue, {
toValue: 0,
duration: 100,
useNativeDriver: true,
}).start(({ finished }) => {
if (finished) {
this.setState({
nextIndex: this.state.prevIndex, // eslint-disable-line react/no-access-state-in-setstate
});
}
});
}
break;
case State.BEGAN:
// console.log("SWIPE BEGAN: ", nativeEvent);
break;
default:
// console.log("SWIPE UNKNOWN STATE: ", nativeEvent);
break;
}
};
render() {
const { stack, animValue, nextIndex, prevIndex, width, height } =
this.state;
const transitionConfig =
this.state.transitionConfig || this.props.transitionConfig;
return (
<View style={styles.container} onLayout={this.onLayout}>
<MaybeScreenContainer style={StyleSheet.absoluteFill}>
{stack.map((node: React.ReactNode, index: number) => {
const isScreenActive =
index === nextIndex || index === prevIndex ? 1 : 0;
return (
<AnimatedRouterScreen
key={`screen${index}`}
active={isScreenActive}
pointerEvents={index === nextIndex ? "auto" : "none"}
style={[
styles.node,
transitionConfig.screenInterpolator({
layout: {
initHeight: height,
initWidth: width,
//width:
//height:
//isMeasured
},
position: animValue,
// progress,
index,
scene: {
index,
//isActive
//isStale
//key,
//route
//descriptor
},
}),
]}
>
<ScreenTransitionContext
style={StyleSheet.absoluteFill}
onSharedElementsUpdated={this.onSharedElementsUpdated}
>
{node}
</ScreenTransitionContext>
</AnimatedRouterScreen>
);
})}
</MaybeScreenContainer>
{this.renderSharedElementTransitions()}
{this.renderBackSwiper()}
</View>
);
}
onLayout = (event: any) => {
const { width, height } = event.nativeEvent.layout;
if (this.state.width !== width || this.state.height !== height) {
this.setState({
width,
height,
animValue: Animated.subtract(
this._animValue,
this._swipeBackAnimValue.interpolate({
inputRange: [0, width],
outputRange: [0, 1],
extrapolate: "clamp",
})
),
});
}
};
onSharedElementsUpdated = (
event: ScreenTransitionContextOnSharedElementsUpdatedEvent
) => {
const { stack, sharedElementScreens } = this.state;
const index = stack.indexOf(event.children);
if (index < 0) {
return;
}
const newSharedElementScreens = [...sharedElementScreens];
newSharedElementScreens[index] = event;
this.setState({
sharedElementScreens: newSharedElementScreens,
});
};
onHardwareBackPress = () => {
if (this.state.stack.length > 1) {
this.pop();
return true;
}
return false;
};
push(node: React.ReactNode, config?: RouterConfig) {
const { nextIndex, prevIndex, actionsQueue } = this.state;
const action: RouterAction = {
action: "push",
node,
config,
};
if (nextIndex !== prevIndex) {
this.setState({
actionsQueue: [...actionsQueue, action],
});
} else {
this.handleAction(action);
}
}
pop(config?: RouterConfig) {
const { nextIndex, prevIndex, actionsQueue } = this.state;
const action: RouterAction = {
action: "pop",
config,
};
if (nextIndex !== prevIndex) {
this.setState({
actionsQueue: [...actionsQueue, action],
});
} else {
this.handleAction(action);
}
}
handleAction({ action, config, node }: RouterAction) {
const { stack, nextIndex, sharedElementScreens } = this.state;
const transitionConfig =
config && config.transitionConfig
? config.transitionConfig
: this.props.transitionConfig;
const sharedElementsConfig = normalizeSharedElementsConfig(
config ? config.sharedElements : undefined
);
if (action === "push") {
this.setState({
stack: [...stack, node],
nextIndex: nextIndex + 1,
sharedElementScreens: [...sharedElementScreens, undefined],
sharedElementsConfig,
transitionConfig,
});
const { transitionSpec } = transitionConfig;
const anim =
transitionSpec.animation === "timing"
? Animated.timing(this._animValue, {
...transitionSpec.config,
toValue: stack.length,
})
: Animated.spring(this._animValue, {
...transitionSpec.config,
toValue: stack.length,
});
anim.start(({ finished }) => {
if (finished) {
this.pruneStack(stack.length + 1);
}
});
} else {
if (stack.length <= 1) {
return;
}
this.setState({
nextIndex: nextIndex - 1,
transitionConfig,
sharedElementsConfig,
});
const { transitionSpec } = transitionConfig;
const anim =
transitionSpec.animation === "timing"
? Animated.timing(this._animValue, {
...transitionSpec.config,
toValue: stack.length - 2,
})
: Animated.spring(this._animValue, {
...transitionSpec.config,
toValue: stack.length - 2,
});
anim.start(({ finished }) => {
if (finished) {
this.pruneStack(stack.length - 1);
}
});
}
}
pruneStack(count: number) {
const { stack, nextIndex, prevIndex, sharedElementScreens } = this.state;
let { actionsQueue } = this.state;
let onComplete;
if (actionsQueue.length) {
const action = actionsQueue[0];
actionsQueue = actionsQueue.slice(0);
actionsQueue.splice(0, 1);
onComplete = () => this.handleAction(action);
}
if (stack.length > count) {
this.setState(
{
stack: stack.slice(0, count),
sharedElementScreens: sharedElementScreens.slice(0, count),
prevIndex: nextIndex,
actionsQueue,
},
onComplete
);
} else if (nextIndex !== prevIndex) {
this.setState(
{
prevIndex: nextIndex,
actionsQueue,
},
onComplete
);
}
}
static push(node: React.ReactNode, config?: RouterConfig) {
return router.push(node, config);
}
static pop(config?: RouterConfig) {
return router.pop(config);
}
} | the_stack |
import * as pathModule from 'path';
import { PathLike, symlink } from 'fs';
import { Node, Link, File } from './node';
import Stats from './Stats';
import Dirent from './Dirent';
import { Buffer, bufferAllocUnsafe, bufferFrom } from './internal/buffer';
import setImmediate from './setImmediate';
import process from './process';
import setTimeoutUnref, { TSetTimeout } from './setTimeoutUnref';
import { Readable, Writable } from 'stream';
import { constants } from './constants';
import { EventEmitter } from 'events';
import { TEncodingExtended, TDataOut, assertEncoding, strToEncoding, ENCODING_UTF8 } from './encoding';
import * as errors from './internal/errors';
import util = require('util');
import createPromisesApi from './promises';
const resolveCrossPlatform = pathModule.resolve;
const {
O_RDONLY,
O_WRONLY,
O_RDWR,
O_CREAT,
O_EXCL,
O_TRUNC,
O_APPEND,
O_SYNC,
O_DIRECTORY,
F_OK,
COPYFILE_EXCL,
COPYFILE_FICLONE_FORCE,
} = constants;
const { sep, relative, join, dirname } = pathModule.posix ? pathModule.posix : pathModule;
const isWin = process.platform === 'win32';
// ---------------------------------------- Types
// Node-style errors with a `code` property.
export interface IError extends Error {
code?: string;
}
export type TFileId = PathLike | number; // Number is used as a file descriptor.
export type TData = TDataOut | Uint8Array; // Data formats users can give us.
export type TFlags = string | number;
export type TMode = string | number; // Mode can be a String, although docs say it should be a Number.
export type TTime = number | string | Date;
export type TCallback<TData> = (error?: IError | null, data?: TData) => void;
// type TCallbackWrite = (err?: IError, bytesWritten?: number, source?: Buffer) => void;
// type TCallbackWriteStr = (err?: IError, written?: number, str?: string) => void;
// ---------------------------------------- Constants
// Default modes for opening files.
const enum MODE {
FILE = 0o666,
DIR = 0o777,
DEFAULT = MODE.FILE,
}
const kMinPoolSpace = 128;
// const kMaxLength = require('buffer').kMaxLength;
// ---------------------------------------- Error messages
// TODO: Use `internal/errors.js` in the future.
const ERRSTR = {
PATH_STR: 'path must be a string or Buffer',
// FD: 'file descriptor must be a unsigned 32-bit integer',
FD: 'fd must be a file descriptor',
MODE_INT: 'mode must be an int',
CB: 'callback must be a function',
UID: 'uid must be an unsigned int',
GID: 'gid must be an unsigned int',
LEN: 'len must be an integer',
ATIME: 'atime must be an integer',
MTIME: 'mtime must be an integer',
PREFIX: 'filename prefix is required',
BUFFER: 'buffer must be an instance of Buffer or StaticBuffer',
OFFSET: 'offset must be an integer',
LENGTH: 'length must be an integer',
POSITION: 'position must be an integer',
};
const ERRSTR_OPTS = tipeof => `Expected options to be either an object or a string, but got ${tipeof} instead`;
// const ERRSTR_FLAG = flag => `Unknown file open flag: ${flag}`;
const ENOENT = 'ENOENT';
const EBADF = 'EBADF';
const EINVAL = 'EINVAL';
const EPERM = 'EPERM';
const EPROTO = 'EPROTO';
const EEXIST = 'EEXIST';
const ENOTDIR = 'ENOTDIR';
const EMFILE = 'EMFILE';
const EACCES = 'EACCES';
const EISDIR = 'EISDIR';
const ENOTEMPTY = 'ENOTEMPTY';
const ENOSYS = 'ENOSYS';
const ERR_FS_EISDIR = 'ERR_FS_EISDIR';
function formatError(errorCode: string, func = '', path = '', path2 = '') {
let pathFormatted = '';
if (path) pathFormatted = ` '${path}'`;
if (path2) pathFormatted += ` -> '${path2}'`;
switch (errorCode) {
case ENOENT:
return `ENOENT: no such file or directory, ${func}${pathFormatted}`;
case EBADF:
return `EBADF: bad file descriptor, ${func}${pathFormatted}`;
case EINVAL:
return `EINVAL: invalid argument, ${func}${pathFormatted}`;
case EPERM:
return `EPERM: operation not permitted, ${func}${pathFormatted}`;
case EPROTO:
return `EPROTO: protocol error, ${func}${pathFormatted}`;
case EEXIST:
return `EEXIST: file already exists, ${func}${pathFormatted}`;
case ENOTDIR:
return `ENOTDIR: not a directory, ${func}${pathFormatted}`;
case EISDIR:
return `EISDIR: illegal operation on a directory, ${func}${pathFormatted}`;
case EACCES:
return `EACCES: permission denied, ${func}${pathFormatted}`;
case ENOTEMPTY:
return `ENOTEMPTY: directory not empty, ${func}${pathFormatted}`;
case EMFILE:
return `EMFILE: too many open files, ${func}${pathFormatted}`;
case ENOSYS:
return `ENOSYS: function not implemented, ${func}${pathFormatted}`;
case ERR_FS_EISDIR:
return `[ERR_FS_EISDIR]: Path is a directory: ${func} returned EISDIR (is a directory) ${path}`
default:
return `${errorCode}: error occurred, ${func}${pathFormatted}`;
}
}
function createError(errorCode: string, func = '', path = '', path2 = '', Constructor = Error) {
const error = new Constructor(formatError(errorCode, func, path, path2));
(error as any).code = errorCode;
return error;
}
// ---------------------------------------- Flags
// List of file `flags` as defined by Node.
export enum FLAGS {
// Open file for reading. An exception occurs if the file does not exist.
r = O_RDONLY,
// Open file for reading and writing. An exception occurs if the file does not exist.
'r+' = O_RDWR,
// Open file for reading in synchronous mode. Instructs the operating system to bypass the local file system cache.
rs = O_RDONLY | O_SYNC,
sr = FLAGS.rs,
// Open file for reading and writing, telling the OS to open it synchronously. See notes for 'rs' about using this with caution.
'rs+' = O_RDWR | O_SYNC,
'sr+' = FLAGS['rs+'],
// Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
w = O_WRONLY | O_CREAT | O_TRUNC,
// Like 'w' but fails if path exists.
wx = O_WRONLY | O_CREAT | O_TRUNC | O_EXCL,
xw = FLAGS.wx,
// Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
'w+' = O_RDWR | O_CREAT | O_TRUNC,
// Like 'w+' but fails if path exists.
'wx+' = O_RDWR | O_CREAT | O_TRUNC | O_EXCL,
'xw+' = FLAGS['wx+'],
// Open file for appending. The file is created if it does not exist.
a = O_WRONLY | O_APPEND | O_CREAT,
// Like 'a' but fails if path exists.
ax = O_WRONLY | O_APPEND | O_CREAT | O_EXCL,
xa = FLAGS.ax,
// Open file for reading and appending. The file is created if it does not exist.
'a+' = O_RDWR | O_APPEND | O_CREAT,
// Like 'a+' but fails if path exists.
'ax+' = O_RDWR | O_APPEND | O_CREAT | O_EXCL,
'xa+' = FLAGS['ax+'],
}
export type TFlagsCopy =
| typeof constants.COPYFILE_EXCL
| typeof constants.COPYFILE_FICLONE
| typeof constants.COPYFILE_FICLONE_FORCE;
export function flagsToNumber(flags: TFlags | undefined): number {
if (typeof flags === 'number') return flags;
if (typeof flags === 'string') {
const flagsNum = FLAGS[flags];
if (typeof flagsNum !== 'undefined') return flagsNum;
}
// throw new TypeError(formatError(ERRSTR_FLAG(flags)));
throw new errors.TypeError('ERR_INVALID_OPT_VALUE', 'flags', flags);
}
// ---------------------------------------- Options
function getOptions<T extends IOptions>(defaults: T, options?: T | string): T {
let opts: T;
if (!options) return defaults;
else {
const tipeof = typeof options;
switch (tipeof) {
case 'string':
opts = Object.assign({}, defaults, { encoding: options as string });
break;
case 'object':
opts = Object.assign({}, defaults, options);
break;
default:
throw TypeError(ERRSTR_OPTS(tipeof));
}
}
if (opts.encoding !== 'buffer') assertEncoding(opts.encoding);
return opts;
}
function optsGenerator<TOpts>(defaults: TOpts): (opts) => TOpts {
return options => getOptions(defaults, options);
}
function validateCallback(callback) {
if (typeof callback !== 'function') throw TypeError(ERRSTR.CB);
return callback;
}
function optsAndCbGenerator<TOpts, TResult>(getOpts): (options, callback?) => [TOpts, TCallback<TResult>] {
return (options, callback?) =>
typeof options === 'function' ? [getOpts(), options] : [getOpts(options), validateCallback(callback)];
}
// General options with optional `encoding` property that most commands accept.
export interface IOptions {
encoding?: BufferEncoding | TEncodingExtended;
}
export interface IFileOptions extends IOptions {
mode?: TMode;
flag?: TFlags;
}
const optsDefaults: IOptions = {
encoding: 'utf8',
};
const getDefaultOpts = optsGenerator<IOptions>(optsDefaults);
const getDefaultOptsAndCb = optsAndCbGenerator<IOptions, any>(getDefaultOpts);
// Options for `fs.readFile` and `fs.readFileSync`.
export interface IReadFileOptions extends IOptions {
flag?: string;
}
const readFileOptsDefaults: IReadFileOptions = {
flag: 'r',
};
const getReadFileOptions = optsGenerator<IReadFileOptions>(readFileOptsDefaults);
// Options for `fs.writeFile` and `fs.writeFileSync`
export interface IWriteFileOptions extends IFileOptions {}
const writeFileDefaults: IWriteFileOptions = {
encoding: 'utf8',
mode: MODE.DEFAULT,
flag: FLAGS[FLAGS.w],
};
const getWriteFileOptions = optsGenerator<IWriteFileOptions>(writeFileDefaults);
// Options for `fs.appendFile` and `fs.appendFileSync`
export interface IAppendFileOptions extends IFileOptions {}
const appendFileDefaults: IAppendFileOptions = {
encoding: 'utf8',
mode: MODE.DEFAULT,
flag: FLAGS[FLAGS.a],
};
const getAppendFileOpts = optsGenerator<IAppendFileOptions>(appendFileDefaults);
const getAppendFileOptsAndCb = optsAndCbGenerator<IAppendFileOptions, void>(getAppendFileOpts);
// Options for `fs.realpath` and `fs.realpathSync`
export interface IRealpathOptions {
encoding?: TEncodingExtended;
}
const realpathDefaults: IReadFileOptions = optsDefaults;
const getRealpathOptions = optsGenerator<IRealpathOptions>(realpathDefaults);
const getRealpathOptsAndCb = optsAndCbGenerator<IRealpathOptions, TDataOut>(getRealpathOptions);
// Options for `fs.watchFile`
export interface IWatchFileOptions {
persistent?: boolean;
interval?: number;
}
// Options for `fs.createReadStream`
export interface IReadStreamOptions {
flags?: TFlags;
encoding?: BufferEncoding;
fd?: number;
mode?: TMode;
autoClose?: boolean;
start?: number;
end?: number;
}
// Options for `fs.createWriteStream`
export interface IWriteStreamOptions {
flags?: TFlags;
defaultEncoding?: BufferEncoding;
fd?: number;
mode?: TMode;
autoClose?: boolean;
start?: number;
}
// Options for `fs.watch`
export interface IWatchOptions extends IOptions {
persistent?: boolean;
recursive?: boolean;
}
// Options for `fs.mkdir` and `fs.mkdirSync`
export interface IMkdirOptions {
mode?: TMode;
recursive?: boolean;
}
const mkdirDefaults: IMkdirOptions = {
mode: MODE.DIR,
recursive: false,
};
const getMkdirOptions = (options): IMkdirOptions => {
if (typeof options === 'number') return Object.assign({}, mkdirDefaults, { mode: options });
return Object.assign({}, mkdirDefaults, options);
};
// Options for `fs.rmdir` and `fs.rmdirSync`
export interface IRmdirOptions {
recursive?: boolean;
}
const rmdirDefaults: IRmdirOptions = {
recursive: false,
};
const getRmdirOptions = (options): IRmdirOptions => {
return Object.assign({}, rmdirDefaults, options);
};
export interface IRmOptions {
force?: boolean;
maxRetries?: number;
recursive?: boolean;
retryDelay?: number;
}
const getRmOpts = optsGenerator<IOptions>(optsDefaults);
const getRmOptsAndCb = optsAndCbGenerator<IRmOptions, any>(getRmOpts);
// Options for `fs.readdir` and `fs.readdirSync`
export interface IReaddirOptions extends IOptions {
withFileTypes?: boolean;
}
const readdirDefaults: IReaddirOptions = {
encoding: 'utf8',
withFileTypes: false,
};
const getReaddirOptions = optsGenerator<IReaddirOptions>(readdirDefaults);
const getReaddirOptsAndCb = optsAndCbGenerator<IReaddirOptions, TDataOut[] | Dirent[]>(getReaddirOptions);
// Options for `fs.fstat`, `fs.fstatSync`, `fs.lstat`, `fs.lstatSync`, `fs.stat`, and `fs.statSync`
export interface IStatOptions {
bigint?: boolean;
}
const statDefaults: IStatOptions = {
bigint: false,
};
const getStatOptions: (options?: any) => IStatOptions = (options = {}) => Object.assign({}, statDefaults, options);
const getStatOptsAndCb: (options: any, callback?: TCallback<Stats>) => [IStatOptions, TCallback<Stats>] = (
options,
callback?,
) =>
typeof options === 'function' ? [getStatOptions(), options] : [getStatOptions(options), validateCallback(callback)];
// ---------------------------------------- Utility functions
function getPathFromURLPosix(url): string {
if (url.hostname !== '') {
throw new errors.TypeError('ERR_INVALID_FILE_URL_HOST', process.platform);
}
const pathname = url.pathname;
for (let n = 0; n < pathname.length; n++) {
if (pathname[n] === '%') {
const third = pathname.codePointAt(n + 2) | 0x20;
if (pathname[n + 1] === '2' && third === 102) {
throw new errors.TypeError('ERR_INVALID_FILE_URL_PATH', 'must not include encoded / characters');
}
}
}
return decodeURIComponent(pathname);
}
export function pathToFilename(path: PathLike): string {
if (typeof path !== 'string' && !Buffer.isBuffer(path)) {
try {
if (!(path instanceof require('url').URL)) throw new TypeError(ERRSTR.PATH_STR);
} catch (err) {
throw new TypeError(ERRSTR.PATH_STR);
}
path = getPathFromURLPosix(path);
}
const pathString = String(path);
nullCheck(pathString);
// return slash(pathString);
return pathString;
}
type TResolve = (filename: string, base?: string) => string;
let resolve: TResolve = (filename, base = process.cwd()) => resolveCrossPlatform(base, filename);
if (isWin) {
const _resolve = resolve;
const { unixify } = require('fs-monkey/lib/correctPath');
resolve = (filename, base) => unixify(_resolve(filename, base));
}
export function filenameToSteps(filename: string, base?: string): string[] {
const fullPath = resolve(filename, base);
const fullPathSansSlash = fullPath.substr(1);
if (!fullPathSansSlash) return [];
return fullPathSansSlash.split(sep);
}
export function pathToSteps(path: PathLike): string[] {
return filenameToSteps(pathToFilename(path));
}
export function dataToStr(data: TData, encoding: string = ENCODING_UTF8): string {
if (Buffer.isBuffer(data)) return data.toString(encoding);
else if (data instanceof Uint8Array) return bufferFrom(data).toString(encoding);
else return String(data);
}
export function dataToBuffer(data: TData, encoding: string = ENCODING_UTF8): Buffer {
if (Buffer.isBuffer(data)) return data;
else if (data instanceof Uint8Array) return bufferFrom(data);
else return bufferFrom(String(data), encoding);
}
export function bufferToEncoding(buffer: Buffer, encoding?: TEncodingExtended): TDataOut {
if (!encoding || encoding === 'buffer') return buffer;
else return buffer.toString(encoding);
}
function nullCheck(path, callback?) {
if (('' + path).indexOf('\u0000') !== -1) {
const er = new Error('Path must be a string without null bytes');
(er as any).code = ENOENT;
if (typeof callback !== 'function') throw er;
process.nextTick(callback, er);
return false;
}
return true;
}
function _modeToNumber(mode: TMode | undefined, def?): number | undefined {
if (typeof mode === 'number') return mode;
if (typeof mode === 'string') return parseInt(mode, 8);
if (def) return modeToNumber(def);
return undefined;
}
function modeToNumber(mode: TMode | undefined, def?): number {
const result = _modeToNumber(mode, def);
if (typeof result !== 'number' || isNaN(result)) throw new TypeError(ERRSTR.MODE_INT);
return result;
}
function isFd(path): boolean {
return path >>> 0 === path;
}
function validateFd(fd) {
if (!isFd(fd)) throw TypeError(ERRSTR.FD);
}
// converts Date or number to a fractional UNIX timestamp
export function toUnixTimestamp(time) {
// tslint:disable-next-line triple-equals
if (typeof time === 'string' && +time == (time as any)) {
return +time;
}
if (time instanceof Date) {
return time.getTime() / 1000;
}
if (isFinite(time)) {
if (time < 0) {
return Date.now() / 1000;
}
return time;
}
throw new Error('Cannot parse time: ' + time);
}
function validateUid(uid: number) {
if (typeof uid !== 'number') throw TypeError(ERRSTR.UID);
}
function validateGid(gid: number) {
if (typeof gid !== 'number') throw TypeError(ERRSTR.GID);
}
// ---------------------------------------- Volume
type DirectoryContent = string | null;
export interface DirectoryJSON {
[key: string]: DirectoryContent;
}
export interface NestedDirectoryJSON {
[key: string]: DirectoryContent | NestedDirectoryJSON;
}
function flattenJSON(nestedJSON: NestedDirectoryJSON): DirectoryJSON {
const flatJSON: DirectoryJSON = {};
function flatten(pathPrefix: string, node: NestedDirectoryJSON) {
for (const path in node) {
const contentOrNode = node[path];
const joinedPath = join(pathPrefix, path);
if (typeof contentOrNode === 'string') {
flatJSON[joinedPath] = contentOrNode;
} else if (typeof contentOrNode === 'object' && contentOrNode !== null && Object.keys(contentOrNode).length > 0) {
// empty directories need an explicit entry and therefore get handled in `else`, non-empty ones are implicitly considered
flatten(joinedPath, contentOrNode);
} else {
// without this branch null, empty-object or non-object entries would not be handled in the same way
// by both fromJSON() and fromNestedJSON()
flatJSON[joinedPath] = null;
}
}
}
flatten('', nestedJSON);
return flatJSON;
}
/**
* `Volume` represents a file system.
*/
export class Volume {
static fromJSON(json: DirectoryJSON, cwd?: string): Volume {
const vol = new Volume();
vol.fromJSON(json, cwd);
return vol;
}
static fromNestedJSON(json: NestedDirectoryJSON, cwd?: string): Volume {
const vol = new Volume();
vol.fromNestedJSON(json, cwd);
return vol;
}
/**
* Global file descriptor counter. UNIX file descriptors start from 0 and go sequentially
* up, so here, in order not to conflict with them, we choose some big number and descrease
* the file descriptor of every new opened file.
* @type {number}
* @todo This should not be static, right?
*/
static fd: number = 0x7fffffff;
// Constructor function used to create new nodes.
// NodeClass: new (...args) => TNode = Node as new (...args) => TNode;
// Hard link to the root of this volume.
// root: Node = new (this.NodeClass)(null, '', true);
root: Link;
// I-node number counter.
ino: number = 0;
// A mapping for i-node numbers to i-nodes (`Node`);
inodes: { [ino: number]: Node } = {};
// List of released i-node numbers, for reuse.
releasedInos: number[] = [];
// A mapping for file descriptors to `File`s.
fds: { [fd: number]: File } = {};
// A list of reusable (opened and closed) file descriptors, that should be
// used first before creating a new file descriptor.
releasedFds: number[] = [];
// Max number of open files.
maxFiles = 10000;
// Current number of open files.
openFiles = 0;
StatWatcher: new () => StatWatcher;
ReadStream: new (...args) => IReadStream;
WriteStream: new (...args) => IWriteStream;
FSWatcher: new () => FSWatcher;
props: {
Node: new (...args) => Node;
Link: new (...args) => Link;
File: new (...args) => File;
};
private promisesApi = createPromisesApi(this);
get promises() {
if (this.promisesApi === null) throw new Error('Promise is not supported in this environment.');
return this.promisesApi;
}
constructor(props = {}) {
this.props = Object.assign({ Node, Link, File }, props);
const root = this.createLink();
root.setNode(this.createNode(true));
const self = this; // tslint:disable-line no-this-assignment
this.StatWatcher = class extends StatWatcher {
constructor() {
super(self);
}
};
const _ReadStream: new (...args) => IReadStream = FsReadStream as any;
this.ReadStream = (class extends _ReadStream {
constructor(...args) {
super(self, ...args);
}
} as any) as new (...args) => IReadStream;
const _WriteStream: new (...args) => IWriteStream = FsWriteStream as any;
this.WriteStream = (class extends _WriteStream {
constructor(...args) {
super(self, ...args);
}
} as any) as new (...args) => IWriteStream;
this.FSWatcher = class extends FSWatcher {
constructor() {
super(self);
}
};
// root.setChild('.', root);
// root.getNode().nlink++;
// root.setChild('..', root);
// root.getNode().nlink++;
this.root = root;
}
createLink(): Link;
createLink(parent: Link, name: string, isDirectory?: boolean, perm?: number): Link;
createLink(parent?: Link, name?: string, isDirectory: boolean = false, perm?: number): Link {
if (!parent) {
return new this.props.Link(this, null, '');
}
if (!name) {
throw new Error('createLink: name cannot be empty');
}
return parent.createChild(name, this.createNode(isDirectory, perm));
}
deleteLink(link: Link): boolean {
const parent = link.parent;
if (parent) {
parent.deleteChild(link);
return true;
}
return false;
}
private newInoNumber(): number {
const releasedFd = this.releasedInos.pop();
if (releasedFd) return releasedFd;
else {
this.ino = (this.ino + 1) % 0xffffffff;
return this.ino;
}
}
private newFdNumber(): number {
const releasedFd = this.releasedFds.pop();
return typeof releasedFd === 'number' ? releasedFd : Volume.fd--;
}
createNode(isDirectory: boolean = false, perm?: number): Node {
const node = new this.props.Node(this.newInoNumber(), perm);
if (isDirectory) node.setIsDirectory();
this.inodes[node.ino] = node;
return node;
}
private getNode(ino: number) {
return this.inodes[ino];
}
private deleteNode(node: Node) {
node.del();
delete this.inodes[node.ino];
this.releasedInos.push(node.ino);
}
// Generates 6 character long random string, used by `mkdtemp`.
genRndStr() {
const str = (Math.random() + 1).toString(36).substr(2, 6);
if (str.length === 6) return str;
else return this.genRndStr();
}
// Returns a `Link` (hard link) referenced by path "split" into steps.
getLink(steps: string[]): Link | null {
return this.root.walk(steps);
}
// Just link `getLink`, but throws a correct user error, if link to found.
getLinkOrThrow(filename: string, funcName?: string): Link {
const steps = filenameToSteps(filename);
const link = this.getLink(steps);
if (!link) throw createError(ENOENT, funcName, filename);
return link;
}
// Just like `getLink`, but also dereference/resolves symbolic links.
getResolvedLink(filenameOrSteps: string | string[]): Link | null {
let steps: string[] = typeof filenameOrSteps === 'string' ? filenameToSteps(filenameOrSteps) : filenameOrSteps;
let link: Link | undefined = this.root;
let i = 0;
while (i < steps.length) {
const step = steps[i];
link = link.getChild(step);
if (!link) return null;
const node = link.getNode();
if (node.isSymlink()) {
steps = node.symlink.concat(steps.slice(i + 1));
link = this.root;
i = 0;
continue;
}
i++;
}
return link;
}
// Just like `getLinkOrThrow`, but also dereference/resolves symbolic links.
getResolvedLinkOrThrow(filename: string, funcName?: string): Link {
const link = this.getResolvedLink(filename);
if (!link) throw createError(ENOENT, funcName, filename);
return link;
}
resolveSymlinks(link: Link): Link | null {
// let node: Node = link.getNode();
// while(link && node.isSymlink()) {
// link = this.getLink(node.symlink);
// if(!link) return null;
// node = link.getNode();
// }
// return link;
return this.getResolvedLink(link.steps.slice(1));
}
// Just like `getLinkOrThrow`, but also verifies that the link is a directory.
private getLinkAsDirOrThrow(filename: string, funcName?: string): Link {
const link = this.getLinkOrThrow(filename, funcName);
if (!link.getNode().isDirectory()) throw createError(ENOTDIR, funcName, filename);
return link;
}
// Get the immediate parent directory of the link.
private getLinkParent(steps: string[]): Link | null {
return this.root.walk(steps, steps.length - 1);
}
private getLinkParentAsDirOrThrow(filenameOrSteps: string | string[], funcName?: string): Link {
const steps = filenameOrSteps instanceof Array ? filenameOrSteps : filenameToSteps(filenameOrSteps);
const link = this.getLinkParent(steps);
if (!link) throw createError(ENOENT, funcName, sep + steps.join(sep));
if (!link.getNode().isDirectory()) throw createError(ENOTDIR, funcName, sep + steps.join(sep));
return link;
}
private getFileByFd(fd: number): File {
return this.fds[String(fd)];
}
private getFileByFdOrThrow(fd: number, funcName?: string): File {
if (!isFd(fd)) throw TypeError(ERRSTR.FD);
const file = this.getFileByFd(fd);
if (!file) throw createError(EBADF, funcName);
return file;
}
/**
* @todo This is not used anymore. Remove.
*/
/*
private getNodeByIdOrCreate(id: TFileId, flags: number, perm: number): Node {
if (typeof id === 'number') {
const file = this.getFileByFd(id);
if (!file) throw Error('File nto found');
return file.node;
} else {
const steps = pathToSteps(id as PathLike);
let link = this.getLink(steps);
if (link) return link.getNode();
// Try creating a node if not found.
if (flags & O_CREAT) {
const dirLink = this.getLinkParent(steps);
if (dirLink) {
const name = steps[steps.length - 1];
link = this.createLink(dirLink, name, false, perm);
return link.getNode();
}
}
throw createError(ENOENT, 'getNodeByIdOrCreate', pathToFilename(id));
}
}
*/
private wrapAsync(method: (...args) => void, args: any[], callback: TCallback<any>) {
validateCallback(callback);
setImmediate(() => {
let result;
try {
result = method.apply(this, args);
} catch (err) {
callback(err);
return;
}
callback(null, result);
});
}
private _toJSON(link = this.root, json = {}, path?: string): DirectoryJSON {
let isEmpty = true;
let children = link.children;
if (link.getNode().isFile()) {
children = { [link.getName()]: link.parent.getChild(link.getName()) };
link = link.parent;
}
for (const name in children) {
isEmpty = false;
const child = link.getChild(name);
if (!child) {
throw new Error('_toJSON: unexpected undefined');
}
const node = child.getNode();
if (node.isFile()) {
let filename = child.getPath();
if (path) filename = relative(path, filename);
json[filename] = node.getString();
} else if (node.isDirectory()) {
this._toJSON(child, json, path);
}
}
let dirPath = link.getPath();
if (path) dirPath = relative(path, dirPath);
if (dirPath && isEmpty) {
json[dirPath] = null;
}
return json;
}
toJSON(paths?: PathLike | PathLike[], json = {}, isRelative = false): DirectoryJSON {
const links: Link[] = [];
if (paths) {
if (!(paths instanceof Array)) paths = [paths];
for (const path of paths) {
const filename = pathToFilename(path);
const link = this.getResolvedLink(filename);
if (!link) continue;
links.push(link);
}
} else {
links.push(this.root);
}
if (!links.length) return json;
for (const link of links) this._toJSON(link, json, isRelative ? link.getPath() : '');
return json;
}
fromJSON(json: DirectoryJSON, cwd: string = process.cwd()) {
for (let filename in json) {
const data = json[filename];
filename = resolve(filename, cwd);
if (typeof data === 'string') {
const dir = dirname(filename);
this.mkdirpBase(dir, MODE.DIR);
this.writeFileSync(filename, data);
} else {
this.mkdirpBase(filename, MODE.DIR);
}
}
}
fromNestedJSON(json: NestedDirectoryJSON, cwd?: string) {
this.fromJSON(flattenJSON(json), cwd);
}
reset() {
this.ino = 0;
this.inodes = {};
this.releasedInos = [];
this.fds = {};
this.releasedFds = [];
this.openFiles = 0;
this.root = this.createLink();
this.root.setNode(this.createNode(true));
}
// Legacy interface
mountSync(mountpoint: string, json: DirectoryJSON) {
this.fromJSON(json, mountpoint);
}
private openLink(link: Link, flagsNum: number, resolveSymlinks: boolean = true): File {
if (this.openFiles >= this.maxFiles) {
// Too many open files.
throw createError(EMFILE, 'open', link.getPath());
}
// Resolve symlinks.
let realLink: Link | null = link;
if (resolveSymlinks) realLink = this.resolveSymlinks(link);
if (!realLink) throw createError(ENOENT, 'open', link.getPath());
const node = realLink.getNode();
// Check whether node is a directory
if (node.isDirectory()) {
if ((flagsNum & (O_RDONLY | O_RDWR | O_WRONLY)) !== O_RDONLY) throw createError(EISDIR, 'open', link.getPath());
} else {
if (flagsNum & O_DIRECTORY) throw createError(ENOTDIR, 'open', link.getPath());
}
// Check node permissions
if (!(flagsNum & O_WRONLY)) {
if (!node.canRead()) {
throw createError(EACCES, 'open', link.getPath());
}
}
if (flagsNum & O_RDWR) {
}
const file = new this.props.File(link, node, flagsNum, this.newFdNumber());
this.fds[file.fd] = file;
this.openFiles++;
if (flagsNum & O_TRUNC) file.truncate();
return file;
}
private openFile(
filename: string,
flagsNum: number,
modeNum: number | undefined,
resolveSymlinks: boolean = true,
): File {
const steps = filenameToSteps(filename);
let link: Link | null = resolveSymlinks ? this.getResolvedLink(steps) : this.getLink(steps);
// Try creating a new file, if it does not exist.
if (!link && flagsNum & O_CREAT) {
// const dirLink: Link = this.getLinkParent(steps);
const dirLink: Link | null = this.getResolvedLink(steps.slice(0, steps.length - 1));
// if(!dirLink) throw createError(ENOENT, 'open', filename);
if (!dirLink) throw createError(ENOENT, 'open', sep + steps.join(sep));
if (flagsNum & O_CREAT && typeof modeNum === 'number') {
link = this.createLink(dirLink, steps[steps.length - 1], false, modeNum);
}
}
if (link) return this.openLink(link, flagsNum, resolveSymlinks);
throw createError(ENOENT, 'open', filename);
}
private openBase(filename: string, flagsNum: number, modeNum: number, resolveSymlinks: boolean = true): number {
const file = this.openFile(filename, flagsNum, modeNum, resolveSymlinks);
if (!file) throw createError(ENOENT, 'open', filename);
return file.fd;
}
openSync(path: PathLike, flags: TFlags, mode: TMode = MODE.DEFAULT): number {
// Validate (1) mode; (2) path; (3) flags - in that order.
const modeNum = modeToNumber(mode);
const fileName = pathToFilename(path);
const flagsNum = flagsToNumber(flags);
return this.openBase(fileName, flagsNum, modeNum);
}
open(path: PathLike, flags: TFlags, /* ... */ callback: TCallback<number>);
open(path: PathLike, flags: TFlags, mode: TMode, callback: TCallback<number>);
open(path: PathLike, flags: TFlags, a: TMode | TCallback<number>, b?: TCallback<number>) {
let mode: TMode = a as TMode;
let callback: TCallback<number> = b as TCallback<number>;
if (typeof a === 'function') {
mode = MODE.DEFAULT;
callback = a;
}
mode = mode || MODE.DEFAULT;
const modeNum = modeToNumber(mode);
const fileName = pathToFilename(path);
const flagsNum = flagsToNumber(flags);
this.wrapAsync(this.openBase, [fileName, flagsNum, modeNum], callback);
}
private closeFile(file: File) {
if (!this.fds[file.fd]) return;
this.openFiles--;
delete this.fds[file.fd];
this.releasedFds.push(file.fd);
}
closeSync(fd: number) {
validateFd(fd);
const file = this.getFileByFdOrThrow(fd, 'close');
this.closeFile(file);
}
close(fd: number, callback: TCallback<void>) {
validateFd(fd);
this.wrapAsync(this.closeSync, [fd], callback);
}
private openFileOrGetById(id: TFileId, flagsNum: number, modeNum?: number): File {
if (typeof id === 'number') {
const file = this.fds[id];
if (!file) throw createError(ENOENT);
return file;
} else {
return this.openFile(pathToFilename(id), flagsNum, modeNum);
}
}
private readBase(fd: number, buffer: Buffer | Uint8Array, offset: number, length: number, position: number): number {
const file = this.getFileByFdOrThrow(fd);
return file.read(buffer, Number(offset), Number(length), position);
}
readSync(fd: number, buffer: Buffer | Uint8Array, offset: number, length: number, position: number): number {
validateFd(fd);
return this.readBase(fd, buffer, offset, length, position);
}
read(
fd: number,
buffer: Buffer | Uint8Array,
offset: number,
length: number,
position: number,
callback: (err?: Error | null, bytesRead?: number, buffer?: Buffer | Uint8Array) => void,
) {
validateCallback(callback);
// This `if` branch is from Node.js
if (length === 0) {
return process.nextTick(() => {
if (callback) callback(null, 0, buffer);
});
}
setImmediate(() => {
try {
const bytes = this.readBase(fd, buffer, offset, length, position);
callback(null, bytes, buffer);
} catch (err) {
callback(err);
}
});
}
private readFileBase(id: TFileId, flagsNum: number, encoding: BufferEncoding): Buffer | string {
let result: Buffer | string;
const isUserFd = typeof id === 'number';
const userOwnsFd: boolean = isUserFd && isFd(id);
let fd: number;
if (userOwnsFd) fd = id as number;
else {
const filename = pathToFilename(id as PathLike);
const steps = filenameToSteps(filename);
const link: Link | null = this.getResolvedLink(steps);
if (link) {
const node = link.getNode();
if (node.isDirectory()) throw createError(EISDIR, 'open', link.getPath());
}
fd = this.openSync(id as PathLike, flagsNum);
}
try {
result = bufferToEncoding(this.getFileByFdOrThrow(fd).getBuffer(), encoding);
} finally {
if (!userOwnsFd) {
this.closeSync(fd);
}
}
return result;
}
readFileSync(file: TFileId, options?: IReadFileOptions | string): TDataOut {
const opts = getReadFileOptions(options);
const flagsNum = flagsToNumber(opts.flag);
return this.readFileBase(file, flagsNum, opts.encoding as BufferEncoding);
}
readFile(id: TFileId, callback: TCallback<TDataOut>);
readFile(id: TFileId, options: IReadFileOptions | string, callback: TCallback<TDataOut>);
readFile(id: TFileId, a: TCallback<TDataOut> | IReadFileOptions | string, b?: TCallback<TDataOut>) {
const [opts, callback] = optsAndCbGenerator<IReadFileOptions, TCallback<TDataOut>>(getReadFileOptions)(a, b);
const flagsNum = flagsToNumber(opts.flag);
this.wrapAsync(this.readFileBase, [id, flagsNum, opts.encoding], callback);
}
private writeBase(fd: number, buf: Buffer, offset?: number, length?: number, position?: number): number {
const file = this.getFileByFdOrThrow(fd, 'write');
return file.write(buf, offset, length, position);
}
writeSync(fd: number, buffer: Buffer | Uint8Array, offset?: number, length?: number, position?: number): number;
writeSync(fd: number, str: string, position?: number, encoding?: BufferEncoding): number;
writeSync(fd: number, a: string | Buffer | Uint8Array, b?: number, c?: number | BufferEncoding, d?: number): number {
validateFd(fd);
let encoding: BufferEncoding | undefined;
let offset: number | undefined;
let length: number | undefined;
let position: number | undefined;
const isBuffer = typeof a !== 'string';
if (isBuffer) {
offset = (b || 0) | 0;
length = c as number;
position = d;
} else {
position = b;
encoding = c as BufferEncoding;
}
const buf: Buffer = dataToBuffer(a, encoding);
if (isBuffer) {
if (typeof length === 'undefined') {
length = buf.length;
}
} else {
offset = 0;
length = buf.length;
}
return this.writeBase(fd, buf, offset, length, position);
}
write(fd: number, buffer: Buffer | Uint8Array, callback: (...args) => void);
write(fd: number, buffer: Buffer | Uint8Array, offset: number, callback: (...args) => void);
write(fd: number, buffer: Buffer | Uint8Array, offset: number, length: number, callback: (...args) => void);
write(
fd: number,
buffer: Buffer | Uint8Array,
offset: number,
length: number,
position: number,
callback: (...args) => void,
);
write(fd: number, str: string, callback: (...args) => void);
write(fd: number, str: string, position: number, callback: (...args) => void);
write(fd: number, str: string, position: number, encoding: BufferEncoding, callback: (...args) => void);
write(fd: number, a?, b?, c?, d?, e?) {
validateFd(fd);
let offset: number;
let length: number | undefined;
let position: number;
let encoding: BufferEncoding | undefined;
let callback: ((...args) => void) | undefined;
const tipa = typeof a;
const tipb = typeof b;
const tipc = typeof c;
const tipd = typeof d;
if (tipa !== 'string') {
if (tipb === 'function') {
callback = b;
} else if (tipc === 'function') {
offset = b | 0;
callback = c;
} else if (tipd === 'function') {
offset = b | 0;
length = c;
callback = d;
} else {
offset = b | 0;
length = c;
position = d;
callback = e;
}
} else {
if (tipb === 'function') {
callback = b;
} else if (tipc === 'function') {
position = b;
callback = c;
} else if (tipd === 'function') {
position = b;
encoding = c;
callback = d;
}
}
const buf: Buffer = dataToBuffer(a, encoding);
if (tipa !== 'string') {
if (typeof length === 'undefined') length = buf.length;
} else {
offset = 0;
length = buf.length;
}
const cb = validateCallback(callback);
setImmediate(() => {
try {
const bytes = this.writeBase(fd, buf, offset, length, position);
if (tipa !== 'string') {
cb(null, bytes, buf);
} else {
cb(null, bytes, a);
}
} catch (err) {
cb(err);
}
});
}
private writeFileBase(id: TFileId, buf: Buffer, flagsNum: number, modeNum: number) {
// console.log('writeFileBase', id, buf, flagsNum, modeNum);
// const node = this.getNodeByIdOrCreate(id, flagsNum, modeNum);
// node.setBuffer(buf);
const isUserFd = typeof id === 'number';
let fd: number;
if (isUserFd) fd = id as number;
else {
fd = this.openBase(pathToFilename(id as PathLike), flagsNum, modeNum);
// fd = this.openSync(id as PathLike, flagsNum, modeNum);
}
let offset = 0;
let length = buf.length;
let position = flagsNum & O_APPEND ? undefined : 0;
try {
while (length > 0) {
const written = this.writeSync(fd, buf, offset, length, position);
offset += written;
length -= written;
if (position !== undefined) position += written;
}
} finally {
if (!isUserFd) this.closeSync(fd);
}
}
writeFileSync(id: TFileId, data: TData, options?: IWriteFileOptions) {
const opts = getWriteFileOptions(options);
const flagsNum = flagsToNumber(opts.flag);
const modeNum = modeToNumber(opts.mode);
const buf = dataToBuffer(data, opts.encoding);
this.writeFileBase(id, buf, flagsNum, modeNum);
}
writeFile(id: TFileId, data: TData, callback: TCallback<void>);
writeFile(id: TFileId, data: TData, options: IWriteFileOptions | string, callback: TCallback<void>);
writeFile(id: TFileId, data: TData, a: TCallback<void> | IWriteFileOptions | string, b?: TCallback<void>) {
let options: IWriteFileOptions | string = a as IWriteFileOptions;
let callback: TCallback<void> | undefined = b;
if (typeof a === 'function') {
options = writeFileDefaults;
callback = a;
}
const cb = validateCallback(callback);
const opts = getWriteFileOptions(options);
const flagsNum = flagsToNumber(opts.flag);
const modeNum = modeToNumber(opts.mode);
const buf = dataToBuffer(data, opts.encoding);
this.wrapAsync(this.writeFileBase, [id, buf, flagsNum, modeNum], cb);
}
private linkBase(filename1: string, filename2: string) {
const steps1 = filenameToSteps(filename1);
const link1 = this.getLink(steps1);
if (!link1) throw createError(ENOENT, 'link', filename1, filename2);
const steps2 = filenameToSteps(filename2);
// Check new link directory exists.
const dir2 = this.getLinkParent(steps2);
if (!dir2) throw createError(ENOENT, 'link', filename1, filename2);
const name = steps2[steps2.length - 1];
// Check if new file already exists.
if (dir2.getChild(name)) throw createError(EEXIST, 'link', filename1, filename2);
const node = link1.getNode();
node.nlink++;
dir2.createChild(name, node);
}
private copyFileBase(src: string, dest: string, flags: number) {
const buf = this.readFileSync(src) as Buffer;
if (flags & COPYFILE_EXCL) {
if (this.existsSync(dest)) {
throw createError(EEXIST, 'copyFile', src, dest);
}
}
if (flags & COPYFILE_FICLONE_FORCE) {
throw createError(ENOSYS, 'copyFile', src, dest);
}
this.writeFileBase(dest, buf, FLAGS.w, MODE.DEFAULT);
}
copyFileSync(src: PathLike, dest: PathLike, flags?: TFlagsCopy) {
const srcFilename = pathToFilename(src);
const destFilename = pathToFilename(dest);
return this.copyFileBase(srcFilename, destFilename, (flags || 0) | 0);
}
copyFile(src: PathLike, dest: PathLike, callback: TCallback<void>);
copyFile(src: PathLike, dest: PathLike, flags: TFlagsCopy, callback: TCallback<void>);
copyFile(src: PathLike, dest: PathLike, a, b?) {
const srcFilename = pathToFilename(src);
const destFilename = pathToFilename(dest);
let flags: TFlagsCopy;
let callback: TCallback<void>;
if (typeof a === 'function') {
flags = 0;
callback = a;
} else {
flags = a;
callback = b;
}
validateCallback(callback);
this.wrapAsync(this.copyFileBase, [srcFilename, destFilename, flags], callback);
}
linkSync(existingPath: PathLike, newPath: PathLike) {
const existingPathFilename = pathToFilename(existingPath);
const newPathFilename = pathToFilename(newPath);
this.linkBase(existingPathFilename, newPathFilename);
}
link(existingPath: PathLike, newPath: PathLike, callback: TCallback<void>) {
const existingPathFilename = pathToFilename(existingPath);
const newPathFilename = pathToFilename(newPath);
this.wrapAsync(this.linkBase, [existingPathFilename, newPathFilename], callback);
}
private unlinkBase(filename: string) {
const steps = filenameToSteps(filename);
const link = this.getLink(steps);
if (!link) throw createError(ENOENT, 'unlink', filename);
// TODO: Check if it is file, dir, other...
if (link.length) throw Error('Dir not empty...');
this.deleteLink(link);
const node = link.getNode();
node.nlink--;
// When all hard links to i-node are deleted, remove the i-node, too.
if (node.nlink <= 0) {
this.deleteNode(node);
}
}
unlinkSync(path: PathLike) {
const filename = pathToFilename(path);
this.unlinkBase(filename);
}
unlink(path: PathLike, callback: TCallback<void>) {
const filename = pathToFilename(path);
this.wrapAsync(this.unlinkBase, [filename], callback);
}
private symlinkBase(targetFilename: string, pathFilename: string): Link {
const pathSteps = filenameToSteps(pathFilename);
// Check if directory exists, where we about to create a symlink.
const dirLink = this.getLinkParent(pathSteps);
if (!dirLink) throw createError(ENOENT, 'symlink', targetFilename, pathFilename);
const name = pathSteps[pathSteps.length - 1];
// Check if new file already exists.
if (dirLink.getChild(name)) throw createError(EEXIST, 'symlink', targetFilename, pathFilename);
// Create symlink.
const symlink: Link = dirLink.createChild(name);
symlink.getNode().makeSymlink(filenameToSteps(targetFilename));
return symlink;
}
// `type` argument works only on Windows.
symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type) {
const targetFilename = pathToFilename(target);
const pathFilename = pathToFilename(path);
this.symlinkBase(targetFilename, pathFilename);
}
symlink(target: PathLike, path: PathLike, callback: TCallback<void>);
symlink(target: PathLike, path: PathLike, type: symlink.Type, callback: TCallback<void>);
symlink(target: PathLike, path: PathLike, a: symlink.Type | TCallback<void>, b?: TCallback<void>) {
const callback: TCallback<void> = validateCallback(typeof a === 'function' ? a : b);
const targetFilename = pathToFilename(target);
const pathFilename = pathToFilename(path);
this.wrapAsync(this.symlinkBase, [targetFilename, pathFilename], callback);
}
private realpathBase(filename: string, encoding: TEncodingExtended | undefined): TDataOut {
const steps = filenameToSteps(filename);
const realLink = this.getResolvedLink(steps);
if (!realLink) throw createError(ENOENT, 'realpath', filename);
return strToEncoding(realLink.getPath(), encoding);
}
realpathSync(path: PathLike, options?: IRealpathOptions | string): TDataOut {
return this.realpathBase(pathToFilename(path), getRealpathOptions(options).encoding);
}
realpath(path: PathLike, callback: TCallback<TDataOut>);
realpath(path: PathLike, options: IRealpathOptions | string, callback: TCallback<TDataOut>);
realpath(path: PathLike, a: TCallback<TDataOut> | IRealpathOptions | string, b?: TCallback<TDataOut>) {
const [opts, callback] = getRealpathOptsAndCb(a, b);
const pathFilename = pathToFilename(path);
this.wrapAsync(this.realpathBase, [pathFilename, opts.encoding], callback);
}
private lstatBase(filename: string, bigint: false): Stats<number>;
private lstatBase(filename: string, bigint: true): Stats<bigint>;
private lstatBase(filename: string, bigint: boolean = false): Stats {
const link = this.getLink(filenameToSteps(filename));
if (!link) throw createError(ENOENT, 'lstat', filename);
return Stats.build(link.getNode(), bigint);
}
lstatSync(path: PathLike): Stats<number>;
lstatSync(path: PathLike, options: { bigint: false }): Stats<number>;
lstatSync(path: PathLike, options: { bigint: true }): Stats<bigint>;
lstatSync(path: PathLike, options?: IStatOptions): Stats {
return this.lstatBase(pathToFilename(path), getStatOptions(options).bigint as any);
}
lstat(path: PathLike, callback: TCallback<Stats>);
lstat(path: PathLike, options: IStatOptions, callback: TCallback<Stats>);
lstat(path: PathLike, a: TCallback<Stats> | IStatOptions, b?: TCallback<Stats>) {
const [opts, callback] = getStatOptsAndCb(a, b);
this.wrapAsync(this.lstatBase, [pathToFilename(path), opts.bigint], callback);
}
private statBase(filename: string): Stats<number>;
private statBase(filename: string, bigint: false): Stats<number>;
private statBase(filename: string, bigint: true): Stats<bigint>;
private statBase(filename: string, bigint: boolean = false): Stats {
const link = this.getResolvedLink(filenameToSteps(filename));
if (!link) throw createError(ENOENT, 'stat', filename);
return Stats.build(link.getNode(), bigint);
}
statSync(path: PathLike): Stats<number>;
statSync(path: PathLike, options: { bigint: false }): Stats<number>;
statSync(path: PathLike, options: { bigint: true }): Stats<bigint>;
statSync(path: PathLike, options?: IStatOptions): Stats {
return this.statBase(pathToFilename(path), getStatOptions(options).bigint as any);
}
stat(path: PathLike, callback: TCallback<Stats>);
stat(path: PathLike, options: IStatOptions, callback: TCallback<Stats>);
stat(path: PathLike, a: TCallback<Stats> | IStatOptions, b?: TCallback<Stats>) {
const [opts, callback] = getStatOptsAndCb(a, b);
this.wrapAsync(this.statBase, [pathToFilename(path), opts.bigint], callback);
}
private fstatBase(fd: number): Stats<number>;
private fstatBase(fd: number, bigint: false): Stats<number>;
private fstatBase(fd: number, bigint: true): Stats<bigint>;
private fstatBase(fd: number, bigint: boolean = false): Stats {
const file = this.getFileByFd(fd);
if (!file) throw createError(EBADF, 'fstat');
return Stats.build(file.node, bigint);
}
fstatSync(fd: number): Stats<number>;
fstatSync(fd: number, options: { bigint: false }): Stats<number>;
fstatSync(fd: number, options: { bigint: true }): Stats<bigint>;
fstatSync(fd: number, options?: IStatOptions): Stats {
return this.fstatBase(fd, getStatOptions(options).bigint as any);
}
fstat(fd: number, callback: TCallback<Stats>);
fstat(fd: number, options: IStatOptions, callback: TCallback<Stats>);
fstat(fd: number, a: TCallback<Stats> | IStatOptions, b?: TCallback<Stats>) {
const [opts, callback] = getStatOptsAndCb(a, b);
this.wrapAsync(this.fstatBase, [fd, opts.bigint], callback);
}
private renameBase(oldPathFilename: string, newPathFilename: string) {
const link = this.getLink(filenameToSteps(oldPathFilename));
if (!link) throw createError(ENOENT, 'rename', oldPathFilename, newPathFilename);
// TODO: Check if it is directory, if non-empty, we cannot move it, right?
const newPathSteps = filenameToSteps(newPathFilename);
// Check directory exists for the new location.
const newPathDirLink = this.getLinkParent(newPathSteps);
if (!newPathDirLink) throw createError(ENOENT, 'rename', oldPathFilename, newPathFilename);
// TODO: Also treat cases with directories and symbolic links.
// TODO: See: http://man7.org/linux/man-pages/man2/rename.2.html
// Remove hard link from old folder.
const oldLinkParent = link.parent;
if (oldLinkParent) {
oldLinkParent.deleteChild(link);
}
// Rename should overwrite the new path, if that exists.
const name = newPathSteps[newPathSteps.length - 1];
link.steps = [...newPathDirLink.steps, name];
newPathDirLink.setChild(link.getName(), link);
}
renameSync(oldPath: PathLike, newPath: PathLike) {
const oldPathFilename = pathToFilename(oldPath);
const newPathFilename = pathToFilename(newPath);
this.renameBase(oldPathFilename, newPathFilename);
}
rename(oldPath: PathLike, newPath: PathLike, callback: TCallback<void>) {
const oldPathFilename = pathToFilename(oldPath);
const newPathFilename = pathToFilename(newPath);
this.wrapAsync(this.renameBase, [oldPathFilename, newPathFilename], callback);
}
private existsBase(filename: string): boolean {
return !!this.statBase(filename);
}
existsSync(path: PathLike): boolean {
try {
return this.existsBase(pathToFilename(path));
} catch (err) {
return false;
}
}
exists(path: PathLike, callback: (exists: boolean) => void) {
const filename = pathToFilename(path);
if (typeof callback !== 'function') throw Error(ERRSTR.CB);
setImmediate(() => {
try {
callback(this.existsBase(filename));
} catch (err) {
callback(false);
}
});
}
private accessBase(filename: string, mode: number) {
const link = this.getLinkOrThrow(filename, 'access');
// TODO: Verify permissions
}
accessSync(path: PathLike, mode: number = F_OK) {
const filename = pathToFilename(path);
mode = mode | 0;
this.accessBase(filename, mode);
}
access(path: PathLike, callback: TCallback<void>);
access(path: PathLike, mode: number, callback: TCallback<void>);
access(path: PathLike, a: TCallback<void> | number, b?: TCallback<void>) {
let mode: number = F_OK;
let callback: TCallback<void>;
if (typeof a !== 'function') {
mode = a | 0; // cast to number
callback = validateCallback(b);
} else {
callback = a;
}
const filename = pathToFilename(path);
this.wrapAsync(this.accessBase, [filename, mode], callback);
}
appendFileSync(id: TFileId, data: TData, options: IAppendFileOptions | string = appendFileDefaults) {
const opts = getAppendFileOpts(options);
// force append behavior when using a supplied file descriptor
if (!opts.flag || isFd(id)) opts.flag = 'a';
this.writeFileSync(id, data, opts);
}
appendFile(id: TFileId, data: TData, callback: TCallback<void>);
appendFile(id: TFileId, data: TData, options: IAppendFileOptions | string, callback: TCallback<void>);
appendFile(id: TFileId, data: TData, a, b?) {
const [opts, callback] = getAppendFileOptsAndCb(a, b);
// force append behavior when using a supplied file descriptor
if (!opts.flag || isFd(id)) opts.flag = 'a';
this.writeFile(id, data, opts, callback);
}
private readdirBase(filename: string, options: IReaddirOptions): TDataOut[] | Dirent[] {
const steps = filenameToSteps(filename);
const link: Link | null = this.getResolvedLink(steps);
if (!link) throw createError(ENOENT, 'readdir', filename);
const node = link.getNode();
if (!node.isDirectory()) throw createError(ENOTDIR, 'scandir', filename);
if (options.withFileTypes) {
const list: Dirent[] = [];
for (const name in link.children) {
const child = link.getChild(name);
if (!child) {
continue;
}
list.push(Dirent.build(child, options.encoding));
}
if (!isWin && options.encoding !== 'buffer')
list.sort((a, b) => {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
});
return list;
}
const list: TDataOut[] = [];
for (const name in link.children) {
list.push(strToEncoding(name, options.encoding));
}
if (!isWin && options.encoding !== 'buffer') list.sort();
return list;
}
readdirSync(path: PathLike, options?: IReaddirOptions | string): TDataOut[] | Dirent[] {
const opts = getReaddirOptions(options);
const filename = pathToFilename(path);
return this.readdirBase(filename, opts);
}
readdir(path: PathLike, callback: TCallback<TDataOut[] | Dirent[]>);
readdir(path: PathLike, options: IReaddirOptions | string, callback: TCallback<TDataOut[] | Dirent[]>);
readdir(path: PathLike, a?, b?) {
const [options, callback] = getReaddirOptsAndCb(a, b);
const filename = pathToFilename(path);
this.wrapAsync(this.readdirBase, [filename, options], callback);
}
private readlinkBase(filename: string, encoding: TEncodingExtended | undefined): TDataOut {
const link = this.getLinkOrThrow(filename, 'readlink');
const node = link.getNode();
if (!node.isSymlink()) throw createError(EINVAL, 'readlink', filename);
const str = sep + node.symlink.join(sep);
return strToEncoding(str, encoding);
}
readlinkSync(path: PathLike, options?: IOptions): TDataOut {
const opts = getDefaultOpts(options);
const filename = pathToFilename(path);
return this.readlinkBase(filename, opts.encoding);
}
readlink(path: PathLike, callback: TCallback<TDataOut>);
readlink(path: PathLike, options: IOptions, callback: TCallback<TDataOut>);
readlink(path: PathLike, a: TCallback<TDataOut> | IOptions, b?: TCallback<TDataOut>) {
const [opts, callback] = getDefaultOptsAndCb(a, b);
const filename = pathToFilename(path);
this.wrapAsync(this.readlinkBase, [filename, opts.encoding], callback);
}
private fsyncBase(fd: number) {
this.getFileByFdOrThrow(fd, 'fsync');
}
fsyncSync(fd: number) {
this.fsyncBase(fd);
}
fsync(fd: number, callback: TCallback<void>) {
this.wrapAsync(this.fsyncBase, [fd], callback);
}
private fdatasyncBase(fd: number) {
this.getFileByFdOrThrow(fd, 'fdatasync');
}
fdatasyncSync(fd: number) {
this.fdatasyncBase(fd);
}
fdatasync(fd: number, callback: TCallback<void>) {
this.wrapAsync(this.fdatasyncBase, [fd], callback);
}
private ftruncateBase(fd: number, len?: number) {
const file = this.getFileByFdOrThrow(fd, 'ftruncate');
file.truncate(len);
}
ftruncateSync(fd: number, len?: number) {
this.ftruncateBase(fd, len);
}
ftruncate(fd: number, callback: TCallback<void>);
ftruncate(fd: number, len: number, callback: TCallback<void>);
ftruncate(fd: number, a: TCallback<void> | number, b?: TCallback<void>) {
const len: number = typeof a === 'number' ? a : 0;
const callback: TCallback<void> = validateCallback(typeof a === 'number' ? b : a);
this.wrapAsync(this.ftruncateBase, [fd, len], callback);
}
private truncateBase(path: PathLike, len?: number) {
const fd = this.openSync(path, 'r+');
try {
this.ftruncateSync(fd, len);
} finally {
this.closeSync(fd);
}
}
truncateSync(id: TFileId, len?: number) {
if (isFd(id)) return this.ftruncateSync(id as number, len);
this.truncateBase(id as PathLike, len);
}
truncate(id: TFileId, callback: TCallback<void>);
truncate(id: TFileId, len: number, callback: TCallback<void>);
truncate(id: TFileId, a: TCallback<void> | number, b?: TCallback<void>) {
const len: number = typeof a === 'number' ? a : 0;
const callback: TCallback<void> = validateCallback(typeof a === 'number' ? b : a);
if (isFd(id)) return this.ftruncate(id as number, len, callback);
this.wrapAsync(this.truncateBase, [id, len], callback);
}
private futimesBase(fd: number, atime: number, mtime: number) {
const file = this.getFileByFdOrThrow(fd, 'futimes');
const node = file.node;
node.atime = new Date(atime * 1000);
node.mtime = new Date(mtime * 1000);
}
futimesSync(fd: number, atime: TTime, mtime: TTime) {
this.futimesBase(fd, toUnixTimestamp(atime), toUnixTimestamp(mtime));
}
futimes(fd: number, atime: TTime, mtime: TTime, callback: TCallback<void>) {
this.wrapAsync(this.futimesBase, [fd, toUnixTimestamp(atime), toUnixTimestamp(mtime)], callback);
}
private utimesBase(filename: string, atime: number, mtime: number) {
const fd = this.openSync(filename, 'r+');
try {
this.futimesBase(fd, atime, mtime);
} finally {
this.closeSync(fd);
}
}
utimesSync(path: PathLike, atime: TTime, mtime: TTime) {
this.utimesBase(pathToFilename(path), toUnixTimestamp(atime), toUnixTimestamp(mtime));
}
utimes(path: PathLike, atime: TTime, mtime: TTime, callback: TCallback<void>) {
this.wrapAsync(this.utimesBase, [pathToFilename(path), toUnixTimestamp(atime), toUnixTimestamp(mtime)], callback);
}
private mkdirBase(filename: string, modeNum: number) {
const steps = filenameToSteps(filename);
// This will throw if user tries to create root dir `fs.mkdirSync('/')`.
if (!steps.length) {
throw createError(EEXIST, 'mkdir', filename);
}
const dir = this.getLinkParentAsDirOrThrow(filename, 'mkdir');
// Check path already exists.
const name = steps[steps.length - 1];
if (dir.getChild(name)) throw createError(EEXIST, 'mkdir', filename);
dir.createChild(name, this.createNode(true, modeNum));
}
/**
* Creates directory tree recursively.
* @param filename
* @param modeNum
*/
private mkdirpBase(filename: string, modeNum: number) {
const steps = filenameToSteps(filename);
let link = this.root;
for (let i = 0; i < steps.length; i++) {
const step = steps[i];
if (!link.getNode().isDirectory()) throw createError(ENOTDIR, 'mkdir', link.getPath());
const child = link.getChild(step);
if (child) {
if (child.getNode().isDirectory()) link = child;
else throw createError(ENOTDIR, 'mkdir', child.getPath());
} else {
link = link.createChild(step, this.createNode(true, modeNum));
}
}
}
mkdirSync(path: PathLike, options?: TMode | IMkdirOptions) {
const opts = getMkdirOptions(options);
const modeNum = modeToNumber(opts.mode, 0o777);
const filename = pathToFilename(path);
if (opts.recursive) this.mkdirpBase(filename, modeNum);
else this.mkdirBase(filename, modeNum);
}
mkdir(path: PathLike, callback: TCallback<void>);
mkdir(path: PathLike, mode: TMode | IMkdirOptions, callback: TCallback<void>);
mkdir(path: PathLike, a: TCallback<void> | TMode | IMkdirOptions, b?: TCallback<void>) {
const opts: TMode | IMkdirOptions = getMkdirOptions(a);
const callback: TCallback<void> = validateCallback(typeof a === 'function' ? a : b);
const modeNum = modeToNumber(opts.mode, 0o777);
const filename = pathToFilename(path);
if (opts.recursive) this.wrapAsync(this.mkdirpBase, [filename, modeNum], callback);
else this.wrapAsync(this.mkdirBase, [filename, modeNum], callback);
}
// legacy interface
mkdirpSync(path: PathLike, mode?: TMode) {
this.mkdirSync(path, { mode, recursive: true });
}
mkdirp(path: PathLike, callback: TCallback<void>);
mkdirp(path: PathLike, mode: TMode, callback: TCallback<void>);
mkdirp(path: PathLike, a: TCallback<void> | TMode, b?: TCallback<void>) {
const mode: TMode | undefined = typeof a === 'function' ? undefined : a;
const callback: TCallback<void> = validateCallback(typeof a === 'function' ? a : b);
this.mkdir(path, { mode, recursive: true }, callback);
}
private mkdtempBase(prefix: string, encoding?: TEncodingExtended, retry: number = 5): TDataOut {
const filename = prefix + this.genRndStr();
try {
this.mkdirBase(filename, MODE.DIR);
return strToEncoding(filename, encoding);
} catch (err) {
if (err.code === EEXIST) {
if (retry > 1) return this.mkdtempBase(prefix, encoding, retry - 1);
else throw Error('Could not create temp dir.');
} else throw err;
}
}
mkdtempSync(prefix: string, options?: IOptions): TDataOut {
const { encoding } = getDefaultOpts(options);
if (!prefix || typeof prefix !== 'string') throw new TypeError('filename prefix is required');
nullCheck(prefix);
return this.mkdtempBase(prefix, encoding);
}
mkdtemp(prefix: string, callback: TCallback<void>);
mkdtemp(prefix: string, options: IOptions, callback: TCallback<void>);
mkdtemp(prefix: string, a: TCallback<void> | IOptions, b?: TCallback<void>) {
const [{ encoding }, callback] = getDefaultOptsAndCb(a, b);
if (!prefix || typeof prefix !== 'string') throw new TypeError('filename prefix is required');
if (!nullCheck(prefix)) return;
this.wrapAsync(this.mkdtempBase, [prefix, encoding], callback);
}
private rmdirBase(filename: string, options?: IRmdirOptions) {
const opts = getRmdirOptions(options);
const link = this.getLinkAsDirOrThrow(filename, 'rmdir');
// Check directory is empty.
if (link.length && !opts.recursive) throw createError(ENOTEMPTY, 'rmdir', filename);
this.deleteLink(link);
}
rmdirSync(path: PathLike, options?: IRmdirOptions) {
this.rmdirBase(pathToFilename(path), options);
}
rmdir(path: PathLike, callback: TCallback<void>);
rmdir(path: PathLike, options: IRmdirOptions, callback: TCallback<void>);
rmdir(path: PathLike, a: TCallback<void> | IRmdirOptions, b?: TCallback<void>) {
const opts: IRmdirOptions = getRmdirOptions(a);
const callback: TCallback<void> = validateCallback(typeof a === 'function' ? a : b);
this.wrapAsync(this.rmdirBase, [pathToFilename(path), opts], callback);
}
private rmBase(filename: string, options: IRmOptions = {}): void {
const link = this.getResolvedLink(filename);
if (!link) {
// "stat" is used to match Node's native error message.
if (!options.force) throw createError(ENOENT, 'stat', filename);
return;
}
if (link.getNode().isDirectory()) {
if (!options.recursive) {
throw createError(ERR_FS_EISDIR, 'rm', filename);
}
}
this.deleteLink(link);
}
public rmSync(path: PathLike, options?: IRmOptions): void {
this.rmBase(pathToFilename(path), options);
}
public rm(path: PathLike, callback: TCallback<void>): void;
public rm(path: PathLike, options: IRmOptions, callback: TCallback<void>): void;
public rm(path: PathLike, a: TCallback<void> | IRmOptions, b?: TCallback<void>): void {
const [opts, callback] = getRmOptsAndCb(a, b);
this.wrapAsync(this.rmBase, [pathToFilename(path), opts], callback);
}
private fchmodBase(fd: number, modeNum: number) {
const file = this.getFileByFdOrThrow(fd, 'fchmod');
file.chmod(modeNum);
}
fchmodSync(fd: number, mode: TMode) {
this.fchmodBase(fd, modeToNumber(mode));
}
fchmod(fd: number, mode: TMode, callback: TCallback<void>) {
this.wrapAsync(this.fchmodBase, [fd, modeToNumber(mode)], callback);
}
private chmodBase(filename: string, modeNum: number) {
const fd = this.openSync(filename, 'r+');
try {
this.fchmodBase(fd, modeNum);
} finally {
this.closeSync(fd);
}
}
chmodSync(path: PathLike, mode: TMode) {
const modeNum = modeToNumber(mode);
const filename = pathToFilename(path);
this.chmodBase(filename, modeNum);
}
chmod(path: PathLike, mode: TMode, callback: TCallback<void>) {
const modeNum = modeToNumber(mode);
const filename = pathToFilename(path);
this.wrapAsync(this.chmodBase, [filename, modeNum], callback);
}
private lchmodBase(filename: string, modeNum: number) {
const fd = this.openBase(filename, O_RDWR, 0, false);
try {
this.fchmodBase(fd, modeNum);
} finally {
this.closeSync(fd);
}
}
lchmodSync(path: PathLike, mode: TMode) {
const modeNum = modeToNumber(mode);
const filename = pathToFilename(path);
this.lchmodBase(filename, modeNum);
}
lchmod(path: PathLike, mode: TMode, callback: TCallback<void>) {
const modeNum = modeToNumber(mode);
const filename = pathToFilename(path);
this.wrapAsync(this.lchmodBase, [filename, modeNum], callback);
}
private fchownBase(fd: number, uid: number, gid: number) {
this.getFileByFdOrThrow(fd, 'fchown').chown(uid, gid);
}
fchownSync(fd: number, uid: number, gid: number) {
validateUid(uid);
validateGid(gid);
this.fchownBase(fd, uid, gid);
}
fchown(fd: number, uid: number, gid: number, callback: TCallback<void>) {
validateUid(uid);
validateGid(gid);
this.wrapAsync(this.fchownBase, [fd, uid, gid], callback);
}
private chownBase(filename: string, uid: number, gid: number) {
const link = this.getResolvedLinkOrThrow(filename, 'chown');
const node = link.getNode();
node.chown(uid, gid);
// if(node.isFile() || node.isSymlink()) {
//
// } else if(node.isDirectory()) {
//
// } else {
// TODO: What do we do here?
// }
}
chownSync(path: PathLike, uid: number, gid: number) {
validateUid(uid);
validateGid(gid);
this.chownBase(pathToFilename(path), uid, gid);
}
chown(path: PathLike, uid: number, gid: number, callback: TCallback<void>) {
validateUid(uid);
validateGid(gid);
this.wrapAsync(this.chownBase, [pathToFilename(path), uid, gid], callback);
}
private lchownBase(filename: string, uid: number, gid: number) {
this.getLinkOrThrow(filename, 'lchown')
.getNode()
.chown(uid, gid);
}
lchownSync(path: PathLike, uid: number, gid: number) {
validateUid(uid);
validateGid(gid);
this.lchownBase(pathToFilename(path), uid, gid);
}
lchown(path: PathLike, uid: number, gid: number, callback: TCallback<void>) {
validateUid(uid);
validateGid(gid);
this.wrapAsync(this.lchownBase, [pathToFilename(path), uid, gid], callback);
}
private statWatchers: Record<string, StatWatcher> = {};
watchFile(path: PathLike, listener: (curr: Stats, prev: Stats) => void): StatWatcher;
watchFile(path: PathLike, options: IWatchFileOptions, listener: (curr: Stats, prev: Stats) => void): StatWatcher;
watchFile(path: PathLike, a, b?): StatWatcher {
const filename = pathToFilename(path);
let options: IWatchFileOptions | null = a;
let listener: (curr: Stats, prev: Stats) => void = b;
if (typeof options === 'function') {
listener = a;
options = null;
}
if (typeof listener !== 'function') {
throw Error('"watchFile()" requires a listener function');
}
let interval = 5007;
let persistent = true;
if (options && typeof options === 'object') {
if (typeof options.interval === 'number') interval = options.interval;
if (typeof options.persistent === 'boolean') persistent = options.persistent;
}
let watcher: StatWatcher = this.statWatchers[filename];
if (!watcher) {
watcher = new this.StatWatcher();
watcher.start(filename, persistent, interval);
this.statWatchers[filename] = watcher;
}
watcher.addListener('change', listener);
return watcher;
}
unwatchFile(path: PathLike, listener?: (curr: Stats, prev: Stats) => void) {
const filename = pathToFilename(path);
const watcher = this.statWatchers[filename];
if (!watcher) return;
if (typeof listener === 'function') {
watcher.removeListener('change', listener);
} else {
watcher.removeAllListeners('change');
}
if (watcher.listenerCount('change') === 0) {
watcher.stop();
delete this.statWatchers[filename];
}
}
createReadStream(path: PathLike, options?: IReadStreamOptions | string): IReadStream {
return new this.ReadStream(path, options);
}
createWriteStream(path: PathLike, options?: IWriteStreamOptions | string): IWriteStream {
return new this.WriteStream(path, options);
}
// watch(path: PathLike): FSWatcher;
// watch(path: PathLike, options?: IWatchOptions | string): FSWatcher;
watch(
path: PathLike,
options?: IWatchOptions | string,
listener?: (eventType: string, filename: string) => void,
): FSWatcher {
const filename = pathToFilename(path);
let givenOptions: typeof options | null = options;
if (typeof options === 'function') {
listener = options;
givenOptions = null;
}
// tslint:disable-next-line prefer-const
let { persistent, recursive, encoding }: IWatchOptions = getDefaultOpts(givenOptions);
if (persistent === undefined) persistent = true;
if (recursive === undefined) recursive = false;
const watcher = new this.FSWatcher();
watcher.start(filename, persistent, recursive, encoding as BufferEncoding);
if (listener) {
watcher.addListener('change', listener);
}
return watcher;
}
}
function emitStop(self) {
self.emit('stop');
}
export class StatWatcher extends EventEmitter {
vol: Volume;
filename: string;
interval: number;
timeoutRef?;
setTimeout: TSetTimeout;
prev: Stats;
constructor(vol: Volume) {
super();
this.vol = vol;
}
private loop() {
this.timeoutRef = this.setTimeout(this.onInterval, this.interval);
}
private hasChanged(stats: Stats): boolean {
// if(!this.prev) return false;
if (stats.mtimeMs > this.prev.mtimeMs) return true;
if (stats.nlink !== this.prev.nlink) return true;
return false;
}
private onInterval = () => {
try {
const stats = this.vol.statSync(this.filename);
if (this.hasChanged(stats)) {
this.emit('change', stats, this.prev);
this.prev = stats;
}
} finally {
this.loop();
}
};
start(path: string, persistent: boolean = true, interval: number = 5007) {
this.filename = pathToFilename(path);
this.setTimeout = persistent ? setTimeout.bind(typeof globalThis !== 'undefined' ? globalThis : global) : setTimeoutUnref;
this.interval = interval;
this.prev = this.vol.statSync(this.filename);
this.loop();
}
stop() {
clearTimeout(this.timeoutRef);
process.nextTick(emitStop, this);
}
}
/* tslint:disable no-var-keyword prefer-const */
// ---------------------------------------- ReadStream
export interface IReadStream extends Readable {
new (path: PathLike, options: IReadStreamOptions);
open();
close(callback: TCallback<void>);
bytesRead: number;
path: string;
}
var pool;
function allocNewPool(poolSize) {
pool = bufferAllocUnsafe(poolSize);
pool.used = 0;
}
util.inherits(FsReadStream, Readable);
exports.ReadStream = FsReadStream;
function FsReadStream(vol, path, options) {
if (!(this instanceof FsReadStream)) return new (FsReadStream as any)(vol, path, options);
this._vol = vol;
// a little bit bigger buffer and water marks by default
options = Object.assign({}, getOptions(options, {}));
if (options.highWaterMark === undefined) options.highWaterMark = 64 * 1024;
Readable.call(this, options);
this.path = pathToFilename(path);
this.fd = options.fd === undefined ? null : options.fd;
this.flags = options.flags === undefined ? 'r' : options.flags;
this.mode = options.mode === undefined ? 0o666 : options.mode;
this.start = options.start;
this.end = options.end;
this.autoClose = options.autoClose === undefined ? true : options.autoClose;
this.pos = undefined;
this.bytesRead = 0;
if (this.start !== undefined) {
if (typeof this.start !== 'number') {
throw new TypeError('"start" option must be a Number');
}
if (this.end === undefined) {
this.end = Infinity;
} else if (typeof this.end !== 'number') {
throw new TypeError('"end" option must be a Number');
}
if (this.start > this.end) {
throw new Error('"start" option must be <= "end" option');
}
this.pos = this.start;
}
if (typeof this.fd !== 'number') this.open();
this.on('end', function() {
if (this.autoClose) {
if (this.destroy) this.destroy();
}
});
}
FsReadStream.prototype.open = function() {
var self = this; // tslint:disable-line no-this-assignment
this._vol.open(this.path, this.flags, this.mode, (er, fd) => {
if (er) {
if (self.autoClose) {
if (self.destroy) self.destroy();
}
self.emit('error', er);
return;
}
self.fd = fd;
self.emit('open', fd);
// start the flow of data.
self.read();
});
};
FsReadStream.prototype._read = function(n) {
if (typeof this.fd !== 'number') {
return this.once('open', function() {
this._read(n);
});
}
if (this.destroyed) return;
if (!pool || pool.length - pool.used < kMinPoolSpace) {
// discard the old pool.
allocNewPool(this._readableState.highWaterMark);
}
// Grab another reference to the pool in the case that while we're
// in the thread pool another read() finishes up the pool, and
// allocates a new one.
var thisPool = pool;
var toRead = Math.min(pool.length - pool.used, n);
var start = pool.used;
if (this.pos !== undefined) toRead = Math.min(this.end - this.pos + 1, toRead);
// already read everything we were supposed to read!
// treat as EOF.
if (toRead <= 0) return this.push(null);
// the actual read.
var self = this; // tslint:disable-line no-this-assignment
this._vol.read(this.fd, pool, pool.used, toRead, this.pos, onread);
// move the pool positions, and internal position for reading.
if (this.pos !== undefined) this.pos += toRead;
pool.used += toRead;
function onread(er, bytesRead) {
if (er) {
if (self.autoClose && self.destroy) {
self.destroy();
}
self.emit('error', er);
} else {
var b = null;
if (bytesRead > 0) {
self.bytesRead += bytesRead;
b = thisPool.slice(start, start + bytesRead);
}
self.push(b);
}
}
};
FsReadStream.prototype._destroy = function(err, cb) {
this.close(err2 => {
cb(err || err2);
});
};
FsReadStream.prototype.close = function(cb) {
if (cb) this.once('close', cb);
if (this.closed || typeof this.fd !== 'number') {
if (typeof this.fd !== 'number') {
this.once('open', closeOnOpen);
return;
}
return process.nextTick(() => this.emit('close'));
}
this.closed = true;
this._vol.close(this.fd, er => {
if (er) this.emit('error', er);
else this.emit('close');
});
this.fd = null;
};
// needed because as it will be called with arguments
// that does not match this.close() signature
function closeOnOpen(fd) {
this.close();
}
// ---------------------------------------- WriteStream
export interface IWriteStream extends Writable {
bytesWritten: number;
path: string;
new (path: PathLike, options: IWriteStreamOptions);
open();
close();
}
util.inherits(FsWriteStream, Writable);
exports.WriteStream = FsWriteStream;
function FsWriteStream(vol, path, options) {
if (!(this instanceof FsWriteStream)) return new (FsWriteStream as any)(vol, path, options);
this._vol = vol;
options = Object.assign({}, getOptions(options, {}));
Writable.call(this, options);
this.path = pathToFilename(path);
this.fd = options.fd === undefined ? null : options.fd;
this.flags = options.flags === undefined ? 'w' : options.flags;
this.mode = options.mode === undefined ? 0o666 : options.mode;
this.start = options.start;
this.autoClose = options.autoClose === undefined ? true : !!options.autoClose;
this.pos = undefined;
this.bytesWritten = 0;
if (this.start !== undefined) {
if (typeof this.start !== 'number') {
throw new TypeError('"start" option must be a Number');
}
if (this.start < 0) {
throw new Error('"start" must be >= zero');
}
this.pos = this.start;
}
if (options.encoding) this.setDefaultEncoding(options.encoding);
if (typeof this.fd !== 'number') this.open();
// dispose on finish.
this.once('finish', function() {
if (this.autoClose) {
this.close();
}
});
}
FsWriteStream.prototype.open = function() {
this._vol.open(
this.path,
this.flags,
this.mode,
function(er, fd) {
if (er) {
if (this.autoClose && this.destroy) {
this.destroy();
}
this.emit('error', er);
return;
}
this.fd = fd;
this.emit('open', fd);
}.bind(this),
);
};
FsWriteStream.prototype._write = function(data, encoding, cb) {
if (!(data instanceof Buffer)) return this.emit('error', new Error('Invalid data'));
if (typeof this.fd !== 'number') {
return this.once('open', function() {
this._write(data, encoding, cb);
});
}
var self = this; // tslint:disable-line no-this-assignment
this._vol.write(this.fd, data, 0, data.length, this.pos, (er, bytes) => {
if (er) {
if (self.autoClose && self.destroy) {
self.destroy();
}
return cb(er);
}
self.bytesWritten += bytes;
cb();
});
if (this.pos !== undefined) this.pos += data.length;
};
FsWriteStream.prototype._writev = function(data, cb) {
if (typeof this.fd !== 'number') {
return this.once('open', function() {
this._writev(data, cb);
});
}
const self = this; // tslint:disable-line no-this-assignment
const len = data.length;
const chunks = new Array(len);
var size = 0;
for (var i = 0; i < len; i++) {
var chunk = data[i].chunk;
chunks[i] = chunk;
size += chunk.length;
}
const buf = Buffer.concat(chunks);
this._vol.write(this.fd, buf, 0, buf.length, this.pos, (er, bytes) => {
if (er) {
if (self.destroy) self.destroy();
return cb(er);
}
self.bytesWritten += bytes;
cb();
});
if (this.pos !== undefined) this.pos += size;
};
FsWriteStream.prototype._destroy = FsReadStream.prototype._destroy;
FsWriteStream.prototype.close = FsReadStream.prototype.close;
// There is no shutdown() for files.
FsWriteStream.prototype.destroySoon = FsWriteStream.prototype.end;
// ---------------------------------------- FSWatcher
export class FSWatcher extends EventEmitter {
_vol: Volume;
_filename: string = '';
_steps: string[];
_filenameEncoded: TDataOut = '';
// _persistent: boolean = true;
_recursive: boolean = false;
_encoding: BufferEncoding = ENCODING_UTF8;
_link: Link;
_timer; // Timer that keeps this task persistent.
constructor(vol: Volume) {
super();
this._vol = vol;
// TODO: Emit "error" messages when watching.
// this._handle.onchange = function(status, eventType, filename) {
// if (status < 0) {
// self._handle.close();
// const error = !filename ?
// errnoException(status, 'Error watching file for changes:') :
// errnoException(status, `Error watching file ${filename} for changes:`);
// error.filename = filename;
// self.emit('error', error);
// } else {
// self.emit('change', eventType, filename);
// }
// };
}
private _getName(): string {
return this._steps[this._steps.length - 1];
}
private _onNodeChange = () => {
this._emit('change');
};
private _onParentChild = (link: Link) => {
if (link.getName() === this._getName()) {
this._emit('rename');
}
};
private _emit = (type: 'change' | 'rename') => {
this.emit('change', type, this._filenameEncoded);
};
private _persist = () => {
this._timer = setTimeout(this._persist, 1e6);
};
start(
path: PathLike,
persistent: boolean = true,
recursive: boolean = false,
encoding: BufferEncoding = ENCODING_UTF8,
) {
this._filename = pathToFilename(path);
this._steps = filenameToSteps(this._filename);
this._filenameEncoded = strToEncoding(this._filename);
// this._persistent = persistent;
this._recursive = recursive;
this._encoding = encoding;
try {
this._link = this._vol.getLinkOrThrow(this._filename, 'FSWatcher');
} catch (err) {
const error = new Error(`watch ${this._filename} ${err.code}`);
(error as any).code = err.code;
(error as any).errno = err.code;
throw error;
}
this._link.getNode().on('change', this._onNodeChange);
this._link.on('child:add', this._onNodeChange);
this._link.on('child:delete', this._onNodeChange);
const parent = this._link.parent;
if (parent) {
// parent.on('child:add', this._onParentChild);
parent.setMaxListeners(parent.getMaxListeners() + 1);
parent.on('child:delete', this._onParentChild);
}
if (persistent) this._persist();
}
close() {
clearTimeout(this._timer);
this._link.getNode().removeListener('change', this._onNodeChange);
const parent = this._link.parent;
if (parent) {
// parent.removeListener('child:add', this._onParentChild);
parent.removeListener('child:delete', this._onParentChild);
}
}
} | the_stack |
namespace ts.projectSystem {
describe("unittests:: tsserver:: ExternalProjects", () => {
describe("can handle tsconfig file name with difference casing", () => {
function verifyConfigFileCasing(lazyConfiguredProjectsFromExternalProject: boolean) {
const f1 = {
path: "/a/b/app.ts",
content: "let x = 1"
};
const config = {
path: "/a/b/tsconfig.json",
content: JSON.stringify({
include: []
})
};
const host = createServerHost([f1, config], { useCaseSensitiveFileNames: false });
const service = createProjectService(host);
service.setHostConfiguration({ preferences: { lazyConfiguredProjectsFromExternalProject } });
const upperCaseConfigFilePath = combinePaths(getDirectoryPath(config.path).toUpperCase(), getBaseFileName(config.path));
service.openExternalProject({
projectFileName: "/a/b/project.csproj",
rootFiles: toExternalFiles([f1.path, upperCaseConfigFilePath]),
options: {}
} as protocol.ExternalProject);
service.checkNumberOfProjects({ configuredProjects: 1 });
const project = service.configuredProjects.get(config.path)!;
if (lazyConfiguredProjectsFromExternalProject) {
assert.equal(project.pendingReload, ConfigFileProgramReloadLevel.Full); // External project referenced configured project pending to be reloaded
checkProjectActualFiles(project, emptyArray);
}
else {
assert.equal(project.pendingReload, ConfigFileProgramReloadLevel.None); // External project referenced configured project loaded
checkProjectActualFiles(project, [upperCaseConfigFilePath]);
}
service.openClientFile(f1.path);
service.checkNumberOfProjects({ configuredProjects: 1, inferredProjects: 1 });
assert.equal(project.pendingReload, ConfigFileProgramReloadLevel.None); // External project referenced configured project is updated
checkProjectActualFiles(project, [upperCaseConfigFilePath]);
checkProjectActualFiles(service.inferredProjects[0], [f1.path]);
}
it("when lazyConfiguredProjectsFromExternalProject not set", () => {
verifyConfigFileCasing(/*lazyConfiguredProjectsFromExternalProject*/ false);
});
it("when lazyConfiguredProjectsFromExternalProject is set", () => {
verifyConfigFileCasing(/*lazyConfiguredProjectsFromExternalProject*/ true);
});
});
it("load global plugins", () => {
const f1 = {
path: "/a/file1.ts",
content: "let x = [1, 2];"
};
const p1 = { projectFileName: "/a/proj1.csproj", rootFiles: [toExternalFile(f1.path)], options: {} };
const host = createServerHost([f1]);
host.require = (_initialPath, moduleName) => {
assert.equal(moduleName, "myplugin");
return {
module: () => ({
create(info: server.PluginCreateInfo) {
const proxy = Harness.LanguageService.makeDefaultProxy(info);
proxy.getSemanticDiagnostics = filename => {
const prev = info.languageService.getSemanticDiagnostics(filename);
const sourceFile: SourceFile = info.project.getSourceFile(toPath(filename, /*basePath*/ undefined, createGetCanonicalFileName(info.serverHost.useCaseSensitiveFileNames)))!;
prev.push({
category: DiagnosticCategory.Warning,
file: sourceFile,
code: 9999,
length: 3,
messageText: `Plugin diagnostic`,
start: 0
});
return prev;
};
return proxy;
}
}),
error: undefined
};
};
const session = createSession(host, { globalPlugins: ["myplugin"] });
session.executeCommand({
seq: 1,
type: "request",
command: "openExternalProjects",
arguments: { projects: [p1] }
} as protocol.OpenExternalProjectsRequest);
const projectService = session.getProjectService();
checkNumberOfProjects(projectService, { externalProjects: 1 });
assert.equal(projectService.externalProjects[0].getProjectName(), p1.projectFileName);
const handlerResponse = session.executeCommand({
seq: 2,
type: "request",
command: "semanticDiagnosticsSync",
arguments: {
file: f1.path,
projectFileName: p1.projectFileName
}
} as protocol.SemanticDiagnosticsSyncRequest);
assert.isDefined(handlerResponse.response);
const response = handlerResponse.response as protocol.Diagnostic[];
assert.equal(response.length, 1);
assert.equal(response[0].text, "Plugin diagnostic");
});
it("remove not-listed external projects", () => {
const f1 = {
path: "/a/app.ts",
content: "let x = 1"
};
const f2 = {
path: "/b/app.ts",
content: "let x = 1"
};
const f3 = {
path: "/c/app.ts",
content: "let x = 1"
};
const makeProject = (f: File) => ({ projectFileName: f.path + ".csproj", rootFiles: [toExternalFile(f.path)], options: {} });
const p1 = makeProject(f1);
const p2 = makeProject(f2);
const p3 = makeProject(f3);
const host = createServerHost([f1, f2, f3]);
const session = createSession(host);
session.executeCommand({
seq: 1,
type: "request",
command: "openExternalProjects",
arguments: { projects: [p1, p2] }
} as protocol.OpenExternalProjectsRequest);
const projectService = session.getProjectService();
checkNumberOfProjects(projectService, { externalProjects: 2 });
assert.equal(projectService.externalProjects[0].getProjectName(), p1.projectFileName);
assert.equal(projectService.externalProjects[1].getProjectName(), p2.projectFileName);
session.executeCommand({
seq: 2,
type: "request",
command: "openExternalProjects",
arguments: { projects: [p1, p3] }
} as protocol.OpenExternalProjectsRequest);
checkNumberOfProjects(projectService, { externalProjects: 2 });
assert.equal(projectService.externalProjects[0].getProjectName(), p1.projectFileName);
assert.equal(projectService.externalProjects[1].getProjectName(), p3.projectFileName);
session.executeCommand({
seq: 3,
type: "request",
command: "openExternalProjects",
arguments: { projects: [] }
} as protocol.OpenExternalProjectsRequest);
checkNumberOfProjects(projectService, { externalProjects: 0 });
session.executeCommand({
seq: 3,
type: "request",
command: "openExternalProjects",
arguments: { projects: [p2] }
} as protocol.OpenExternalProjectsRequest);
assert.equal(projectService.externalProjects[0].getProjectName(), p2.projectFileName);
});
it("should not close external project with no open files", () => {
const file1 = {
path: "/a/b/f1.ts",
content: "let x =1;"
};
const file2 = {
path: "/a/b/f2.ts",
content: "let y =1;"
};
const externalProjectName = "externalproject";
const host = createServerHost([file1, file2]);
const projectService = createProjectService(host);
projectService.openExternalProject({
rootFiles: toExternalFiles([file1.path, file2.path]),
options: {},
projectFileName: externalProjectName
});
checkNumberOfExternalProjects(projectService, 1);
checkNumberOfInferredProjects(projectService, 0);
// open client file - should not lead to creation of inferred project
projectService.openClientFile(file1.path, file1.content);
checkNumberOfExternalProjects(projectService, 1);
checkNumberOfInferredProjects(projectService, 0);
// close client file - external project should still exists
projectService.closeClientFile(file1.path);
checkNumberOfExternalProjects(projectService, 1);
checkNumberOfInferredProjects(projectService, 0);
projectService.closeExternalProject(externalProjectName);
checkNumberOfExternalProjects(projectService, 0);
checkNumberOfInferredProjects(projectService, 0);
});
it("external project for dynamic file", () => {
const externalProjectName = "^ScriptDocument1 file1.ts";
const externalFiles = toExternalFiles(["^ScriptDocument1 file1.ts"]);
const host = createServerHost([]);
const projectService = createProjectService(host);
projectService.openExternalProject({
rootFiles: externalFiles,
options: {},
projectFileName: externalProjectName
});
checkNumberOfExternalProjects(projectService, 1);
checkNumberOfInferredProjects(projectService, 0);
verifyDynamic(projectService, "/^scriptdocument1 file1.ts");
externalFiles[0].content = "let x =1;";
projectService.applyChangesInOpenFiles(arrayIterator(externalFiles));
});
it("when file name starts with ^", () => {
const file: File = {
path: `${tscWatch.projectRoot}/file.ts`,
content: "const x = 10;"
};
const app: File = {
path: `${tscWatch.projectRoot}/^app.ts`,
content: "const y = 10;"
};
const host = createServerHost([file, app, libFile]);
const service = createProjectService(host);
service.openExternalProjects([{
projectFileName: `${tscWatch.projectRoot}/myproject.njsproj`,
rootFiles: [
toExternalFile(file.path),
toExternalFile(app.path)
],
options: { },
}]);
});
it("external project that included config files", () => {
const file1 = {
path: "/a/b/f1.ts",
content: "let x =1;"
};
const config1 = {
path: "/a/b/tsconfig.json",
content: JSON.stringify(
{
compilerOptions: {},
files: ["f1.ts"]
}
)
};
const file2 = {
path: "/a/c/f2.ts",
content: "let y =1;"
};
const config2 = {
path: "/a/c/tsconfig.json",
content: JSON.stringify(
{
compilerOptions: {},
files: ["f2.ts"]
}
)
};
const file3 = {
path: "/a/d/f3.ts",
content: "let z =1;"
};
const externalProjectName = "externalproject";
const host = createServerHost([file1, file2, file3, config1, config2]);
const projectService = createProjectService(host);
projectService.openExternalProject({
rootFiles: toExternalFiles([config1.path, config2.path, file3.path]),
options: {},
projectFileName: externalProjectName
});
checkNumberOfProjects(projectService, { configuredProjects: 2 });
const proj1 = projectService.configuredProjects.get(config1.path);
const proj2 = projectService.configuredProjects.get(config2.path);
assert.isDefined(proj1);
assert.isDefined(proj2);
// open client file - should not lead to creation of inferred project
projectService.openClientFile(file1.path, file1.content);
checkNumberOfProjects(projectService, { configuredProjects: 2 });
assert.strictEqual(projectService.configuredProjects.get(config1.path), proj1);
assert.strictEqual(projectService.configuredProjects.get(config2.path), proj2);
projectService.openClientFile(file3.path, file3.content);
checkNumberOfProjects(projectService, { configuredProjects: 2, inferredProjects: 1 });
assert.strictEqual(projectService.configuredProjects.get(config1.path), proj1);
assert.strictEqual(projectService.configuredProjects.get(config2.path), proj2);
projectService.closeExternalProject(externalProjectName);
// open file 'file1' from configured project keeps project alive
checkNumberOfProjects(projectService, { configuredProjects: 1, inferredProjects: 1 });
assert.strictEqual(projectService.configuredProjects.get(config1.path), proj1);
assert.isUndefined(projectService.configuredProjects.get(config2.path));
projectService.closeClientFile(file3.path);
checkNumberOfProjects(projectService, { configuredProjects: 1, inferredProjects: 1 });
assert.strictEqual(projectService.configuredProjects.get(config1.path), proj1);
assert.isUndefined(projectService.configuredProjects.get(config2.path));
assert.isTrue(projectService.inferredProjects[0].isOrphan());
projectService.closeClientFile(file1.path);
checkNumberOfProjects(projectService, { configuredProjects: 1, inferredProjects: 1 });
assert.strictEqual(projectService.configuredProjects.get(config1.path), proj1);
assert.isUndefined(projectService.configuredProjects.get(config2.path));
assert.isTrue(projectService.inferredProjects[0].isOrphan());
projectService.openClientFile(file2.path, file2.content);
checkNumberOfProjects(projectService, { configuredProjects: 1 });
assert.isUndefined(projectService.configuredProjects.get(config1.path));
assert.isDefined(projectService.configuredProjects.get(config2.path));
});
it("external project with included config file opened after configured project", () => {
const file1 = {
path: "/a/b/f1.ts",
content: "let x = 1"
};
const configFile = {
path: "/a/b/tsconfig.json",
content: JSON.stringify({ compilerOptions: {} })
};
const externalProjectName = "externalproject";
const host = createServerHost([file1, configFile]);
const projectService = createProjectService(host);
projectService.openClientFile(file1.path);
checkNumberOfProjects(projectService, { configuredProjects: 1 });
projectService.openExternalProject({
rootFiles: toExternalFiles([configFile.path]),
options: {},
projectFileName: externalProjectName
});
checkNumberOfProjects(projectService, { configuredProjects: 1 });
projectService.closeClientFile(file1.path);
// configured project is alive since it is opened as part of external project
checkNumberOfProjects(projectService, { configuredProjects: 1 });
projectService.closeExternalProject(externalProjectName);
checkNumberOfProjects(projectService, { configuredProjects: 0 });
});
it("external project with included config file opened after configured project and then closed", () => {
const file1 = {
path: "/a/b/f1.ts",
content: "let x = 1"
};
const file2 = {
path: "/a/f2.ts",
content: "let x = 1"
};
const configFile = {
path: "/a/b/tsconfig.json",
content: JSON.stringify({ compilerOptions: {} })
};
const externalProjectName = "externalproject";
const host = createServerHost([file1, file2, libFile, configFile]);
const projectService = createProjectService(host);
projectService.openClientFile(file1.path);
checkNumberOfProjects(projectService, { configuredProjects: 1 });
const project = projectService.configuredProjects.get(configFile.path);
projectService.openExternalProject({
rootFiles: toExternalFiles([configFile.path]),
options: {},
projectFileName: externalProjectName
});
checkNumberOfProjects(projectService, { configuredProjects: 1 });
assert.strictEqual(projectService.configuredProjects.get(configFile.path), project);
projectService.closeExternalProject(externalProjectName);
// configured project is alive since file is still open
checkNumberOfProjects(projectService, { configuredProjects: 1 });
assert.strictEqual(projectService.configuredProjects.get(configFile.path), project);
projectService.closeClientFile(file1.path);
checkNumberOfProjects(projectService, { configuredProjects: 1 });
assert.strictEqual(projectService.configuredProjects.get(configFile.path), project);
projectService.openClientFile(file2.path);
checkNumberOfProjects(projectService, { inferredProjects: 1 });
assert.isUndefined(projectService.configuredProjects.get(configFile.path));
});
it("can correctly update external project when set of root files has changed", () => {
const file1 = {
path: "/a/b/f1.ts",
content: "let x = 1"
};
const file2 = {
path: "/a/b/f2.ts",
content: "let y = 1"
};
const host = createServerHost([file1, file2]);
const projectService = createProjectService(host);
projectService.openExternalProject({ projectFileName: "project", options: {}, rootFiles: toExternalFiles([file1.path]) });
checkNumberOfProjects(projectService, { externalProjects: 1 });
checkProjectActualFiles(projectService.externalProjects[0], [file1.path]);
projectService.openExternalProject({ projectFileName: "project", options: {}, rootFiles: toExternalFiles([file1.path, file2.path]) });
checkNumberOfProjects(projectService, { externalProjects: 1 });
checkProjectRootFiles(projectService.externalProjects[0], [file1.path, file2.path]);
});
it("can update external project when set of root files was not changed", () => {
const file1 = {
path: "/a/b/f1.ts",
content: `export * from "m"`
};
const file2 = {
path: "/a/b/f2.ts",
content: "export let y = 1"
};
const file3 = {
path: "/a/m.ts",
content: "export let y = 1"
};
const host = createServerHost([file1, file2, file3]);
const projectService = createProjectService(host);
projectService.openExternalProject({ projectFileName: "project", options: { moduleResolution: ModuleResolutionKind.NodeJs }, rootFiles: toExternalFiles([file1.path, file2.path]) });
checkNumberOfProjects(projectService, { externalProjects: 1 });
checkProjectRootFiles(projectService.externalProjects[0], [file1.path, file2.path]);
checkProjectActualFiles(projectService.externalProjects[0], [file1.path, file2.path]);
projectService.openExternalProject({ projectFileName: "project", options: { moduleResolution: ModuleResolutionKind.Classic }, rootFiles: toExternalFiles([file1.path, file2.path]) });
checkNumberOfProjects(projectService, { externalProjects: 1 });
checkProjectRootFiles(projectService.externalProjects[0], [file1.path, file2.path]);
checkProjectActualFiles(projectService.externalProjects[0], [file1.path, file2.path, file3.path]);
});
it("language service disabled state is updated in external projects", () => {
const f1 = {
path: "/a/app.js",
content: "var x = 1"
};
const f2 = {
path: "/a/largefile.js",
content: ""
};
const host = createServerHost([f1, f2]);
const originalGetFileSize = host.getFileSize;
host.getFileSize = (filePath: string) =>
filePath === f2.path ? server.maxProgramSizeForNonTsFiles + 1 : originalGetFileSize.call(host, filePath);
const service = createProjectService(host);
const projectFileName = "/a/proj.csproj";
service.openExternalProject({
projectFileName,
rootFiles: toExternalFiles([f1.path, f2.path]),
options: {}
});
service.checkNumberOfProjects({ externalProjects: 1 });
assert.isFalse(service.externalProjects[0].languageServiceEnabled, "language service should be disabled - 1");
service.openExternalProject({
projectFileName,
rootFiles: toExternalFiles([f1.path]),
options: {}
});
service.checkNumberOfProjects({ externalProjects: 1 });
assert.isTrue(service.externalProjects[0].languageServiceEnabled, "language service should be enabled");
service.openExternalProject({
projectFileName,
rootFiles: toExternalFiles([f1.path, f2.path]),
options: {}
});
service.checkNumberOfProjects({ externalProjects: 1 });
assert.isFalse(service.externalProjects[0].languageServiceEnabled, "language service should be disabled - 2");
});
describe("deleting config file opened from the external project works", () => {
function verifyDeletingConfigFile(lazyConfiguredProjectsFromExternalProject: boolean) {
const site = {
path: "/user/someuser/project/js/site.js",
content: ""
};
const configFile = {
path: "/user/someuser/project/tsconfig.json",
content: "{}"
};
const projectFileName = "/user/someuser/project/WebApplication6.csproj";
const host = createServerHost([libFile, site, configFile]);
const projectService = createProjectService(host);
projectService.setHostConfiguration({ preferences: { lazyConfiguredProjectsFromExternalProject } });
const externalProject: protocol.ExternalProject = {
projectFileName,
rootFiles: [toExternalFile(site.path), toExternalFile(configFile.path)],
options: { allowJs: false },
typeAcquisition: { include: [] }
};
projectService.openExternalProjects([externalProject]);
let knownProjects = projectService.synchronizeProjectList([]);
checkNumberOfProjects(projectService, { configuredProjects: 1, externalProjects: 0, inferredProjects: 0 });
const configProject = configuredProjectAt(projectService, 0);
checkProjectActualFiles(configProject, lazyConfiguredProjectsFromExternalProject ?
emptyArray : // Since no files opened from this project, its not loaded
[configFile.path]);
host.deleteFile(configFile.path);
knownProjects = projectService.synchronizeProjectList(map(knownProjects, proj => proj.info!)); // TODO: GH#18217 GH#20039
checkNumberOfProjects(projectService, { configuredProjects: 0, externalProjects: 0, inferredProjects: 0 });
externalProject.rootFiles.length = 1;
projectService.openExternalProjects([externalProject]);
checkNumberOfProjects(projectService, { configuredProjects: 0, externalProjects: 1, inferredProjects: 0 });
checkProjectActualFiles(projectService.externalProjects[0], [site.path, libFile.path]);
}
it("when lazyConfiguredProjectsFromExternalProject not set", () => {
verifyDeletingConfigFile(/*lazyConfiguredProjectsFromExternalProject*/ false);
});
it("when lazyConfiguredProjectsFromExternalProject is set", () => {
verifyDeletingConfigFile(/*lazyConfiguredProjectsFromExternalProject*/ true);
});
});
describe("correctly handling add/remove tsconfig - 1", () => {
function verifyAddRemoveConfig(lazyConfiguredProjectsFromExternalProject: boolean) {
const f1 = {
path: "/a/b/app.ts",
content: "let x = 1;"
};
const f2 = {
path: "/a/b/lib.ts",
content: ""
};
const tsconfig = {
path: "/a/b/tsconfig.json",
content: ""
};
const host = createServerHost([f1, f2]);
const projectService = createProjectService(host);
projectService.setHostConfiguration({ preferences: { lazyConfiguredProjectsFromExternalProject } });
// open external project
const projectName = "/a/b/proj1";
projectService.openExternalProject({
projectFileName: projectName,
rootFiles: toExternalFiles([f1.path, f2.path]),
options: {}
});
projectService.openClientFile(f1.path);
projectService.checkNumberOfProjects({ externalProjects: 1 });
checkProjectActualFiles(projectService.externalProjects[0], [f1.path, f2.path]);
// rename lib.ts to tsconfig.json
host.renameFile(f2.path, tsconfig.path);
projectService.openExternalProject({
projectFileName: projectName,
rootFiles: toExternalFiles([f1.path, tsconfig.path]),
options: {}
});
projectService.checkNumberOfProjects({ configuredProjects: 1 });
if (lazyConfiguredProjectsFromExternalProject) {
checkProjectActualFiles(configuredProjectAt(projectService, 0), emptyArray); // Configured project created but not loaded till actually needed
projectService.ensureInferredProjectsUpToDate_TestOnly();
}
checkProjectActualFiles(configuredProjectAt(projectService, 0), [f1.path, tsconfig.path]);
// rename tsconfig.json back to lib.ts
host.renameFile(tsconfig.path, f2.path);
projectService.openExternalProject({
projectFileName: projectName,
rootFiles: toExternalFiles([f1.path, f2.path]),
options: {}
});
projectService.checkNumberOfProjects({ externalProjects: 1 });
checkProjectActualFiles(projectService.externalProjects[0], [f1.path, f2.path]);
}
it("when lazyConfiguredProjectsFromExternalProject not set", () => {
verifyAddRemoveConfig(/*lazyConfiguredProjectsFromExternalProject*/ false);
});
it("when lazyConfiguredProjectsFromExternalProject is set", () => {
verifyAddRemoveConfig(/*lazyConfiguredProjectsFromExternalProject*/ true);
});
});
describe("correctly handling add/remove tsconfig - 2", () => {
function verifyAddRemoveConfig(lazyConfiguredProjectsFromExternalProject: boolean) {
const f1 = {
path: "/a/b/app.ts",
content: "let x = 1;"
};
const cLib = {
path: "/a/b/c/lib.ts",
content: ""
};
const cTsconfig = {
path: "/a/b/c/tsconfig.json",
content: "{}"
};
const dLib = {
path: "/a/b/d/lib.ts",
content: ""
};
const dTsconfig = {
path: "/a/b/d/tsconfig.json",
content: "{}"
};
const host = createServerHost([f1, cLib, cTsconfig, dLib, dTsconfig]);
const projectService = createProjectService(host);
projectService.setHostConfiguration({ preferences: { lazyConfiguredProjectsFromExternalProject } });
// open external project
const projectName = "/a/b/proj1";
projectService.openExternalProject({
projectFileName: projectName,
rootFiles: toExternalFiles([f1.path]),
options: {}
});
projectService.checkNumberOfProjects({ externalProjects: 1 });
checkProjectActualFiles(projectService.externalProjects[0], [f1.path]);
// add two config file as root files
projectService.openExternalProject({
projectFileName: projectName,
rootFiles: toExternalFiles([f1.path, cTsconfig.path, dTsconfig.path]),
options: {}
});
projectService.checkNumberOfProjects({ configuredProjects: 2 });
if (lazyConfiguredProjectsFromExternalProject) {
checkProjectActualFiles(configuredProjectAt(projectService, 0), emptyArray); // Configured project created but not loaded till actually needed
checkProjectActualFiles(configuredProjectAt(projectService, 1), emptyArray); // Configured project created but not loaded till actually needed
projectService.ensureInferredProjectsUpToDate_TestOnly();
}
checkProjectActualFiles(configuredProjectAt(projectService, 0), [cLib.path, cTsconfig.path]);
checkProjectActualFiles(configuredProjectAt(projectService, 1), [dLib.path, dTsconfig.path]);
// remove one config file
projectService.openExternalProject({
projectFileName: projectName,
rootFiles: toExternalFiles([f1.path, dTsconfig.path]),
options: {}
});
projectService.checkNumberOfProjects({ configuredProjects: 1 });
checkProjectActualFiles(configuredProjectAt(projectService, 0), [dLib.path, dTsconfig.path]);
// remove second config file
projectService.openExternalProject({
projectFileName: projectName,
rootFiles: toExternalFiles([f1.path]),
options: {}
});
projectService.checkNumberOfProjects({ externalProjects: 1 });
checkProjectActualFiles(projectService.externalProjects[0], [f1.path]);
// open two config files
// add two config file as root files
projectService.openExternalProject({
projectFileName: projectName,
rootFiles: toExternalFiles([f1.path, cTsconfig.path, dTsconfig.path]),
options: {}
});
projectService.checkNumberOfProjects({ configuredProjects: 2 });
if (lazyConfiguredProjectsFromExternalProject) {
checkProjectActualFiles(configuredProjectAt(projectService, 0), emptyArray); // Configured project created but not loaded till actually needed
checkProjectActualFiles(configuredProjectAt(projectService, 1), emptyArray); // Configured project created but not loaded till actually needed
projectService.ensureInferredProjectsUpToDate_TestOnly();
}
checkProjectActualFiles(configuredProjectAt(projectService, 0), [cLib.path, cTsconfig.path]);
checkProjectActualFiles(configuredProjectAt(projectService, 1), [dLib.path, dTsconfig.path]);
// close all projects - no projects should be opened
projectService.closeExternalProject(projectName);
projectService.checkNumberOfProjects({});
}
it("when lazyConfiguredProjectsFromExternalProject not set", () => {
verifyAddRemoveConfig(/*lazyConfiguredProjectsFromExternalProject*/ false);
});
it("when lazyConfiguredProjectsFromExternalProject is set", () => {
verifyAddRemoveConfig(/*lazyConfiguredProjectsFromExternalProject*/ true);
});
});
it("correctly handles changes in lib section of config file", () => {
const libES5 = {
path: "/compiler/lib.es5.d.ts",
content: "declare const eval: any"
};
const libES2015Promise = {
path: "/compiler/lib.es2015.promise.d.ts",
content: "declare class Promise<T> {}"
};
const app = {
path: "/src/app.ts",
content: "var x: Promise<string>;"
};
const config1 = {
path: "/src/tsconfig.json",
content: JSON.stringify(
{
compilerOptions: {
module: "commonjs",
target: "es5",
noImplicitAny: true,
sourceMap: false,
lib: [
"es5"
]
}
})
};
const config2 = {
path: config1.path,
content: JSON.stringify(
{
compilerOptions: {
module: "commonjs",
target: "es5",
noImplicitAny: true,
sourceMap: false,
lib: [
"es5",
"es2015.promise"
]
}
})
};
const host = createServerHost([libES5, libES2015Promise, app, config1], { executingFilePath: "/compiler/tsc.js" });
const projectService = createProjectService(host);
projectService.openClientFile(app.path);
projectService.checkNumberOfProjects({ configuredProjects: 1 });
checkProjectActualFiles(configuredProjectAt(projectService, 0), [libES5.path, app.path, config1.path]);
host.writeFile(config2.path, config2.content);
host.checkTimeoutQueueLengthAndRun(2);
projectService.checkNumberOfProjects({ configuredProjects: 1 });
checkProjectActualFiles(configuredProjectAt(projectService, 0), [libES5.path, libES2015Promise.path, app.path, config2.path]);
});
it("should handle non-existing directories in config file", () => {
const f = {
path: "/a/src/app.ts",
content: "let x = 1;"
};
const config = {
path: "/a/tsconfig.json",
content: JSON.stringify({
compilerOptions: {},
include: [
"src/**/*",
"notexistingfolder/*"
]
})
};
const host = createServerHost([f, config]);
const projectService = createProjectService(host);
projectService.openClientFile(f.path);
projectService.checkNumberOfProjects({ configuredProjects: 1 });
const project = projectService.configuredProjects.get(config.path)!;
assert.isTrue(project.hasOpenRef()); // f
projectService.closeClientFile(f.path);
projectService.checkNumberOfProjects({ configuredProjects: 1 });
assert.strictEqual(projectService.configuredProjects.get(config.path), project);
assert.isFalse(project.hasOpenRef()); // No files
assert.isFalse(project.isClosed());
projectService.openClientFile(f.path);
projectService.checkNumberOfProjects({ configuredProjects: 1 });
assert.strictEqual(projectService.configuredProjects.get(config.path), project);
assert.isTrue(project.hasOpenRef()); // f
assert.isFalse(project.isClosed());
});
it("handles loads existing configured projects of external projects when lazyConfiguredProjectsFromExternalProject is disabled", () => {
const f1 = {
path: "/a/b/app.ts",
content: "let x = 1"
};
const config = {
path: "/a/b/tsconfig.json",
content: JSON.stringify({})
};
const projectFileName = "/a/b/project.csproj";
const host = createServerHost([f1, config]);
const service = createProjectService(host);
service.setHostConfiguration({ preferences: { lazyConfiguredProjectsFromExternalProject: true } });
service.openExternalProject({
projectFileName,
rootFiles: toExternalFiles([f1.path, config.path]),
options: {}
} as protocol.ExternalProject);
service.checkNumberOfProjects({ configuredProjects: 1 });
const project = service.configuredProjects.get(config.path)!;
assert.equal(project.pendingReload, ConfigFileProgramReloadLevel.Full); // External project referenced configured project pending to be reloaded
checkProjectActualFiles(project, emptyArray);
service.setHostConfiguration({ preferences: { lazyConfiguredProjectsFromExternalProject: false } });
assert.equal(project.pendingReload, ConfigFileProgramReloadLevel.None); // External project referenced configured project loaded
checkProjectActualFiles(project, [config.path, f1.path]);
service.closeExternalProject(projectFileName);
service.checkNumberOfProjects({});
service.openExternalProject({
projectFileName,
rootFiles: toExternalFiles([f1.path, config.path]),
options: {}
} as protocol.ExternalProject);
service.checkNumberOfProjects({ configuredProjects: 1 });
const project2 = service.configuredProjects.get(config.path)!;
assert.equal(project2.pendingReload, ConfigFileProgramReloadLevel.None); // External project referenced configured project loaded
checkProjectActualFiles(project2, [config.path, f1.path]);
});
it("handles creation of external project with jsconfig before jsconfig creation watcher is invoked", () => {
const projectFileName = `${tscWatch.projectRoot}/WebApplication36.csproj`;
const tsconfig: File = {
path: `${tscWatch.projectRoot}/tsconfig.json`,
content: "{}"
};
const files = [libFile, tsconfig];
const host = createServerHost(files);
const service = createProjectService(host);
// Create external project
service.openExternalProjects([{
projectFileName,
rootFiles: [{ fileName: tsconfig.path }],
options: { allowJs: false }
}]);
checkNumberOfProjects(service, { configuredProjects: 1 });
const configProject = service.configuredProjects.get(tsconfig.path.toLowerCase())!;
checkProjectActualFiles(configProject, [tsconfig.path]);
// write js file, open external project and open it for edit
const jsFilePath = `${tscWatch.projectRoot}/javascript.js`;
host.writeFile(jsFilePath, "");
service.openExternalProjects([{
projectFileName,
rootFiles: [{ fileName: tsconfig.path }, { fileName: jsFilePath }],
options: { allowJs: false }
}]);
service.applyChangesInOpenFiles(singleIterator({ fileName: jsFilePath, scriptKind: ScriptKind.JS, content: "" }));
checkNumberOfProjects(service, { configuredProjects: 1, inferredProjects: 1 });
checkProjectActualFiles(configProject, [tsconfig.path]);
const inferredProject = service.inferredProjects[0];
checkProjectActualFiles(inferredProject, [libFile.path, jsFilePath]);
// write jsconfig file
const jsConfig: File = {
path: `${tscWatch.projectRoot}/jsconfig.json`,
content: "{}"
};
// Dont invoke file creation watchers as the repro suggests
host.ensureFileOrFolder(jsConfig, /*ignoreWatchInvokedWithTriggerAsFileCreate*/ true);
// Open external project
service.openExternalProjects([{
projectFileName,
rootFiles: [{ fileName: jsConfig.path }, { fileName: tsconfig.path }, { fileName: jsFilePath }],
options: { allowJs: false }
}]);
checkNumberOfProjects(service, { configuredProjects: 2, inferredProjects: 1 });
checkProjectActualFiles(configProject, [tsconfig.path]);
assert.isTrue(inferredProject.isOrphan());
const jsConfigProject = service.configuredProjects.get(jsConfig.path.toLowerCase())!;
checkProjectActualFiles(jsConfigProject, [jsConfig.path, jsFilePath, libFile.path]);
});
it("does not crash if external file does not exist", () => {
const f1 = {
path: "/a/file1.ts",
content: "let x = [1, 2];",
};
const p1 = {
projectFileName: "/a/proj1.csproj",
rootFiles: [toExternalFile(f1.path)],
options: {},
};
const host = createServerHost([f1]);
host.require = (_initialPath, moduleName) => {
assert.equal(moduleName, "myplugin");
return {
module: () => ({
create(info: server.PluginCreateInfo) {
return Harness.LanguageService.makeDefaultProxy(info);
},
getExternalFiles() {
return ["/does/not/exist"];
},
}),
error: undefined,
};
};
const session = createSession(host, {
globalPlugins: ["myplugin"],
});
const projectService = session.getProjectService();
// When the external project is opened, the graph will be updated,
// and in the process getExternalFiles() above will be called.
// Since the external file does not exist, there will not be a script
// info for it. If tsserver does not handle this case, the following
// method call will crash.
projectService.openExternalProject(p1);
checkNumberOfProjects(projectService, { externalProjects: 1 });
});
});
} | the_stack |
import assert from 'assert';
import clsx from 'clsx';
import dedent from 'dedent';
import React, {
createContext,
useContext,
useMemo,
Fragment,
ReactNode,
CSSProperties,
ComponentType,
} from 'react';
import { Atoms, atoms } from '../../css/atoms/atoms';
import {
BackgroundProvider,
BackgroundVariant,
useBackgroundLightness,
} from '../Box/BackgroundContext';
import { Box, BoxProps } from '../Box/Box';
import { Text, TextProps } from '../Text/Text';
import { FieldOverlay } from '../private/FieldOverlay/FieldOverlay';
import { touchableText } from '../../hooks/typography';
import { virtualTouchable } from '../private/touchable/virtualTouchable';
import ActionsContext from '../Actions/ActionsContext';
import * as styles from './ButtonRenderer.css';
export const buttonVariants = [
'solid',
'ghost',
'soft',
'transparent',
] as const;
export const buttonWeights = ['weak', 'regular', 'strong'] as const;
const borderRadius = 'large';
type ButtonSize = 'standard' | 'small';
type ButtonTone = 'brandAccent' | 'critical';
type ButtonWeight = typeof buttonWeights[number];
type ButtonVariant = typeof buttonVariants[number];
type ButtonStyles = {
textTone: TextProps['tone'];
backgroundContext: BackgroundVariant | undefined;
backgroundClassName: BoxProps['className'];
backgroundHoverClassName: BoxProps['className'];
backgroundActiveClassName: BoxProps['className'];
boxShadow: Atoms['boxShadow'];
};
const buttonVariantStyles: Record<
ButtonVariant,
Record<'default' | ButtonTone, ButtonStyles>
> = {
solid: {
default: {
textTone: undefined,
backgroundContext: 'formAccent',
backgroundClassName: atoms({ background: 'formAccent' }),
backgroundHoverClassName: atoms({ background: 'formAccentHover' }),
backgroundActiveClassName: atoms({ background: 'formAccentActive' }),
boxShadow: undefined,
},
brandAccent: {
textTone: undefined,
backgroundContext: 'brandAccent',
backgroundClassName: atoms({ background: 'brandAccent' }),
backgroundHoverClassName: atoms({ background: 'brandAccentHover' }),
backgroundActiveClassName: atoms({ background: 'brandAccentActive' }),
boxShadow: undefined,
},
critical: {
textTone: undefined,
backgroundContext: 'critical',
backgroundClassName: atoms({ background: 'critical' }),
backgroundHoverClassName: atoms({ background: 'criticalHover' }),
backgroundActiveClassName: atoms({ background: 'criticalActive' }),
boxShadow: undefined,
},
},
ghost: {
default: {
textTone: 'formAccent',
backgroundContext: undefined,
backgroundClassName: undefined,
backgroundHoverClassName: atoms({ background: 'formAccentSoft' }),
backgroundActiveClassName: atoms({
background: 'formAccentSoftActive',
}),
boxShadow: 'borderFormAccentLarge',
},
brandAccent: {
textTone: 'brandAccent',
backgroundContext: undefined,
backgroundClassName: undefined,
backgroundHoverClassName: atoms({ background: 'brandAccentSoft' }),
backgroundActiveClassName: atoms({
background: 'brandAccentSoftActive',
}),
boxShadow: 'borderBrandAccentLarge',
},
critical: {
textTone: 'critical',
backgroundContext: undefined,
backgroundClassName: undefined,
backgroundHoverClassName: atoms({ background: 'criticalSoft' }),
backgroundActiveClassName: atoms({ background: 'criticalSoftActive' }),
boxShadow: 'borderCriticalLarge',
},
},
soft: {
default: {
textTone: 'formAccent',
backgroundContext: 'formAccentSoft',
backgroundClassName: atoms({ background: 'formAccentSoft' }),
backgroundHoverClassName: atoms({ background: 'formAccentSoftHover' }),
backgroundActiveClassName: atoms({
background: 'formAccentSoftActive',
}),
boxShadow: undefined,
},
brandAccent: {
textTone: 'brandAccent',
backgroundContext: 'brandAccentSoft',
backgroundClassName: atoms({ background: 'brandAccentSoft' }),
backgroundHoverClassName: atoms({
background: 'brandAccentSoftHover',
}),
backgroundActiveClassName: atoms({
background: 'brandAccentSoftActive',
}),
boxShadow: undefined,
},
critical: {
textTone: 'critical',
backgroundContext: 'criticalSoft',
backgroundClassName: atoms({ background: 'criticalSoft' }),
backgroundHoverClassName: atoms({ background: 'criticalSoftHover' }),
backgroundActiveClassName: atoms({ background: 'criticalSoftActive' }),
boxShadow: undefined,
},
},
transparent: {
default: {
textTone: 'formAccent',
backgroundContext: undefined,
backgroundClassName: undefined,
backgroundHoverClassName: atoms({ background: 'formAccentSoft' }),
backgroundActiveClassName: atoms({
background: 'formAccentSoftActive',
}),
boxShadow: undefined,
},
brandAccent: {
textTone: 'brandAccent',
backgroundContext: undefined,
backgroundClassName: undefined,
backgroundHoverClassName: atoms({ background: 'brandAccentSoft' }),
backgroundActiveClassName: atoms({
background: 'brandAccentSoftActive',
}),
boxShadow: undefined,
},
critical: {
textTone: 'critical',
backgroundContext: undefined,
backgroundClassName: undefined,
backgroundHoverClassName: atoms({ background: 'criticalSoft' }),
backgroundActiveClassName: atoms({ background: 'criticalSoftActive' }),
boxShadow: undefined,
},
},
};
const useButtonVariant = (variant: ButtonVariant, tone?: ButtonTone) => {
if (useBackgroundLightness() === 'dark' && !tone && variant !== 'solid') {
return {
textTone: undefined,
backgroundClassName:
variant === 'soft' ? styles.invertedBackgrounds.soft : undefined,
backgroundHoverClassName: styles.invertedBackgrounds.hover,
backgroundActiveClassName: styles.invertedBackgrounds.active,
boxShadow:
variant === 'ghost' ? 'borderStandardInvertedLarge' : undefined,
} as ButtonStyles;
}
return (
buttonVariantStyles[variant][tone ?? 'default'] ??
buttonVariantStyles[variant].default
);
};
const ButtonChildrenContext = createContext<{
size: ButtonSize;
tone: ButtonTone | undefined;
variant: ButtonVariant;
loading: boolean;
}>({
size: 'standard',
variant: 'solid',
tone: undefined,
loading: false,
});
interface ButtonChildrenProps {
children: ReactNode;
}
const ButtonChildren = ({ children }: ButtonChildrenProps) => {
const { size, variant, tone, loading } = useContext(ButtonChildrenContext);
const buttonVariant = useButtonVariant(variant, tone);
return (
<Fragment>
<FieldOverlay
borderRadius={borderRadius}
className={buttonVariant.backgroundClassName}
visible={Boolean(buttonVariant.backgroundClassName)}
/>
<FieldOverlay
borderRadius={borderRadius}
variant="focus"
onlyVisibleForKeyboardNavigation
className={styles.focusOverlay}
/>
<FieldOverlay
borderRadius={borderRadius}
className={[
buttonVariant.backgroundHoverClassName,
styles.hoverOverlay,
]}
/>
<FieldOverlay
borderRadius={borderRadius}
className={[
buttonVariant.backgroundActiveClassName,
styles.activeOverlay,
]}
/>
{buttonVariant.boxShadow ? (
<Box
boxShadow={buttonVariant.boxShadow}
borderRadius={borderRadius}
position="absolute"
top={0}
bottom={0}
left={0}
right={0}
/>
) : null}
<Box
position="relative"
paddingX={
size === 'small' || variant === 'transparent' ? 'small' : 'medium'
}
paddingY={
size === 'small' ? styles.constants.smallButtonPaddingSize : undefined
}
pointerEvents="none"
textAlign="center"
overflow="hidden"
userSelect="none"
className={size === 'standard' ? touchableText.standard : undefined}
>
<Text
baseline={false}
weight="medium"
tone={buttonVariant.textTone}
size={size === 'small' ? 'small' : undefined}
>
{children}
{loading ? (
<Box aria-hidden component="span" display="inlineBlock">
<Box component="span" className={styles.loadingDot}>
.
</Box>
<Box component="span" className={styles.loadingDot}>
.
</Box>
<Box component="span" className={styles.loadingDot}>
.
</Box>
</Box>
) : null}
</Text>
</Box>
</Fragment>
);
};
export interface PrivateButtonRendererProps {
size?: ButtonSize;
tone?: ButtonTone;
variant?: ButtonVariant;
bleedY?: boolean;
/** @deprecated The `weight` prop has been deprecated. Please choose a [variant](https://seek-oss.github.io/braid-design-system/components/Button#variants) instead. */
weight?: ButtonWeight;
loading?: boolean;
children: (
ButtonChildren: ComponentType<ButtonChildrenProps>,
styleProps: {
style: CSSProperties;
className: string;
},
) => ReactNode;
}
const resolveToneAndVariant = ({
weight,
tone,
variant = 'solid',
}: {
weight?: ButtonWeight;
tone?: ButtonTone;
variant?: ButtonVariant;
}): { variant: ButtonVariant; tone?: ButtonTone } => {
if (weight === 'strong') {
return {
tone: tone || 'brandAccent',
variant: 'solid',
};
}
if (weight === 'regular') {
return {
tone,
variant: 'solid',
};
}
if (weight === 'weak') {
return {
tone,
variant: 'ghost',
};
}
return {
tone,
variant,
};
};
export const PrivateButtonRenderer = ({
size: sizeProp,
tone: toneProp,
variant: variantProp,
bleedY,
weight,
loading = false,
children,
}: PrivateButtonRendererProps) => {
const actionsContext = useContext(ActionsContext);
assert(
!(actionsContext && sizeProp),
'You shouldn\'t set a "size" prop on Button elements nested inside Actions. Instead, set the size on the Actions element, e.g. <Actions size="small"><Button>...</Button></Actions>',
);
assert(
!(weight && variantProp),
'You shouldn\'t set a "weight" and "variant" prop together. Please migrate from "weight" to "variant".',
);
const { tone, variant } = resolveToneAndVariant({
weight,
tone: toneProp,
variant: variantProp,
});
if (process.env.NODE_ENV !== 'production') {
if (weight && /^(strong|regular|weak)$/.test(weight)) {
const needsTone = Boolean(tone);
const needsVariant = variant && variant !== 'solid';
// eslint-disable-next-line no-console
console.warn(
dedent`
The \`weight\` prop has been deprecated.${
needsVariant || needsTone
? ` Please migrate to${needsVariant ? ` \`variant\`` : ''}${
needsTone ? `${needsVariant ? ' and' : ''} \`tone\`` : ''
}.`
: ` You can migrate by removing the \`weight="${weight}"\` prop.`
}
%c -<Button weight="${weight}">...</Button>
%c +<Button${needsTone ? ` tone="${tone}"` : ''}${
needsVariant ? ` variant="${variant}"` : ''
}>...</Button>
`,
'color: red',
'color: green',
);
}
}
const size = sizeProp ?? actionsContext?.size ?? 'standard';
const { backgroundContext } = useButtonVariant(variant, tone);
const buttonStyles = clsx(
atoms({
reset: 'button',
cursor: !loading ? 'pointer' : undefined,
width: 'full',
position: 'relative',
display: 'block',
borderRadius,
transform: { active: 'touchable' },
transition: 'touchable',
outline: 'none',
}),
styles.root,
size === 'small' ? virtualTouchable({ xAxis: false }) : null,
size === 'standard' ? styles.standard : styles.small,
bleedY ? styles.bleedY : null,
);
const buttonChildrenContextValue = useMemo(
() => ({ size, tone, variant, loading }),
[size, tone, variant, loading],
);
const buttonProps = {
style: {},
className: buttonStyles,
};
const button = (
<ButtonChildrenContext.Provider value={buttonChildrenContextValue}>
{children(ButtonChildren, buttonProps)}
</ButtonChildrenContext.Provider>
);
return backgroundContext ? (
<BackgroundProvider value={backgroundContext}>{button}</BackgroundProvider>
) : (
button
);
};
/** @deprecated `ButtonRenderer` has been deprecated. Use [Button](https://seek-oss.github.io/braid-design-system/components/Button) or [ButtonLink](https://seek-oss.github.io/braid-design-system/components/ButtonLink) instead. If your usage of `ButtonRenderer` is not covered by either of these, please let us know. */
export const ButtonRenderer = PrivateButtonRenderer; | the_stack |
import { AbstractDatabase } from '../abstract/AbstractDatabase'
import { Table, TablePrimary, TableIndex, TableUnique } from '../abstract/Table'
import { TableColumn } from '../abstract/TableColumn'
import * as Operations from './Operation'
// @ts-ignore
import isEqual from 'lodash.isequal'
export async function computeDiff (from: AbstractDatabase, to: AbstractDatabase, {
updateComments = false,
} = {}): Promise<Operations.Operation []> {
const differ = new Differ(from, to, {
updateComments,
})
return differ.diff()
}
class Differ {
private from: AbstractDatabase
private to: AbstractDatabase
private updateComments: boolean
private operations: Operations.Operation[] = []
private tableCount = 0
constructor (from: AbstractDatabase, to: AbstractDatabase, options: any) {
this.from = from
this.to = to
this.updateComments = options.updateComments
}
public diff (): Operations.Operation[] {
this.operations.length = 0
const sameTableQueue: Array<{ fromTable: Table, toTable: Table }> = []
const addTableQueue = this.to.tables.slice()
for (const fromTable of this.from.tables) {
let removed = true
for (let i = 0, l = addTableQueue.length; i < l; i++) {
const toTable = addTableQueue[i]
// Same table
if (toTable.name === fromTable.name) {
removed = false
}
// Rename table
const { annotations } = toTable
if (annotations && annotations.oldNames && annotations.oldNames.includes(fromTable.name)) {
removed = false
this.renameTable(fromTable, toTable)
}
// Same or Rename
if (!removed) {
sameTableQueue.push({ fromTable, toTable })
// A new table shouldn't be added
addTableQueue.splice(i, 1)
break
}
}
// Drop table
if (removed) {
this.dropTable(fromTable)
}
}
// Create table
for (const toTable of addTableQueue) {
this.createTable(toTable)
}
// Compare tables
for (const { fromTable, toTable } of sameTableQueue) {
// Comment
if (this.updateComments && fromTable.comment !== toTable.comment) {
this.setTableComment(toTable)
}
const sameColumnQueue: Array<{ fromCol: TableColumn, toCol: TableColumn }> = []
const addColumnQueue = toTable.columns.slice()
for (const fromCol of fromTable.columns) {
let removed = true
for (let i = 0, l = addColumnQueue.length; i < l; i++) {
const toCol = addColumnQueue[i]
// Same column
if (toCol.name === fromCol.name) {
removed = false
}
// Rename column
const { annotations } = toCol
if (annotations && annotations.oldNames && annotations.oldNames.includes(fromCol.name)) {
removed = false
this.renameColumn(toTable, fromCol, toCol)
}
// Same or Rename
if (!removed) {
sameColumnQueue.push({ fromCol, toCol })
// A new table shouldn't be added
addColumnQueue.splice(i, 1)
break
}
}
// Drop column
if (removed) {
this.dropColumn(fromTable, fromCol)
}
}
// Add columns
for (const column of addColumnQueue) {
this.createColumn(toTable, column)
}
// Compare columns
for (const { fromCol, toCol } of sameColumnQueue) {
// Comment
if ((this.updateComments && fromCol.comment !== toCol.comment) ||
fromCol.type !== toCol.type || !isEqual(fromCol.args, toCol.args) ||
fromCol.nullable !== toCol.nullable ||
fromCol.defaultValue !== toCol.defaultValue ||
(Array.isArray(fromCol.defaultValue) && !isEqual(fromCol.defaultValue, toCol.defaultValue)) ||
(typeof fromCol.defaultValue === 'object' && !isEqual(fromCol.defaultValue, toCol.defaultValue))
) {
this.alterColumn(toTable, toCol)
}
// Foreign key
if ((fromCol.foreign && !toCol.foreign) ||
(!fromCol.foreign && toCol.foreign) ||
(fromCol.foreign && toCol.foreign &&
(fromCol.foreign.tableName !== toCol.foreign.tableName ||
fromCol.foreign.columnName !== toCol.foreign.columnName)
)) {
if (fromCol.foreign) { this.dropForeignKey(toTable, fromCol) }
if (toCol.foreign) { this.createForeignKey(toTable, toCol) }
}
}
// Primary index
if (!isEqual(fromTable.primaries, toTable.primaries)) {
const [index] = toTable.primaries
this.setPrimary(toTable, index)
}
// Index
this.compareIndex(
fromTable.indexes,
toTable.indexes,
// @ts-ignore
(index: TableIndex) => this.createIndex(toTable, index),
(index: TableIndex) => this.dropIndex(fromTable, index),
)
// Unique contraint
this.compareIndex(
fromTable.uniques,
toTable.uniques,
(index: TableUnique) => this.createUnique(toTable, index),
(index: TableUnique) => this.dropUnique(fromTable, index),
)
}
return this.operations
}
private createTable (table: Table) {
const op: Operations.TableCreateOperation = {
type: 'table.create',
table: table.name,
priority: this.tableCount++,
}
this.operations.push(op)
// Comment
if (table.comment) {
this.setTableComment(table)
}
// Columns
for (const column of table.columns) {
this.createColumn(table, column)
}
// Primary index
if (table.primaries.length) {
const [index] = table.primaries
this.setPrimary(table, index)
}
// Index
for (const index of table.indexes) {
this.createIndex(table, index)
}
// Unique contraint
for (const index of table.uniques) {
this.createUnique(table, index)
}
}
private renameTable (fromTable: Table, toTable: Table) {
const op: Operations.TableRenameOperation = {
type: 'table.rename',
fromName: fromTable.name,
toName: toTable.name,
priority: 0,
}
this.operations.push(op)
}
private dropTable (table: Table) {
const op: Operations.TableDropOperation = {
type: 'table.drop',
table: table.name,
priority: 0,
}
this.operations.push(op)
}
private setTableComment (table: Table) {
const op: Operations.TableCommentSetOperation = {
type: 'table.comment.set',
table: table.name,
comment: table.comment,
priority: 0,
}
this.operations.push(op)
}
private setPrimary (table: Table, index: TablePrimary | null) {
const op: Operations.TablePrimarySetOperation = {
type: 'table.primary.set',
table: table.name,
columns: index ? index.columns : null,
indexName: index ? index.name : null,
priority: 0,
}
this.operations.push(op)
}
private createIndex (table: Table, index: TableIndex) {
const op: Operations.TableIndexCreateOperation = {
type: 'table.index.create',
table: table.name,
columns: index.columns,
indexName: index.name,
indexType: index.type,
priority: 0,
}
this.operations.push(op)
}
private dropIndex (table: Table, index: TableIndex) {
const op: Operations.TableIndexDropOperation = {
type: 'table.index.drop',
table: table.name,
columns: index.columns,
indexName: index.name,
priority: 0,
}
this.operations.push(op)
}
private createUnique (table: Table, index: TableUnique) {
const op: Operations.TableUniqueCreateOperation = {
type: 'table.unique.create',
table: table.name,
columns: index.columns,
indexName: index.name,
priority: 0,
}
this.operations.push(op)
}
/**
* @param {Table} table
* @param {TableUnique} index
*/
private dropUnique (table: Table, index: TableUnique) {
const op: Operations.TableUniqueDropOperation = {
type: 'table.unique.drop',
table: table.name,
columns: index.columns,
indexName: index.name,
priority: 0,
}
this.operations.push(op)
}
private createForeignKey (table: Table, column: TableColumn) {
if (column.foreign && column.foreign.tableName && column.foreign.columnName) {
const op: Operations.TableForeignCreateOperation = {
type: 'table.foreign.create',
table: table.name,
column: column.name,
referenceTable: column.foreign.tableName,
referenceColumn: column.foreign.columnName,
priority: 0,
}
this.operations.push(op)
}
}
private dropForeignKey (table: Table, column: TableColumn) {
if (column.foreign) {
const op: Operations.TableForeignDropOperation = {
type: 'table.foreign.drop',
table: table.name,
column: column.name,
priority: 0,
}
this.operations.push(op)
}
}
private createColumn (table: Table, column: TableColumn) {
const op: Operations.ColumnCreateOperation = {
type: 'column.create',
table: table.name,
column: column.name,
columnType: column.type,
args: column.args,
comment: column.comment,
nullable: column.nullable,
defaultValue: column.defaultValue,
priority: 0,
}
this.operations.push(op)
// Foreign key
this.createForeignKey(table, column)
}
private renameColumn (table: Table, fromCol: TableColumn, toCol: TableColumn) {
const op: Operations.ColumnRenameOperation = {
type: 'column.rename',
table: table.name,
fromName: fromCol.name,
toName: toCol.name,
priority: 0,
}
this.operations.push(op)
}
private alterColumn (table: Table, column: TableColumn) {
const op: Operations.ColumnAlterOperation = {
type: 'column.alter',
table: table.name,
column: column.name,
columnType: column.type,
args: column.args,
comment: column.comment,
nullable: column.nullable,
defaultValue: column.defaultValue,
priority: 0,
}
this.operations.push(op)
}
private dropColumn (table: Table, column: TableColumn) {
const op: Operations.ColumnDropOperation = {
type: 'column.drop',
table: table.name,
column: column.name,
priority: 0,
}
this.operations.push(op)
}
private compareIndex (
fromList: Array<TableIndex | TableUnique>,
toList: Array<TableIndex | TableUnique>,
create: (index: TableIndex | TableUnique) => void,
drop: (index: TableIndex | TableUnique) => void,
) {
const addIndexQueue = toList.slice()
for (const fromIndex of fromList) {
let removed = true
for (let i = 0, l = addIndexQueue.length; i < l; i++) {
const toIndex = addIndexQueue[i]
if (
fromIndex.name === toIndex.name &&
// @ts-ignore
fromIndex.type === toIndex.type &&
isEqual(fromIndex.columns.sort(), toIndex.columns.sort())
) {
removed = false
addIndexQueue.splice(i, 1)
break
}
}
if (removed) {
drop(fromIndex)
}
}
for (const index of addIndexQueue) {
create(index)
}
}
} | the_stack |
import {MDCFloatingLabel} from '../../mdc-floating-label/index';
import {MDCLineRipple} from '../../mdc-line-ripple/index';
import {MDCNotchedOutline} from '../../mdc-notched-outline/index';
import {MDCRipple} from '../../mdc-ripple/index';
import {emitEvent} from '../../../testing/dom/events';
import {createMockFoundation} from '../../../testing/helpers/foundation';
import {cssClasses as characterCounterCssClasses} from '../../mdc-textfield/character-counter/constants';
import {cssClasses as helperTextCssClasses} from '../../mdc-textfield/helper-text/constants';
import {MDCTextField, MDCTextFieldCharacterCounter, MDCTextFieldFoundation, MDCTextFieldHelperText, MDCTextFieldIcon,} from '../../mdc-textfield/index';
const {cssClasses, strings} = MDCTextFieldFoundation;
const getFixture = () => {
const wrapper = document.createElement('div');
wrapper.innerHTML = `
<label class="mdc-text-field mdc-text-field--filled mdc-text-field--with-leading-icon">
<span class="mdc-floating-label" id="my-label">My Label</span>
<i class="material-icons mdc-text-field__icon mdc-text-field__icon--leading" tabindex="0" role="button">event</i>
<input type="text" class="mdc-text-field__input" aria-labelledby="my-label">
<span class="mdc-line-ripple"></span>
</label>
`;
const el = wrapper.firstElementChild as HTMLElement;
wrapper.removeChild(el);
return el;
};
const getHelperLineWithHelperText = () => {
const wrapper = document.createElement('div');
wrapper.innerHTML = `
<div class="${cssClasses.HELPER_LINE}">
<div class="${helperTextCssClasses.ROOT}">helper text</div>
</div>
`;
const el = wrapper.firstElementChild as HTMLElement;
wrapper.removeChild(el);
return el;
};
const getHelperLineWithCharacterCounter = () => {
const wrapper = document.createElement('div');
wrapper.innerHTML = `
<div class="${cssClasses.HELPER_LINE}">
<div class="${characterCounterCssClasses.ROOT}">helper text</div>
</div>
`;
const el = wrapper.firstElementChild as HTMLElement;
wrapper.removeChild(el);
return el;
};
const getFixtureWithPrefix = () => {
const wrapper = document.createElement('div');
wrapper.innerHTML = `
<label class="mdc-text-field mdc-text-field--filled">
<span class="mdc-floating-label" id="my-label">My Label</span>
<span class="mdc-text-field__affix mdc-text-field__affix--prefix">$</span>
<input type="text" class="mdc-text-field__input" aria-labelledby="my-label">
<span class="mdc-line-ripple"></span>
</label>
`;
const el = wrapper.firstElementChild as HTMLElement;
wrapper.removeChild(el);
return el;
};
const getFixtureWithSuffix = () => {
const wrapper = document.createElement('div');
wrapper.innerHTML = `
<label class="mdc-text-field mdc-text-field--filled">
<span class="mdc-floating-label" id="my-label">My Label</span>
<input type="text" class="mdc-text-field__input" aria-labelledby="my-label">
<span class="mdc-text-field__affix mdc-text-field__affix--suffix">/100</span>
<span class="mdc-line-ripple"></span>
</label>
`;
const el = wrapper.firstElementChild as HTMLElement;
wrapper.removeChild(el);
return el;
};
describe('MDCTextField', () => {
it('attachTo returns an MDCTextField instance', () => {
expect(MDCTextField.attachTo(getFixture()) instanceof MDCTextField)
.toBeTruthy();
});
class FakeRipple {
readonly destroy: jasmine.Spy;
constructor(readonly root: HTMLElement) {
this.destroy = jasmine.createSpy('.destroy');
}
}
class FakeLineRipple {
readonly listen: jasmine.Spy;
readonly unlisten: jasmine.Spy;
readonly destroy: jasmine.Spy;
readonly activate: jasmine.Spy;
readonly deactivate: jasmine.Spy;
readonly setRippleCenter: jasmine.Spy;
constructor() {
this.listen = jasmine.createSpy('.listen');
this.unlisten = jasmine.createSpy('.unlisten');
this.destroy = jasmine.createSpy('.destroy');
this.activate = jasmine.createSpy('.activate');
this.deactivate = jasmine.createSpy('.deactivate');
this.setRippleCenter = jasmine.createSpy('.setRippleCenter');
}
}
class FakeHelperText {
readonly destroy: jasmine.Spy;
constructor() {
this.destroy = jasmine.createSpy('.destroy');
}
}
class FakeCharacterCounter {
readonly destroy: jasmine.Spy;
constructor() {
this.destroy = jasmine.createSpy('.destroy');
}
}
class FakeIcon {
readonly destroy: jasmine.Spy;
constructor() {
this.destroy = jasmine.createSpy('.destroy');
}
}
class FakeLabel {
readonly destroy: jasmine.Spy;
readonly shake: jasmine.Spy;
readonly setRequired: jasmine.Spy;
constructor() {
this.destroy = jasmine.createSpy('.destroy');
this.shake = jasmine.createSpy('.shake');
this.setRequired = jasmine.createSpy('.setRequired');
}
}
class FakeOutline {
readonly destroy: jasmine.Spy;
constructor() {
this.destroy = jasmine.createSpy('.destroy');
}
}
it('#constructor instantiates a ripple on the root element by default',
() => {
const root = getFixture();
const component = new MDCTextField(
root, undefined, (el: HTMLElement) => new FakeRipple(el));
expect(component.root).toEqual(root);
});
it('#constructor does not instantiate a ripple when ${cssClasses.OUTLINED} class is present',
() => {
const root = getFixture();
root.classList.add(cssClasses.OUTLINED);
const component = new MDCTextField(root);
expect(component.ripple).toEqual(null);
});
it('#constructor does not instantiate a ripple when ${cssClasses.TEXTAREA} class is present',
() => {
const root = getFixture();
root.classList.add(cssClasses.TEXTAREA);
const component = new MDCTextField(root);
expect(component.ripple).toEqual(null);
});
it('#constructor when given a `mdc-text-field--filled` element, initializes a default ripple when no ' +
'ripple factory given',
() => {
const root = getFixture();
const component = new MDCTextField(root);
expect(component.ripple).toEqual(jasmine.any(MDCRipple));
});
it('#constructor instantiates a line ripple on the `.mdc-line-ripple` element if present',
() => {
const root = getFixture();
const component = new MDCTextField(root);
expect(component['lineRipple']).toEqual(jasmine.any(MDCLineRipple));
});
it('#constructor instantiates a helper text if present', () => {
const root = getFixture();
const helperText = getHelperLineWithHelperText();
document.body.appendChild(root);
document.body.appendChild(helperText);
const component = new MDCTextField(root);
expect(component['helperText'])
.toEqual(jasmine.any(MDCTextFieldHelperText));
document.body.removeChild(root);
document.body.removeChild(helperText);
});
it('#constructor instantiates a character counter if present', () => {
const root = getFixture();
const characterCounter = getHelperLineWithCharacterCounter();
document.body.appendChild(root);
root.querySelector('input')!.maxLength = 12;
document.body.appendChild(characterCounter);
const component = new MDCTextField(root);
expect(component['characterCounter'])
.toEqual(jasmine.any(MDCTextFieldCharacterCounter));
document.body.removeChild(root);
document.body.removeChild(characterCounter);
});
it('#constructor instantiates a leading icon if an icon element is present',
() => {
const root = getFixture();
const component = new MDCTextField(root);
expect(component['leadingIcon']).toEqual(jasmine.any(MDCTextFieldIcon));
expect(component['trailingIcon']).toEqual(null);
});
it('#constructor instantiates an icon for both icon elements if present',
() => {
const root = getFixture();
root.classList.add('mdc-text-field--with-trailing-icon');
const wrapper = document.createElement('div');
wrapper.innerHTML =
`<i class="mdc-text-field__icon mdc-text-field__icon--trailing material-icons">3d_rotations</i>`;
const el = wrapper.firstElementChild as HTMLElement;
wrapper.removeChild(el);
root.appendChild(el);
const component = new MDCTextField(root);
expect(component['leadingIcon']).toEqual(jasmine.any(MDCTextFieldIcon));
expect(component['trailingIcon']).toEqual(jasmine.any(MDCTextFieldIcon));
});
it('#constructor instantiates a trailing icon if the icon is present', () => {
const root = getFixture();
const leadingIcon = root.querySelector('.mdc-text-field__icon');
root.removeChild(leadingIcon as HTMLElement);
const wrapper = document.createElement('div');
wrapper.innerHTML =
`<i class="mdc-text-field__icon mdc-text-field__icon--trailing material-icons">3d_rotations</i>`;
const trailingIcon = wrapper.firstElementChild as HTMLElement;
root.appendChild(trailingIcon);
root.classList.add('mdc-text-field--with-trailing-icon');
root.classList.remove('mdc-text-field--with-leading-icon');
const component = new MDCTextField(root);
expect(component['leadingIcon']).toEqual(null);
expect(component['trailingIcon']).toEqual(jasmine.any(MDCTextFieldIcon));
});
it('#constructor instantiates a label on the `.mdc-floating-label` element if present',
() => {
const root = getFixture();
const component = new MDCTextField(root);
expect(component['label']).toEqual(jasmine.any(MDCFloatingLabel));
});
it('#constructor instantiates an outline on the `.mdc-notched-outline` element if present',
() => {
const wrapper = document.createElement('div');
wrapper.innerHTML = `<span class="mdc-notched-outline"></span>`;
const child = wrapper.firstElementChild as HTMLElement;
wrapper.removeChild(child);
const root = getFixture();
root.appendChild(child);
const component = new MDCTextField(root);
expect(component['outline']).toEqual(jasmine.any(MDCNotchedOutline));
});
it('#constructor handles undefined optional sub-elements gracefully', () => {
const wrapper = document.createElement('div');
wrapper.innerHTML = `
<label class="mdc-text-field mdc-text-field--filled">
<input type="text" class="mdc-text-field__input" id="my-text-field">
</label>
`;
const root = wrapper.firstElementChild as HTMLElement;
wrapper.removeChild(root);
expect(() => new MDCTextField(root)).not.toThrow();
});
it('default adapter methods handle sub-elements when present', () => {
const root = getFixture();
const component = new MDCTextField(root);
const adapter = (component.getDefaultFoundation() as any).adapter;
expect(adapter.hasClass('foo')).toBe(false);
expect(adapter.getLabelWidth()).toBeGreaterThan(0);
expect(() => adapter.floatLabel).not.toThrow();
});
it('default adapter methods handle undefined optional sub-elements gracefully',
() => {
const wrapper = document.createElement('div');
wrapper.innerHTML = `
<label class="mdc-text-field mdc-text-field--filled">
<input type="text" class="mdc-text-field__input" id="my-text-field">
</label>
`;
const root = wrapper.firstElementChild as HTMLElement;
wrapper.removeChild(root);
const component = new MDCTextField(root);
const adapter = (component.getDefaultFoundation() as any).adapter;
expect(adapter.getLabelWidth()).toEqual(0);
expect(adapter.hasLabel()).toBe(false);
expect(adapter.hasOutline()).toBe(false);
expect(() => adapter.floatLabel).not.toThrow();
expect(() => adapter.shakeLabel).not.toThrow();
expect(() => adapter.activateLineRipple).not.toThrow();
expect(() => adapter.deactivateLineRipple).not.toThrow();
expect(() => adapter.setLineRippleTransformOrigin).not.toThrow();
expect(() => adapter.closeOutline).not.toThrow();
expect(() => adapter.notchOutline).not.toThrow();
});
/**
* @param {!HTMLElement=} root
* @return {{
* root: HTMLElement,
* component: MDCTextField,
* foundation: MDCTextFieldFoundation,
* adapter: MDCTextFieldAdapter,
* outline: MDCNotchedOutline,
* icon: MDCTextFieldIcon,
* lineRipple: MDCLineRipple,
* label: MDCFloatingLabel,
* helperText: MDCTextFieldHelperText,
* characterCounter: MDCTextFieldCharacterCounter,
* }}
*/
function setupTest(root = getFixture()) {
const lineRipple = new FakeLineRipple();
const helperText = new FakeHelperText();
const characterCounter = new FakeCharacterCounter();
const icon = new FakeIcon();
const label = new FakeLabel();
const outline = new FakeOutline();
const component = new MDCTextField(
root, undefined, (el: HTMLElement) => new FakeRipple(el),
() => lineRipple, () => helperText, () => characterCounter, () => icon,
() => label, () => outline);
const foundation = component['foundation'];
const adapter = foundation['adapter'];
return {
root,
component,
foundation,
adapter,
lineRipple,
helperText,
characterCounter,
icon,
label,
outline
};
}
it('#destroy cleans up the ripple if present', () => {
const root = getFixture();
const component = new MDCTextField(
root, undefined, (el: HTMLElement) => new FakeRipple(el));
component.destroy();
expect(component.ripple!.destroy).toHaveBeenCalled();
});
it('#destroy cleans up the line ripple if present', () => {
const {component, lineRipple} = setupTest();
component.destroy();
expect(lineRipple.destroy).toHaveBeenCalled();
});
it('#destroy cleans up the helper text if present', () => {
const root = getFixture();
const helperTextElement = getHelperLineWithHelperText();
document.body.appendChild(root);
document.body.appendChild(helperTextElement);
const {component, helperText} = setupTest(root);
component.destroy();
expect(helperText.destroy).toHaveBeenCalled();
document.body.removeChild(root);
document.body.removeChild(helperTextElement);
});
it('#destroy cleans up the character counter if present', () => {
const root = getFixture();
const characterCounterElement = getHelperLineWithCharacterCounter();
document.body.appendChild(root);
document.body.appendChild(characterCounterElement);
const {component, characterCounter} = setupTest(root);
component.destroy();
expect(characterCounter.destroy).toHaveBeenCalled();
document.body.removeChild(root);
document.body.removeChild(characterCounterElement);
});
it('#destroy cleans up the icon if present', () => {
const {component, icon} = setupTest();
component.destroy();
expect(icon.destroy).toHaveBeenCalled();
});
it('#destroy cleans up the label if present', () => {
const {component, label} = setupTest();
component.destroy();
expect(label.destroy).toHaveBeenCalled();
});
it('#destroy cleans up the outline if present', () => {
const wrapper = document.createElement('div');
wrapper.innerHTML = `<span class="mdc-notched-outline"></span>`;
const child = wrapper.firstElementChild as HTMLElement;
wrapper.removeChild(child);
const root = getFixture();
root.appendChild(child);
const {component, outline} = setupTest(root);
component.destroy();
expect(outline.destroy).toHaveBeenCalled();
});
it('#destroy handles undefined optional sub-elements gracefully', () => {
const wrapper = document.createElement('div');
wrapper.innerHTML = `
<label class="mdc-text-field mdc-text-field--filled">
<input type="text" class="mdc-text-field__input" id="my-text-field">
</label>
`;
const root = wrapper.firstElementChild as HTMLElement;
wrapper.removeChild(root);
const component = new MDCTextField(root);
expect(() => component.destroy).not.toThrow();
});
it('#destroy handles undefined optional ripple gracefully', () => {
const root = getFixture();
const component = new MDCTextField(root);
component.ripple = null;
expect(() => component.destroy).not.toThrow();
});
it('#destroy calls destroy for both icon elements if present', () => {
const root = getFixture();
root.classList.add('mdc-text-field--with-trailing-icon');
const wrapper = document.createElement('div');
wrapper.innerHTML =
`<i class="mdc-text-field__icon mdc-text-field__icon--trailing material-icons">3d_rotations</i>`;
const child = wrapper.firstElementChild as HTMLElement;
wrapper.removeChild(child);
root.appendChild(child);
const component = new MDCTextField(root);
// The non-null assertion is deemed unnecessary, but without it tests on
// GitHub side fail to compile with error `Object is possibly 'null'`
// tslint:disable:no-unnecessary-type-assertion
component['leadingIcon']!.destroy =
jasmine.createSpy('leadingIcon_.destroy');
component['trailingIcon']!.destroy =
jasmine.createSpy('trailingIcon_.destroy');
component.destroy();
expect(component['leadingIcon']!.destroy).toHaveBeenCalled();
expect(component['trailingIcon']!.destroy).toHaveBeenCalled();
// tslint:enable:no-unnecessary-type-assertion
});
it('#initialSyncWithDOM sets disabled if input element is not disabled',
() => {
const {component} = setupTest();
component.initialSyncWithDOM();
expect(component.disabled).toBeFalsy();
});
it('#focus calls focus on the input element', () => {
const {root, component} = setupTest();
const input =
root.querySelector('.mdc-text-field__input') as HTMLInputElement;
input.focus = jasmine.createSpy('focus');
component.focus();
expect(input.focus).toHaveBeenCalledTimes(1);
});
it('get/set disabled updates the input element', () => {
const {root, component} = setupTest();
const input =
root.querySelector('.mdc-text-field__input') as HTMLInputElement;
component.disabled = true;
expect(input.disabled).toBeTruthy();
component.disabled = false;
expect(input.disabled).toBeFalsy();
});
it('get/set disabled updates the component styles', () => {
const {root, component} = setupTest();
component.disabled = true;
expect(root.classList.contains(cssClasses.DISABLED)).toBeTruthy();
component.disabled = false;
expect(root.classList.contains(cssClasses.DISABLED)).toBeFalsy();
});
it('set valid updates the component styles', () => {
const {root, component} = setupTest();
component.valid = false;
expect(root.classList.contains(cssClasses.INVALID)).toBeTruthy();
component.valid = true;
expect(root.classList.contains(cssClasses.INVALID)).toBeFalsy();
});
it('set helperTextContent has no effect when no helper text element is present',
() => {
const {component} = setupTest();
expect(() => {
component.helperTextContent = 'foo';
}).not.toThrow();
});
it('set leadingIconAriaLabel has no effect when no icon element is present',
() => {
const {component} = setupTest();
expect(() => {
component.leadingIconAriaLabel = 'foo';
}).not.toThrow();
});
it('set trailingIconAriaLabel has no effect when no icon element is present',
() => {
const {component} = setupTest();
expect(() => {
component.trailingIconAriaLabel = 'foo';
}).not.toThrow();
});
it('set leadingIconContent has no effect when no icon element is present',
() => {
const {component} = setupTest();
expect(() => {
component.leadingIconContent = 'foo';
}).not.toThrow();
});
it('set trailingIconContent has no effect when no icon element is present',
() => {
const {component} = setupTest();
expect(() => {
component.trailingIconContent = 'foo';
}).not.toThrow();
});
it('#adapter.addClass adds a class to the root element', () => {
const {root, component} = setupTest();
(component.getDefaultFoundation() as any).adapter.addClass('foo');
expect(root.classList.contains('foo')).toBeTruthy();
});
it('layout calls foundation notchOutline', () => {
const {component, foundation} = setupTest();
foundation.notchOutline = jasmine.createSpy('notchOutline');
component.layout();
expect(foundation.notchOutline).toHaveBeenCalledWith(false);
});
it('#adapter.removeClass removes a class from the root element', () => {
const {root, component} = setupTest();
root.classList.add('foo');
(component.getDefaultFoundation() as any).adapter.removeClass('foo');
expect(root.classList.contains('foo')).toBeFalsy();
});
it('#adapter.setInputAttr sets attribute on input element', () => {
const {root, component} = setupTest();
const input =
root.querySelector('.mdc-text-field__input') as HTMLInputElement;
(component.getDefaultFoundation() as any)
.adapter.setInputAttr('foo', 'bar');
expect(input.getAttribute('foo')).toEqual('bar');
});
it('#adapter.removeInputAttr removes attribute on input element', () => {
const {root, component} = setupTest();
const input =
root.querySelector('.mdc-text-field__input') as HTMLInputElement;
input.setAttribute('foo', 'bar!');
(component.getDefaultFoundation() as any).adapter.removeInputAttr('foo');
expect(input.getAttribute('foo')).toBe(null);
});
it('#adapter.registerInputInteractionHandler adds a handler to the input element for a given event',
() => {
const {root, component} = setupTest();
const input =
root.querySelector('.mdc-text-field__input') as HTMLInputElement;
const handler = jasmine.createSpy('eventHandler');
(component.getDefaultFoundation() as any)
.adapter.registerInputInteractionHandler('click', handler);
emitEvent(input, 'click');
expect(handler).toHaveBeenCalledWith(jasmine.anything());
});
it('#adapter.deregisterInputInteractionHandler removes a handler from the input element for a given event',
() => {
const {root, component} = setupTest();
const input =
root.querySelector('.mdc-text-field__input') as HTMLInputElement;
const handler = jasmine.createSpy('eventHandler');
input.addEventListener('click', handler);
(component.getDefaultFoundation() as any)
.adapter.deregisterInputInteractionHandler('click', handler);
emitEvent(input, 'click');
expect(handler).not.toHaveBeenCalled();
});
it('#adapter.registerTextFieldInteractionHandler adds an event handler for a given event on the root',
() => {
const {root, component} = setupTest();
const handler = jasmine.createSpy('TextFieldInteractionHandler');
(component.getDefaultFoundation() as any)
.adapter.registerTextFieldInteractionHandler('click', handler);
emitEvent(root, 'click');
expect(handler).toHaveBeenCalledWith(jasmine.anything());
});
it('#adapter.deregisterTextFieldInteractionHandler removes an event handler for a given event from the root',
() => {
const {root, component} = setupTest();
const handler = jasmine.createSpy('TextFieldInteractionHandler');
root.addEventListener('click', handler);
(component.getDefaultFoundation() as any)
.adapter.registerTextFieldInteractionHandler('click', handler);
emitEvent(root, 'click');
expect(handler).toHaveBeenCalledWith(jasmine.anything());
});
it('#adapter.registerValidationAttributeChangeHandler creates a working mutation observer',
(done) => {
const {root, component} = setupTest();
const handler = jasmine.createSpy('ValidationAttributeChangeHandler');
handler.withArgs(jasmine.any(Array)).and.callFake((arr: string[]) => {
if (arr.indexOf('required') !== -1) {
done();
}
});
component['foundation']['adapter']
.registerValidationAttributeChangeHandler(handler);
(root.querySelector('.mdc-text-field__input') as HTMLInputElement)
.required = true;
});
it('#adapter.deregisterValidationAttributeChangeHandler disconnects the passed observer',
() => {
const {component} = setupTest();
const disconnect = jasmine.createSpy('ValidationDisconnect');
const observer = new MutationObserver(() => undefined);
observer.disconnect = disconnect;
component['foundation']['adapter']
.deregisterValidationAttributeChangeHandler(observer);
expect(disconnect).toHaveBeenCalled();
});
it('#adapter.getNativeInput returns the component input element', () => {
const {root, component} = setupTest();
expect((component.getDefaultFoundation() as any).adapter.getNativeInput())
.toEqual(root.querySelector('.mdc-text-field__input'));
});
it('#adapter.activateLineRipple calls the activate method on the line ripple',
() => {
const {component, lineRipple} = setupTest();
(component.getDefaultFoundation() as any).adapter.activateLineRipple();
expect(lineRipple.activate).toHaveBeenCalled();
});
it('#adapter.deactivateLineRipple calls the deactivate method on the line ripple',
() => {
const {component, lineRipple} = setupTest();
(component.getDefaultFoundation() as any)
.adapter.deactivateLineRipple();
expect(lineRipple.deactivate).toHaveBeenCalled();
});
it('#adapter.setLineRippleTransformOrigin calls the setRippleCenter method on the line ripple',
() => {
const {component, lineRipple} = setupTest();
(component.getDefaultFoundation() as any)
.adapter.setLineRippleTransformOrigin(100);
expect(lineRipple.setRippleCenter).toHaveBeenCalledWith(100);
});
it('should not focus input when clicking icon', () => {
const root = getFixture();
const icon = root.querySelector('.mdc-text-field__icon') as HTMLElement;
const component = new MDCTextField(root);
document.body.appendChild(root);
root.click();
const input = (component as any).input as HTMLInputElement;
expect(document.activeElement).toBe(input, 'input should be focused');
input.blur();
expect(document.activeElement).not.toBe(input, 'ensure input was blurred');
icon.click();
expect(document.activeElement)
.not.toBe(input, 'input should not be focused');
document.body.removeChild(root);
});
function setupMockFoundationTest(root = getFixture()) {
const mockFoundation = createMockFoundation(MDCTextFieldFoundation);
const component = new MDCTextField(root, mockFoundation);
return {root, component, mockFoundation};
}
it('get/set value', () => {
const {component, mockFoundation} = setupMockFoundationTest();
component.value;
expect(mockFoundation.getValue).toHaveBeenCalled();
component.value = 'foo';
expect(mockFoundation.setValue).toHaveBeenCalledWith('foo');
});
it('set leadingIconAriaLabel', () => {
const {component, mockFoundation} = setupMockFoundationTest();
component.leadingIconAriaLabel = 'label';
expect(mockFoundation.setLeadingIconAriaLabel)
.toHaveBeenCalledWith('label');
});
it('set leadingIconContent', () => {
const {component, mockFoundation} = setupMockFoundationTest();
component.leadingIconContent = 'label';
expect(mockFoundation.setLeadingIconContent).toHaveBeenCalledWith('label');
});
it('set trailingIconAriaLabel', () => {
const {component, mockFoundation} = setupMockFoundationTest();
component.trailingIconAriaLabel = 'label';
expect(mockFoundation.setTrailingIconAriaLabel)
.toHaveBeenCalledWith('label');
});
it('set trailingIconContent', () => {
const {component, mockFoundation} = setupMockFoundationTest();
component.trailingIconContent = 'label';
expect(mockFoundation.setTrailingIconContent).toHaveBeenCalledWith('label');
});
it('get/set valid', () => {
const {component, mockFoundation} = setupMockFoundationTest();
component.valid;
expect(mockFoundation.isValid).toHaveBeenCalled();
component.valid = true;
expect(mockFoundation.setValid).toHaveBeenCalledWith(true);
});
it('get/set required', () => {
const {component} = setupMockFoundationTest();
component.required = true;
expect(component.required).toBe(true);
component.required = false;
expect(component.required).toBe(false);
});
it('set useNativeValidation', () => {
const {component, mockFoundation} = setupMockFoundationTest();
component.useNativeValidation = true;
expect(mockFoundation.setUseNativeValidation).toHaveBeenCalledWith(true);
});
it('get/set pattern', () => {
const {component} = setupMockFoundationTest();
component.pattern = '.{8,}';
expect(component.pattern).toEqual('.{8,}');
component.pattern = '.*';
expect(component.pattern).toEqual('.*');
});
it('get/set minLength', () => {
const {component} = setupMockFoundationTest();
component.minLength = 8;
expect(component.minLength).toEqual(8);
component.minLength = 0;
expect(component.minLength).toEqual(0);
});
it('get/set maxLength', () => {
const {component} = setupMockFoundationTest();
component.maxLength = 10;
expect(component.maxLength).toEqual(10);
component.maxLength = -1;
// IE11 has a different value for no maxLength property
expect(component.maxLength).not.toEqual(10);
});
it('get/set min', () => {
const {component} = setupMockFoundationTest();
component.min = '8';
expect(component.min).toEqual('8');
component.min = '0';
expect(component.min).toEqual('0');
});
it('get/set max', () => {
const {component} = setupMockFoundationTest();
expect(component.max).toEqual('');
component.max = '10';
expect(component.max).toEqual('10');
component.max = '';
expect(component.max).toEqual('');
});
it('get/set step', () => {
const {component} = setupMockFoundationTest();
component.step = '8';
expect(component.step).toEqual('8');
component.step = '10';
expect(component.step).toEqual('10');
});
it('get prefixText returns prefix textContent, or null without a prefix',
() => {
const root = getFixture();
const component = new MDCTextField(root);
expect(component.prefixText).toEqual(null);
const prefixRoot = getFixtureWithPrefix();
const prefixComponent = new MDCTextField(prefixRoot);
expect(prefixComponent.prefixText).toEqual('$');
});
it('set prefixText changes prefix textContent, if it exists', () => {
const root = getFixture();
const component = new MDCTextField(root);
component.prefixText = 'foo' as string | null;
expect(component.prefixText).toEqual(null);
const prefixRoot = getFixtureWithPrefix();
const prefixComponent = new MDCTextField(prefixRoot);
prefixComponent.prefixText = 'foo';
expect(prefixComponent.prefixText).toEqual('foo');
const prefixEl = prefixRoot.querySelector(strings.PREFIX_SELECTOR)!;
expect(prefixEl.textContent).toEqual('foo');
});
it('get suffixText returns suffix textContent, or null without a suffix',
() => {
const root = getFixture();
const component = new MDCTextField(root);
expect(component.suffixText).toEqual(null);
const suffixRoot = getFixtureWithSuffix();
const suffixComponent = new MDCTextField(suffixRoot);
expect(suffixComponent.suffixText).toEqual('/100');
});
it('set suffixText changes suffix textContent, if it exists', () => {
const root = getFixture();
const component = new MDCTextField(root);
component.suffixText = 'foo' as string | null;
expect(component.suffixText).toEqual(null);
const suffixRoot = getFixtureWithSuffix();
const suffixComponent = new MDCTextField(suffixRoot);
suffixComponent.suffixText = 'foo';
expect(suffixComponent.suffixText).toEqual('foo');
const suffixEl = suffixRoot.querySelector(strings.SUFFIX_SELECTOR)!;
expect(suffixEl.textContent).toEqual('foo');
});
}); | the_stack |
import {
BuiltinTypes, createRefToElmWithValue, CORE_ANNOTATIONS, ElemID, ObjectType, createRestriction, ListType,
} from '@salto-io/adapter-api'
import * as constants from '../../../constants'
import { enums } from '../enums'
export const mapreducescriptInnerTypes: ObjectType[] = []
const mapreducescriptElemID = new ElemID(constants.NETSUITE, 'mapreducescript')
const mapreducescript_customplugintypes_plugintypeElemID = new ElemID(constants.NETSUITE, 'mapreducescript_customplugintypes_plugintype')
const mapreducescript_customplugintypes_plugintype = new ObjectType({
elemID: mapreducescript_customplugintypes_plugintypeElemID,
annotations: {
},
fields: {
plugintype: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was single-select list */),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: This field accepts references to the plugintype custom type. */
},
path: [constants.NETSUITE, constants.TYPES_PATH, mapreducescriptElemID.name],
})
mapreducescriptInnerTypes.push(mapreducescript_customplugintypes_plugintype)
const mapreducescript_customplugintypesElemID = new ElemID(constants.NETSUITE, 'mapreducescript_customplugintypes')
const mapreducescript_customplugintypes = new ObjectType({
elemID: mapreducescript_customplugintypesElemID,
annotations: {
},
fields: {
plugintype: {
refType: createRefToElmWithValue(new ListType(mapreducescript_customplugintypes_plugintype)),
annotations: {
},
},
},
path: [constants.NETSUITE, constants.TYPES_PATH, mapreducescriptElemID.name],
})
mapreducescriptInnerTypes.push(mapreducescript_customplugintypes)
const mapreducescript_scriptcustomfields_scriptcustomfield_customfieldfilters_customfieldfilterElemID = new ElemID(constants.NETSUITE, 'mapreducescript_scriptcustomfields_scriptcustomfield_customfieldfilters_customfieldfilter')
const mapreducescript_scriptcustomfields_scriptcustomfield_customfieldfilters_customfieldfilter = new ObjectType({
elemID: mapreducescript_scriptcustomfields_scriptcustomfield_customfieldfilters_customfieldfilterElemID,
annotations: {
},
fields: {
fldfilter: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was single-select list */),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: This field accepts references to the following custom types: transactioncolumncustomfield transactionbodycustomfield othercustomfield itemoptioncustomfield itemnumbercustomfield itemcustomfield entitycustomfield customrecordcustomfield crmcustomfield For information about other possible values, see generic_standard_field. */
fldfilterchecked: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is F. */
fldfiltercomparetype: {
refType: createRefToElmWithValue(enums.generic_customfield_fldfiltercomparetype),
annotations: {
},
}, /* Original description: For information about possible values, see generic_customfield_fldfiltercomparetype. The default value is 'EQ'. */
fldfiltersel: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was multi-select list */),
annotations: {
},
}, /* Original description: You can specify multiple values by separating each value with a pipe (|) symbol. This field accepts references to the following custom types: scriptdeployment workflowactionscript workflowstatecustomfield workflowcustomfield workflow scriptdeployment usereventscript transactioncolumncustomfield transactionbodycustomfield transactionForm scriptdeployment suitelet scriptdeployment scheduledscript savedsearch role scriptdeployment restlet scriptdeployment portlet othercustomfield scriptdeployment massupdatescript scriptdeployment mapreducescript itemoptioncustomfield itemnumbercustomfield itemcustomfield entryForm entitycustomfield statuses customtransactiontype instance customrecordcustomfield customrecordtype customvalue crmcustomfield scriptdeployment clientscript scriptdeployment bundleinstallationscript advancedpdftemplate addressForm */
fldfilterval: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
},
fldfilternotnull: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is F. */
fldfilternull: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is F. */
fldcomparefield: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was single-select list */),
annotations: {
},
}, /* Original description: This field accepts references to the following custom types: transactioncolumncustomfield transactionbodycustomfield othercustomfield itemoptioncustomfield itemnumbercustomfield itemcustomfield entitycustomfield customrecordcustomfield crmcustomfield For information about other possible values, see generic_standard_field. */
},
path: [constants.NETSUITE, constants.TYPES_PATH, mapreducescriptElemID.name],
})
mapreducescriptInnerTypes.push(mapreducescript_scriptcustomfields_scriptcustomfield_customfieldfilters_customfieldfilter)
const mapreducescript_scriptcustomfields_scriptcustomfield_customfieldfiltersElemID = new ElemID(constants.NETSUITE, 'mapreducescript_scriptcustomfields_scriptcustomfield_customfieldfilters')
const mapreducescript_scriptcustomfields_scriptcustomfield_customfieldfilters = new ObjectType({
elemID: mapreducescript_scriptcustomfields_scriptcustomfield_customfieldfiltersElemID,
annotations: {
},
fields: {
customfieldfilter: {
refType: createRefToElmWithValue(new ListType(mapreducescript_scriptcustomfields_scriptcustomfield_customfieldfilters_customfieldfilter)),
annotations: {
},
},
},
path: [constants.NETSUITE, constants.TYPES_PATH, mapreducescriptElemID.name],
})
mapreducescriptInnerTypes.push(mapreducescript_scriptcustomfields_scriptcustomfield_customfieldfilters)
const mapreducescript_scriptcustomfields_scriptcustomfield_roleaccesses_roleaccessElemID = new ElemID(constants.NETSUITE, 'mapreducescript_scriptcustomfields_scriptcustomfield_roleaccesses_roleaccess')
const mapreducescript_scriptcustomfields_scriptcustomfield_roleaccesses_roleaccess = new ObjectType({
elemID: mapreducescript_scriptcustomfields_scriptcustomfield_roleaccesses_roleaccessElemID,
annotations: {
},
fields: {
role: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was single-select list */),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: This field accepts references to the role custom type. For information about other possible values, see customrecordtype_permittedrole. */
accesslevel: {
refType: createRefToElmWithValue(enums.generic_accesslevel_searchlevel),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: For information about possible values, see generic_accesslevel_searchlevel. The default value is '0'. */
searchlevel: {
refType: createRefToElmWithValue(enums.generic_accesslevel_searchlevel),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: For information about possible values, see generic_accesslevel_searchlevel. The default value is '0'. */
},
path: [constants.NETSUITE, constants.TYPES_PATH, mapreducescriptElemID.name],
})
mapreducescriptInnerTypes.push(mapreducescript_scriptcustomfields_scriptcustomfield_roleaccesses_roleaccess)
const mapreducescript_scriptcustomfields_scriptcustomfield_roleaccessesElemID = new ElemID(constants.NETSUITE, 'mapreducescript_scriptcustomfields_scriptcustomfield_roleaccesses')
const mapreducescript_scriptcustomfields_scriptcustomfield_roleaccesses = new ObjectType({
elemID: mapreducescript_scriptcustomfields_scriptcustomfield_roleaccessesElemID,
annotations: {
},
fields: {
roleaccess: {
refType: createRefToElmWithValue(new ListType(mapreducescript_scriptcustomfields_scriptcustomfield_roleaccesses_roleaccess)),
annotations: {
},
},
},
path: [constants.NETSUITE, constants.TYPES_PATH, mapreducescriptElemID.name],
})
mapreducescriptInnerTypes.push(mapreducescript_scriptcustomfields_scriptcustomfield_roleaccesses)
const mapreducescript_scriptcustomfields_scriptcustomfieldElemID = new ElemID(constants.NETSUITE, 'mapreducescript_scriptcustomfields_scriptcustomfield')
const mapreducescript_scriptcustomfields_scriptcustomfield = new ObjectType({
elemID: mapreducescript_scriptcustomfields_scriptcustomfieldElemID,
annotations: {
},
fields: {
scriptid: {
refType: createRefToElmWithValue(BuiltinTypes.SERVICE_ID),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
[constants.IS_ATTRIBUTE]: true,
},
}, /* Original description: This attribute value can be up to 40 characters long. The default value is ‘custscript’. */
fieldtype: {
refType: createRefToElmWithValue(enums.generic_customfield_fieldtype),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: For information about possible values, see generic_customfield_fieldtype. The default value is 'TEXT'. */
label: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was single-select list */),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
[CORE_ANNOTATIONS.RESTRICTION]: createRestriction({ max_length: 200 }),
},
}, /* Original description: This field value can be up to 200 characters long. This field accepts references to the string custom type. */
selectrecordtype: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was single-select list */),
annotations: {
},
}, /* Original description: This field is mandatory when the fieldtype value is equal to any of the following lists or values: SELECT, MULTISELECT. This field accepts references to the following custom types: customrecordtype customlist For information about other possible values, see generic_customfield_selectrecordtype. */
applyformatting: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is T. */
defaultchecked: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is F. */
defaultselection: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was single-select list */),
annotations: {
},
}, /* Original description: This field accepts references to the following custom types: scriptdeployment workflowactionscript workflowstatecustomfield workflowcustomfield workflow scriptdeployment usereventscript transactioncolumncustomfield transactionbodycustomfield transactionForm scriptdeployment suitelet scriptdeployment scheduledscript savedsearch role scriptdeployment restlet scriptdeployment portlet othercustomfield scriptdeployment massupdatescript scriptdeployment mapreducescript itemoptioncustomfield itemnumbercustomfield itemcustomfield entryForm entitycustomfield statuses customtransactiontype instance customrecordcustomfield customrecordtype customvalue crmcustomfield scriptdeployment clientscript scriptdeployment bundleinstallationscript advancedpdftemplate addressForm */
defaultvalue: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
},
description: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
},
displaytype: {
refType: createRefToElmWithValue(enums.generic_customfield_displaytype),
annotations: {
},
}, /* Original description: For information about possible values, see generic_customfield_displaytype. The default value is 'NORMAL'. */
dynamicdefault: {
refType: createRefToElmWithValue(enums.generic_customfield_dynamicdefault),
annotations: {
},
}, /* Original description: For information about possible values, see generic_customfield_dynamicdefault. */
help: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was single-select list */),
annotations: {
},
}, /* Original description: This field accepts references to the string custom type. */
linktext: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
},
minvalue: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
},
maxvalue: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
},
storevalue: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is T. */
accesslevel: {
refType: createRefToElmWithValue(enums.generic_accesslevel_searchlevel),
annotations: {
},
}, /* Original description: For information about possible values, see generic_accesslevel_searchlevel. The default value is '2'. */
checkspelling: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is F. */
displayheight: {
refType: createRefToElmWithValue(BuiltinTypes.NUMBER),
annotations: {
},
}, /* Original description: This field value must be greater than or equal to 0. */
displaywidth: {
refType: createRefToElmWithValue(BuiltinTypes.NUMBER),
annotations: {
},
}, /* Original description: This field value must be greater than or equal to 0. */
isformula: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is F. */
ismandatory: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is F. */
maxlength: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
},
onparentdelete: {
refType: createRefToElmWithValue(enums.generic_customfield_onparentdelete),
annotations: {
},
}, /* Original description: For information about possible values, see generic_customfield_onparentdelete. */
searchcomparefield: {
refType: createRefToElmWithValue(enums.generic_standard_field),
annotations: {
},
}, /* Original description: For information about possible values, see generic_standard_field. */
searchdefault: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was single-select list */),
annotations: {
},
}, /* Original description: This field accepts references to the savedsearch custom type. */
searchlevel: {
refType: createRefToElmWithValue(enums.generic_accesslevel_searchlevel),
annotations: {
},
}, /* Original description: For information about possible values, see generic_accesslevel_searchlevel. The default value is '2'. */
setting: {
refType: createRefToElmWithValue(enums.script_setting),
annotations: {
},
}, /* Original description: For information about possible values, see script_setting. */
customfieldfilters: {
refType: createRefToElmWithValue(mapreducescript_scriptcustomfields_scriptcustomfield_customfieldfilters),
annotations: {
},
},
roleaccesses: {
refType: createRefToElmWithValue(mapreducescript_scriptcustomfields_scriptcustomfield_roleaccesses),
annotations: {
},
},
},
path: [constants.NETSUITE, constants.TYPES_PATH, mapreducescriptElemID.name],
})
mapreducescriptInnerTypes.push(mapreducescript_scriptcustomfields_scriptcustomfield)
const mapreducescript_scriptcustomfieldsElemID = new ElemID(constants.NETSUITE, 'mapreducescript_scriptcustomfields')
const mapreducescript_scriptcustomfields = new ObjectType({
elemID: mapreducescript_scriptcustomfieldsElemID,
annotations: {
},
fields: {
scriptcustomfield: {
refType: createRefToElmWithValue(new ListType(mapreducescript_scriptcustomfields_scriptcustomfield)),
annotations: {
},
},
},
path: [constants.NETSUITE, constants.TYPES_PATH, mapreducescriptElemID.name],
})
mapreducescriptInnerTypes.push(mapreducescript_scriptcustomfields)
const mapreducescript_scriptdeployments_scriptdeployment_recurrence_dailyElemID = new ElemID(constants.NETSUITE, 'mapreducescript_scriptdeployments_scriptdeployment_recurrence_daily')
const mapreducescript_scriptdeployments_scriptdeployment_recurrence_daily = new ObjectType({
elemID: mapreducescript_scriptdeployments_scriptdeployment_recurrence_dailyElemID,
annotations: {
},
fields: {
startdate: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
},
starttime: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
},
everyxdays: {
refType: createRefToElmWithValue(BuiltinTypes.NUMBER),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: This field value must range from 1 through 1000. (inclusive) */
enddate: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
},
repeat: {
refType: createRefToElmWithValue(enums.generic_repeat_time),
annotations: {
},
}, /* Original description: For information about possible values, see generic_repeat_time. */
},
path: [constants.NETSUITE, constants.TYPES_PATH, mapreducescriptElemID.name],
})
mapreducescriptInnerTypes.push(mapreducescript_scriptdeployments_scriptdeployment_recurrence_daily)
const mapreducescript_scriptdeployments_scriptdeployment_recurrence_everyweekdayElemID = new ElemID(constants.NETSUITE, 'mapreducescript_scriptdeployments_scriptdeployment_recurrence_everyweekday')
const mapreducescript_scriptdeployments_scriptdeployment_recurrence_everyweekday = new ObjectType({
elemID: mapreducescript_scriptdeployments_scriptdeployment_recurrence_everyweekdayElemID,
annotations: {
},
fields: {
startdate: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
},
starttime: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
},
enddate: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
},
repeat: {
refType: createRefToElmWithValue(enums.generic_repeat_time),
annotations: {
},
}, /* Original description: For information about possible values, see generic_repeat_time. */
},
path: [constants.NETSUITE, constants.TYPES_PATH, mapreducescriptElemID.name],
})
mapreducescriptInnerTypes.push(mapreducescript_scriptdeployments_scriptdeployment_recurrence_everyweekday)
const mapreducescript_scriptdeployments_scriptdeployment_recurrence_monthlyElemID = new ElemID(constants.NETSUITE, 'mapreducescript_scriptdeployments_scriptdeployment_recurrence_monthly')
const mapreducescript_scriptdeployments_scriptdeployment_recurrence_monthly = new ObjectType({
elemID: mapreducescript_scriptdeployments_scriptdeployment_recurrence_monthlyElemID,
annotations: {
},
fields: {
startdate: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
},
starttime: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
},
everyxmonths: {
refType: createRefToElmWithValue(BuiltinTypes.NUMBER),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: This field value must range from 1 through 1000. (inclusive) */
enddate: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
},
repeat: {
refType: createRefToElmWithValue(enums.generic_repeat_time),
annotations: {
},
}, /* Original description: For information about possible values, see generic_repeat_time. */
},
path: [constants.NETSUITE, constants.TYPES_PATH, mapreducescriptElemID.name],
})
mapreducescriptInnerTypes.push(mapreducescript_scriptdeployments_scriptdeployment_recurrence_monthly)
const mapreducescript_scriptdeployments_scriptdeployment_recurrence_monthlydayofweekElemID = new ElemID(constants.NETSUITE, 'mapreducescript_scriptdeployments_scriptdeployment_recurrence_monthlydayofweek')
const mapreducescript_scriptdeployments_scriptdeployment_recurrence_monthlydayofweek = new ObjectType({
elemID: mapreducescript_scriptdeployments_scriptdeployment_recurrence_monthlydayofweekElemID,
annotations: {
},
fields: {
startdate: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
},
starttime: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
},
orderofweek: {
refType: createRefToElmWithValue(enums.generic_order_of_week),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: For information about possible values, see generic_order_of_week. */
dayofweek: {
refType: createRefToElmWithValue(enums.generic_day_of_week),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: For information about possible values, see generic_day_of_week. */
everyxmonths: {
refType: createRefToElmWithValue(BuiltinTypes.NUMBER),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: This field value must range from 1 through 1000. (inclusive) */
enddate: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
},
repeat: {
refType: createRefToElmWithValue(enums.generic_repeat_time),
annotations: {
},
}, /* Original description: For information about possible values, see generic_repeat_time. */
},
path: [constants.NETSUITE, constants.TYPES_PATH, mapreducescriptElemID.name],
})
mapreducescriptInnerTypes.push(mapreducescript_scriptdeployments_scriptdeployment_recurrence_monthlydayofweek)
const mapreducescript_scriptdeployments_scriptdeployment_recurrence_singleElemID = new ElemID(constants.NETSUITE, 'mapreducescript_scriptdeployments_scriptdeployment_recurrence_single')
const mapreducescript_scriptdeployments_scriptdeployment_recurrence_single = new ObjectType({
elemID: mapreducescript_scriptdeployments_scriptdeployment_recurrence_singleElemID,
annotations: {
},
fields: {
startdate: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
},
starttime: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
},
repeat: {
refType: createRefToElmWithValue(enums.generic_repeat_time),
annotations: {
},
}, /* Original description: For information about possible values, see generic_repeat_time. */
},
path: [constants.NETSUITE, constants.TYPES_PATH, mapreducescriptElemID.name],
})
mapreducescriptInnerTypes.push(mapreducescript_scriptdeployments_scriptdeployment_recurrence_single)
const mapreducescript_scriptdeployments_scriptdeployment_recurrence_weeklyElemID = new ElemID(constants.NETSUITE, 'mapreducescript_scriptdeployments_scriptdeployment_recurrence_weekly')
const mapreducescript_scriptdeployments_scriptdeployment_recurrence_weekly = new ObjectType({
elemID: mapreducescript_scriptdeployments_scriptdeployment_recurrence_weeklyElemID,
annotations: {
},
fields: {
startdate: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
},
starttime: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
},
everyxweeks: {
refType: createRefToElmWithValue(BuiltinTypes.NUMBER),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: This field value must range from 1 through 1000. (inclusive) */
sunday: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: The default value is F. */
monday: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: The default value is F. */
tuesday: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: The default value is F. */
wednesday: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: The default value is F. */
thursday: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: The default value is F. */
friday: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: The default value is F. */
saturday: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: The default value is F. */
enddate: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
},
repeat: {
refType: createRefToElmWithValue(enums.generic_repeat_time),
annotations: {
},
}, /* Original description: For information about possible values, see generic_repeat_time. */
},
path: [constants.NETSUITE, constants.TYPES_PATH, mapreducescriptElemID.name],
})
mapreducescriptInnerTypes.push(mapreducescript_scriptdeployments_scriptdeployment_recurrence_weekly)
const mapreducescript_scriptdeployments_scriptdeployment_recurrence_yearlyElemID = new ElemID(constants.NETSUITE, 'mapreducescript_scriptdeployments_scriptdeployment_recurrence_yearly')
const mapreducescript_scriptdeployments_scriptdeployment_recurrence_yearly = new ObjectType({
elemID: mapreducescript_scriptdeployments_scriptdeployment_recurrence_yearlyElemID,
annotations: {
},
fields: {
startdate: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
},
starttime: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
},
enddate: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
},
repeat: {
refType: createRefToElmWithValue(enums.generic_repeat_time),
annotations: {
},
}, /* Original description: For information about possible values, see generic_repeat_time. */
},
path: [constants.NETSUITE, constants.TYPES_PATH, mapreducescriptElemID.name],
})
mapreducescriptInnerTypes.push(mapreducescript_scriptdeployments_scriptdeployment_recurrence_yearly)
const mapreducescript_scriptdeployments_scriptdeployment_recurrence_yearlydayofweekElemID = new ElemID(constants.NETSUITE, 'mapreducescript_scriptdeployments_scriptdeployment_recurrence_yearlydayofweek')
const mapreducescript_scriptdeployments_scriptdeployment_recurrence_yearlydayofweek = new ObjectType({
elemID: mapreducescript_scriptdeployments_scriptdeployment_recurrence_yearlydayofweekElemID,
annotations: {
},
fields: {
startdate: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
},
starttime: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
},
orderofweek: {
refType: createRefToElmWithValue(enums.generic_order_of_week),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: For information about possible values, see generic_order_of_week. */
dayofweek: {
refType: createRefToElmWithValue(enums.generic_day_of_week),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: For information about possible values, see generic_day_of_week. */
enddate: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
},
repeat: {
refType: createRefToElmWithValue(enums.generic_repeat_time),
annotations: {
},
}, /* Original description: For information about possible values, see generic_repeat_time. */
},
path: [constants.NETSUITE, constants.TYPES_PATH, mapreducescriptElemID.name],
})
mapreducescriptInnerTypes.push(mapreducescript_scriptdeployments_scriptdeployment_recurrence_yearlydayofweek)
const mapreducescript_scriptdeployments_scriptdeployment_recurrenceElemID = new ElemID(constants.NETSUITE, 'mapreducescript_scriptdeployments_scriptdeployment_recurrence')
const mapreducescript_scriptdeployments_scriptdeployment_recurrence = new ObjectType({
elemID: mapreducescript_scriptdeployments_scriptdeployment_recurrenceElemID,
annotations: {
},
fields: {
daily: {
refType: createRefToElmWithValue(mapreducescript_scriptdeployments_scriptdeployment_recurrence_daily),
annotations: {
},
},
everyweekday: {
refType: createRefToElmWithValue(mapreducescript_scriptdeployments_scriptdeployment_recurrence_everyweekday),
annotations: {
},
},
monthly: {
refType: createRefToElmWithValue(mapreducescript_scriptdeployments_scriptdeployment_recurrence_monthly),
annotations: {
},
},
monthlydayofweek: {
refType: createRefToElmWithValue(mapreducescript_scriptdeployments_scriptdeployment_recurrence_monthlydayofweek),
annotations: {
},
},
single: {
refType: createRefToElmWithValue(mapreducescript_scriptdeployments_scriptdeployment_recurrence_single),
annotations: {
},
},
weekly: {
refType: createRefToElmWithValue(mapreducescript_scriptdeployments_scriptdeployment_recurrence_weekly),
annotations: {
},
},
yearly: {
refType: createRefToElmWithValue(mapreducescript_scriptdeployments_scriptdeployment_recurrence_yearly),
annotations: {
},
},
yearlydayofweek: {
refType: createRefToElmWithValue(mapreducescript_scriptdeployments_scriptdeployment_recurrence_yearlydayofweek),
annotations: {
},
},
},
path: [constants.NETSUITE, constants.TYPES_PATH, mapreducescriptElemID.name],
})
mapreducescriptInnerTypes.push(mapreducescript_scriptdeployments_scriptdeployment_recurrence)
const mapreducescript_scriptdeployments_scriptdeploymentElemID = new ElemID(constants.NETSUITE, 'mapreducescript_scriptdeployments_scriptdeployment')
const mapreducescript_scriptdeployments_scriptdeployment = new ObjectType({
elemID: mapreducescript_scriptdeployments_scriptdeploymentElemID,
annotations: {
},
fields: {
scriptid: {
refType: createRefToElmWithValue(BuiltinTypes.SERVICE_ID),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
[constants.IS_ATTRIBUTE]: true,
},
}, /* Original description: This attribute value can be up to 40 characters long. The default value is ‘customdeploy’. */
status: {
refType: createRefToElmWithValue(enums.script_status),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: For information about possible values, see script_status. The default value is 'TESTING'. */
title: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
},
isdeployed: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is T. */
loglevel: {
refType: createRefToElmWithValue(enums.script_loglevel),
annotations: {
},
}, /* Original description: For information about possible values, see script_loglevel. The default value is 'DEBUG'. */
runasrole: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was single-select list */),
annotations: {
},
}, /* Original description: This field accepts references to the role custom type. For information about other possible values, see generic_role. */
buffersize: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
}, /* Original description: The default value is '1'. */
concurrencylimit: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
}, /* Original description: The default value is '1'. */
queueallstagesatonce: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is T. */
yieldaftermins: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
}, /* Original description: The default value is '60'. */
recurrence: {
refType: createRefToElmWithValue(mapreducescript_scriptdeployments_scriptdeployment_recurrence),
annotations: {
},
},
},
path: [constants.NETSUITE, constants.TYPES_PATH, mapreducescriptElemID.name],
})
mapreducescriptInnerTypes.push(mapreducescript_scriptdeployments_scriptdeployment)
const mapreducescript_scriptdeploymentsElemID = new ElemID(constants.NETSUITE, 'mapreducescript_scriptdeployments')
export const mapreducescript_scriptdeployments = new ObjectType({
elemID: mapreducescript_scriptdeploymentsElemID,
annotations: {
},
fields: {
scriptdeployment: {
refType: createRefToElmWithValue(new ListType(mapreducescript_scriptdeployments_scriptdeployment)),
annotations: {
},
},
},
path: [constants.NETSUITE, constants.TYPES_PATH, mapreducescriptElemID.name],
})
mapreducescriptInnerTypes.push(mapreducescript_scriptdeployments)
export const mapreducescript = new ObjectType({
elemID: mapreducescriptElemID,
annotations: {
},
fields: {
scriptid: {
refType: createRefToElmWithValue(BuiltinTypes.SERVICE_ID),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
[constants.IS_ATTRIBUTE]: true,
[CORE_ANNOTATIONS.RESTRICTION]: createRestriction({ regex: '^customscript[0-9a-z_]+' }),
},
}, /* Original description: This attribute value can be up to 40 characters long. The default value is ‘customscript’. */
name: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was single-select list */),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
[CORE_ANNOTATIONS.RESTRICTION]: createRestriction({ max_length: 40 }),
},
}, /* Original description: This field value can be up to 40 characters long. This field accepts references to the string custom type. */
scriptfile: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was filereference */),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: This field must reference a .js file. */
description: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was single-select list */),
annotations: {
[CORE_ANNOTATIONS.RESTRICTION]: createRestriction({ max_length: 999 }),
},
}, /* Original description: This field value can be up to 999 characters long. This field accepts references to the string custom type. */
isinactive: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is F. */
notifyadmins: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is F. */
notifyemails: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
[CORE_ANNOTATIONS.RESTRICTION]: createRestriction({ max_length: 999 }),
},
}, /* Original description: This field value can be up to 999 characters long. */
notifygroup: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
}, /* Original description: Note Account-specific values are not supported by SDF. */
notifyowner: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is T. */
customplugintypes: {
refType: createRefToElmWithValue(mapreducescript_customplugintypes),
annotations: {
},
},
scriptcustomfields: {
refType: createRefToElmWithValue(mapreducescript_scriptcustomfields),
annotations: {
},
},
scriptdeployments: {
refType: createRefToElmWithValue(mapreducescript_scriptdeployments),
annotations: {
},
},
},
path: [constants.NETSUITE, constants.TYPES_PATH, mapreducescriptElemID.name],
}) | the_stack |
import Scanner, { isAlphaWord, isAlpha, isNumber, isAlphaNumericWord, isSpace, isQuote } from '@emmetio/scanner';
import { AllTokens, Literal, OperatorType, NumberValue, ColorValue, WhiteSpace, Operator, Bracket, StringValue, Field } from './tokens';
import { Chars } from './utils';
export * from './tokens';
export default function tokenize(abbr: string, isValue?: boolean): AllTokens[] {
let brackets = 0;
let token: AllTokens | undefined;
const scanner = new Scanner(abbr);
const tokens: AllTokens[] = [];
while (!scanner.eof()) {
token = getToken(scanner, brackets === 0 && !isValue);
if (!token) {
throw scanner.error('Unexpected character');
}
if (token.type === 'Bracket') {
if (!brackets && token.open) {
mergeTokens(scanner, tokens);
}
brackets += token.open ? 1 : -1;
if (brackets < 0) {
throw scanner.error('Unexpected bracket', token.start);
}
}
tokens.push(token);
// Forcibly consume next operator after unit-less numeric value or color:
// next dash `-` must be used as value delimiter
if (shouldConsumeDashAfter(token) && (token = operator(scanner))) {
tokens.push(token);
}
}
return tokens;
}
/**
* Returns next token from given scanner, if possible
*/
export function getToken(scanner: Scanner, short?: boolean) {
return field(scanner)
|| numberValue(scanner)
|| colorValue(scanner)
|| stringValue(scanner)
|| bracket(scanner)
|| operator(scanner)
|| whiteSpace(scanner)
|| literal(scanner, short);
}
function field(scanner: Scanner): Field | undefined {
const start = scanner.pos;
if (scanner.eat(Chars.Dollar) && scanner.eat(Chars.CurlyBracketOpen)) {
scanner.start = scanner.pos;
let index: number | undefined;
let name: string = '';
if (scanner.eatWhile(isNumber)) {
// It’s a field
index = Number(scanner.current());
name = scanner.eat(Chars.Colon) ? consumePlaceholder(scanner) : '';
} else if (isAlpha(scanner.peek())) {
// It’s a variable
name = consumePlaceholder(scanner);
}
if (scanner.eat(Chars.CurlyBracketClose)) {
return {
type: 'Field',
index, name,
start,
end: scanner.pos
};
}
throw scanner.error('Expecting }');
}
// If we reached here then there’s no valid field here, revert
// back to starting position
scanner.pos = start;
}
/**
* Consumes a placeholder: value right after `:` in field. Could be empty
*/
function consumePlaceholder(stream: Scanner): string {
const stack: number[] = [];
stream.start = stream.pos;
while (!stream.eof()) {
if (stream.eat(Chars.CurlyBracketOpen)) {
stack.push(stream.pos);
} else if (stream.eat(Chars.CurlyBracketClose)) {
if (!stack.length) {
stream.pos--;
break;
}
stack.pop();
} else {
stream.pos++;
}
}
if (stack.length) {
stream.pos = stack.pop()!;
throw stream.error(`Expecting }`);
}
return stream.current();
}
/**
* Consumes literal from given scanner
* @param short Use short notation for consuming value.
* The difference between “short” and “full” notation is that first one uses
* alpha characters only and used for extracting keywords from abbreviation,
* while “full” notation also supports numbers and dashes
*/
function literal(scanner: Scanner, short?: boolean): Literal | undefined {
const start = scanner.pos;
if (scanner.eat(isIdentPrefix)) {
// SCSS or LESS variable
// NB a bit dirty hack: if abbreviation starts with identifier prefix,
// consume alpha characters only to allow embedded variables
scanner.eatWhile(start ? isKeyword : isLiteral);
} else if (scanner.eat(isAlphaWord)) {
scanner.eatWhile(short ? isLiteral : isKeyword);
} else {
// Allow dots only at the beginning of literal
scanner.eat(Chars.Dot);
scanner.eatWhile(isLiteral);
}
if (start !== scanner.pos) {
scanner.start = start;
return createLiteral(scanner, scanner.start = start);
}
}
function createLiteral(scanner: Scanner, start = scanner.start, end = scanner.pos): Literal {
return {
type: 'Literal',
value: scanner.substring(start, end),
start,
end
};
}
/**
* Consumes numeric CSS value (number with optional unit) from current stream,
* if possible
*/
function numberValue(scanner: Scanner): NumberValue | undefined {
const start = scanner.pos;
if (consumeNumber(scanner)) {
scanner.start = start;
const rawValue = scanner.current();
// eat unit, which can be a % or alpha word
scanner.start = scanner.pos;
scanner.eat(Chars.Percent) || scanner.eatWhile(isAlphaWord);
return {
type: 'NumberValue',
value: Number(rawValue),
rawValue,
unit: scanner.current(),
start,
end: scanner.pos
};
}
}
/**
* Consumes quoted string value from given scanner
*/
function stringValue(scanner: Scanner): StringValue | undefined {
const ch = scanner.peek();
const start = scanner.pos;
let finished = false;
if (isQuote(ch)) {
scanner.pos++;
while (!scanner.eof()) {
// Do not throw error on malformed string
if (scanner.eat(ch)) {
finished = true;
break;
} else {
scanner.pos++;
}
}
scanner.start = start;
return {
type: 'StringValue',
value: scanner.substring(start + 1, scanner.pos - (finished ? 1 : 0)),
quote: ch === Chars.SingleQuote ? 'single' : 'double',
start,
end: scanner.pos
};
}
}
/**
* Consumes a color token from given string
*/
function colorValue(scanner: Scanner): ColorValue | Literal | undefined {
// supported color variations:
// #abc → #aabbccc
// #0 → #000000
// #fff.5 → rgba(255, 255, 255, 0.5)
// #t → transparent
const start = scanner.pos;
if (scanner.eat(Chars.Hash)) {
const valueStart = scanner.pos;
let color = '';
let alpha = '';
if (scanner.eatWhile(isHex)) {
color = scanner.substring(valueStart, scanner.pos);
alpha = colorAlpha(scanner);
} else if (scanner.eat(Chars.Transparent)) {
color = '0';
alpha = colorAlpha(scanner) || '0';
} else {
alpha = colorAlpha(scanner);
}
if (color || alpha || scanner.eof()) {
const { r, g, b, a } = parseColor(color, alpha);
return {
type: 'ColorValue',
r, g, b, a,
raw: scanner.substring(start + 1, scanner.pos),
start,
end: scanner.pos
};
} else {
// Consumed # but no actual value: invalid color value, treat it as literal
return createLiteral(scanner, start);
}
}
scanner.pos = start;
}
/**
* Consumes alpha value of color: `.1`
*/
function colorAlpha(scanner: Scanner): string {
const start = scanner.pos;
if (scanner.eat(Chars.Dot)) {
scanner.start = start;
if (scanner.eatWhile(isNumber)) {
return scanner.current();
}
return '1';
}
return '';
}
/**
* Consumes white space characters as string literal from given scanner
*/
function whiteSpace(scanner: Scanner): WhiteSpace | undefined {
const start = scanner.pos;
if (scanner.eatWhile(isSpace)) {
return {
type: 'WhiteSpace',
start,
end: scanner.pos
};
}
}
/**
* Consumes bracket from given scanner
*/
function bracket(scanner: Scanner): Bracket | undefined {
const ch = scanner.peek();
if (isBracket(ch)) {
return {
type: 'Bracket',
open: ch === Chars.RoundBracketOpen,
start: scanner.pos++,
end: scanner.pos
};
}
}
/**
* Consumes operator from given scanner
*/
function operator(scanner: Scanner): Operator | undefined {
const op = operatorType(scanner.peek());
if (op) {
return {
type: 'Operator',
operator: op,
start: scanner.pos++,
end: scanner.pos
};
}
}
/**
* Eats number value from given stream
* @return Returns `true` if number was consumed
*/
function consumeNumber(stream: Scanner): boolean {
const start = stream.pos;
stream.eat(Chars.Dash);
const afterNegative = stream.pos;
const hasDecimal = stream.eatWhile(isNumber);
const prevPos = stream.pos;
if (stream.eat(Chars.Dot)) {
// It’s perfectly valid to have numbers like `1.`, which enforces
// value to float unit type
const hasFloat = stream.eatWhile(isNumber);
if (!hasDecimal && !hasFloat) {
// Lone dot
stream.pos = prevPos;
}
}
// Edge case: consumed dash only: not a number, bail-out
if (stream.pos === afterNegative) {
stream.pos = start;
}
return stream.pos !== start;
}
function isIdentPrefix(code: number): boolean {
return code === Chars.At || code === Chars.Dollar;
}
/**
* If given character is an operator, returns it’s type
*/
function operatorType(ch: number): OperatorType | undefined {
return (ch === Chars.Sibling && OperatorType.Sibling)
|| (ch === Chars.Excl && OperatorType.Important)
|| (ch === Chars.Comma && OperatorType.ArgumentDelimiter)
|| (ch === Chars.Colon && OperatorType.PropertyDelimiter)
|| (ch === Chars.Dash && OperatorType.ValueDelimiter)
|| void 0;
}
/**
* Check if given code is a hex value (/0-9a-f/)
*/
function isHex(code: number): boolean {
return isNumber(code) || isAlpha(code, 65, 70); // A-F
}
function isKeyword(code: number): boolean {
return isAlphaNumericWord(code) || code === Chars.Dash;
}
function isBracket(code: number) {
return code === Chars.RoundBracketOpen || code === Chars.RoundBracketClose;
}
function isLiteral(code: number) {
return isAlphaWord(code) || code === Chars.Percent || code === Chars.Slash;
}
/**
* Parses given color value from abbreviation into RGBA format
*/
function parseColor(value: string, alpha?: string): { r: number, g: number, b: number, a: number } {
let r = '0';
let g = '0';
let b = '0';
let a = Number(alpha != null && alpha !== '' ? alpha : 1);
if (value === 't') {
a = 0;
} else {
switch (value.length) {
case 0:
break;
case 1:
r = g = b = value + value;
break;
case 2:
r = g = b = value;
break;
case 3:
r = value[0] + value[0];
g = value[1] + value[1];
b = value[2] + value[2];
break;
default:
value += value;
r = value.slice(0, 2);
g = value.slice(2, 4);
b = value.slice(4, 6);
}
}
return {
r: parseInt(r, 16),
g: parseInt(g, 16),
b: parseInt(b, 16),
a
};
}
/**
* Check if scanner reader must consume dash after given token.
* Used in cases where user must explicitly separate numeric values
*/
function shouldConsumeDashAfter(token: AllTokens): boolean {
return token.type === 'ColorValue' || (token.type === 'NumberValue' && !token.unit);
}
/**
* Merges last adjacent tokens into a single literal.
* This function is used to overcome edge case when function name was parsed
* as a list of separate tokens. For example, a `scale3d()` value will be
* parsed as literal and number tokens (`scale` and `3d`) which is a perfectly
* valid abbreviation but undesired result. This function will detect last adjacent
* literal and number values and combine them into single literal
*/
function mergeTokens(scanner: Scanner, tokens: AllTokens[]) {
let start = 0;
let end = 0;
while (tokens.length) {
const token = last(tokens)!;
if (token.type === 'Literal' || token.type === 'NumberValue') {
start = token.start!;
if (!end) {
end = token.end!;
}
tokens.pop();
} else {
break;
}
}
if (start !== end) {
tokens.push(createLiteral(scanner, start, end));
}
}
function last<T>(arr: T[]): T | undefined {
return arr[arr.length - 1];
} | the_stack |
* @module PropertyEditors
*/
import "./SliderEditor.scss";
import classnames from "classnames";
import * as React from "react";
import {
PropertyEditorParams, PropertyEditorParamTypes, PropertyValue, PropertyValueFormat, SliderEditorParams, StandardEditorNames, StandardTypeNames,
} from "@itwin/appui-abstract";
import { Icon } from "@itwin/core-react";
import { Slider, TooltipProps } from "@itwin/itwinui-react";
import { PropertyEditorProps, TypeEditor } from "./EditorContainer";
import { PropertyEditorBase, PropertyEditorManager } from "./PropertyEditorManager";
import { PopupButton, PopupContent, PopupOkCancelButtons } from "./PopupButton";
/** @internal */
interface SliderEditorState {
value: number;
isDisabled?: boolean;
min: number;
max: number;
size?: number;
step?: number;
showTooltip?: boolean;
tooltipBelow?: boolean;
formatTooltip?: (value: number) => string;
thumbMode?: "allow-crossing" | "inhibit-crossing";
trackDisplayMode?: "auto" | "none" | "odd-segments" | "even-segments";
minLabel?: React.ReactNode;
maxLabel?: React.ReactNode;
tickLabels?: React.ReactNode;
}
/** SliderEditor React component that is a property editor with numeric input & up/down buttons
* @public
*/
export class SliderEditor extends React.PureComponent<PropertyEditorProps, SliderEditorState> implements TypeEditor {
private _isMounted = false;
private _enterKey = false;
private _divElement = React.createRef<HTMLDivElement>();
/** @internal */
public override readonly state: Readonly<SliderEditorState> = {
value: 0,
min: 0,
max: 100,
};
public async getPropertyValue(): Promise<PropertyValue | undefined> {
const record = this.props.propertyRecord;
let propertyValue: PropertyValue | undefined;
// istanbul ignore else
if (record && record.value.valueFormat === PropertyValueFormat.Primitive) {
propertyValue = {
valueFormat: PropertyValueFormat.Primitive,
value: this.state.value,
displayValue: "",
};
}
return propertyValue;
}
public get htmlElement(): HTMLElement | null {
return this._divElement.current;
}
public get hasFocus(): boolean {
let containsFocus = false;
// istanbul ignore else
if (this.htmlElement)
containsFocus = this.htmlElement.contains(document.activeElement);
return containsFocus;
}
private _handleChange = (values: readonly number[]): void => {
const newValue = values[0];
// istanbul ignore else
if (this._isMounted)
this.setState({
value: newValue,
});
};
/** @internal */
public override componentDidMount() {
this._isMounted = true;
this.setStateFromProps(); // eslint-disable-line @typescript-eslint/no-floating-promises
}
/** @internal */
public override componentWillUnmount() {
this._isMounted = false;
}
/** @internal */
public override componentDidUpdate(prevProps: PropertyEditorProps) {
if (this.props.propertyRecord !== prevProps.propertyRecord) {
this.setStateFromProps(); // eslint-disable-line @typescript-eslint/no-floating-promises
}
}
private internalFormatTooltip = (value: number, step = 1) => {
if (Number.isInteger(step))
return value.toFixed(0);
const stepString = step.toString();
const decimalIndex = stepString.indexOf(".");
const numDecimals = step.toString().length - (decimalIndex + 1);
return value.toFixed(numDecimals);
};
private async setStateFromProps() {
const record = this.props.propertyRecord;
let initialValue = 0;
// istanbul ignore else
if (record && record.value.valueFormat === PropertyValueFormat.Primitive) {
initialValue = record.value.value as number;
}
let size: number | undefined;
let min = 0;
let max = 100;
let step: number | undefined;
let showTooltip: boolean | undefined;
let tooltipBelow: boolean | undefined;
let formatTooltip: ((value: number) => string) | undefined;
let tickLabels: string[] | undefined;
let minLabel: React.ReactNode | undefined;
let maxLabel: React.ReactNode | undefined;
let trackDisplayMode: "auto" | "none" | "odd-segments" | "even-segments" | undefined;
let thumbMode: "allow-crossing" | "inhibit-crossing" | undefined;
const isDisabled = record ? record.isDisabled : undefined;
if (record && record.property && record.property.editor && record.property.editor.params) {
const sliderParams = record.property.editor.params.find((param: PropertyEditorParams) => param.type === PropertyEditorParamTypes.Slider) as SliderEditorParams;
// istanbul ignore else
if (sliderParams) {
min = sliderParams.minimum;
max = sliderParams.maximum;
size = sliderParams.size;
step = sliderParams.step;
thumbMode = 1 === sliderParams.mode ? "allow-crossing" : "inhibit-crossing";
trackDisplayMode = !sliderParams.reversed ? "auto" : "odd-segments";
showTooltip = sliderParams.showTooltip;
tooltipBelow = sliderParams.tooltipBelow;
formatTooltip = sliderParams.formatTooltip;
minLabel = !sliderParams.showMinMax ? "" : sliderParams.minIconSpec ? <Icon iconSpec={sliderParams.minIconSpec} /> : undefined;
maxLabel = !sliderParams.showMinMax ? "" : sliderParams.maxIconSpec ? <Icon iconSpec={sliderParams.maxIconSpec} /> : undefined;
if (sliderParams.showTicks) {
const count = sliderParams.getTickCount ? sliderParams.getTickCount() : 0;
if (count) {
tickLabels = [];
const increment = (max - min) / count;
for (let i = 0; i <= count; i++) {
const value = (i * increment) + min;
if (sliderParams.showTickLabels) {
const label = sliderParams.formatTick ? sliderParams.formatTick(value) : this.internalFormatTooltip(value, step);
tickLabels.push(label);
} else {
tickLabels.push("");
}
}
} else if (sliderParams.getTickValues) {
tickLabels = sliderParams.getTickValues().map((val: number) => sliderParams.formatTick ? sliderParams.formatTick(val) : this.internalFormatTooltip(val, step));
}
}
}
}
// istanbul ignore else
if (this._isMounted)
this.setState({
value: initialValue, isDisabled,
size,
min, max, step, trackDisplayMode,
showTooltip, tooltipBelow, formatTooltip,
minLabel,
maxLabel,
tickLabels,
thumbMode,
});
}
private _handleEnter = async (): Promise<void> => {
this._enterKey = true;
await this._handleCommit();
};
private _handleClose = async (): Promise<void> => {
if (this._enterKey) {
this._enterKey = false;
} else {
// istanbul ignore else
if (this.props.onCancel)
this.props.onCancel();
}
};
private _handleOk = async (_event: React.MouseEvent): Promise<void> => {
await this._handleCommit();
};
private _handleCancel = (_event: React.MouseEvent): void => {
// istanbul ignore else
if (this.props.onCancel) {
this.props.onCancel();
}
};
private _handleCommit = async (): Promise<void> => {
// istanbul ignore else
if (this.props.propertyRecord && this.props.onCommit) {
const propertyValue = await this.getPropertyValue();
// istanbul ignore else
if (propertyValue !== undefined) {
this.props.onCommit({ propertyRecord: this.props.propertyRecord, newValue: propertyValue });
}
}
};
private tooltipProps = (_index: number, val: number) => {
const content = this.state.formatTooltip ? this.state.formatTooltip(val) : this.internalFormatTooltip(val, this.state.step);
return { placement: this.state.tooltipBelow ? "bottom" : "top", content, visible: this.state.showTooltip } as Partial<Omit<TooltipProps, "children">>;
};
/** @internal */
public override render(): React.ReactNode {
const className = classnames("components-cell-editor", "components-slider-editor", this.props.className);
const minSize = this.state.size ? this.state.size : 100;
const style: React.CSSProperties = {
...this.props.style,
minWidth: `${minSize}px`,
};
const popupContent = (
<Slider
className="components-slider-editor-slider"
style={style}
values={[this.state.value]}
min={this.state.min}
max={this.state.max}
step={this.state.step}
thumbMode={this.state.thumbMode}
trackDisplayMode={this.state.trackDisplayMode}
disabled={this.state.isDisabled}
minLabel={this.state.minLabel}
maxLabel={this.state.maxLabel}
tooltipProps={this.tooltipProps}
tickLabels={this.state.tickLabels}
onChange={this._handleChange}
/>
);
return (
<div className={className} ref={this._divElement}>
<PopupButton label={this.state.value} onClose={this._handleClose} onEnter={this._handleEnter}
setFocus={this.props.setFocus} focusTarget=".core-slider-handle">
<PopupContent>
{popupContent}
<PopupOkCancelButtons onOk={this._handleOk} onCancel={this._handleCancel} />
</PopupContent>
</PopupButton>
</div>
);
}
}
/** Slider Property Editor registered for the "number" type name and "slider" editor name.
* It uses the [[SliderEditor]] React component.
* @public
*/
export class SliderPropertyEditor extends PropertyEditorBase {
public get reactNode(): React.ReactNode {
return <SliderEditor />;
}
}
PropertyEditorManager.registerEditor(StandardTypeNames.Number, SliderPropertyEditor, StandardEditorNames.Slider);
PropertyEditorManager.registerEditor(StandardTypeNames.Int, SliderPropertyEditor, StandardEditorNames.Slider);
PropertyEditorManager.registerEditor(StandardTypeNames.Float, SliderPropertyEditor, StandardEditorNames.Slider);
PropertyEditorManager.registerEditor(StandardTypeNames.Double, SliderPropertyEditor, StandardEditorNames.Slider); | the_stack |
import {
PublicKey,
SystemProgram,
SYSVAR_RENT_PUBKEY,
TransactionInstruction,
} from '@solana/web3.js';
import { programIds } from '../utils/ids';
import { deserializeBorsh } from './../utils/borsh';
import { serialize } from 'borsh';
import BN from 'bn.js';
import { PublicKeyInput } from 'node:crypto';
import { ParsedAccount } from '..';
export const METADATA_PREFIX = 'metadata';
export const EDITION = 'edition';
export const MAX_NAME_LENGTH = 32;
export const MAX_SYMBOL_LENGTH = 10;
export const MAX_URI_LENGTH = 200;
export const MAX_METADATA_LEN =
1 + 32 + MAX_NAME_LENGTH + MAX_SYMBOL_LENGTH + MAX_URI_LENGTH + 200;
export const MAX_NAME_SYMBOL_LEN = 1 + 32 + 8;
export const MAX_MASTER_EDITION_KEN = 1 + 9 + 8 + 32;
export enum MetadataKey {
MetadataV1 = 0,
NameSymbolTupleV1 = 1,
EditionV1 = 2,
MasterEditionV1 = 3,
}
export enum MetadataCategory {
Audio = 'audio',
Video = 'video',
Image = 'image',
}
export interface IMetadataExtension {
name: string;
symbol: string;
description: string;
// preview image
image: string;
// stores link to item on meta
externalUrl: string;
royalty: number;
files?: File[];
category: MetadataCategory;
}
export class MasterEdition {
key: MetadataKey;
supply: BN;
maxSupply?: BN;
/// Can be used to mint tokens that give one-time permission to mint a single limited edition.
masterMint: PublicKey;
constructor(args: {
key: MetadataKey;
supply: BN;
maxSupply?: BN;
/// Can be used to mint tokens that give one-time permission to mint a single limited edition.
masterMint: PublicKey;
}) {
this.key = MetadataKey.MasterEditionV1;
this.supply = args.supply;
this.maxSupply = args.maxSupply;
this.masterMint = args.masterMint;
}
}
export class Edition {
key: MetadataKey;
/// Points at MasterEdition struct
parent: PublicKey;
/// Starting at 0 for master record, this is incremented for each edition minted.
edition: BN;
constructor(args: { key: MetadataKey; parent: PublicKey; edition: BN }) {
this.key = MetadataKey.EditionV1;
this.parent = args.parent;
this.edition = args.edition;
}
}
export class Metadata {
key: MetadataKey;
nonUniqueSpecificUpdateAuthority?: PublicKey;
mint: PublicKey;
name: string;
symbol: string;
uri: string;
extended?: IMetadataExtension;
masterEdition?: PublicKey;
edition?: PublicKey;
nameSymbolTuple?: PublicKey;
constructor(args: {
nonUniqueSpecificUpdateAuthority?: PublicKey;
mint: PublicKey;
name: string;
symbol: string;
uri: string;
}) {
this.key = MetadataKey.MetadataV1;
this.nonUniqueSpecificUpdateAuthority =
args.nonUniqueSpecificUpdateAuthority;
this.mint = args.mint;
this.name = args.name;
this.symbol = args.symbol;
this.uri = args.uri;
}
}
export class NameSymbolTuple {
key: MetadataKey;
updateAuthority: PublicKey;
metadata: PublicKey;
constructor(args: { updateAuthority: Buffer; metadata: Buffer }) {
this.key = MetadataKey.NameSymbolTupleV1;
this.updateAuthority = new PublicKey(args.updateAuthority);
this.metadata = new PublicKey(args.metadata);
}
}
class CreateMetadataArgs {
instruction: number = 0;
allowDuplicates: boolean = false;
name: string;
symbol: string;
uri: string;
constructor(args: {
name: string;
symbol: string;
uri: string;
allowDuplicates?: boolean;
}) {
this.name = args.name;
this.symbol = args.symbol;
this.uri = args.uri;
this.allowDuplicates = !!args.allowDuplicates;
}
}
class UpdateMetadataArgs {
instruction: number = 1;
uri: string;
// Not used by this app, just required for instruction
nonUniqueSpecificUpdateAuthority: PublicKey | null;
constructor(args: {
uri: string;
nonUniqueSpecificUpdateAuthority?: string;
}) {
this.uri = args.uri;
this.nonUniqueSpecificUpdateAuthority = args.nonUniqueSpecificUpdateAuthority
? new PublicKey(args.nonUniqueSpecificUpdateAuthority)
: null;
}
}
class TransferUpdateAuthorityArgs {
instruction: number = 2;
constructor() {}
}
class CreateMasterEditionArgs {
instruction: number = 3;
maxSupply: BN | null;
constructor(args: { maxSupply: BN | null }) {
this.maxSupply = args.maxSupply;
}
}
export const METADATA_SCHEMA = new Map<any, any>([
[
CreateMetadataArgs,
{
kind: 'struct',
fields: [
['instruction', 'u8'],
['allowDuplicates', 'u8'],
['name', 'string'],
['symbol', 'string'],
['uri', 'string'],
],
},
],
[
UpdateMetadataArgs,
{
kind: 'struct',
fields: [
['instruction', 'u8'],
['uri', 'string'],
[
'nonUniqueSpecificUpdateAuthority',
{ kind: 'option', type: 'pubkey' },
],
],
},
],
[
TransferUpdateAuthorityArgs,
{
kind: 'struct',
fields: [['instruction', 'u8']],
},
],
[
CreateMasterEditionArgs,
{
kind: 'struct',
fields: [
['instruction', 'u8'],
['maxSupply', { kind: 'option', type: 'u64' }],
],
},
],
[
MasterEdition,
{
kind: 'struct',
fields: [
['key', 'u8'],
['supply', 'u64'],
['maxSupply', { kind: 'option', type: 'u64' }],
['masterMint', 'pubkey'],
],
},
],
[
Edition,
{
kind: 'struct',
fields: [
['key', 'u8'],
['parent', 'pubkey'],
['edition', 'u64'],
],
},
],
[
Metadata,
{
kind: 'struct',
fields: [
['key', 'u8'],
[
'nonUniqueSpecificUpdateAuthority',
{ kind: 'option', type: 'pubkey' },
],
['mint', 'pubkey'],
['name', 'string'],
['symbol', 'string'],
['uri', 'string'],
],
},
],
[
NameSymbolTuple,
{
kind: 'struct',
fields: [
['key', 'u8'],
['updateAuthority', 'pubkey'],
['metadata', 'pubkey'],
],
},
],
]);
export const decodeMetadata = async (buffer: Buffer): Promise<Metadata> => {
const metadata = deserializeBorsh(
METADATA_SCHEMA,
Metadata,
buffer,
) as Metadata;
metadata.nameSymbolTuple = await getNameSymbol(metadata);
metadata.edition = await getEdition(metadata.mint);
metadata.masterEdition = await getEdition(metadata.mint);
return metadata;
};
export const decodeEdition = (buffer: Buffer) => {
return deserializeBorsh(METADATA_SCHEMA, Edition, buffer) as Edition;
};
export const decodeMasterEdition = (buffer: Buffer) => {
return deserializeBorsh(
METADATA_SCHEMA,
MasterEdition,
buffer,
) as MasterEdition;
};
export const decodeNameSymbolTuple = (buffer: Buffer) => {
return deserializeBorsh(
METADATA_SCHEMA,
NameSymbolTuple,
buffer,
) as NameSymbolTuple;
};
export async function transferUpdateAuthority(
account: PublicKey,
currentUpdateAuthority: PublicKey,
newUpdateAuthority: PublicKey,
instructions: TransactionInstruction[],
) {
const metadataProgramId = programIds().metadata;
const data = Buffer.from(
serialize(METADATA_SCHEMA, new TransferUpdateAuthorityArgs()),
);
const keys = [
{
pubkey: account,
isSigner: false,
isWritable: true,
},
{
pubkey: currentUpdateAuthority,
isSigner: true,
isWritable: false,
},
{
pubkey: newUpdateAuthority,
isSigner: false,
isWritable: false,
},
];
instructions.push(
new TransactionInstruction({
keys,
programId: metadataProgramId,
data: data,
}),
);
}
export async function updateMetadata(
symbol: string,
name: string,
uri: string,
newNonUniqueSpecificUpdateAuthority: string | undefined,
mintKey: PublicKey,
updateAuthority: PublicKey,
instructions: TransactionInstruction[],
metadataAccount?: PublicKey,
nameSymbolAccount?: PublicKey,
) {
const metadataProgramId = programIds().metadata;
metadataAccount =
metadataAccount ||
(
await PublicKey.findProgramAddress(
[
Buffer.from('metadata'),
metadataProgramId.toBuffer(),
mintKey.toBuffer(),
],
metadataProgramId,
)
)[0];
nameSymbolAccount =
nameSymbolAccount ||
(
await PublicKey.findProgramAddress(
[
Buffer.from('metadata'),
metadataProgramId.toBuffer(),
Buffer.from(name),
Buffer.from(symbol),
],
metadataProgramId,
)
)[0];
const value = new UpdateMetadataArgs({
uri,
nonUniqueSpecificUpdateAuthority: !newNonUniqueSpecificUpdateAuthority
? undefined
: newNonUniqueSpecificUpdateAuthority,
});
const data = Buffer.from(serialize(METADATA_SCHEMA, value));
const keys = [
{
pubkey: metadataAccount,
isSigner: false,
isWritable: true,
},
{
pubkey: updateAuthority,
isSigner: true,
isWritable: false,
},
{
pubkey: nameSymbolAccount,
isSigner: false,
isWritable: false,
},
];
instructions.push(
new TransactionInstruction({
keys,
programId: metadataProgramId,
data,
}),
);
return [metadataAccount, nameSymbolAccount];
}
export async function createMetadata(
symbol: string,
name: string,
uri: string,
allowDuplicates: boolean,
updateAuthority: PublicKey,
mintKey: PublicKey,
mintAuthorityKey: PublicKey,
instructions: TransactionInstruction[],
payer: PublicKey,
) {
const metadataProgramId = programIds().metadata;
const metadataAccount = (
await PublicKey.findProgramAddress(
[
Buffer.from('metadata'),
metadataProgramId.toBuffer(),
mintKey.toBuffer(),
],
metadataProgramId,
)
)[0];
const nameSymbolAccount = (
await PublicKey.findProgramAddress(
[
Buffer.from('metadata'),
metadataProgramId.toBuffer(),
Buffer.from(name),
Buffer.from(symbol),
],
metadataProgramId,
)
)[0];
const value = new CreateMetadataArgs({ name, symbol, uri, allowDuplicates });
const data = Buffer.from(serialize(METADATA_SCHEMA, value));
const keys = [
{
pubkey: nameSymbolAccount,
isSigner: false,
isWritable: true,
},
{
pubkey: metadataAccount,
isSigner: false,
isWritable: true,
},
{
pubkey: mintKey,
isSigner: false,
isWritable: false,
},
{
pubkey: mintAuthorityKey,
isSigner: true,
isWritable: false,
},
{
pubkey: payer,
isSigner: true,
isWritable: false,
},
{
pubkey: updateAuthority,
isSigner: false,
isWritable: false,
},
{
pubkey: SystemProgram.programId,
isSigner: false,
isWritable: false,
},
{
pubkey: SYSVAR_RENT_PUBKEY,
isSigner: false,
isWritable: false,
},
];
instructions.push(
new TransactionInstruction({
keys,
programId: metadataProgramId,
data,
}),
);
return [metadataAccount, nameSymbolAccount];
}
export async function createMasterEdition(
name: string,
symbol: string,
maxSupply: BN | undefined,
mintKey: PublicKey,
masterMintKey: PublicKey,
updateAuthorityKey: PublicKey,
mintAuthorityKey: PublicKey,
instructions: TransactionInstruction[],
payer: PublicKey,
) {
const metadataProgramId = programIds().metadata;
const metadataAccount = (
await PublicKey.findProgramAddress(
[
Buffer.from(METADATA_PREFIX),
metadataProgramId.toBuffer(),
mintKey.toBuffer(),
],
metadataProgramId,
)
)[0];
const nameSymbolAccount = (
await PublicKey.findProgramAddress(
[
Buffer.from(METADATA_PREFIX),
metadataProgramId.toBuffer(),
Buffer.from(name),
Buffer.from(symbol),
],
metadataProgramId,
)
)[0];
const editionAccount = (
await PublicKey.findProgramAddress(
[
Buffer.from(METADATA_PREFIX),
metadataProgramId.toBuffer(),
mintKey.toBuffer(),
Buffer.from(EDITION),
],
metadataProgramId,
)
)[0];
const value = new CreateMasterEditionArgs({ maxSupply: maxSupply || null });
const data = Buffer.from(serialize(METADATA_SCHEMA, value));
const keys = [
{
pubkey: editionAccount,
isSigner: false,
isWritable: true,
},
{
pubkey: mintKey,
isSigner: false,
isWritable: true,
},
{
pubkey: masterMintKey,
isSigner: false,
isWritable: false,
},
{
pubkey: updateAuthorityKey,
isSigner: true,
isWritable: false,
},
{
pubkey: mintAuthorityKey,
isSigner: true,
isWritable: false,
},
{
pubkey: metadataAccount,
isSigner: false,
isWritable: false,
},
{
pubkey: nameSymbolAccount,
isSigner: false,
isWritable: false,
},
{
pubkey: payer,
isSigner: true,
isWritable: false,
},
{
pubkey: programIds().token,
isSigner: false,
isWritable: false,
},
{
pubkey: SystemProgram.programId,
isSigner: false,
isWritable: false,
},
{
pubkey: SYSVAR_RENT_PUBKEY,
isSigner: false,
isWritable: false,
},
];
instructions.push(
new TransactionInstruction({
keys,
programId: metadataProgramId,
data,
}),
);
}
export async function mintNewEditionFromMasterEditionViaToken(
newMint: PublicKey,
tokenMint: PublicKey,
newMintAuthority: PublicKey,
masterMint: PublicKey,
authorizationTokenHoldingAccount: PublicKey,
burnAuthority: PublicKey,
updateAuthorityOfMaster: PublicKey,
instructions: TransactionInstruction[],
payer: PublicKey,
) {
const metadataProgramId = programIds().metadata;
const newMetadataKey = await getMetadata(newMint);
const masterMetadataKey = await getMetadata(tokenMint);
const newEdition = await getEdition(newMint);
const masterEdition = await getEdition(tokenMint);
const data = Buffer.from([5]);
const keys = [
{
pubkey: newMetadataKey,
isSigner: false,
isWritable: true,
},
{
pubkey: newEdition,
isSigner: false,
isWritable: true,
},
{
pubkey: masterEdition,
isSigner: false,
isWritable: true,
},
{
pubkey: newMint,
isSigner: false,
isWritable: true,
},
{
pubkey: newMintAuthority,
isSigner: true,
isWritable: false,
},
{
pubkey: masterMint,
isSigner: false,
isWritable: true,
},
{
pubkey: authorizationTokenHoldingAccount,
isSigner: false,
isWritable: true,
},
{
pubkey: burnAuthority,
isSigner: true,
isWritable: false,
},
{
pubkey: payer,
isSigner: true,
isWritable: false,
},
{
pubkey: updateAuthorityOfMaster,
isSigner: false,
isWritable: false,
},
{
pubkey: masterMetadataKey,
isSigner: false,
isWritable: false,
},
{
pubkey: programIds().token,
isSigner: false,
isWritable: false,
},
{
pubkey: SystemProgram.programId,
isSigner: false,
isWritable: false,
},
{
pubkey: SYSVAR_RENT_PUBKEY,
isSigner: false,
isWritable: false,
},
];
instructions.push(
new TransactionInstruction({
keys,
programId: metadataProgramId,
data,
}),
);
}
export async function getNameSymbol(metadata: Metadata): Promise<PublicKey> {
const PROGRAM_IDS = programIds();
return (
await PublicKey.findProgramAddress(
[
Buffer.from(METADATA_PREFIX),
PROGRAM_IDS.metadata.toBuffer(),
metadata.mint.toBuffer(),
Buffer.from(metadata.name),
Buffer.from(metadata.symbol),
],
PROGRAM_IDS.metadata,
)
)[0];
}
export async function getEdition(tokenMint: PublicKey): Promise<PublicKey> {
const PROGRAM_IDS = programIds();
return (
await PublicKey.findProgramAddress(
[
Buffer.from(METADATA_PREFIX),
PROGRAM_IDS.metadata.toBuffer(),
tokenMint.toBuffer(),
Buffer.from(EDITION),
],
PROGRAM_IDS.metadata,
)
)[0];
}
export async function getMetadata(tokenMint: PublicKey): Promise<PublicKey> {
const PROGRAM_IDS = programIds();
return (
await PublicKey.findProgramAddress(
[
Buffer.from(METADATA_PREFIX),
PROGRAM_IDS.metadata.toBuffer(),
tokenMint.toBuffer(),
],
PROGRAM_IDS.metadata,
)
)[0];
} | the_stack |
import { Yok } from "../lib/common/yok";
import * as stubs from "./stubs";
import { PackageManager } from "../lib/package-manager";
import { PackageInstallationManager } from "../lib/package-installation-manager";
import { NodePackageManager } from "../lib/node-package-manager";
import { YarnPackageManager } from "../lib/yarn-package-manager";
import { PnpmPackageManager } from "../lib/pnpm-package-manager";
import { ProjectData } from "../lib/project-data";
import { ChildProcess } from "../lib/common/child-process";
import { Options } from "../lib/options";
import { CommandsService } from "../lib/common/services/commands-service";
import { StaticConfig } from "../lib/config";
import { HostInfo } from "../lib/common/host-info";
import { Errors } from "../lib/common/errors";
import { PlatformsDataService } from "../lib/services/platforms-data-service";
import { ProjectDataService } from "../lib/services/project-data-service";
import { ProjectFilesManager } from "../lib/common/services/project-files-manager";
import { ResourceLoader } from "../lib/common/resource-loader";
import { PluginsService } from "../lib/services/plugins-service";
import { AddPluginCommand } from "../lib/commands/plugin/add-plugin";
import { MessagesService } from "../lib/common/services/messages-service";
import { NodeModulesBuilder } from "../lib/tools/node-modules/node-modules-builder";
import { AndroidProjectService } from "../lib/services/android-project-service";
import { AndroidToolsInfo } from "../lib/android-tools-info";
import { assert } from "chai";
import { LocalToDevicePathDataFactory } from "../lib/common/mobile/local-to-device-path-data-factory";
import { MobileHelper } from "../lib/common/mobile/mobile-helper";
import { ProjectFilesProvider } from "../lib/providers/project-files-provider";
import { DevicePlatformsConstants } from "../lib/common/mobile/device-platforms-constants";
import { XmlValidator } from "../lib/xml-validator";
import { SettingsService } from "../lib/common/test/unit-tests/stubs";
import StaticConfigLib = require("../lib/config");
import * as path from "path";
import * as temp from "temp";
import * as _ from "lodash";
import { PLUGINS_BUILD_DATA_FILENAME, PlatformTypes } from "../lib/constants"; // PACKAGE_JSON_FILE_NAME, CONFIG_FILE_NAME_JS, CONFIG_FILE_NAME_TS
import { GradleCommandService } from "../lib/services/android/gradle-command-service";
import { GradleBuildService } from "../lib/services/android/gradle-build-service";
import { GradleBuildArgsService } from "../lib/services/android/gradle-build-args-service";
import * as util from "util";
import { IPluginData, IPluginsService } from "../lib/definitions/plugins";
import { IProjectData } from "../lib/definitions/project";
import { IStringDictionary } from "../lib/common/declarations";
import { IInjector } from "../lib/common/definitions/yok";
import {
IEventActionData,
IGoogleAnalyticsData,
} from "../lib/common/definitions/google-analytics";
// import { ProjectConfigService } from "../lib/services/project-config-service";
import { FileSystem } from "../lib/common/file-system";
import { ProjectHelper } from "../lib/common/project-helper";
// import { basename } from 'path';
temp.track();
let isErrorThrown = false;
interface ITestCase {
testName: string;
inputDependencies: any[];
expectedOutput: any[] | Error;
expectedWarning?: string;
}
function createTestInjector() {
const testInjector = new Yok();
testInjector.register("messagesService", MessagesService);
testInjector.register("userSettingsService", {
getSettingValue: async (settingName: string): Promise<void> => undefined,
});
testInjector.register("packageManager", PackageManager);
testInjector.register(
"projectConfigService",
stubs.PackageInstallationManagerStub
);
testInjector.register("npm", NodePackageManager);
testInjector.register("yarn", YarnPackageManager);
testInjector.register("pnpm", PnpmPackageManager);
testInjector.register("fs", FileSystem);
// const fileSystemStub = new stubs.FileSystemStub();
// fileSystemStub.exists = (fileName: string) => {
// if (fileName.indexOf('nativescript.config.ts')) {
// return false;
// }
// return true;
// };
// fileSystemStub.readText = (filename: string, encoding?: IReadFileOptions | string): string => {
// if (filename.indexOf("package.json") > -1) {
// return `{}`; //packageJsonContent;
// } else if (filename.indexOf(CONFIG_FILE_NAME_JS) > -1) {
// return `module.exports = {}`;
// } else if (filename.indexOf(CONFIG_FILE_NAME_TS) > -1) {
// return `export default {}`;
// }
// };
// testInjector.register("fs", fileSystemStub);
testInjector.register("adb", {});
testInjector.register("androidDebugBridgeResultHandler", {});
testInjector.register("projectData", ProjectData);
testInjector.register("platforsmData", stubs.NativeProjectDataStub);
testInjector.register("childProcess", ChildProcess);
testInjector.register("platformsDataService", PlatformsDataService);
testInjector.register("androidEmulatorServices", {});
testInjector.register("androidToolsInfo", AndroidToolsInfo);
testInjector.register("sysInfo", {});
testInjector.register("androidProjectService", AndroidProjectService);
testInjector.register("iOSProjectService", {});
testInjector.register("devicesService", {});
testInjector.register("projectDataService", ProjectDataService);
testInjector.register("prompter", {});
testInjector.register("resources", ResourceLoader);
testInjector.register("nodeModulesBuilder", NodeModulesBuilder);
testInjector.register("options", Options);
testInjector.register("errors", Errors);
testInjector.register("logger", stubs.LoggerStub);
testInjector.register("staticConfig", StaticConfig);
testInjector.register("hooksService", stubs.HooksServiceStub);
testInjector.register("optionsTracker", {
trackOptions: () => Promise.resolve(null),
});
testInjector.register("commandsService", CommandsService);
testInjector.register("hostInfo", HostInfo);
testInjector.register("projectHelper", ProjectHelper);
testInjector.register("pluginsService", PluginsService);
testInjector.register("analyticsService", {
trackException: () => {
return Promise.resolve();
},
checkConsent: () => {
return Promise.resolve();
},
trackFeature: () => {
return Promise.resolve();
},
trackEventActionInGoogleAnalytics: (data: IEventActionData) =>
Promise.resolve(),
trackInGoogleAnalytics: (data: IGoogleAnalyticsData) => Promise.resolve(),
trackAcceptFeatureUsage: (settings: { acceptTrackFeatureUsage: boolean }) =>
Promise.resolve(),
});
testInjector.register("projectFilesManager", ProjectFilesManager);
testInjector.register("pluginVariablesService", {
savePluginVariablesInProjectFile: (pluginData: IPluginData) =>
Promise.resolve(),
interpolatePluginVariables: (
pluginData: IPluginData,
pluginConfigurationFileContent: string
) => Promise.resolve(pluginConfigurationFileContent),
});
testInjector.register(
"packageInstallationManager",
PackageInstallationManager
);
testInjector.register(
"localToDevicePathDataFactory",
LocalToDevicePathDataFactory
);
testInjector.register("mobileHelper", MobileHelper);
testInjector.register("projectFilesProvider", ProjectFilesProvider);
testInjector.register("devicePlatformsConstants", DevicePlatformsConstants);
testInjector.register("projectTemplatesService", {
defaultTemplate: Promise.resolve(""),
});
testInjector.register("xmlValidator", XmlValidator);
testInjector.register("config", StaticConfigLib.Configuration);
testInjector.register("helpService", {
showCommandLineHelp: async (): Promise<void> => undefined,
});
testInjector.register("settingsService", SettingsService);
testInjector.register("httpClient", {});
testInjector.register("extensibilityService", {});
testInjector.register(
"androidPluginBuildService",
stubs.AndroidPluginBuildServiceStub
);
testInjector.register("analyticsSettingsService", {
getPlaygroundInfo: () => Promise.resolve(null),
});
testInjector.register(
"androidResourcesMigrationService",
stubs.AndroidResourcesMigrationServiceStub
);
testInjector.register("platformEnvironmentRequirements", {});
testInjector.register("filesHashService", {
hasChangesInShasums: (
oldPluginNativeHashes: IStringDictionary,
currentPluginNativeHashes: IStringDictionary
) => true,
generateHashes: async (files: string[]): Promise<IStringDictionary> => ({}),
});
testInjector.register("pacoteService", {
manifest: async (packageName: string) => {
const projectData = testInjector.resolve("projectData");
const fs = testInjector.resolve("fs");
let result = {};
let packageJsonPath = null;
const packageToInstall = packageName.split("@")[0];
if (fs.exists(packageToInstall)) {
packageJsonPath = path.join(packageName, "package.json");
} else {
packageJsonPath = path.join(
projectData.projectDir,
"node_modules",
packageToInstall,
"package.json"
);
}
if (fs.exists(packageJsonPath)) {
result = fs.readJson(packageJsonPath);
}
return result;
},
extractPackage: async (
packageName: string,
destinationDirectory: string,
options?: IPacoteExtractOptions
): Promise<void> => undefined,
});
testInjector.register("gradleCommandService", GradleCommandService);
testInjector.register("gradleBuildService", GradleBuildService);
testInjector.register("gradleBuildArgsService", GradleBuildArgsService);
testInjector.register("cleanupService", {
setShouldDispose: (shouldDispose: boolean): void => undefined,
});
testInjector.register("nodeModulesDependenciesBuilder", {});
testInjector.register("tempService", stubs.TempServiceStub);
testInjector.register(
"projectConfigService",
stubs.ProjectConfigServiceStub.initWithConfig({
id: "org.nativescript.Test",
})
);
return testInjector;
}
function createProjectFile(testInjector: IInjector): string {
const fs = testInjector.resolve("fs") as FileSystem;
const tempFolder = temp.mkdirSync("pluginsService");
const options = testInjector.resolve("options");
options.path = tempFolder;
const packageJsonData = {
name: "testModuleName",
description: "@nativescript/core", // important for project file checks - currently just looking for the @nativescript/core keyword
version: "0.1.0",
devDependencies: {
"tns-android": "1.4.0",
},
// "nativescript": {
// "id": "org.nativescript.Test",
// "tns-android": {
// "version": "1.4.0"
// }
// }
};
fs.writeJson(path.join(tempFolder, "package.json"), packageJsonData);
// fs.writeFile(
// path.join(tempFolder, CONFIG_FILE_NAME_TS),
// `export default { id: 'org.nativescript.Test' }`
// );
return tempFolder;
}
function mockBeginCommand(
testInjector: IInjector,
expectedErrorMessage: string
) {
const errors = testInjector.resolve("errors");
errors.beginCommand = async (
action: () => Promise<boolean>
): Promise<boolean> => {
try {
return await action();
} catch (err) {
// await new Promise(resolve => setTimeout(resolve, 100000));
isErrorThrown = true;
assert.equal(err.toString(), expectedErrorMessage);
}
};
}
async function addPluginWhenExpectingToFail(
testInjector: IInjector,
plugin: string,
expectedErrorMessage: string,
command?: string
) {
createProjectFile(testInjector);
const pluginsService: IPluginsService = testInjector.resolve(
"pluginsService"
);
pluginsService.getAllInstalledPlugins = async (projectData: IProjectData) => {
return <any[]>[{ name: "" }];
};
pluginsService.ensureAllDependenciesAreInstalled = () => {
return Promise.resolve();
};
mockBeginCommand(testInjector, "Exception: " + expectedErrorMessage);
isErrorThrown = false;
const commandsService = testInjector.resolve(CommandsService);
await commandsService.tryExecuteCommand(`plugin|${command}`, [plugin]);
assert.isTrue(isErrorThrown);
}
describe("Plugins service", () => {
let testInjector: IInjector;
const commands = ["add", "install"];
beforeEach(() => {
testInjector = createTestInjector();
testInjector.registerCommand("plugin|add", AddPluginCommand);
testInjector.registerCommand("plugin|install", AddPluginCommand);
});
_.each(commands, (command) => {
describe(`plugin ${command}`, () => {
it("fails when no param is specified to plugin install command", async () => {
await addPluginWhenExpectingToFail(
testInjector,
null,
"You must specify plugin name.",
command
);
});
it("fails when invalid nativescript plugin name is specified", async () => {
await addPluginWhenExpectingToFail(
testInjector,
"lodash",
"lodash is not a valid NativeScript plugin. Verify that the plugin package.json file contains a nativescript key and try again.",
command
);
});
it("fails when the plugin is already installed", async () => {
const pluginName = "plugin1";
const projectFolder = createProjectFile(testInjector);
const fs = testInjector.resolve("fs");
// Add plugin
const projectFilePath = path.join(projectFolder, "package.json");
const projectData = require(projectFilePath);
projectData.dependencies = {};
projectData.dependencies[pluginName] = "^1.0.0";
fs.writeJson(projectFilePath, projectData);
const pluginsService: IPluginsService = testInjector.resolve(
"pluginsService"
);
pluginsService.getAllInstalledPlugins = async (
projData: IProjectData
) => {
return <any[]>[{ name: "plugin1" }];
};
mockBeginCommand(
testInjector,
"Exception: " + 'Plugin "plugin1" is already installed.'
);
isErrorThrown = false;
const commandsService = testInjector.resolve(CommandsService);
await commandsService.tryExecuteCommand(`plugin|${command}`, [
pluginName,
]);
assert.isTrue(isErrorThrown);
});
it("fails when the plugin does not support the installed framework", async () => {
let isWarningMessageShown = false;
const expectedWarningMessage =
"mySamplePlugin requires at least version 1.5.0 of platform android. Currently installed version is 1.4.0.";
// Creates plugin in temp folder
const pluginName = "mySamplePlugin";
const projectFolder = createProjectFile(testInjector);
const pluginFolderPath = path.join(projectFolder, pluginName);
const pluginJsonData = {
name: pluginName,
version: "0.0.1",
nativescript: {
platforms: {
android: "1.5.0",
},
},
};
const fs = testInjector.resolve("fs");
fs.writeJson(
path.join(pluginFolderPath, "package.json"),
pluginJsonData
);
// Adds android platform
fs.createDirectory(path.join(projectFolder, "platforms"));
fs.createDirectory(path.join(projectFolder, "platforms", "android"));
fs.createDirectory(
path.join(projectFolder, "platforms", "android", "app")
);
// Mock logger.warn
const logger = testInjector.resolve("logger");
logger.warn = (message: string) => {
assert.equal(message, expectedWarningMessage);
isWarningMessageShown = true;
};
// Mock pluginsService
const pluginsService: IPluginsService = testInjector.resolve(
"pluginsService"
);
const projectData: IProjectData = testInjector.resolve("projectData");
projectData.initializeProjectData();
pluginsService.getAllInstalledPlugins = async (
projData: IProjectData
) => {
return <any[]>[{ name: "" }];
};
// Mock platformsDataService
const platformsDataService = testInjector.resolve(
"platformsDataService"
);
platformsDataService.getPlatformData = (platform: string) => {
return {
appDestinationDirectoryPath: path.join(
projectFolder,
"platforms",
"android"
),
frameworkPackageName: "tns-android",
normalizedPlatformName: "Android",
};
};
const projectDataService = testInjector.resolve("projectDataService");
projectDataService.getRuntimePackage = (
projectDir: string,
platform: PlatformTypes
) => {
return {
name: "tns-android",
version: "1.4.0",
};
};
await pluginsService.add(pluginFolderPath, projectData);
assert.isTrue(isWarningMessageShown);
});
it("adds plugin by name", async () => {
const pluginName = "plugin1";
const projectFolder = createProjectFile(testInjector);
const pluginsService: IPluginsService = testInjector.resolve(
"pluginsService"
);
pluginsService.getAllInstalledPlugins = async (
projectData: IProjectData
) => {
return <any[]>[{ name: "" }];
};
const commandsService = testInjector.resolve(CommandsService);
await commandsService.tryExecuteCommand(`plugin|${command}`, [
pluginName,
]);
const fs = testInjector.resolve("fs");
// Asserts that the all plugin's content is successfully added to node_modules folder
const nodeModulesFolderPath = path.join(projectFolder, "node_modules");
assert.isTrue(fs.exists(nodeModulesFolderPath));
const pluginFolderPath = path.join(nodeModulesFolderPath, pluginName);
assert.isTrue(fs.exists(pluginFolderPath));
const pluginFiles = ["injex.js", "main.js", "package.json"];
_.each(pluginFiles, (pluginFile) => {
assert.isTrue(fs.exists(path.join(pluginFolderPath, pluginFile)));
});
// Asserts that the plugin is added in package.json file
const packageJsonContent = fs.readJson(
path.join(projectFolder, "package.json")
);
const actualDependencies = packageJsonContent.dependencies;
const expectedDependencies = { plugin1: "^1.0.3" };
const expectedDependenciesExact = { plugin1: "1.0.3" };
assert.isTrue(
_.isEqual(actualDependencies, expectedDependencies) ||
_.isEqual(actualDependencies, expectedDependenciesExact)
);
});
it("adds plugin by name and version", async () => {
const pluginName = "plugin1";
const projectFolder = createProjectFile(testInjector);
const pluginsService: IPluginsService = testInjector.resolve(
"pluginsService"
);
pluginsService.getAllInstalledPlugins = async (
projectData: IProjectData
) => {
return <any[]>[{ name: "" }];
};
const commandsService = testInjector.resolve(CommandsService);
await commandsService.tryExecuteCommand(`plugin|${command}`, [
pluginName + "@1.0.0",
]);
const fs = testInjector.resolve("fs");
// Assert that the all plugin's content is successfully added to node_modules folder
const nodeModulesFolderPath = path.join(projectFolder, "node_modules");
assert.isTrue(fs.exists(nodeModulesFolderPath));
const pluginFolderPath = path.join(nodeModulesFolderPath, pluginName);
assert.isTrue(fs.exists(pluginFolderPath));
const pluginFiles = ["injex.js", "main.js", "package.json"];
_.each(pluginFiles, (pluginFile) => {
assert.isTrue(fs.exists(path.join(pluginFolderPath, pluginFile)));
});
// Assert that the plugin is added in package.json file
const packageJsonContent = fs.readJson(
path.join(projectFolder, "package.json")
);
const actualDependencies = packageJsonContent.dependencies;
const expectedDependencies = { plugin1: "^1.0.0" };
const expectedDependenciesExact = { plugin1: "1.0.0" };
assert.isTrue(
_.isEqual(actualDependencies, expectedDependencies) ||
_.isEqual(actualDependencies, expectedDependenciesExact)
);
});
it("adds plugin by local path", async () => {
// Creates a plugin in tempFolder
const pluginName = "mySamplePlugin";
const projectFolder = createProjectFile(testInjector);
const pluginFolderPath = path.join(projectFolder, pluginName);
const pluginJsonData = {
name: pluginName,
version: "0.0.1",
nativescript: {
platforms: {},
},
};
const fs = testInjector.resolve("fs");
fs.writeJson(
path.join(pluginFolderPath, "package.json"),
pluginJsonData
);
const pluginsService: IPluginsService = testInjector.resolve(
"pluginsService"
);
pluginsService.getAllInstalledPlugins = async (
projectData: IProjectData
) => {
return <any[]>[{ name: "" }];
};
const commandsService = testInjector.resolve(CommandsService);
await commandsService.tryExecuteCommand(`plugin|${command}`, [
pluginFolderPath,
]);
// Assert that the all plugin's content is successfully added to node_modules folder
const nodeModulesFolderPath = path.join(projectFolder, "node_modules");
assert.isTrue(fs.exists(nodeModulesFolderPath));
assert.isTrue(fs.exists(path.join(nodeModulesFolderPath, pluginName)));
const pluginFiles = ["package.json"];
_.each(pluginFiles, (pluginFile) => {
assert.isTrue(
fs.exists(path.join(nodeModulesFolderPath, pluginName, pluginFile))
);
});
});
it("adds plugin by github url", () => {
// TODO: add test
});
it("doesn't install dev dependencies when --production option is specified", async () => {
// Creates a plugin in tempFolder
const pluginName = "mySamplePlugin";
const projectFolder = createProjectFile(testInjector);
const pluginFolderPath = path.join(projectFolder, pluginName);
const pluginJsonData = {
name: pluginName,
version: "0.0.1",
nativescript: {
platforms: {},
},
devDependencies: {
grunt: "0.4.2",
},
};
const fs = testInjector.resolve("fs");
fs.writeJson(
path.join(pluginFolderPath, "package.json"),
pluginJsonData
);
const pluginsService: IPluginsService = testInjector.resolve(
"pluginsService"
);
pluginsService.getAllInstalledPlugins = async (
projectData: IProjectData
) => {
return <any[]>[{ name: "" }];
};
// Mock options
const options = testInjector.resolve("options");
options.production = true;
const commandsService = testInjector.resolve(CommandsService);
await commandsService.tryExecuteCommand(`plugin|${command}`, [
pluginFolderPath,
]);
const nodeModulesFolderPath = path.join(projectFolder, "node_modules");
assert.isFalse(
fs.exists(
path.join(
nodeModulesFolderPath,
pluginName,
"node_modules",
"grunt"
)
)
);
});
it("install dev dependencies when --production option is not specified", async () => {
// Creates a plugin in tempFolder
const pluginName = "mySamplePlugin";
const projectFolder = createProjectFile(testInjector);
const pluginFolderPath = path.join(projectFolder, pluginName);
const pluginJsonData = {
name: pluginName,
version: "0.0.1",
nativescript: {
platforms: {},
},
dependencies: {
lodash: "3.8.0",
},
devDependencies: {
grunt: "0.4.2",
},
};
const fs = testInjector.resolve("fs");
fs.writeJson(
path.join(pluginFolderPath, "package.json"),
pluginJsonData
);
const pluginsService: IPluginsService = testInjector.resolve(
"pluginsService"
);
pluginsService.getAllInstalledPlugins = async (
projectData: IProjectData
) => {
return <any[]>[{ name: "" }];
};
// Mock options
const options = testInjector.resolve("options");
options.production = false;
const commandsService = testInjector.resolve(CommandsService);
await commandsService.tryExecuteCommand(`plugin|${command}`, [
pluginFolderPath,
]);
});
});
});
describe("preparePluginNativeCode", () => {
const setupTest = (opts: {
hasChangesInShasums?: boolean;
newPluginHashes?: IStringDictionary;
buildDataFileExists?: boolean;
hasPluginPlatformsDir?: boolean;
}): any => {
const testData: any = {
pluginsService: null,
isPreparePluginNativeCodeCalled: false,
dataPassedToWriteJson: null,
};
const unitTestsInjector = new Yok();
unitTestsInjector.register("platformsDataService", {
getPlatformData: (_platform: string, pData: IProjectData) => ({
projectRoot: "projectRoot",
platformProjectService: {
preparePluginNativeCode: async (
pluginData: IPluginData,
projData: IProjectData
) => {
testData.isPreparePluginNativeCodeCalled = true;
},
},
normalizedPlatformName: "iOS",
}),
});
const pluginHashes = opts.newPluginHashes || { file1: "hash1" };
const samplePluginData: IPluginData = <any>{
fullPath: "plugin_full_path",
name: "plugin_name",
pluginPlatformsFolderPath: (_platform: string) =>
path.join("plugin_dir", "platforms", _platform.toLowerCase()),
};
unitTestsInjector.register("filesHashService", {
hasChangesInShasums: (
oldPluginNativeHashes: IStringDictionary,
currentPluginNativeHashes: IStringDictionary
) => !!opts.hasChangesInShasums,
generateHashes: async (files: string[]): Promise<IStringDictionary> =>
pluginHashes,
});
unitTestsInjector.register("fs", {
exists: (file: string) => {
if (file.indexOf(PLUGINS_BUILD_DATA_FILENAME) !== -1) {
return !!opts.buildDataFileExists;
}
if (file.indexOf("platforms") !== -1) {
return !!opts.hasPluginPlatformsDir;
}
return true;
},
readJson: (file: string) => ({
[samplePluginData.name]: pluginHashes,
}),
writeJson: (file: string, json: any) => {
testData.dataPassedToWriteJson = json;
},
enumerateFilesInDirectorySync: (): string[] => ["some_file"],
});
unitTestsInjector.register("packageManager", {});
unitTestsInjector.register("options", {});
unitTestsInjector.register("logger", {});
unitTestsInjector.register("errors", {});
unitTestsInjector.register("injector", unitTestsInjector);
unitTestsInjector.register("mobileHelper", MobileHelper);
unitTestsInjector.register(
"devicePlatformsConstants",
DevicePlatformsConstants
);
unitTestsInjector.register("nodeModulesDependenciesBuilder", {});
unitTestsInjector.register("tempService", stubs.TempServiceStub);
const pluginsService: PluginsService = unitTestsInjector.resolve(
PluginsService
);
testData.pluginsService = pluginsService;
testData.pluginData = samplePluginData;
return testData;
};
const platform = "platform";
const projectData: IProjectData = <any>{};
it("does not prepare the files when plugin does not have platforms dir", async () => {
const testData = setupTest({ hasPluginPlatformsDir: false });
await testData.pluginsService.preparePluginNativeCode({
pluginData: testData.pluginData,
platform,
projectData,
});
assert.isFalse(testData.isPreparePluginNativeCodeCalled);
});
it("prepares the files when plugin has platforms dir and has not been built before", async () => {
const newPluginHashes = { file: "hash" };
const testData = setupTest({
newPluginHashes,
hasPluginPlatformsDir: true,
});
await testData.pluginsService.preparePluginNativeCode({
pluginData: testData.pluginData,
platform,
projectData,
});
assert.isTrue(testData.isPreparePluginNativeCodeCalled);
assert.deepStrictEqual(testData.dataPassedToWriteJson, {
[testData.pluginData.name]: newPluginHashes,
});
});
it("does not prepare the files when plugin has platforms dir and files have not changed since then", async () => {
const testData = setupTest({
hasChangesInShasums: false,
buildDataFileExists: true,
hasPluginPlatformsDir: true,
});
await testData.pluginsService.preparePluginNativeCode({
pluginData: testData.pluginData,
platform,
projectData,
});
assert.isFalse(testData.isPreparePluginNativeCodeCalled);
});
});
const createUnitTestsInjector = () => {
const unitTestsInjector = new Yok();
unitTestsInjector.register("platformsDataService", {});
unitTestsInjector.register("filesHashService", {});
unitTestsInjector.register("fs", {
exists: (filePath: string) => filePath.indexOf("ios") !== -1,
readDirectory: (dir: string) =>
dir.indexOf("nativescript-ui-core") !== -1 ? ["a.framework"] : [],
});
unitTestsInjector.register("packageManager", {});
unitTestsInjector.register("options", {});
unitTestsInjector.register("logger", stubs.LoggerStub);
unitTestsInjector.register("errors", stubs.ErrorsStub);
unitTestsInjector.register("injector", unitTestsInjector);
unitTestsInjector.register("mobileHelper", MobileHelper);
unitTestsInjector.register(
"devicePlatformsConstants",
DevicePlatformsConstants
);
unitTestsInjector.register("nodeModulesDependenciesBuilder", {});
unitTestsInjector.register("tempService", stubs.TempServiceStub);
return unitTestsInjector;
};
describe("convertToPluginData", () => {
const pluginDir = "pluginDir";
const dataFromPluginPackageJson = {
name: "name",
version: "1.0.0",
directory: pluginDir,
nativescript: {
platforms: {
ios: "6.0.0",
android: "6.0.0",
},
},
};
it("returns correct pluginData", () => {
const unitTestsInjector = createUnitTestsInjector();
const pluginsService: PluginsService = unitTestsInjector.resolve(
PluginsService
);
const pluginData = (<any>pluginsService).convertToPluginData(
dataFromPluginPackageJson,
"my project dir"
);
// Remove the comparison of a function
delete pluginData["pluginPlatformsFolderPath"];
assert.deepStrictEqual(pluginData, <any>{
name: "name",
version: "1.0.0",
fullPath: pluginDir,
isPlugin: true,
platformsData: { android: "6.0.0", ios: "6.0.0" },
pluginVariables: undefined,
});
});
it("always returns lowercased platform in the path to plugins dir", () => {
const unitTestsInjector = createUnitTestsInjector();
const pluginsService: PluginsService = unitTestsInjector.resolve(
PluginsService
);
const pluginData = (<any>pluginsService).convertToPluginData(
dataFromPluginPackageJson,
"my project dir"
);
const expectediOSPath = path.join(pluginDir, "platforms", "ios");
const expectedAndroidPath = path.join(pluginDir, "platforms", "android");
assert.equal(
pluginData.pluginPlatformsFolderPath("iOS"),
expectediOSPath
);
assert.equal(
pluginData.pluginPlatformsFolderPath("ios"),
expectediOSPath
);
assert.equal(
pluginData.pluginPlatformsFolderPath("IOS"),
expectediOSPath
);
assert.equal(
pluginData.pluginPlatformsFolderPath("Android"),
expectedAndroidPath
);
assert.equal(
pluginData.pluginPlatformsFolderPath("android"),
expectedAndroidPath
);
assert.equal(
pluginData.pluginPlatformsFolderPath("ANDROID"),
expectedAndroidPath
);
});
});
describe("getAllProductionPlugins", () => {
const testCases: ITestCase[] = [
{
testName:
"returns empty array when none of the dependencies is nativescript plugin",
inputDependencies: [
{
name: "css-tree",
directory: "/Users/username/projectDir/node_modules/css-tree",
depth: 0,
version: "1.0.0-alpha.39",
dependencies: ["mdn-data", "source-map"],
},
{
name: "nativescript-hook",
directory:
"/Users/username/projectDir/node_modules/nativescript-hook",
depth: 0,
version: "0.2.5",
dependencies: ["glob", "mkdirp"],
},
],
expectedOutput: <any[]>[],
},
{
testName: "returns correct data when there's no duplication of plugins",
inputDependencies: [
{
name: "tns-core-modules",
directory:
"/Users/username/projectDir/node_modules/tns-core-modules",
depth: 0,
version: "6.3.2",
nativescript: {
platforms: {
ios: "5.0.0",
android: "5.0.0",
},
},
dependencies: ["@nativescript/core"],
},
{
name: "@nativescript/theme",
directory:
"/Users/username/projectDir/node_modules/@nativescript/theme",
depth: 0,
version: "2.2.1",
nativescript: {
platforms: {
android: "6.2.0",
ios: "6.2.0",
},
},
dependencies: [],
},
],
expectedOutput: [
{
fullPath:
"/Users/username/projectDir/node_modules/tns-core-modules",
isPlugin: true,
name: "tns-core-modules",
platformsData: {
android: "5.0.0",
ios: "5.0.0",
},
version: "6.3.2",
},
{
fullPath:
"/Users/username/projectDir/node_modules/@nativescript/theme",
isPlugin: true,
name: "@nativescript/theme",
platformsData: {
android: "6.2.0",
ios: "6.2.0",
},
version: "2.2.1",
},
],
},
{
testName:
"prints warning when same version of plugin is installed multiple times",
inputDependencies: [
{
name: "nativescript-ui-listview",
directory:
"/Users/username/projectDir/node_modules/nativescript-ui-listview",
depth: 0,
version: "8.0.1",
nativescript: {
platforms: {
android: "6.0.0",
ios: "6.0.0",
},
},
dependencies: ["nativescript-ui-core"],
},
{
name: "nativescript-ui-core",
directory:
"/Users/username/projectDir/node_modules/nativescript-ui-core",
depth: 0,
version: "4.0.0",
nativescript: {
platforms: {
android: "6.0.0",
ios: "6.0.0",
},
},
dependencies: [],
},
{
name: "nativescript-ui-core",
directory:
"/Users/username/projectDir/node_modules/nativescript-ui-listview/node_modules/nativescript-ui-core",
depth: 1,
version: "4.0.0",
nativescript: {
platforms: {
android: "6.0.0",
ios: "6.0.0",
},
},
dependencies: [],
},
],
expectedOutput: [
{
fullPath:
"/Users/username/projectDir/node_modules/nativescript-ui-listview",
isPlugin: true,
name: "nativescript-ui-listview",
platformsData: {
android: "6.0.0",
ios: "6.0.0",
},
version: "8.0.1",
},
{
fullPath:
"/Users/username/projectDir/node_modules/nativescript-ui-core",
isPlugin: true,
name: "nativescript-ui-core",
platformsData: {
android: "6.0.0",
ios: "6.0.0",
},
version: "4.0.0",
},
],
expectedWarning:
"Detected the framework a.framework is installed multiple times from the same versions of plugin (4.0.0) at locations: /Users/username/projectDir/node_modules/nativescript-ui-core, " +
"/Users/username/projectDir/node_modules/nativescript-ui-listview/node_modules/nativescript-ui-core",
},
{
testName:
"fails when different versions of the same plugin are detected",
inputDependencies: [
{
name: "nativescript-ui-listview",
directory:
"/Users/username/projectDir/node_modules/nativescript-ui-listview",
depth: 0,
version: "8.0.1",
nativescript: {
platforms: {
android: "6.0.0",
ios: "6.0.0",
},
},
dependencies: ["nativescript-ui-core"],
},
{
name: "nativescript-ui-core",
directory:
"/Users/username/projectDir/node_modules/nativescript-ui-core",
depth: 0,
version: "3.0.0",
nativescript: {
platforms: {
android: "6.0.0",
ios: "6.0.0",
},
},
dependencies: [],
},
{
name: "nativescript-ui-core",
directory:
"/Users/username/projectDir/node_modules/nativescript-ui-listview/node_modules/nativescript-ui-core",
depth: 1,
version: "4.0.0",
nativescript: {
platforms: {
android: "6.0.0",
ios: "6.0.0",
},
},
dependencies: [],
},
],
expectedOutput: new Error(
`Cannot use the same framework a.framework multiple times in your application.
This framework comes from nativescript-ui-core plugin, which is installed multiple times in node_modules:\n` +
"* Path: /Users/username/projectDir/node_modules/nativescript-ui-core, version: 3.0.0\n" +
"* Path: /Users/username/projectDir/node_modules/nativescript-ui-listview/node_modules/nativescript-ui-core, version: 4.0.0\n\n" +
`Probably you need to update your dependencies, remove node_modules and try again.`
),
},
{
testName:
"fails when same framework is installed from multiple plugins",
inputDependencies: [
{
name: "nativescript-ui-core-forked",
directory:
"/Users/username/projectDir/node_modules/nativescript-ui-core-forked",
depth: 0,
version: "3.0.0",
nativescript: {
platforms: {
android: "6.0.0",
ios: "6.0.0",
},
},
dependencies: [],
},
{
name: "nativescript-ui-core",
directory:
"/Users/username/projectDir/node_modules/nativescript-ui-core",
depth: 0,
version: "3.0.0",
nativescript: {
platforms: {
android: "6.0.0",
ios: "6.0.0",
},
},
dependencies: [],
},
],
expectedOutput: new Error(
`Detected the framework a.framework is installed from multiple plugins at locations:\n` +
"/Users/username/projectDir/node_modules/nativescript-ui-core-forked/platforms/ios/a.framework\n".replace(
/\//g,
path.sep
) +
"/Users/username/projectDir/node_modules/nativescript-ui-core/platforms/ios/a.framework\n\n".replace(
/\//g,
path.sep
) +
`Probably you need to update your dependencies, remove node_modules and try again.`
),
},
];
for (const testCase of testCases) {
it(testCase.testName, () => {
const unitTestsInjector: IInjector = createUnitTestsInjector();
const pluginsService: IPluginsService = unitTestsInjector.resolve(
PluginsService
);
if (testCase.expectedOutput instanceof Error) {
assert.throws(
() =>
pluginsService.getAllProductionPlugins(
<any>{ projectDir: "projectDir" },
"ios",
testCase.inputDependencies
),
testCase.expectedOutput.message
);
} else {
const plugins = pluginsService.getAllProductionPlugins(
<any>{ projectDir: "projectDir" },
"ios",
testCase.inputDependencies
);
if (testCase.expectedWarning) {
const logger = unitTestsInjector.resolve<stubs.LoggerStub>(
"logger"
);
assert.equal(testCase.expectedWarning + "\n", logger.warnOutput);
}
for (const plugin of plugins) {
// deepEqual does not compare functions
delete plugin.pluginPlatformsFolderPath;
// pluginVariables is a legacy feature and out of the scope for current tests
delete plugin.pluginVariables;
}
assert.deepStrictEqual(plugins, testCase.expectedOutput);
}
});
}
it(`caches result based on dependencies`, () => {
const unitTestsInjector: IInjector = createUnitTestsInjector();
const pluginsService: IPluginsService = unitTestsInjector.resolve(
PluginsService
);
const inputDependencies = [
{
name: "nativescript-ui-core",
directory:
"/Users/username/projectDir/node_modules/nativescript-ui-core",
depth: 0,
version: "6.3.0",
nativescript: {
platforms: {
ios: "5.0.0",
android: "5.0.0",
},
},
dependencies: ["@nativescript/core"],
},
{
name: "nativescript-ui-core",
directory:
"/Users/username/projectDir/node_modules/some-package/nativescript-ui-core",
depth: 1,
version: "6.3.0",
nativescript: {
platforms: {
ios: "5.0.0",
android: "5.0.0",
},
},
dependencies: ["@nativescript/core"],
},
];
_.range(3).forEach(() => {
pluginsService.getAllProductionPlugins(
<any>{ projectDir: "projectDir" },
"ios",
inputDependencies
);
});
const logger = unitTestsInjector.resolve<stubs.LoggerStub>("logger");
const expectedWarnMessage =
"Detected the framework a.framework is installed multiple times from the same versions of plugin (%s) at locations: /Users/username/projectDir/node_modules/nativescript-ui-core, /Users/username/projectDir/node_modules/some-package/nativescript-ui-core\n";
assert.equal(
logger.warnOutput,
util.format(expectedWarnMessage, "6.3.0"),
"The warn message must be shown only once - the result of the private method must be cached as input dependencies have not changed"
);
inputDependencies[0].version = "1.0.0";
inputDependencies[1].version = "1.0.0";
pluginsService.getAllProductionPlugins(
<any>{ projectDir: "projectDir" },
"ios",
inputDependencies
);
assert.equal(
logger.warnOutput,
util.format(expectedWarnMessage, "6.3.0") +
util.format(expectedWarnMessage, "1.0.0"),
"When something in input dependencies change, the cached value shouldn't be taken into account"
);
});
});
}); | the_stack |
// Work In Progress
/// <reference types="jquery" />
export const DOM: dom.DOMUtils;
export const PluginManager: AddOnManager;
export const ScriptLoader: dom.ScriptLoader;
export const ThemeManager: AddOnManager;
export const EditorManager: EditorManager;
export const baseURL: string;
export const activeEditor: Editor;
export function create(s: string, p: {}, root?: {}): void;
export function createNS(n: string, o: {}): {};
export function each(o: {}, cb: () => void, s?: {}): void;
export function explode(s: string, d: string): void;
export function grep(a: any[], f: () => void): any[];
export function inArray(item: any, arr: any[]): number;
export function is(obj: {}, type?: string): boolean;
export function isArray(obj: {}): boolean;
export function makeMap(items: any[], delim?: string, map?: {}): {};
export function map(array: any[], callback: () => void): any[];
export function resolve(n: string, o?: {}): {};
export function toArray(obj: {}): any[];
export function trim(s: string): string;
export function walk(o: {}, f: () => void, n?: string, s?: string): void;
export function init(settings: Settings): void;
export function triggerSave(): void;
export function get(id: string | number): Editor;
export interface Settings {
base_url?: string;
table_toolbar?: string;
table_appearance_options?: boolean;
table_clone_elements?: string;
table_grid?: boolean;
table_tab_navigation?: boolean;
table_default_attributes?: object | string;
table_default_styles?: object | string;
table_class_list?: object[];
table_cell_class_list?: object[];
table_row_class_list?: object[];
table_advtab?: boolean;
table_cell_advtab?: boolean;
table_row_advtab?: boolean;
auto_focus?: string;
cache_suffix?: string;
content_security_policy?: string;
external_plugins?: {};
hidden_input?: boolean;
paste_data_images?: boolean;
advlist_number_styles?: string;
init_instance_callback?(editor: Editor): void;
plugins?: string | string[];
selector?: string;
setup?(edtor: Editor): void;
target?: Element;
branding?: boolean;
color_picker_callback?(callback: (hexColor: string) => void, value: string): void;
custom_ui_selector?: string;
elementpath?: boolean;
event_root?: boolean;
fixed_toolbar_container?: string;
height?: number | string;
inline?: boolean;
insert_button_items?: string;
insert_toolbar?: string;
max_height?: number;
max_width?: number;
menu?: settings.Menu;
menubar?: string | boolean;
min_height?: number | string;
min_width?: number | string;
preview_styles?: boolean | string;
removed_menuitems?: string;
resize?: boolean | string;
selection_toolbar?: string;
skin_url?: string;
skin?: false | string;
statusbar?: boolean;
theme_url?: string;
theme?: string;
toolbar?: boolean | string | string[];
width?: number | string;
body_class?: string;
body_id?: string;
content_css?: string | string[];
content_style?: string;
inline_boundaries?: boolean;
visual_anchor_class?: string;
visual_table_class?: string;
visual?: boolean;
allow_conditional_comments?: boolean;
allow_html_in_named_anchor?: boolean;
allow_unsafe_link_target?: boolean;
convert_fonts_to_spans?: boolean;
custom_elements?: string;
doctype?: string;
element_format?: string;
encoding?: string;
entities?: string;
entity_encoding?: string;
extended_valid_elements?: string;
fix_list_elements?: boolean;
force_hex_style_colors?: boolean;
forced_root_block?: string;
forced_root_block_attrs?: {};
invalid_elements?: string;
invalid_styles?: string | {};
keep_styles?: boolean;
protect?: RegExp[];
remove_trailing_brs?: boolean;
schema?: string;
valid_children?: string;
valid_classes?: string | {};
valid_elements?: string;
valid_styles?: {};
block_formats?: string;
font_formats?: string;
fontsize_formats?: string;
formats?: {};
removeFormat?: Array<{}>;
indentation?: string;
style_formats?: Array<{}>;
style_formats_autohide?: boolean;
style_formats_merge?: boolean;
browser_spellcheck?: boolean;
gecko_spellcheck?: boolean;
automatic_uploads?: boolean;
file_browser_callback?(field_name: string, url: string, type: string, win: Window): void;
file_browser_callback_types?: string;
file_picker_callback?(callback: (filename: string, metadata: {}) => void, valud: string, meta: {}): void;
file_picker_types?: string;
images_dataimg_filter?(img: any): void;
images_reuse_filename?: boolean;
images_upload_base_path?: string;
images_upload_credentials?: boolean;
images_upload_handler?(blobInfo: any, success: (msg: string) => void, failure: (msg: string) => void): void;
images_upload_url?: string;
directionality?: string;
language?: string;
language_url?: string;
allow_script_urls?: boolean;
convert_urls?: boolean;
document_base_url?: string;
relative_urls?: boolean;
remove_script_host?: boolean;
urlconverter_callback?(url: string, node: HTMLElement, on_save: boolean, name: string): void;
anchor_bottom?: string;
anchor_top?: string;
br_in_pre?: boolean;
custom_undo_redo_levels?: number;
end_container_on_empty_block?: boolean;
nowrap?: boolean;
object_resizing?: boolean | string;
type_ahead_urls?: boolean;
autosave_ask_before_unload?: boolean;
autosave_interval?: string;
autosave_prefix?: string;
autosave_restore_when_empty?: boolean;
autosave_retention?: string;
imagetools_cors_hosts?: string[];
imagetools_proxy?: string;
imagetools_toolbar?: string;
imagetools_api_key?: string;
spellchecker_rpc_url?: string;
spellchecker_language?: string;
spellchecker_languages?: string;
spellchecker_dialog?: boolean;
spellchecker_whitelist?: string[];
spellchecker_on_load?: boolean;
spellchecker_active?: boolean;
}
export namespace settings {
interface Menu {
file?: MenuItem;
edit?: MenuItem;
insert?: MenuItem;
view?: MenuItem;
format?: MenuItem;
table?: MenuItem;
tools?: MenuItem;
}
interface MenuItem {
title: string;
items: string;
}
}
export interface AddOnManager {
add(id: string, addOn: (editor: Editor, url: string) => void): Theme | Plugin;
addComponents(pluginName: string, scripts: string[]): void;
get(name: string): Theme | Plugin;
load(name: string, addOnUrl: string, success?: () => void, scope?: {}, failure?: () => void): void;
requireLangPack(name: string, languages?: string): void;
}
export class Editor extends util.Observable {
constructor(id: string, settings: Settings, editorManager: EditorManager);
$: dom.DomQuery;
baseURI: util.URI;
contentCSS: string[];
contentStyles: string[];
documentBaseURI: util.URI;
dom: dom.DOMUtils;
formatter: Formatter;
id: string;
initialized: boolean;
notificationManager: notificationManager;
parser: html.DomParser;
schema: html.Schema;
selection: dom.Selection;
serializer: dom.Serializer;
settings: Settings;
theme: Theme;
undoManager: UndoManager;
windowManager: WindowManager;
addButton(name: string, settings: {}): void;
addCommand(name: string, callback: (ui: boolean, value: {}) => boolean, scope?: {}): void;
addContextToolbar(predicate: ((el: Node) => boolean) | string, items: string): void;
addMenuItem(name: string, settings: {}): void;
addQueryStateHandler(name: string, callback: () => boolean, scope?: {}): void;
addQueryValueHandler(name: string, callback: () => {}, scope?: {}): void;
addShortcut(pattern: string, desc: string, cmdFunc: string, sc?: {}): boolean;
addSidebar(name: string, settings: {}): void;
addVisual(elm?: Element): void;
convertURL(url: string, name: string, elm: string): string;
destroy(automatic?: boolean): void;
execCallback(name: string): {};
execCommand(cmd: string, ui?: boolean, value?: any, args?: {}): void;
focus(skipFocus: boolean): void;
getBody(): HTMLBodyElement;
getContainer(): Element;
getContent(args?: {}): string;
getContentAreaContainer(): Element;
getDoc(): Document;
getElement(): Element;
getLang(name: string, defaultVal?: string): void;
getParam(name: string, defaultVal?: string, type?: string): string;
getWin(): Window;
hasEventListeners(name: string): boolean;
hide(): void;
init(): void;
insertContent(content: string, args?: {}): void;
isDirty(): boolean;
isHidden(): boolean;
load(args?: {}): string;
nodeChanged(args?: {}): void;
queryCommandState(cmd: string): boolean;
queryCommandSupported(cmd: string): boolean;
queryCommandValue(cmd: string): {};
remove(): void;
render(): void;
save(args: {}): string;
setContent(content: string, args?: {}): string;
setDirty(state: boolean): void;
setMode(mode: string): void;
setProgressState(state: boolean, time: number): boolean;
show(): void;
translate(text: string): string;
uploadImages(callback: () => void): Promise<any>;
}
export interface EditorCommands {
addCommands(command_list: {}, type?: string): void;
execCommand(command: string, ui?: boolean, value?: {}, args?: {}): boolean;
queryCommandState(command: string): boolean | number;
queryCommandSupported(command: string): boolean;
queryCommandValue(command: string): {};
}
export interface EditorManager extends util.Observable {
$: dom.DomQuery;
activeEditor: Editor;
baseURI: util.URI;
baseURL: string;
documentBaseURL: string;
editors: Editor[];
i18n: {};
majorVersion: string;
minorVersion: string;
releaseDate: string;
suffix: string;
add(editor: Editor): Editor;
addI18n(code: string, items: {}): void;
createEditor(id: string, settings: {}): Editor;
execCommand(cmd: string, ui?: boolean, value?: string): boolean;
get(id: string): Editor;
init(settings: Settings): Promise<Editor>;
overrideDefaults(defaultSettings: {}): void;
remove(selector: Editor): Editor;
setActive(editor: Editor): void;
translate(text: string): string;
triggerSave(): void;
}
export interface Env {
android: boolean;
ceFalse: boolean;
contentEditable: boolean;
documentMode: boolean;
fileApi: boolean;
gecko: boolean;
iOS: boolean;
ie: boolean;
mac: boolean;
noCaretAfter: boolean;
opera: boolean;
range: boolean;
transparentSrc: boolean;
webKit: boolean;
}
export namespace Events {
interface Event {
type: string;
target: string;
isDefaultPrevented(): boolean;
isImmediatePropagationStopped(): boolean;
isPropagationStopped(): boolean;
preventDefault(): void;
stopImmediatePropagation(): void;
stopPropagation(): void;
}
interface FocusBlurEvent extends Event {
blurredEditor: Editor;
}
interface ContentEvent extends Event {
format: string;
set: boolean;
content: string;
}
interface ProcessEvent extends Event {
content: string;
forced_root_block: string;
format: string;
get: boolean;
get_inner: boolean;
node: Node;
selection: true;
}
interface NodeChangeEvent extends Event {
element: Node;
parents: Node[];
selectionChange: boolean;
}
interface UndoRedoEvent extends Event {
level: {};
}
interface ChangeEvent extends Event {
lastLevel: {};
level: {};
}
interface CommandEvent extends Event {
command: string;
ui: boolean;
value: string;
}
}
export class FocusManager {
constructor();
static isEditorUIElement(elm: Element): boolean;
}
export interface Formatter {
apply(name: string, vars?: {}, node?: html.Node): void;
canApply(name: string): boolean;
formatChanged(formats: string, callback: () => void, similar: boolean): void;
get(name?: string): any[] | {};
getCssText(format: string): string;
match(name: string, vars?: {}, node?: html.Node): boolean;
matchAll(names: any[], vars?: {}): any[];
matchNode(node: html.Node, name: string, vars: {}, similar: boolean): {};
register(name: {}, format?: {}): void;
remove(name: string, vars?: {}, node?: html.Node): void;
toggle(name: string, vars?: {}, node?: html.Node): void;
unregister(name: string): void;
}
export class Formatter implements Formatter {
constructor(ed: Editor);
}
export interface Shortcuts {
add(pattern: string, desc: string, cmdFunc: () => void | string, scope?: {}): boolean;
remove(pattern: string): boolean;
}
export interface Theme {
renderUI(obj: {}): {};
}
export interface UndoManager {
add(level?: {}, event?: DocumentEvent): {};
beforeChange(): void;
clear(): void;
extra(callback1: () => void, callback2: () => void): void;
hasRedo(): boolean;
hasUndo(): boolean;
ignore(callback: () => void): void;
redo(): {};
transact(callback: () => void): {};
undo(): {};
}
export interface WindowManager {
alert(message: string, callback: () => void, scope?: {}): void;
close(): void;
confirm(message: string, callback: () => void, scope?: {}): void;
getParams(): {};
getWindows(): Window[];
open(args: {}, params: {}): void;
setParams(params: {}): void;
}
export interface notificationManager {
close(): void;
getNotifications(): Array<{}>;
open(args?: {}): void;
}
export namespace ui {
interface ControlSettings {
menu: Menu;
}
interface Collection {}
interface Container {
add(items: any): Collection;
items(): Collection;
}
interface Moveable {
moveRel(elm: Node, rel: string): Control;
}
interface FloatPanel extends Control, Moveable {}
interface Menu extends FloatPanel, Control, Container {}
interface Factory {
create(settings: any): Control;
}
class Control {
constructor();
$el: JQuery;
on(name: string, callback: string): Control;
tooltip(): Control;
settings: ControlSettings;
disabled(state: boolean): void;
active(state: boolean): void;
}
}
export namespace dom {
interface BookmarkManager {
getBookmark(type?: number, normalized?: boolean): {};
isBookmarkNode(node: HTMLElement): boolean;
moveToBookmark(bookmark: {}): boolean;
}
interface DOMUtils {
add<T>(parentElm: string, name: string, attrs?: {}, html?: string, create?: boolean): Element | T[];
addClass<T>(elm: string, cls: string): string | T[];
addStyle(cssText: string): void;
bind(target: Element, name: string, func: () => void, scope?: {}): () => void;
create(name: string, attrs?: {}, html?: string): Element;
createFragment(html: string): DocumentFragment;
createHTML(name: string, attrs?: {}, html?: string): string;
createRng(): Range;
decode(s: string): string;
destroy(): void;
encode(text: string): string;
findCommonAncestor(a: Element, b: Element): Element;
fire(target: Node, name: string, evt: {}): Event;
get(n: string): Element;
getAttrib(elm: string, name: string, defaultVal: string): string;
getAttribs(elm?: HTMLElement): NodeList;
getNext(node: Node, selector: string): Node;
getOuterHTML(elm: string): string;
getParent(node: Node, selector: any, root?: Node): Node;
getParents<T>(node: Node, selector: () => void, root?: Node): T[];
getPos(elm: Element, rootElm?: Element): {};
getPrev(node: Node, selector: string): Node;
getRect(elm: Element): {};
getRoot(): Element;
getSize(elm: Element): {};
getStyle(elm: string, name: string, computed: boolean): string;
getViewPort(win?: Window): {};
hasClass(elm: string, cls: string): boolean;
hide(elm: string): void;
insertAfter<T>(node: Element, referenceNode: Element): Element | T[];
is(elm: Node, selector: string): boolean;
isBlock(node: Node): boolean;
isEmpty(elements?: {}): boolean;
isHidden(elm: string): boolean;
loadCSS(url: string): void;
nodeIndex(node: Node, normalized?: boolean): number;
parseStyle(cssText: string): {};
remove<T>(node: string | Element, keepChildren?: boolean): Element | T[];
removeAllAttribs(e: Element): void;
removeClass<T>(elm: string, cls: string): string | T[];
rename(elm: Element, name: string): Element;
replace(newElm: Element, oldElm: Element, keepChildren?: boolean): void;
run<T>(elm: string, func: () => void, scope?: {}): {} | T[];
select<T>(selector: string, scope?: {}): T[];
serializeStyle(styles: {}, name?: string): string;
setAttrib(elm: Element, name: string, value: string): void;
setAttribs(elm: Element, attrs: {}): void;
setHTML(elm: Element, html: string): void;
setOuterHTML(elm: Element, html: {}): void;
setStyle(elm: string, name: string, value: string): void;
setStyles(elm: Element, styles: {}): void;
show(elm: string): void;
split(parentElm: Element, splitElm: Element, replacementElm?: Element): Element;
toHex(rgbVal: string): string;
toggleClass(elm: Element, cls: string, state?: string): void;
unbind<T>(target: Element, name: string, func: () => void): boolean | T[];
uniqueId(prefix?: string): string;
}
class DOMUtils implements DOMUtils {
constructor(doc: Document, settings?: {});
}
interface DomQuery {
add<T>(items: T[], sort?: boolean): DomQuery;
addClass(className: string): DomQuery;
after(content: string): DomQuery;
append(content: string): DomQuery;
appendTo(val: string): DomQuery;
attr(name: string, value?: string): DomQuery | string;
before(content: string): DomQuery;
children(node: Element | string): DomQuery;
clone(): DomQuery;
closest(selector: string): DomQuery;
contents(node: Element | string): DomQuery;
css(name: string, value?: string): DomQuery | string;
each(callback: () => void): DomQuery;
each(obj: {}, callback: () => void): void;
empty(): DomQuery;
eq(index: number): DomQuery;
extend(target: {}, object: {}): {};
filter(selector: string): DomQuery;
find(selector: string): DomQuery;
first(): DomQuery;
grep<T>(array: T[], callback: () => void): T[];
hasClass(className: string): boolean;
hide(): DomQuery;
html(value?: string): DomQuery | string;
inArray<T>(item: {}, array: T[]): number;
is(selector: string): boolean;
isArray(array: {}): boolean;
last(): DomQuery;
makeArray<T>(object: {}): T[];
next(node: Element | string): DomQuery;
nextUntil(node: Element | string, until: string): DomQuery;
off(name?: string, callback?: () => void): DomQuery;
offset(offset?: {}): {} | DomQuery;
on(name: string, callback: () => void): DomQuery;
parent(node: Element | string): DomQuery;
parents(node: Element | string): DomQuery;
parentsUntil(node: Element | string, until: string): DomQuery;
prepend(content: string): DomQuery;
prependTo(val: string): DomQuery;
prev(node: Element | string): DomQuery;
prevUntil(node: Element | string, until: string): DomQuery;
remove(): DomQuery;
removeAttr(name: string): DomQuery | string;
removeClass(className: string): DomQuery;
replaceWith(content: string): DomQuery;
show(): DomQuery;
slice(start: number, end?: number): DomQuery;
text(value?: string): DomQuery | string;
toArray<T>(): T[];
toggleClass(className: string, state?: boolean): DomQuery;
trigger(name: string): DomQuery;
trim(str: string): string;
unwrap(): DomQuery;
wrap(content: string): DomQuery;
wrapAll(content: string): DomQuery;
wrapInner(content: string): DomQuery;
}
class DomQuery implements DomQuery {
constructor(selector?: string, context?: Document);
}
interface EventUtils {
bind(target: {}, names: string, callback: () => void, scope: {}): () => void;
clean(target: {}): EventUtils;
fire(target: {}, name: string, args?: {}): EventUtils;
unbind(target: {}, names?: string, callback?: () => void): EventUtils;
}
interface RangeUtils {
compareRanges(rng1: Range, rng2: Range): boolean;
getCaretRangeFromPoint(clientX: number, clientY: number, doc: Document): Range;
}
interface ScriptLoader {
add(url: string, success?: () => void, scope?: {}, failure?: () => void): void;
isDone(url: string): boolean;
load(url: string, callback1?: () => void, callback2?: () => void): void;
loadQueue(success?: () => void, failure?: () => void, scope?: {}): void;
loadScripts(scripts: string[], callback1?: () => void, scope?: {}, callback2?: () => void): void;
markDone(url: string): void;
}
interface Selection {
collapse(toStart?: boolean): void;
getBookmark(type?: number, normalized?: boolean): {};
getContent(args?: {}): string;
getEnd(real?: boolean): Element;
getNode(): Element;
getRng(w3c: boolean): Range;
getSel(): Selection;
getStart(real?: boolean): Element;
isCollapsed(): boolean;
moveToBookmark(bookmark: {}): boolean;
select(node: Element, content?: boolean): Element;
selectorChanged(selector: string, callback: () => void): void;
setContent(content: string, args?: {}): void;
setCursorLocation(node?: Node, offset?: number): void;
setNode(elm: Element): Element;
setRng(rng: Range, forward?: boolean): void;
}
class Selection implements Selection {
constructor(dom: DOMUtils, win: Window, editor: Editor, serializer: Serializer);
}
interface Serializer {
addAttributeFilter(callback: () => void): void;
addNodeFilter(callback: () => void): void;
addRules(rules: string): void;
addTempAttr(name: string): void;
serialize(node: HTMLElement, args: {}): void;
setRules(rules: string): void;
}
class Serializer implements Serializer {
constructor(settings: {}, editor?: Editor);
}
interface TreeWalker {
current(): html.Node;
next(): html.Node;
prev(): html.Node;
}
}
export class TreeWalker implements TreeWalker {
constructor(startNode: html.Node, rootNode: html.Node);
}
export namespace geom {
interface Rect {
clamp(rect: Rect, clampRect: Rect, fixedSize: boolean): Rect;
create(x: number, y: number, w: number, h: number): Rect;
findBestRelativePosition(rect: Rect, targetRect: Rect, constrainRect: Rect, rels: any[]): void;
fromClientRect(clientRect: ClientRect): Rect;
inflate(rect: Rect, w: number, h: number): Rect;
intersect(rect: Rect, cropRect: Rect): Rect;
relativePosition(rect: Rect, targetRect: Rect, rel: string): void;
}
}
export namespace html {
interface DomParser {
addAttributeFilter(attributes: string, callback: () => void): void;
addNodeFilter(attributes: string, callback: () => void): void;
filterNode(node: Node): Node;
parse(html: string, args?: {}): Node;
}
class DomParser implements DomParser {
constructor(settings: {}, schema: Schema);
}
interface Entities {
decode(text: string): string;
encodeAllRaw(text: string): string;
encodeNamed(text: string, attr?: boolean, entities?: {}): string;
encodeNumeric(text: string, attr?: boolean): string;
encodeRaw(text: string, attr?: boolean): string;
getEncodeFunc(name: string, entities?: string): () => void;
}
interface Node {
append(node: Node): Node;
attr(name: string, value?: string): string | Node;
clone(): Node;
create(name: string, attrs: {}): void;
empty(): Node;
getAll(name: string): Node[];
insert(node: Node, ref_node: Node, before?: boolean): Node;
isEmpty(elements: {}): boolean;
remove(): Node;
replace(node: Node): Node;
unwrap(): void;
walk(prev?: boolean): Node;
wrap(wrapperNode: Node): Node;
}
class Node implements Node {
constructor(name: string, type: number);
}
interface SaxParser {
parse(html: string): void;
}
class SaxParser implements SaxParser {
constructor(settings: {}, schema: Schema);
}
interface Schema {
addCustomElements(custom_elements: string): void;
addValidChildren(valid_children: string): void;
addValidElements(valid_elements: string): void;
getBlockElements(): {[name: string]: {}};
getBoolAttrs(): {[name: string]: {}};
getCustomElements(): {[name: string]: {}};
getElementRule(name: string): {};
getInvalidStyles(): void;
getMoveCaretBeforeOnEnterElements(): {[name: string]: {}};
getNonEmptyElements(): {[name: string]: {}};
getSelfClosingElements(): {[name: string]: {}};
getShortEndedElements(): {[name: string]: {}};
getSpecialElements(): {[name: string]: {}};
getTextBlockElements(): {[name: string]: {}};
getTextInlineElements(): {[name: string]: {}};
getValidClasses(): void;
getValidStyles(): void;
getWhiteSpaceElements(): {[name: string]: {}};
isValid(name: string, attr?: string): boolean;
isValidChild(name: string, child: string): boolean;
setValidElements(valid_elements: string): void;
}
class Schema implements Schema {
constructor(settings: {});
}
interface Serializer {
serialize(node: Node): string;
}
class Serializer implements Serializer {
constructor(settings: {}, schema: Schema);
}
interface Styles {
parse(css: string): {};
serialize(styles: {}, elementName: string): string;
toHex(color: string): string;
}
interface Writer {
cdata(text: string): void;
doctype(text: string): void;
end(name: string): void;
getContent(): string;
pi(name: string, text: string): void;
reset(): void;
start(name: string, attrs?: any[], empty?: boolean): void;
text(text: string, raw: boolean): void;
}
}
export class Writer implements Writer {
constructor(settings: {});
}
export namespace util {
interface Color {
parse(value: {}): Color;
toHex(): string;
toHsv(): {};
toRgb(): {};
}
class Color implements Color {
constructor(value: string | {});
}
interface Delay {
clearInterval(interval: number): void;
clearTimeout(timeout: number): void;
debounce(callback: () => void, time: number): () => void;
requestAnimationFrame(callback: () => void, element?: HTMLElement): void;
setEditorInterval(callback: () => void, time: number): number;
setEditorTimeout(editor: Editor, callback: () => void, time: number): number;
setInterval(callback: () => void, time: number): number;
setTimeout(callback: () => void, time: number): number;
}
interface EventDispatcher {
fire(name: string, args?: {}): {};
has(name: string): boolean;
isNative(name: string): boolean;
off(name: string, callback?: () => void): {};
on(name: string, callback: () => void, first?: boolean): {};
once(name: string, callback: () => void, first: boolean): {};
}
interface i18n {
rtl: boolean;
add(code: string, items: Array<{}>): void;
getCode(): string;
setCode(newCode: string): void;
translate(text: string): string;
}
interface JSON {
parse(s: string): {};
serialize(obj: {}, quote?: string): string;
}
interface JSONRequest {
send(args: {}): void;
sendRPC(o: {}): void;
}
interface LocalStorage {
length: number;
clear(): void;
getItem(key: string): string;
key(index: number): string;
removeItem(key: string): void;
setItem(key: string, value: string): void;
}
class Observable {
fire(name: string, args?: {}, bubble?: boolean): {};
hasEventListeners(name: string): boolean;
off(name?: string, callback?: () => void): {};
on(name: string, callback: (event: any) => void, first?: boolean): {};
once(name: string, callback: (event: any) => void): {};
}
interface Tools {
create(s: string, p: {}, root?: {}): void;
createNS(n: string, o?: {}): {};
each(o: {}, cb: () => void, s?: {}): void;
explode(s: string, d: string): void;
grep<T>(a: T[], f: () => void): T[];
inArray<T>(item: T, arr: T[]): number;
is(obj: {}, type: string): boolean;
isArray(obj: {}): boolean;
makeMap<T>(items: T[], delim?: string, map?: {}): {};
map<T, S>(array: T[], callback: (c: T) => S): S[];
resolve(n: string, o?: {}): {};
toArray<T>(obj: {}): T[];
trim(s: string): string;
walk(o: {}, f: () => void, n?: string, s?: string): void;
}
interface URI {
getURI(noProtoHost: boolean): URI;
isSameOrigin(uri: URI): boolean;
setPath(path: string): void;
toAbsPath(base: string, path: string): void;
toAbsolute(uri: string, noHost: boolean): string;
toRelPath(base: string, path: string): void;
toRelative(uri: string): string;
}
class URI implements URI {
constructor(url: string, settings?: {});
}
interface XHR {
fire(name: string, args?: {}, bubble?: boolean): {};
hasEventListeners(name: string): boolean;
off(name?: string, callback?: () => void): {};
on(name: string, callback: () => void, first?: boolean): {};
once(name: string, callback: () => void): {};
send(settings: {}): void;
}
} | the_stack |
import { expect } from "chai";
import { mount } from "enzyme";
import * as React from "react";
import sinon from "sinon";
import { PropertyRecord } from "@itwin/appui-abstract";
import { Orientation } from "@itwin/core-react";
import { fireEvent, render } from "@testing-library/react";
import { LinksRenderer } from "../../../../components-react/properties/LinkHandler";
import { PrimitivePropertyRenderer } from "../../../../components-react/properties/renderers/PrimitivePropertyRenderer";
import { PropertyValueRendererManager } from "../../../../components-react/properties/ValueRendererManager";
import { FlatNonPrimitivePropertyRenderer } from "../../../../components-react/propertygrid/internal/flat-properties/FlatNonPrimitivePropertyRenderer";
import { FlatPropertyRenderer } from "../../../../components-react/propertygrid/internal/flat-properties/FlatPropertyRenderer";
import TestUtils from "../../../TestUtils";
describe("FlatPropertyRenderer", () => {
let propertyRecord: PropertyRecord;
before(async () => {
await TestUtils.initializeUiComponents();
});
after(() => {
TestUtils.terminateUiComponents();
});
beforeEach(() => {
propertyRecord = TestUtils.createPrimitiveStringProperty("Label", "Model");
});
it("updates displayed value if propertyRecord changes", async () => {
const originalValue = "OriginalValue";
const recordValue = "ChangedValue";
propertyRecord = TestUtils.createPrimitiveStringProperty("Label", originalValue);
const propertyRenderer = mount(
<FlatPropertyRenderer
orientation={Orientation.Horizontal}
propertyRecord={propertyRecord}
isExpanded={false}
onExpansionToggled={() => { }}
/>);
await TestUtils.flushAsyncOperations();
propertyRenderer.update();
expect(propertyRenderer.find(LinksRenderer).prop("value")).to.be.equal(originalValue);
propertyRenderer.setProps({ propertyRecord: TestUtils.createPrimitiveStringProperty("Label", recordValue) });
await TestUtils.flushAsyncOperations();
propertyRenderer.update();
expect(propertyRenderer.find(LinksRenderer).prop("value")).to.be.equal(recordValue);
});
it("uses provided propertyValueRendererManager", async () => {
class RendererManager extends PropertyValueRendererManager {
public override render({ }) {
return ("Test");
}
}
const { getByText } = render(
<FlatPropertyRenderer
orientation={Orientation.Horizontal}
propertyRecord={propertyRecord}
propertyValueRendererManager={new RendererManager()}
isExpanded={false}
onExpansionToggled={() => { }}
/>);
expect(getByText("Test")).to.be.not.null;
});
it("highlights matches in primitive values", async () => {
const { container } = render(
<FlatPropertyRenderer
orientation={Orientation.Horizontal}
propertyRecord={TestUtils.createPrimitiveStringProperty("Label", "abc")}
highlight={{ highlightedText: "b", applyOnLabel: true, applyOnValue: true }}
isExpanded={false}
onExpansionToggled={() => { }}
/>);
const highlightedNodes = container.querySelectorAll("mark");
expect(highlightedNodes.length).to.eq(2);
});
it("renders as primitive value if property is an empty array", () => {
propertyRecord = TestUtils.createArrayProperty("EmptyArray");
const propertyRenderer = mount(
<FlatPropertyRenderer
orientation={Orientation.Horizontal}
propertyRecord={propertyRecord}
isExpanded={false}
onExpansionToggled={() => { }}
/>);
expect(propertyRenderer.find(PrimitivePropertyRenderer).exists()).to.be.true;
});
it("highlights matches in empty array values", () => {
const { container } = render(
<FlatPropertyRenderer
orientation={Orientation.Horizontal}
propertyRecord={TestUtils.createArrayProperty("EmptyArray")}
highlight={{ highlightedText: "rr", applyOnLabel: true, applyOnValue: true }}
isExpanded={false}
onExpansionToggled={() => { }}
/>);
const highlightedNode = container.querySelector("mark");
expect(highlightedNode).to.be.not.null;
expect(highlightedNode!.textContent).to.eq("rr");
});
it("renders struct as a non primitive value", () => {
propertyRecord = TestUtils.createArrayProperty("StringArray", [TestUtils.createPrimitiveStringProperty("Label", "Model")]);
const propertyRenderer = mount(
<FlatPropertyRenderer
orientation={Orientation.Horizontal}
propertyRecord={propertyRecord}
isExpanded={false}
onExpansionToggled={() => { }}
/>);
expect(propertyRenderer.find(FlatNonPrimitivePropertyRenderer).exists()).to.be.true;
});
it("renders array as a non primitive value", () => {
propertyRecord = TestUtils.createStructProperty("Struct");
const propertyRenderer = mount(
<FlatPropertyRenderer
orientation={Orientation.Horizontal}
propertyRecord={propertyRecord}
isExpanded={false}
onExpansionToggled={() => { }}
/>);
expect(propertyRenderer.find(FlatNonPrimitivePropertyRenderer).exists()).to.be.true;
});
it("renders an editor correctly", () => {
const propertyRenderer = mount(
<FlatPropertyRenderer
orientation={Orientation.Horizontal}
propertyRecord={propertyRecord}
isEditing={true}
isExpanded={false}
onExpansionToggled={() => { }}
/>);
expect(propertyRenderer.find("input.components-text-editor").length).to.eq(1);
});
it("calls onEditCommit on Enter key when editing", async () => {
const spyMethod = sinon.spy();
const propertyRenderer = render(
<FlatPropertyRenderer
category={{ name: "Cat1", label: "Category 1", expand: true }}
orientation={Orientation.Horizontal}
propertyRecord={propertyRecord}
isEditing={true}
onEditCommit={spyMethod}
isExpanded={false}
onExpansionToggled={() => { }}
/>);
const inputNode = propertyRenderer.container.querySelector("input");
expect(inputNode).not.to.be.null;
fireEvent.keyDown(inputNode as HTMLElement, { key: "Enter" });
await TestUtils.flushAsyncOperations();
expect(spyMethod.calledOnce).to.be.true;
});
it("does not attempt to call onEditCommit callback when it is not present and throw", async () => {
const propertyRenderer = render(
<FlatPropertyRenderer
category={{ name: "Cat1", label: "Category 1", expand: true }}
orientation={Orientation.Horizontal}
propertyRecord={propertyRecord}
isEditing={true}
isExpanded={false}
onExpansionToggled={() => { }}
/>);
const inputNode = propertyRenderer.container.querySelector("input");
expect(inputNode).not.to.be.null;
fireEvent.keyDown(inputNode as HTMLElement, { key: "Enter" });
await TestUtils.flushAsyncOperations();
});
it("calls onEditCancel on Escape key when editing", () => {
const spyMethod = sinon.spy();
const propertyRenderer = render(
<FlatPropertyRenderer
orientation={Orientation.Horizontal}
propertyRecord={propertyRecord}
isEditing={true}
onEditCancel={spyMethod}
isExpanded={false}
onExpansionToggled={() => { }}
/>);
const inputNode = propertyRenderer.container.querySelector("input");
expect(inputNode).not.to.be.null;
fireEvent.keyDown(inputNode as HTMLElement, { key: "Escape" });
expect(spyMethod.calledOnce).to.be.true;
});
it("does not remove Editor on Enter if callback is not provided", () => {
const propertyRenderer = mount(
<FlatPropertyRenderer
orientation={Orientation.Horizontal}
propertyRecord={propertyRecord}
isEditing={true}
isExpanded={false}
onExpansionToggled={() => { }}
/>);
const inputNode = propertyRenderer.find("input");
expect(inputNode.exists()).to.be.true;
inputNode.simulate("keyDown", { key: "Enter" });
expect(propertyRenderer.find("input").exists()).to.be.true;
});
it("does not remove Editor on Escape if callback is not provided", () => {
const propertyRenderer = mount(
<FlatPropertyRenderer
orientation={Orientation.Horizontal}
propertyRecord={propertyRecord}
isEditing={true}
isExpanded={false}
onExpansionToggled={() => { }}
/>);
const inputNode = propertyRenderer.find("input");
expect(inputNode.exists()).to.be.true;
inputNode.simulate("keyDown", { key: "Escape" });
expect(propertyRenderer.find("input").exists()).to.be.true;
});
it("does not wrap valueElement in span if it's not a string", async () => {
propertyRecord.property.typename = "mycustomRenderer";
const myCustomRenderer = {
canRender: () => true,
// eslint-disable-next-line react/display-name
render: () => <div>My value</div>,
};
PropertyValueRendererManager.defaultManager.registerRenderer("mycustomRenderer", myCustomRenderer);
const propertyRenderer = mount(
<FlatPropertyRenderer
orientation={Orientation.Horizontal}
propertyRecord={propertyRecord}
isExpanded={false}
onExpansionToggled={() => { }}
/>);
await TestUtils.flushAsyncOperations();
propertyRenderer.update();
const originalRender = mount(<div>My value</div>).html();
const propsRender = mount(<>{propertyRenderer.find(PrimitivePropertyRenderer).prop("valueElementRenderer")!()}</>).html();
expect(originalRender).to.be.eq(propsRender);
});
describe("onHeightChanged", () => {
const record = TestUtils.createPrimitiveStringProperty("test", "test");
function renderFlatPropertyRenderer(isEditing: boolean, onHeightChanged?: (newHeight: number) => void) {
return (
<FlatPropertyRenderer
orientation={Orientation.Horizontal}
propertyRecord={record}
isExpanded={false}
isEditing={isEditing}
onExpansionToggled={() => { }}
onHeightChanged={onHeightChanged}
/>
);
}
it("gets called when entering editing state", () => {
const onHeightChanged = sinon.fake();
const { rerender } = render(renderFlatPropertyRenderer(false, onHeightChanged));
expect(onHeightChanged).to.have.not.been.called;
rerender(renderFlatPropertyRenderer(true, onHeightChanged));
expect(onHeightChanged).to.have.been.calledOnceWith(27);
});
it("does not get called when component is mounted in editing state", () => {
const onHeightChanged = sinon.fake();
render(renderFlatPropertyRenderer(true, onHeightChanged));
expect(onHeightChanged).to.have.not.been.called;
});
it("does not attempt to call when it is not present and throw", () => {
const { rerender } = render(renderFlatPropertyRenderer(false));
rerender(renderFlatPropertyRenderer(true));
});
});
}); | the_stack |
import { pluralize } from 'ember-inflector';
import { camelize } from '@ember/string';
import RSVP from 'rsvp';
import DS from 'ember-data';
import Ember from 'ember';
import FirebaseAppService from '../services/firebase-app';
import ModelRegistry from 'ember-data/types/registries/model';
import { inject as service } from '@ember/service';
import { get, set } from '@ember/object';
import { database } from 'firebase/app';
/**
* Persist your Ember Data models in the Firebase Realtime Database
*
* ```js
* // app/adapters/application.js
* import RealtimeDatabaseAdapter from 'emberfire/adapters/realtime-database';
*
* export default RealtimeDatabaseAdapter.extend({
* // configuration goes here
* });
* ```
*
*/
export default class RealtimeDatabaseAdapter extends DS.Adapter.extend({
namespace: undefined as string|undefined,
firebaseApp: service('firebase-app'),
databaseURL: undefined,
database: undefined as RSVP.Promise<database.Database>|undefined,
defaultSerializer: '-realtime-database'
}) {
/**
* Override the default FirebaseApp Service used by the RealtimeDatabaseAdapter: `service('firebase-app')`
*
* ```js
* // app/adapters/application.js
* import RealtimeDatabaseAdapter from 'emberfire/adapters/realtime-database';
* import { inject as service } from '@ember/service';
*
* export default RealtimeDatabaseAdapter.extend({
* firebaseApp: service('firebase-different-app')
* });
* ```
*
*/
// @ts-ignore repeat here for the tyepdocs
firebaseApp: Ember.ComputedProperty<FirebaseAppService, FirebaseAppService>;
/**
* Namespace all of the paths
*
* ```js
* // app/adapters/application.js
* import RealtimeDatabaseAdapter from 'emberfire/adapters/realtime-database';
*
* export default RealtimeDatabaseAdapter.extend({
* namespace: 'environments/production'
* });
* ```
*
*/
// @ts-ignore repeat here for the tyepdocs
namespace: string|undefined;
/**
* Override the default database used by the RealtimeDatabaseAdapter
*
* ```js
* // app/adapters/application.js
* import RealtimeDatabaseAdapter from 'emberfire/adapters/realtime-database';
*
* export default RealtimeDatabaseAdapter.extend({
* databaseURL: 'https://DIFFERENT_DATABASE.firebaseio.com'
* });
* ```
*
*/
// @ts-ignore repeat here for the tyepdocs
databaseURL?: string;
findRecord<K extends keyof ModelRegistry>(_store: DS.Store, type: ModelRegistry[K], id: string) {
return docReference(this, type, id).then(doc => doc.once('value'));
}
findAll<K extends keyof ModelRegistry>(store: DS.Store, type: ModelRegistry[K]) {
return this.query(store, type)
}
findHasMany<K extends keyof ModelRegistry>(store: DS.Store, snapshot: DS.Snapshot<K>, url: string, relationship: {[key:string]: any}) {
const adapter = store.adapterFor(relationship.type as never) as any; // TODO kill the any
if (adapter !== this) {
return adapter.findHasMany(store, snapshot, url, relationship) as RSVP.Promise<any>;
} else if (relationship.options.subcollection) {
throw `subcollections (${relationship.parentModelName}.${relationship.key}) are not supported by the Realtime Database, consider using embedded relationships or check out Firestore`;
} else {
return rootCollection(this, relationship.type).then(ref => queryDocs(
ref.orderByChild(relationship.parentModelName).equalTo(snapshot.id),
relationship.options.query
));
}
}
findBelongsTo<K extends keyof ModelRegistry>(store: DS.Store, snapshot: DS.Snapshot<K>, url: any, relationship: any) {
const adapter = store.adapterFor(relationship.type as never) as any; // TODO kill the any
if (adapter !== this) {
return adapter.findBelongsTo(store, snapshot, url, relationship) as RSVP.Promise<any>;
} else {
return docReference(this, relationship.type, snapshot.id).then(ref => ref.once('value'));
}
}
query<K extends keyof ModelRegistry>(_store: DS.Store, type: ModelRegistry[K], options?: QueryOptions) {
return rootCollection(this, type).then(ref => queryDocs(ref, queryOptionsToQueryFn(options)));
}
queryRecord<K extends keyof ModelRegistry>(_store: DS.Store, type: ModelRegistry[K], options?: QueryOptions) {
const query = rootCollection(this, type).then(ref => queryDocs(ref.limitToFirst(1), queryOptionsToQueryFn(options)));
return query.then(results => {
let snapshot = undefined as database.DataSnapshot|undefined;
results.forEach(doc => !!(snapshot = doc));
if (snapshot) {
return snapshot;
} else {
throw new DS.NotFoundError();
}
});
}
shouldBackgroundReloadRecord() {
return false; // TODO can we make this dependent on a listener attached
}
updateRecord<K extends keyof ModelRegistry>(_: DS.Store, type: ModelRegistry[K], snapshot: DS.Snapshot<K>) {
const id = snapshot.id;
const data = this.serialize(snapshot, { includeId: false });
// TODO is this correct? e.g, clear dirty state and trigger didChange; what about failure?
return docReference(this, type, id).then(ref => ref.set(data));
}
createRecord<K extends keyof ModelRegistry>(_store: DS.Store, type: ModelRegistry[K], snapshot: DS.Snapshot<K>) {
const id = snapshot.id;
const data = this.serialize(snapshot, { includeId: false });
if (id) {
return docReference(this, type, id).then(ref => ref.set(data).then(() => ({ref, data})));
} else {
return rootCollection(this, type).then(ref => ref.push()).then(ref => {
(snapshot as any)._internalModel.setId(ref.key!);
return ref.set(data).then(() => ({ref, data}));
});
}
}
deleteRecord<K extends keyof ModelRegistry>(_: DS.Store, type: ModelRegistry[K], snapshot: DS.Snapshot<K>) {
return docReference(this, type, snapshot.id).then(ref => ref.remove());
}
}
export type ReferenceOrQuery = database.Reference | database.Query;
export type ReferenceOrQueryFn = (ref: ReferenceOrQuery) => ReferenceOrQuery;
export type QueryFn = (ref: database.Reference) => ReferenceOrQuery;
// Keeping this for compatability with version 2
export enum OrderBy { Key = '_key', Value = '_value', Priority = '_priority' }
export type BoundOp = string|number|boolean|null|[string|number|boolean|null,string];
export type QueryOptionsOnlyQuery = {
query: (ref: database.Reference) => database.Reference|database.Query
}
// TODO adapterOptions?
export type QueryOptions = ({
filter?: {[key:string]:string|number|boolean|null},
endAt?: BoundOp,
equalTo?: BoundOp,
limitToFirst?: number,
limitToLast?: number,
orderBy?: string|OrderBy,
startAt?: BoundOp
} | QueryOptionsOnlyQuery) & { include?: string }
const isQueryOnly = (arg: any): arg is QueryOptionsOnlyQuery => arg.query !== undefined;
// query: ref => ref.orderByChild('asdf')
// filter: { published: true }
// orderBy: OrderBy.Key, equalTo: 'asdf'
// orderBy: 'publishedAt'
const queryOptionsToQueryFn = (options?:QueryOptions) => (collectionRef:database.Reference) => {
let ref = collectionRef as ReferenceOrQuery;
if (options) {
if (isQueryOnly(options)) { return options.query(collectionRef); }
if (options.filter) {
Object.keys(options.filter).forEach(field => {
ref = ref.orderByChild(field).equalTo(options.filter![field]);
})
}
if (options.orderBy) {
switch(options.orderBy) {
case OrderBy.Key:
ref = ref.orderByKey();
break;
case OrderBy.Priority:
ref = ref.orderByPriority();
break;
case OrderBy.Value:
ref = ref.orderByValue();
break;
default:
ref = ref.orderByChild(options.orderBy);
}
}
if (options.equalTo !== undefined) { ref = options.equalTo && typeof options.equalTo === "object" ? ref.equalTo(options.equalTo[0], options.equalTo[1]) : ref.equalTo(options.equalTo) }
if (options.startAt !== undefined) { ref = options.startAt && typeof options.startAt === "object" ? ref.startAt(options.startAt[0], options.startAt[1]) : ref.startAt(options.startAt) }
if (options.endAt !== undefined) { ref = options.endAt && typeof options.endAt === "object" ? ref.endAt(options.endAt[0], options.endAt[1]) : ref.endAt(options.endAt) }
if (options.limitToFirst) { ref = ref.limitToFirst(options.limitToFirst) }
if (options.limitToLast) { ref = ref.limitToLast(options.limitToLast) }
}
return ref;
}
const noop = (ref: database.Reference) => ref;
const queryDocs = (referenceOrQuery: ReferenceOrQuery, query?: ReferenceOrQueryFn) => getDocs((query || noop)(referenceOrQuery));
// TODO allow override
const collectionNameForType = (type: any) => pluralize(camelize(typeof(type) === 'string' ? type : type.modelName));
export const rootCollection = (adapter: RealtimeDatabaseAdapter, type: any) => databaseInstance(adapter).then(database => database.ref([get(adapter, 'namespace'), collectionNameForType(type)].join('/')));
const getDocs = (query: ReferenceOrQuery) => query.once('value').then(value => ((value as any).query = query) && value);
const docReference = (adapter: RealtimeDatabaseAdapter, type: any, id: string) => rootCollection(adapter, type).then(ref => ref.child(id));
const databaseInstance = (adapter: RealtimeDatabaseAdapter) => {
let database = get(adapter, 'database');
if (!database) {
const app = get(adapter, 'firebaseApp');
const databaseURL = get(adapter, 'databaseURL');
database = app.database(databaseURL);
set(adapter, 'database', database);
}
return database!;
}
declare module 'ember-data' {
interface AdapterRegistry {
'realtime-database': RealtimeDatabaseAdapter;
}
} | the_stack |
namespace eui.sys {
let STATE = "eui.State";
let ADD_ITEMS = "eui.AddItems";
let SET_PROPERTY = "eui.SetProperty";
let SET_STATEPROPERTY = "eui.SetStateProperty";
let BINDING_PROPERTIES = "eui.Binding.$bindProperties";
/**
* @private
* 代码生成工具基类
*/
export class CodeBase {
/**
* @private
*
* @returns
*/
public toCode():string {
return "";
}
/**
* @private
*/
public indent:number = 0;
/**
* @private
* 获取缩进字符串
*/
public getIndent(indent?:number):string {
if (indent === void 0)
indent = this.indent;
let str = "";
for (let i = 0; i < indent; i++) {
str += " ";
}
return str;
}
}
/**
* @private
*/
export class EXClass extends CodeBase {
/**
* @private
* 构造函数代码块
*/
public constructCode:EXCodeBlock;
/**
* @private
* 类名,不包括模块名
*/
public className:string = "";
/**
* @private
* 父类类名,包括完整模块名
*/
public superClass:string = "";
/**
* @private
* 内部类区块
*/
private innerClassBlock:EXClass[] = [];
/**
* @private
* 添加一个内部类
*/
public addInnerClass(clazz:EXClass):void {
if (this.innerClassBlock.indexOf(clazz) == -1) {
this.innerClassBlock.push(clazz);
}
}
/**
* @private
* 变量定义区块
*/
private variableBlock:EXVariable[] = [];
/**
* @private
* 添加变量
*/
public addVariable(variableItem:EXVariable):void {
if (this.variableBlock.indexOf(variableItem) == -1) {
this.variableBlock.push(variableItem);
}
}
/**
* @private
* 根据变量名获取变量定义
*/
public getVariableByName(name:string):EXVariable {
let list = this.variableBlock;
let length = list.length;
for (let i = 0; i < length; i++) {
let item = list[i];
if (item.name == name) {
return item;
}
}
return null;
}
/**
* @private
* 函数定义区块
*/
private functionBlock:EXFunction[] = [];
/**
* @private
* 添加函数
*/
public addFunction(functionItem:EXFunction):void {
if (this.functionBlock.indexOf(functionItem) == -1) {
this.functionBlock.push(functionItem);
}
}
/**
* @private
* 根据函数名返回函数定义块
*/
public getFuncByName(name:string):EXFunction {
let list = this.functionBlock;
let length = list.length;
for (let i = 0; i < length; i++) {
let item = list[i];
if (item.name == name) {
return item;
}
}
return null;
}
/**
* @private
*
* @returns
*/
public toCode():string {
let indent = this.indent;
let indentStr = this.getIndent(indent);
let indent1Str = this.getIndent(indent + 1);
let indent2Str = this.getIndent(indent + 2);
//打印类起始块
let returnStr = indentStr + "(function (";
if (this.superClass) {
returnStr += "_super) {\n" + indent1Str + "__extends(" + this.className + ", _super);\n";
}
else {
returnStr += ") {\n";
}
//打印内部类列表
let innerClasses = this.innerClassBlock;
let length = innerClasses.length;
for (let i = 0; i < length; i++) {
let clazz = innerClasses[i];
clazz.indent = indent + 1;
returnStr += indent1Str + "var " + clazz.className + " = " + clazz.toCode() + "\n\n";
}
returnStr += indent1Str + "function " + this.className + "() {\n";
if (this.superClass) {
returnStr += indent2Str + "_super.call(this);\n";
}
//打印变量列表
let variables = this.variableBlock;
length = variables.length;
for (let i = 0; i < length; i++) {
let variable = variables[i];
if (variable.defaultValue) {
returnStr += indent2Str + variable.toCode() + "\n";
}
}
//打印构造函数
if (this.constructCode) {
let codes = this.constructCode.toCode().split("\n");
length = codes.length;
for (let i = 0; i < length; i++) {
let code = codes[i];
returnStr += indent2Str + code + "\n";
}
}
returnStr += indent1Str + "}\n";
returnStr += indent1Str + "var _proto = " + this.className + ".prototype;\n\n";
//打印函数列表
let functions = this.functionBlock;
length = functions.length;
for (let i = 0; i < length; i++) {
let functionItem = functions[i];
functionItem.indent = indent + 1;
returnStr += functionItem.toCode() + "\n";
}
//打印类结尾
returnStr += indent1Str + "return " + this.className + ";\n" + indentStr;
if (this.superClass) {
returnStr += "})(" + this.superClass + ");";
}
else {
returnStr += "})();";
}
return returnStr;
}
}
/**
* @private
*/
export class EXCodeBlock extends CodeBase {
/**
* @private
* 添加变量声明语句
* @param name 变量名
* @param value 变量初始值
*/
public addVar(name:string, value?:string):void {
let valueStr = value ? " = " + value : "";
this.addCodeLine("var " + name + valueStr + ";");
}
/**
* @private
* 添加赋值语句
* @param target 要赋值的目标
* @param value 值
* @param prop 目标的属性(用“.”访问),不填则是对目标赋值
*/
public addAssignment(target:string, value:string, prop?:string):void {
let propStr = prop ? "." + prop : "";
this.addCodeLine(target + propStr + " = " + value + ";");
}
/**
* @private
* 添加返回值语句
*/
public addReturn(data:string):void {
this.addCodeLine("return " + data + ";");
}
/**
* @private
* 添加一条空行
*/
public addEmptyLine():void {
this.addCodeLine("");
}
/**
* @private
* 开始添加if语句块,自动调用startBlock();
*/
public startIf(expression:string):void {
this.addCodeLine("if(" + expression + ")");
this.startBlock();
}
/**
* @private
* 开始else语句块,自动调用startBlock();
*/
public startElse():void {
this.addCodeLine("else");
this.startBlock();
}
/**
* @private
* 开始else if语句块,自动调用startBlock();
*/
public startElseIf(expression:string):void {
this.addCodeLine("else if(" + expression + ")");
this.startBlock();
}
/**
* @private
* 添加一个左大括号,开始新的语句块
*/
public startBlock():void {
this.addCodeLine("{");
this.indent++;
}
/**
* @private
* 添加一个右大括号,结束当前的语句块
*/
public endBlock():void {
this.indent--;
this.addCodeLine("}");
}
/**
* @private
* 添加执行函数语句块
* @param functionName 要执行的函数名称
* @param args 函数参数列表
*/
public doFunction(functionName:string, args:string[]):void {
let argsStr = args.join(",");
this.addCodeLine(functionName + "(" + argsStr + ")");
}
/**
* @private
*/
private lines:string[] = [];
/**
* @private
* 添加一行代码
*/
public addCodeLine(code:string):void {
this.lines.push(this.getIndent() + code);
}
/**
* @private
* 添加一行代码到指定行
*/
public addCodeLineAt(code:string, index:number):void {
this.lines.splice(index, 0, this.getIndent() + code);
}
/**
* @private
* 是否存在某行代码内容
*/
public containsCodeLine(code:string):boolean {
return this.lines.indexOf(code) != -1;
}
/**
* @private
* 在结尾追加另一个代码块的内容
*/
public concat(cb:EXCodeBlock):void {
this.lines = this.lines.concat(cb.lines);
}
/**
* @private
*
* @returns
*/
public toCode():string {
return this.lines.join("\n");
}
}
/**
* @private
*/
export class EXFunction extends CodeBase {
/**
* @private
* 代码块
*/
public codeBlock:EXCodeBlock = null;
/**
* @private
*/
public isGet:boolean = false;
/**
* @private
* 函数名
*/
public name:string = "";
/**
* @private
*
* @returns
*/
public toCode():string {
let indentStr:string = this.getIndent();
let indent1Str:string = this.getIndent(this.indent + 1);
let codeIndent:string;
let returnStr = indentStr;
if (this.isGet) {
codeIndent = this.getIndent(this.indent + 2);
returnStr += 'Object.defineProperty(_proto, "skinParts", {\n';
returnStr += indent1Str + "get: function () {\n";
}
else {
codeIndent = indent1Str;
returnStr += "_proto." + this.name + " = function () {\n";
}
if (this.codeBlock) {
let lines = this.codeBlock.toCode().split("\n");
let length = lines.length;
for (let i = 0; i < length; i++) {
let line = lines[i];
returnStr += codeIndent + line + "\n";
}
}
if (this.isGet) {
returnStr += indent1Str + "},\n" + indent1Str + "enumerable: true,\n" +
indent1Str + "configurable: true\n" + indentStr + "});";
}
else {
returnStr += indentStr + "};";
}
return returnStr;
}
}
/**
* @private
*/
export class EXVariable extends CodeBase {
/**
* @private
*/
public constructor(name:string, defaultValue?:string) {
super();
this.indent = 2;
this.name = name;
this.defaultValue = defaultValue;
}
/**
* @private
* 变量名
*/
public name:string;
/**
* @private
* 默认值
*/
public defaultValue:string;
/**
* @private
*
* @returns
*/
public toCode():string {
if (!this.defaultValue) {
return "";
}
return "this." + this.name + " = " + this.defaultValue + ";";
}
}
/**
* @private
*/
export class EXState extends CodeBase {
/**
* @private
*/
public constructor(name:string, stateGroups?:any[]) {
super();
this.name = name;
if (stateGroups)
this.stateGroups = stateGroups;
}
/**
* @private
* 视图状态名称
*/
public name:string = "";
/**
* @private
*/
public stateGroups:any[] = [];
/**
* @private
*/
public addItems:any[] = [];
/**
* @private
*/
public setProperty:any[] = [];
/**
* @private
* 添加一个覆盖
*/
public addOverride(item:CodeBase):void {
if (item instanceof EXAddItems)
this.addItems.push(item);
else
this.setProperty.push(item);
}
/**
* @private
*
* @returns
*/
public toCode():string {
let indentStr:string = this.getIndent(1);
let returnStr:string = "new " + STATE + " (\"" + this.name + "\",\n" + indentStr + "[\n";
let index:number = 0;
let isFirst:boolean = true;
let overrides:any[] = this.addItems.concat(this.setProperty);
while (index < overrides.length) {
if (isFirst)
isFirst = false;
else
returnStr += ",\n";
let item:CodeBase = overrides[index];
let codes:any[] = item.toCode().split("\n");
let length:number = codes.length;
for (let i:number = 0; i < length; i++) {
let code:string = codes[i];
codes[i] = indentStr + indentStr + code;
}
returnStr += codes.join("\n");
index++;
}
returnStr += "\n" + indentStr + "])";
return returnStr;
}
}
/**
* @private
*/
export class EXAddItems extends CodeBase {
/**
* @private
*/
public constructor(target:string, property:string, position:number, relativeTo:string) {
super();
this.target = target;
this.property = property;
this.position = position;
this.relativeTo = relativeTo;
}
/**
* @private
* 要添加的实例
*/
public target:string;
/**
* @private
* 要添加到的属性
*/
public property:string;
/**
* @private
* 添加的位置
*/
public position:number;
/**
* @private
* 相对的显示元素
*/
public relativeTo:string;
/**
* @private
*
* @returns
*/
public toCode():string {
let returnStr:string = "new " + ADD_ITEMS + "(\"" + this.target + "\",\"" + this.property + "\"," + this.position + ",\"" + this.relativeTo + "\")";
return returnStr;
}
}
/**
* @private
*/
export class EXSetProperty extends CodeBase {
/**
* @private
*/
public constructor(target:string, name:string, value:string) {
super();
this.target = target;
this.name = name;
this.value = value;
}
/**
* @private
* 要修改的属性名
*/
public name:string;
/**
* @private
* 目标实例名
*/
public target:string;
/**
* @private
* 属性值
*/
public value:string;
/**
* @private
*
* @returns
*/
public toCode():string {
return "new " + SET_PROPERTY + "(\"" + this.target + "\",\"" + this.name + "\"," + this.value + ")";
}
}
/**
* @private
*/
export class EXSetStateProperty extends CodeBase {
/**
* @private
*/
public constructor(target:string, property:string, templates:string[], chainIndex:number[]) {
super();
if (target) {
target = "this." + target;
} else {
target = "this";
}
this.target = target;
this.property = property;
this.templates = templates;
this.chainIndex = chainIndex;
}
/**
* @private
* 目标实例名
*/
public target:string;
/**
* @private
* 目标属性名
*/
public property:string;
/**
* @private
* 绑定的模板列表
*/
public templates:string[];
/**
* @private
* chainIndex是一个索引列表,每个索引指向templates中的一个值,该值是代表属性链。
*/
public chainIndex:number[];
/**
* @private
*
* @returns
*/
public toCode():string {
let expression = this.templates.join(",");
let chain = this.chainIndex.join(",");
return "new " + SET_STATEPROPERTY + "(this, [" + expression + "]," + "[" + chain + "]," +
this.target + ",\"" + this.property + "\")";
}
}
/**
* @private
*/
export class EXBinding extends CodeBase {
/**
* @private
*/
public constructor(target:string, property:string, templates:string[], chainIndex:number[]) {
super();
this.target = target;
this.property = property;
this.templates = templates;
this.chainIndex = chainIndex;
}
/**
* @private
* 目标实例名
*/
public target:string;
/**
* @private
* 目标属性名
*/
public property:string;
/**
* @private
* 绑定的模板列表
*/
public templates:string[];
/**
* @private
* chainIndex是一个索引列表,每个索引指向templates中的一个值,该值是代表属性链。
*/
public chainIndex:number[];
/**
* @private
*
* @returns
*/
public toCode():string {
let expression = this.templates.join(",");
let chain = this.chainIndex.join(",");
return BINDING_PROPERTIES + "(this, [" + expression + "]," + "[" + chain + "]," +
this.target + ",\"" + this.property + "\")";
}
}
} | the_stack |
import React, { useEffect, useState } from 'react';
import {
Box,
Icon,
StatelessTextInput as Input,
Row,
Text,
Button,
Col,
LoadingSpinner,
} from '@tlon/indigo-react';
import Invoice from './Invoice';
import BridgeInvoice from './BridgeInvoice';
import ExternalInvoice from './ExternalInvoice';
import FeePicker from './FeePicker';
import Error from '../Error';
import Signer from './Signer';
import { validate } from 'bitcoin-address-validation';
import * as ob from 'urbit-ob';
import { useSettings } from '../../hooks/useSettings';
import { api } from '../../lib/api';
import { deSig } from '../../lib/util';
enum focusFields {
payee,
currency,
sats,
note,
empty = '',
}
export enum feeLevels {
low,
mid,
high,
}
export enum signMethods {
bridge = 'bridge',
masterTicket = 'masterTicket',
external = 'external',
}
enum payeeTypes {
ship,
address,
initial = '',
}
export type FeeChoices = {
[feeLevels.low]: [number, number];
[feeLevels.mid]: [number, number];
[feeLevels.high]: [number, number];
};
type Props = {
stopSending: () => void;
value: string;
conversion: number;
};
const Send: React.FC<Props> = ({ stopSending, value, conversion }) => {
const { error, setError, network, psbt, denomination, shipWallets } =
useSettings();
const [signing, setSigning] = useState(false);
const [denomAmount, setDenomAmount] = useState(0.0);
const [satsAmount, setSatsAmount] = useState(0);
const [payee, setPayee] = useState('');
const [checkingPatp, setCheckingPatp] = useState(false);
const [payeeType, setPayeeType] = useState<payeeTypes>(payeeTypes.initial);
const [ready, setReady] = useState(false);
const [validPayee, setValidPayee] = useState(false);
const [focusedField, setFocusedField] = useState(focusFields.empty);
const [feeChoices, setFeeChoices] = useState<FeeChoices>({
[feeLevels.low]: [10, 1],
[feeLevels.mid]: [10, 1],
[feeLevels.high]: [10, 1],
});
const [feeValue, setFeeValue] = useState(feeLevels.mid);
const [showFeePicker, setShowFeePicker] = useState(false);
const [note, setNote] = useState('');
const [choosingSignMethod, setChoosingSignMethod] = useState(false);
const [signMethod, setSignMethod] = useState<signMethods>(signMethods.bridge);
const feeDismiss = () => {
setShowFeePicker(false);
};
const handleSetSignMethod = (signMethod: signMethods) => {
setSignMethod(signMethod);
setChoosingSignMethod(false);
};
const checkPayee = (e: React.ChangeEvent<HTMLInputElement>) => {
setError('');
const validPatPCommand = (validPatP: string) => {
let command = { 'check-payee': validPatP };
api.btcWalletCommand(command);
setTimeout(() => {
setCheckingPatp(false);
}, 5000);
setCheckingPatp(true);
setPayeeType(payeeTypes.ship);
setPayee(validPatP);
};
let payeeReceived = e.target.value;
let isPatp = ob.isValidPatp(`~${deSig(payeeReceived)}`);
let isAddress = validate(payeeReceived);
if (isPatp) {
validPatPCommand(`~${deSig(payeeReceived)}`);
} else if (isAddress) {
setPayee(payeeReceived);
setReady(true);
setCheckingPatp(false);
setPayeeType(payeeTypes.address);
setValidPayee(true);
} else {
setPayee(payeeReceived);
setReady(false);
setCheckingPatp(false);
setPayeeType(payeeTypes.initial);
setValidPayee(false);
}
};
const toggleSignMethod = () => {
setChoosingSignMethod(!choosingSignMethod);
};
const initPayment = () => {
if (payeeType === payeeTypes.ship) {
let command = {
'init-payment': {
payee,
value: satsAmount,
feyb: feeChoices[feeValue][1],
note: note || null,
},
};
api.btcWalletCommand(command).then(() => setSigning(true));
} else if (payeeType === payeeTypes.address) {
let command = {
'init-payment-external': {
address: payee,
value: satsAmount,
feyb: 1,
note: note || null,
},
};
api.btcWalletCommand(command).then(() => setSigning(true));
}
};
useEffect(() => {
if (network === 'bitcoin') {
let url = 'https://bitcoiner.live/api/fees/estimates/latest';
fetch(url)
.then((res) => res.json())
.then((n) => {
// let estimates = Object.keys(n.estimates);
// let mid = Math.floor(estimates.length / 2);
// let high = estimates.length - 1;
setFeeChoices({
[feeLevels.high]: [30, n.estimates[30]['sat_per_vbyte']],
[feeLevels.mid]: [180, n.estimates[180]['sat_per_vbyte']],
[feeLevels.low]: [360, n.estimates[360]['sat_per_vbyte']],
});
});
}
}, []);
useEffect(() => {
if (!ready && !checkingPatp) {
if (shipWallets.payee === payee.slice(1) && shipWallets.hasWallet) {
setReady(true);
setCheckingPatp(false);
setValidPayee(true);
}
}
}, [ready, checkingPatp, shipWallets, payee]);
let payeeColor = 'black';
let payeeBg = 'white';
let payeeBorder = 'lightGray';
if (error) {
payeeColor = 'red';
payeeBorder = 'red';
payeeBg = 'veryLightRed';
} else if (focusedField === focusFields.payee && validPayee) {
payeeColor = 'green';
payeeBorder = 'green';
payeeBg = 'veryLightGreen';
} else if (focusedField !== focusFields.payee && validPayee) {
payeeColor = 'blue';
payeeBorder = 'white';
payeeBg = 'white';
} else if (focusedField !== focusFields.payee && !validPayee) {
payeeColor = 'red';
payeeBorder = 'red';
payeeBg = 'veryLightRed';
} else if (
focusedField === focusFields.payee &&
!validPayee &&
!checkingPatp &&
payeeType === payeeTypes.ship
) {
payeeColor = 'red';
payeeBorder = 'red';
payeeBg = 'veryLightRed';
}
const signReady = ready && satsAmount > 0 && !signing;
let invoice = null;
switch (signMethod) {
case signMethods.masterTicket: {
invoice = (
<Invoice
stopSending={stopSending}
payee={payee}
satsAmount={satsAmount}
/>
);
break;
}
case signMethods.bridge: {
invoice = (
<BridgeInvoice
stopSending={stopSending}
payee={payee}
satsAmount={satsAmount}
/>
);
break;
}
case signMethods.external: {
invoice = (
<ExternalInvoice
stopSending={stopSending}
payee={payee}
satsAmount={satsAmount}
/>
);
break;
}
default:
break;
}
return (
<>
{signing && psbt ? (
invoice
) : (
<Col
width="100%"
backgroundColor="white"
borderRadius="48px"
mb={5}
p={5}
>
<Col width="100%">
<Row justifyContent="space-between" alignItems="center">
<Text highlight color="blue" fontSize={1}>
Send BTC
</Text>
<Text highlight color="blue" fontSize={1}>
{value}
</Text>
<Icon icon="X" cursor="pointer" onClick={() => stopSending()} />
</Row>
<Row alignItems="center" mt={6} justifyContent="space-between">
<Row
justifyContent="space-between"
width="calc(40% - 30px)"
alignItems="center"
>
<Text gray fontSize={1} fontWeight="600">
To
</Text>
{checkingPatp ? (
<LoadingSpinner background="midOrange" foreground="orange" />
) : null}
</Row>
<Input
// autoFocus
onFocus={() => {
setFocusedField(focusFields.payee);
}}
onBlur={() => {
setFocusedField(focusFields.empty);
}}
color={payeeColor}
backgroundColor={payeeBg}
borderColor={payeeBorder}
ml={2}
flexGrow="1"
fontSize="14px"
placeholder="~sampel-palnet or BTC address"
value={payee}
fontFamily="mono"
disabled={signing}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
checkPayee(e)
}
/>
</Row>
{error && (
<Row alignItems="center" justifyContent="space-between">
{/* yes this is a hack */}
<Box width="calc(40% - 30px)" />
<Error error={error} fontSize="14px" />
</Row>
)}
<Row alignItems="center" mt={4} justifyContent="space-between">
<Text gray fontSize={1} fontWeight="600" width="40%">
Amount
</Text>
<Input
onFocus={() => {
setFocusedField(focusFields.currency);
}}
onBlur={() => {
setFocusedField(focusFields.empty);
}}
fontSize="14px"
width="100%"
type="number"
borderColor={
focusedField === focusFields.currency ? 'lightGray' : 'none'
}
disabled={signing}
value={denomAmount}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setDenomAmount(parseFloat(e.target.value));
setSatsAmount(
Math.round(
(parseFloat(e.target.value) / conversion) * 100000000
)
);
}}
/>
<Text color="lighterGray" fontSize={1} ml={3}>
{denomination}
</Text>
</Row>
<Row alignItems="center" mt={2} justifyContent="space-between">
{/* yes this is a hack */}
<Box width="40%" />
<Input
onFocus={() => {
setFocusedField(focusFields.sats);
}}
onBlur={() => {
setFocusedField(focusFields.empty);
}}
fontSize="14px"
width="100%"
type="number"
borderColor={
focusedField === focusFields.sats ? 'lightGray' : 'none'
}
disabled={signing}
value={satsAmount}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setDenomAmount(
parseFloat(e.target.value) * (conversion / 100000000)
);
setSatsAmount(parseInt(e.target.value, 10));
}}
/>
<Text color="lightGray" fontSize={1} ml={3}>
sats
</Text>
</Row>
<Row mt={4} width="100%" justifyContent="space-between">
<Text gray fontSize={1} fontWeight="600" width="40%">
Fee
</Text>
<Row
alignItems="center"
backgroundColor="blue"
borderRadius="24px"
paddingX="12px"
paddingY="8px"
>
<Text mr={2} color="white" fontSize="14px">
{feeChoices[feeValue][1]} sats/vbyte
</Text>
<Button
borderRadius="24px"
height="24px"
width="24px"
border="none"
backgroundColor="rgba(33, 157, 255)"
onClick={() => {
setShowFeePicker((prev) => {
if (prev) {
return false;
}
return true;
});
}}
>
<Icon
icon="ChevronSouth"
width="12px"
color="white"
cursor="pointer"
/>
</Button>
</Row>
</Row>
<Col alignItems="center">
{!showFeePicker ? null : (
<FeePicker
feeChoices={feeChoices}
feeValue={feeValue}
setFeeValue={setFeeValue}
feeDismiss={feeDismiss}
/>
)}
</Col>
<Row
mt={4}
width="100%"
justifyContent="space-between"
alignItems="center"
>
<Text gray fontSize={1} fontWeight="600" width="40%">
Note
</Text>
<Input
onFocus={() => {
setFocusedField(focusFields.note);
}}
onBlur={() => {
setFocusedField(focusFields.empty);
}}
fontSize="14px"
width="100%"
placeholder="What's this for?"
type="text"
borderColor={
focusedField === focusFields.note ? 'lightGray' : 'none'
}
disabled={signing}
value={note}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setNote(e.target.value);
}}
/>
</Row>
</Col>
<Row
flexDirection="row"
alignItems="center"
mt={4}
justifyContent="flex-end"
>
{!(signing && !error) ? null : (
<LoadingSpinner background="midOrange" foreground="orange" />
)}
<Signer
signReady={signReady}
choosingSignMethod={choosingSignMethod}
signMethod={signMethod}
setSignMethod={handleSetSignMethod}
initPayment={initPayment}
/>
<Button
ml={2}
width="48px"
fontSize={1}
fontWeight="bold"
borderRadius="24px"
height="48px"
onClick={() => toggleSignMethod()}
color={signReady ? 'white' : 'lighterGray'}
backgroundColor={
signReady ? 'rgba(33, 157, 255, 0.2)' : 'veryLightGray'
}
disabled={!signReady}
border="none"
style={{ cursor: signReady ? 'pointer' : 'default' }}
>
<Icon
icon="ChevronSouth"
color={signReady ? 'blue' : 'lighterGray'}
/>
</Button>
</Row>
{signMethod === signMethods.masterTicket && (
<Row mt={4} alignItems="center">
<Icon icon="Info" color="yellow" height={4} width={4} />
<Text fontSize="14px" fontWeight="regular" color="gray" ml={2}>
We recommend that you sign transactions using Bridge to protect
your master ticket.
</Text>
</Row>
)}
</Col>
)}
</>
);
};
export default Send; | the_stack |
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Run 'yarn update-api-types' to regenerate.
*/
/**
* FIPS Code. FIPS codes are either 2-digit state codes, 5-digit county codes, or 5-digit CBSA codes.
*/
export type Fips = string;
/**
* 2-letter ISO-3166 Country code.
*/
export type Country = string;
/**
* 2-letter ANSI state code. For CBSA regions, state is omitted.
*/
export type State = string | null;
/**
* County name
*/
export type County = string | null;
/**
* An enumeration.
*/
export type AggregationLevel =
| 'country'
| 'state'
| 'county'
| 'cbsa'
| 'place';
/**
* Latitude of point within the state or county. Currently a placeholder.
*/
export type Lat = number | null;
/**
* Location ID as defined here: https://github.com/covidatlas/li/blob/master/docs/reports-v1.md#general-notes
*/
export type Locationid = string;
/**
* Longitude of point within the state or county. Currently a placeholder.
*/
export type Long = number | null;
/**
* Total Population in geographic region.
*/
export type Population = number;
/**
* Ratio of people who test positive calculated using a 7-day rolling average.
*/
export type Testpositivityratio = number | null;
/**
* Method used to determine test positivity ratio.
*/
export type TestPositivityRatioMethod =
| 'CMSTesting'
| 'CDCTesting'
| 'HHSTesting'
| 'Valorum'
| 'covid_tracking'
| 'other';
/**
* The number of cases per 100k population calculated using a 7-day rolling average.
*/
export type Casedensity = number | null;
/**
* Ratio of currently hired tracers to estimated tracers needed based on 7-day daily case average.
*/
export type Contacttracercapacityratio = number | null;
/**
* R_t, or the estimated number of infections arising from a typical case.
*/
export type Infectionrate = number | null;
/**
* 90th percentile confidence interval upper endpoint of the infection rate.
*/
export type Infectionrateci90 = number | null;
export type Icuheadroomratio = number | null;
/**
* Current number of covid patients in the ICU.
*/
export type Currenticucovid = number;
/**
* Method used to determine number of current ICU patients with covid.
*/
export type CovidPatientsMethod = 'actual' | 'estimated';
/**
* Current number of covid patients in icu.
*/
export type Currenticunoncovid = number;
/**
* Method used to determine number of current ICU patients without covid.
*/
export type NonCovidPatientsMethod =
| 'actual'
| 'estimated_from_typical_utilization'
| 'estimated_from_total_icu_actual';
/**
* Ratio of staffed intensive care unit (ICU) beds that are currently in use.
*/
export type Icucapacityratio = number | null;
/**
* Ratio of population that has initiated vaccination.
*/
export type Vaccinationsinitiatedratio = number | null;
/**
* Ratio of population that has completed vaccination.
*/
export type Vaccinationscompletedratio = number | null;
/**
* Risk levels for region.
*/
export type Risklevels = RiskLevels;
/**
* COVID Risk Level.
*
* ## Risk Level Definitions
* *Low* - On track to contain COVID
* *Medium* - Slow disease growth
* *High* - At risk of outbreak
* *Critical* - Active or imminent outbreak
* *Unknown* - Risk unknown
* *Extreme* - Severe outbreak
*/
export type RiskLevel = 0 | 1 | 2 | 3 | 4 | 5;
/**
* Cumulative confirmed or suspected cases.
*/
export type Cases = number | null;
/**
* Cumulative deaths that are suspected or confirmed to have been caused by COVID-19.
*/
export type Deaths = number | null;
/**
* Cumulative positive test results to date
*/
export type Positivetests = number | null;
/**
* Cumulative negative test results to date
*/
export type Negativetests = number | null;
/**
* Number of Contact Tracers
*/
export type Contacttracers = number | null;
/**
*
* Information about acute bed utilization details.
*
* Fields:
* * capacity - Current staffed acute bed capacity.
* * currentUsageTotal - Total number of acute beds currently in use
* * currentUsageCovid - Number of acute beds currently in use by COVID patients.
* * typicalUsageRate - Typical acute bed utilization rate.
*
*/
export type Hospitalbeds = HospitalResourceUtilization;
/**
* Total capacity for resource.
*/
export type Capacity = number | null;
/**
* Currently used capacity for resource by all patients (COVID + Non-COVID)
*/
export type Currentusagetotal = number | null;
/**
* Currently used capacity for resource by COVID
*/
export type Currentusagecovid = number | null;
/**
* Typical used capacity rate for resource. This excludes any COVID usage.
*/
export type Typicalusagerate = number | null;
/**
*
* Information about ICU bed utilization details.
*
* Fields:
* * capacity - Current staffed ICU bed capacity.
* * currentUsageTotal - Total number of ICU beds currently in use
* * currentUsageCovid - Number of ICU beds currently in use by COVID patients.
* * typicalUsageRate - Typical ICU utilization rate.
*
*/
export type Icubeds = HospitalResourceUtilization;
/**
*
* New confirmed or suspected cases.
*
*
* New cases are a processed timeseries of cases - summing new cases may not equal
* the cumulative case count.
*
* Processing steps:
* 1. If a region does not report cases for a period of time but then begins reporting again,
* we will exclude the first day that reporting recommences. This first day likely includes
* multiple days worth of cases and can be misleading to the overall series.
* 2. We remove any days with negative new cases.
* 3. We apply an outlier detection filter to the timeseries, which removes any data
* points that seem improbable given recent numbers. Many times this is due to
* backfill of previously unreported cases.
*
*/
export type Newcases = number | null;
/**
*
* New confirmed or suspected COVID-19 deaths.
*
* New deaths is an estimate of deaths per day; summing new deaths may not equal the
* cumulative death count.
*
* Processing steps:
* 1. If a region does not report deaths for a period of time but then begins reporting again,
* we will exclude the first day that reporting recommences. This first day likely includes
* multiple days worth of deaths and can be misleading to the overall series.
* 2. We remove any days with negative new deaths.
* 3. We apply an outlier detection filter to the timeseries, which removes any data
* points that seem improbable given recent numbers. Many times this is due to
* backfill of previously unreported deaths.
*
*/
export type Newdeaths = number | null;
/**
* Number of vaccine doses distributed.
*/
export type Vaccinesdistributed = number | null;
/**
*
* Number of vaccinations initiated.
*
* This value may vary by type of vaccine, but for Moderna and Pfizer this indicates
* number of people vaccinated with the first dose.
*
*/
export type Vaccinationsinitiated = number | null;
/**
*
* Number of vaccinations completed.
*
* This value may vary by type of vaccine, but for Moderna and Pfizer this indicates
* number of people vaccinated with both the first and second dose.
*
*/
export type Vaccinationscompleted = number | null;
/**
* Annotations for cases
*/
export type Cases1 = FieldAnnotations;
/**
* The data source of a field (metric or actual). This enumeration lists the places from which
* CAN fetches data. The source is tracked on a per field and region timeseries basis.
*/
export type FieldSourceType =
| 'NYTimes'
| 'CMSTesting'
| 'CDCTesting'
| 'HHSTesting'
| 'HHSHospital'
| 'Valorum'
| 'covid_tracking'
| 'USAFacts'
| 'TestAndTrace'
| 'CANScrapersStateProviders'
| 'other';
/**
* URL of a webpage containing the data at the source
*/
export type Url = string | null;
/**
* A human readable name of the source
*/
export type Name = string | null;
export type Sources = FieldSource[];
/**
* Date of anomaly
*/
export type Date = string;
/**
* The type of the annotation.
*
* Each enumeration refers to the method used to generate the annotation.
*/
export type TagType =
| 'cumulative_tail_truncated'
| 'cumulative_long_tail_truncated'
| 'zscore_outlier'
| 'provenance'
| 'source_url'
| 'source';
/**
* Original value on this date detected as anomalous.
*/
export type OriginalObservation = number;
export type Anomalies = AnomalyAnnotation[];
/**
* Annotations for deaths
*/
export type Deaths1 = FieldAnnotations;
/**
* Annotations for positiveTests
*/
export type Positivetests1 = FieldAnnotations;
/**
* Annotations for negativeTests
*/
export type Negativetests1 = FieldAnnotations;
/**
* Annotations for contactTracers
*/
export type Contacttracers1 = FieldAnnotations;
/**
* Annotations for hospitalBeds
*/
export type Hospitalbeds1 = FieldAnnotations;
/**
* Annotations for icuBeds
*/
export type Icubeds1 = FieldAnnotations;
/**
* Annotations for newCases
*/
export type Newcases1 = FieldAnnotations;
/**
* Annotations for newDeaths
*/
export type Newdeaths1 = FieldAnnotations;
/**
* Annotations for vaccinesDistributed
*/
export type Vaccinesdistributed1 = FieldAnnotations;
/**
* Annotations for vaccinationsInitiated
*/
export type Vaccinationsinitiated1 = FieldAnnotations;
/**
* Annotations for vaccinationsCompleted
*/
export type Vaccinationscompleted1 = FieldAnnotations;
/**
* Annotations for testPositivityRatio
*/
export type Testpositivityratio1 = FieldAnnotations;
/**
* Annotations for caseDensity
*/
export type Casedensity1 = FieldAnnotations;
/**
* Annotations for contactTracerCapacityRatio
*/
export type Contacttracercapacityratio1 = FieldAnnotations;
/**
* Annotations for infectionRate
*/
export type Infectionrate1 = FieldAnnotations;
/**
* Annotations for infectionRateCI90
*/
export type Infectionrateci901 = FieldAnnotations;
/**
* Annotations for icuHeadroomRatio
*/
export type Icuheadroomratio1 = FieldAnnotations;
/**
* Annotations for icuCapacityRatio
*/
export type Icucapacityratio1 = FieldAnnotations;
/**
* Annotations for vaccinationsInitiatedRatio
*/
export type Vaccinationsinitiatedratio1 = FieldAnnotations;
/**
* Annotations for vaccinationsCompletedRatio
*/
export type Vaccinationscompletedratio1 = FieldAnnotations;
/**
* Date of latest data
*/
export type Lastupdateddate = string;
/**
* URL linking to Covid Act Now location page.
*/
export type Url1 = string | null;
/**
* Summary of actual and prediction data for a single region.
*/
export interface RegionSummary {
fips: Fips;
country: Country;
state: State;
county: County;
/**
* Level of region.
*/
level: AggregationLevel;
lat: Lat;
locationId: Locationid;
long: Long;
population: Population;
metrics: Metrics;
riskLevels: Risklevels;
actuals: Actuals;
annotations: Annotations;
lastUpdatedDate: Lastupdateddate;
url: Url1;
}
/**
* Calculated metrics data based on known actuals.
*/
export interface Metrics {
testPositivityRatio: Testpositivityratio;
testPositivityRatioDetails?: TestPositivityRatioDetails | null;
caseDensity: Casedensity;
contactTracerCapacityRatio: Contacttracercapacityratio;
infectionRate: Infectionrate;
infectionRateCI90: Infectionrateci90;
icuHeadroomRatio: Icuheadroomratio;
icuHeadroomDetails?: ICUHeadroomMetricDetails | null;
icuCapacityRatio: Icucapacityratio;
vaccinationsInitiatedRatio?: Vaccinationsinitiatedratio;
vaccinationsCompletedRatio?: Vaccinationscompletedratio;
}
/**
* Details about how the test positivity ratio was calculated.
*/
export interface TestPositivityRatioDetails {
/**
* Source data for test positivity ratio.
*/
source: TestPositivityRatioMethod;
}
/**
* Details about how the ICU Headroom Metric was calculated.
*/
export interface ICUHeadroomMetricDetails {
currentIcuCovid: Currenticucovid;
/**
* Method used to determine number of current ICU patients with covid.
*/
currentIcuCovidMethod: CovidPatientsMethod;
currentIcuNonCovid: Currenticunoncovid;
/**
* Method used to determine number of current ICU patients without covid.
*/
currentIcuNonCovidMethod: NonCovidPatientsMethod;
}
/**
* COVID risk levels for a region.
*/
export interface RiskLevels {
/**
* Overall risk level for region.
*/
overall: RiskLevel;
/**
* Test positivity ratio risk level.
*/
testPositivityRatio: RiskLevel;
/**
* Case density risk level.
*/
caseDensity: RiskLevel;
/**
* Contact tracer capacity ratio risk level.
*/
contactTracerCapacityRatio: RiskLevel;
/**
* Infection rate risk level.
*/
infectionRate: RiskLevel;
/**
* ICU headroom ratio risk level.
*/
icuHeadroomRatio: RiskLevel;
/**
* ICU capacity ratio risk level.
*/
icuCapacityRatio: RiskLevel;
}
/**
* Known actuals data.
*/
export interface Actuals {
cases: Cases;
deaths: Deaths;
positiveTests: Positivetests;
negativeTests: Negativetests;
contactTracers: Contacttracers;
hospitalBeds: Hospitalbeds;
icuBeds: Icubeds;
newCases: Newcases;
newDeaths: Newdeaths;
vaccinesDistributed?: Vaccinesdistributed;
vaccinationsInitiated?: Vaccinationsinitiated;
vaccinationsCompleted?: Vaccinationscompleted;
}
/**
* Base model for API output.
*/
export interface HospitalResourceUtilization {
capacity: Capacity;
currentUsageTotal: Currentusagetotal;
currentUsageCovid: Currentusagecovid;
typicalUsageRate: Typicalusagerate;
}
/**
* Annotations for each field.
*/
export interface Annotations {
cases?: Cases1;
deaths?: Deaths1;
positiveTests?: Positivetests1;
negativeTests?: Negativetests1;
contactTracers?: Contacttracers1;
hospitalBeds?: Hospitalbeds1;
icuBeds?: Icubeds1;
newCases?: Newcases1;
newDeaths?: Newdeaths1;
vaccinesDistributed?: Vaccinesdistributed1;
vaccinationsInitiated?: Vaccinationsinitiated1;
vaccinationsCompleted?: Vaccinationscompleted1;
testPositivityRatio?: Testpositivityratio1;
caseDensity?: Casedensity1;
contactTracerCapacityRatio?: Contacttracercapacityratio1;
infectionRate?: Infectionrate1;
infectionRateCI90?: Infectionrateci901;
icuHeadroomRatio?: Icuheadroomratio1;
icuCapacityRatio?: Icucapacityratio1;
vaccinationsInitiatedRatio?: Vaccinationsinitiatedratio1;
vaccinationsCompletedRatio?: Vaccinationscompletedratio1;
}
/**
* Annotations associated with one field.
*/
export interface FieldAnnotations {
sources: Sources;
anomalies: Anomalies;
}
/**
* Base model for API output.
*/
export interface FieldSource {
/**
* The type of data source from a CAN list of data source types
*/
type?: FieldSourceType;
url?: Url;
name?: Name;
}
/**
* Base model for API output.
*/
export interface AnomalyAnnotation {
date: Date;
/**
* Type of annotation
*/
type: TagType;
original_observation: OriginalObservation;
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/versionsMappers";
import * as Parameters from "../models/parameters";
import { LuisAuthoringContext } from "../luisAuthoringContext";
/** Class representing a Versions. */
export class Versions {
private readonly client: LuisAuthoringContext;
/**
* Create a Versions.
* @param {LuisAuthoringContext} client Reference to the service client.
*/
constructor(client: LuisAuthoringContext) {
this.client = client;
}
/**
* Creates a new version from the selected version.
* @param appId The application ID.
* @param versionId The version ID.
* @param versionCloneObject A model containing the new version ID.
* @param [options] The optional parameters
* @returns Promise<Models.VersionsCloneResponse>
*/
clone(appId: string, versionId: string, versionCloneObject: Models.TaskUpdateObject, options?: msRest.RequestOptionsBase): Promise<Models.VersionsCloneResponse>;
/**
* @param appId The application ID.
* @param versionId The version ID.
* @param versionCloneObject A model containing the new version ID.
* @param callback The callback
*/
clone(appId: string, versionId: string, versionCloneObject: Models.TaskUpdateObject, callback: msRest.ServiceCallback<string>): void;
/**
* @param appId The application ID.
* @param versionId The version ID.
* @param versionCloneObject A model containing the new version ID.
* @param options The optional parameters
* @param callback The callback
*/
clone(appId: string, versionId: string, versionCloneObject: Models.TaskUpdateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<string>): void;
clone(appId: string, versionId: string, versionCloneObject: Models.TaskUpdateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<string>, callback?: msRest.ServiceCallback<string>): Promise<Models.VersionsCloneResponse> {
return this.client.sendOperationRequest(
{
appId,
versionId,
versionCloneObject,
options
},
cloneOperationSpec,
callback) as Promise<Models.VersionsCloneResponse>;
}
/**
* Gets a list of versions for this application ID.
* @param appId The application ID.
* @param [options] The optional parameters
* @returns Promise<Models.VersionsListResponse>
*/
list(appId: string, options?: Models.VersionsListOptionalParams): Promise<Models.VersionsListResponse>;
/**
* @param appId The application ID.
* @param callback The callback
*/
list(appId: string, callback: msRest.ServiceCallback<Models.VersionInfo[]>): void;
/**
* @param appId The application ID.
* @param options The optional parameters
* @param callback The callback
*/
list(appId: string, options: Models.VersionsListOptionalParams, callback: msRest.ServiceCallback<Models.VersionInfo[]>): void;
list(appId: string, options?: Models.VersionsListOptionalParams | msRest.ServiceCallback<Models.VersionInfo[]>, callback?: msRest.ServiceCallback<Models.VersionInfo[]>): Promise<Models.VersionsListResponse> {
return this.client.sendOperationRequest(
{
appId,
options
},
listOperationSpec,
callback) as Promise<Models.VersionsListResponse>;
}
/**
* Gets the version information such as date created, last modified date, endpoint URL, count of
* intents and entities, training and publishing status.
* @param appId The application ID.
* @param versionId The version ID.
* @param [options] The optional parameters
* @returns Promise<Models.VersionsGetResponse>
*/
get(appId: string, versionId: string, options?: msRest.RequestOptionsBase): Promise<Models.VersionsGetResponse>;
/**
* @param appId The application ID.
* @param versionId The version ID.
* @param callback The callback
*/
get(appId: string, versionId: string, callback: msRest.ServiceCallback<Models.VersionInfo>): void;
/**
* @param appId The application ID.
* @param versionId The version ID.
* @param options The optional parameters
* @param callback The callback
*/
get(appId: string, versionId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.VersionInfo>): void;
get(appId: string, versionId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.VersionInfo>, callback?: msRest.ServiceCallback<Models.VersionInfo>): Promise<Models.VersionsGetResponse> {
return this.client.sendOperationRequest(
{
appId,
versionId,
options
},
getOperationSpec,
callback) as Promise<Models.VersionsGetResponse>;
}
/**
* Updates the name or description of the application version.
* @param appId The application ID.
* @param versionId The version ID.
* @param versionUpdateObject A model containing Name and Description of the application.
* @param [options] The optional parameters
* @returns Promise<Models.VersionsUpdateResponse>
*/
update(appId: string, versionId: string, versionUpdateObject: Models.TaskUpdateObject, options?: msRest.RequestOptionsBase): Promise<Models.VersionsUpdateResponse>;
/**
* @param appId The application ID.
* @param versionId The version ID.
* @param versionUpdateObject A model containing Name and Description of the application.
* @param callback The callback
*/
update(appId: string, versionId: string, versionUpdateObject: Models.TaskUpdateObject, callback: msRest.ServiceCallback<Models.OperationStatus>): void;
/**
* @param appId The application ID.
* @param versionId The version ID.
* @param versionUpdateObject A model containing Name and Description of the application.
* @param options The optional parameters
* @param callback The callback
*/
update(appId: string, versionId: string, versionUpdateObject: Models.TaskUpdateObject, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void;
update(appId: string, versionId: string, versionUpdateObject: Models.TaskUpdateObject, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.VersionsUpdateResponse> {
return this.client.sendOperationRequest(
{
appId,
versionId,
versionUpdateObject,
options
},
updateOperationSpec,
callback) as Promise<Models.VersionsUpdateResponse>;
}
/**
* Deletes an application version.
* @param appId The application ID.
* @param versionId The version ID.
* @param [options] The optional parameters
* @returns Promise<Models.VersionsDeleteMethodResponse>
*/
deleteMethod(appId: string, versionId: string, options?: msRest.RequestOptionsBase): Promise<Models.VersionsDeleteMethodResponse>;
/**
* @param appId The application ID.
* @param versionId The version ID.
* @param callback The callback
*/
deleteMethod(appId: string, versionId: string, callback: msRest.ServiceCallback<Models.OperationStatus>): void;
/**
* @param appId The application ID.
* @param versionId The version ID.
* @param options The optional parameters
* @param callback The callback
*/
deleteMethod(appId: string, versionId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void;
deleteMethod(appId: string, versionId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.VersionsDeleteMethodResponse> {
return this.client.sendOperationRequest(
{
appId,
versionId,
options
},
deleteMethodOperationSpec,
callback) as Promise<Models.VersionsDeleteMethodResponse>;
}
/**
* Exports a LUIS application to JSON format.
* @param appId The application ID.
* @param versionId The version ID.
* @param [options] The optional parameters
* @returns Promise<Models.VersionsExportMethodResponse>
*/
exportMethod(appId: string, versionId: string, options?: msRest.RequestOptionsBase): Promise<Models.VersionsExportMethodResponse>;
/**
* @param appId The application ID.
* @param versionId The version ID.
* @param callback The callback
*/
exportMethod(appId: string, versionId: string, callback: msRest.ServiceCallback<Models.LuisApp>): void;
/**
* @param appId The application ID.
* @param versionId The version ID.
* @param options The optional parameters
* @param callback The callback
*/
exportMethod(appId: string, versionId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.LuisApp>): void;
exportMethod(appId: string, versionId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.LuisApp>, callback?: msRest.ServiceCallback<Models.LuisApp>): Promise<Models.VersionsExportMethodResponse> {
return this.client.sendOperationRequest(
{
appId,
versionId,
options
},
exportMethodOperationSpec,
callback) as Promise<Models.VersionsExportMethodResponse>;
}
/**
* Imports a new version into a LUIS application.
* @param appId The application ID.
* @param luisApp A LUIS application structure.
* @param [options] The optional parameters
* @returns Promise<Models.VersionsImportMethodResponse>
*/
importMethod(appId: string, luisApp: Models.LuisApp, options?: Models.VersionsImportMethodOptionalParams): Promise<Models.VersionsImportMethodResponse>;
/**
* @param appId The application ID.
* @param luisApp A LUIS application structure.
* @param callback The callback
*/
importMethod(appId: string, luisApp: Models.LuisApp, callback: msRest.ServiceCallback<string>): void;
/**
* @param appId The application ID.
* @param luisApp A LUIS application structure.
* @param options The optional parameters
* @param callback The callback
*/
importMethod(appId: string, luisApp: Models.LuisApp, options: Models.VersionsImportMethodOptionalParams, callback: msRest.ServiceCallback<string>): void;
importMethod(appId: string, luisApp: Models.LuisApp, options?: Models.VersionsImportMethodOptionalParams | msRest.ServiceCallback<string>, callback?: msRest.ServiceCallback<string>): Promise<Models.VersionsImportMethodResponse> {
return this.client.sendOperationRequest(
{
appId,
luisApp,
options
},
importMethodOperationSpec,
callback) as Promise<Models.VersionsImportMethodResponse>;
}
/**
* Deleted an unlabelled utterance in a version of the application.
* @param appId The application ID.
* @param versionId The version ID.
* @param utterance The utterance text to delete.
* @param [options] The optional parameters
* @returns Promise<Models.VersionsDeleteUnlabelledUtteranceResponse>
*/
deleteUnlabelledUtterance(appId: string, versionId: string, utterance: string, options?: msRest.RequestOptionsBase): Promise<Models.VersionsDeleteUnlabelledUtteranceResponse>;
/**
* @param appId The application ID.
* @param versionId The version ID.
* @param utterance The utterance text to delete.
* @param callback The callback
*/
deleteUnlabelledUtterance(appId: string, versionId: string, utterance: string, callback: msRest.ServiceCallback<Models.OperationStatus>): void;
/**
* @param appId The application ID.
* @param versionId The version ID.
* @param utterance The utterance text to delete.
* @param options The optional parameters
* @param callback The callback
*/
deleteUnlabelledUtterance(appId: string, versionId: string, utterance: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void;
deleteUnlabelledUtterance(appId: string, versionId: string, utterance: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.VersionsDeleteUnlabelledUtteranceResponse> {
return this.client.sendOperationRequest(
{
appId,
versionId,
utterance,
options
},
deleteUnlabelledUtteranceOperationSpec,
callback) as Promise<Models.VersionsDeleteUnlabelledUtteranceResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const cloneOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "apps/{appId}/versions/{versionId}/clone",
urlParameters: [
Parameters.endpoint,
Parameters.appId,
Parameters.versionId0
],
requestBody: {
parameterPath: "versionCloneObject",
mapper: {
...Mappers.TaskUpdateObject,
required: true
}
},
responses: {
201: {
bodyMapper: {
serializedName: "parsedResponse",
type: {
name: "String"
}
}
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "apps/{appId}/versions",
urlParameters: [
Parameters.endpoint,
Parameters.appId
],
queryParameters: [
Parameters.skip,
Parameters.take
],
responses: {
200: {
bodyMapper: {
serializedName: "parsedResponse",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "VersionInfo"
}
}
}
}
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "apps/{appId}/versions/{versionId}/",
urlParameters: [
Parameters.endpoint,
Parameters.appId,
Parameters.versionId0
],
responses: {
200: {
bodyMapper: Mappers.VersionInfo
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const updateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "apps/{appId}/versions/{versionId}/",
urlParameters: [
Parameters.endpoint,
Parameters.appId,
Parameters.versionId0
],
requestBody: {
parameterPath: "versionUpdateObject",
mapper: {
...Mappers.TaskUpdateObject,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.OperationStatus
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const deleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "apps/{appId}/versions/{versionId}/",
urlParameters: [
Parameters.endpoint,
Parameters.appId,
Parameters.versionId0
],
responses: {
200: {
bodyMapper: Mappers.OperationStatus
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const exportMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "apps/{appId}/versions/{versionId}/export",
urlParameters: [
Parameters.endpoint,
Parameters.appId,
Parameters.versionId0
],
responses: {
200: {
bodyMapper: Mappers.LuisApp
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const importMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "apps/{appId}/versions/import",
urlParameters: [
Parameters.endpoint,
Parameters.appId
],
queryParameters: [
Parameters.versionId1
],
requestBody: {
parameterPath: "luisApp",
mapper: {
...Mappers.LuisApp,
required: true
}
},
responses: {
201: {
bodyMapper: {
serializedName: "parsedResponse",
type: {
name: "String"
}
}
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const deleteUnlabelledUtteranceOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "apps/{appId}/versions/{versionId}/suggest",
urlParameters: [
Parameters.endpoint,
Parameters.appId,
Parameters.versionId0
],
requestBody: {
parameterPath: "utterance",
mapper: {
required: true,
serializedName: "utterance",
type: {
name: "String"
}
}
},
responses: {
200: {
bodyMapper: Mappers.OperationStatus
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
}; | the_stack |
import { ISessionContext, Toolbar } from '@jupyterlab/apputils';
import { CodeEditor } from '@jupyterlab/codeeditor';
import { IChangedArgs as IChangedArgsGeneric } from '@jupyterlab/coreutils';
import { IModelDB } from '@jupyterlab/observables';
import { IRenderMime } from '@jupyterlab/rendermime-interfaces';
import { Contents, Kernel } from '@jupyterlab/services';
import * as models from '@jupyterlab/shared-models';
import { ITranslator } from '@jupyterlab/translation';
import { LabIcon } from '@jupyterlab/ui-components';
import { IIterator } from '@lumino/algorithm';
import { PartialJSONValue, ReadonlyPartialJSONValue } from '@lumino/coreutils';
import { IDisposable } from '@lumino/disposable';
import { ISignal } from '@lumino/signaling';
import { DockLayout, Widget } from '@lumino/widgets';
/**
* The document registry.
*/
export declare class DocumentRegistry implements IDisposable {
/**
* Construct a new document registry.
*/
constructor(options?: DocumentRegistry.IOptions);
/**
* A signal emitted when the registry has changed.
*/
get changed(): ISignal<this, DocumentRegistry.IChangedArgs>;
/**
* Get whether the document registry has been disposed.
*/
get isDisposed(): boolean;
/**
* Dispose of the resources held by the document registry.
*/
dispose(): void;
/**
* Add a widget factory to the registry.
*
* @param factory - The factory instance to register.
*
* @returns A disposable which will unregister the factory.
*
* #### Notes
* If a factory with the given `'name'` is already registered,
* a warning will be logged, and this will be a no-op.
* If `'*'` is given as a default extension, the factory will be registered
* as the global default.
* If an extension or global default is already registered, this factory
* will override the existing default.
* The factory cannot be named an empty string or the string `'default'`.
*/
addWidgetFactory(factory: DocumentRegistry.WidgetFactory): IDisposable;
/**
* Add a model factory to the registry.
*
* @param factory - The factory instance.
*
* @returns A disposable which will unregister the factory.
*
* #### Notes
* If a factory with the given `name` is already registered, or
* the given factory is already registered, a warning will be logged
* and this will be a no-op.
*/
addModelFactory(factory: DocumentRegistry.ModelFactory): IDisposable;
/**
* Add a widget extension to the registry.
*
* @param widgetName - The name of the widget factory.
*
* @param extension - A widget extension.
*
* @returns A disposable which will unregister the extension.
*
* #### Notes
* If the extension is already registered for the given
* widget name, a warning will be logged and this will be a no-op.
*/
addWidgetExtension(widgetName: string, extension: DocumentRegistry.WidgetExtension): IDisposable;
/**
* Add a file type to the document registry.
*
* @params fileType - The file type object to register.
*
* @returns A disposable which will unregister the command.
*
* #### Notes
* These are used to populate the "Create New" dialog.
*/
addFileType(fileType: Partial<DocumentRegistry.IFileType>): IDisposable;
/**
* Get a list of the preferred widget factories.
*
* @param path - The file path to filter the results.
*
* @returns A new array of widget factories.
*
* #### Notes
* Only the widget factories whose associated model factory have
* been registered will be returned.
* The first item is considered the default. The returned array
* has widget factories in the following order:
* - path-specific default factory
* - path-specific default rendered factory
* - global default factory
* - all other path-specific factories
* - all other global factories
*/
preferredWidgetFactories(path: string): DocumentRegistry.WidgetFactory[];
/**
* Get the default rendered widget factory for a path.
*
* @param path - The path to for which to find a widget factory.
*
* @returns The default rendered widget factory for the path.
*
* ### Notes
* If the widget factory has registered a separate set of `defaultRendered`
* file types and there is a match in that set, this returns that.
* Otherwise, this returns the same widget factory as
* [[defaultWidgetFactory]].
*/
defaultRenderedWidgetFactory(path: string): DocumentRegistry.WidgetFactory;
/**
* Get the default widget factory for a path.
*
* @param path - An optional file path to filter the results.
*
* @returns The default widget factory for an path.
*
* #### Notes
* This is equivalent to the first value in [[preferredWidgetFactories]].
*/
defaultWidgetFactory(path?: string): DocumentRegistry.WidgetFactory;
/**
* Set overrides for the default widget factory for a file type.
*
* Normally, a widget factory informs the document registry which file types
* it should be the default for using the `defaultFor` option in the
* IWidgetFactoryOptions. This function can be used to override that after
* the fact.
*
* @param fileType: The name of the file type.
*
* @param factory: The name of the factory.
*
* #### Notes
* If `factory` is undefined, then any override will be unset, and the
* default factory will revert to the original value.
*
* If `factory` or `fileType` are not known to the docregistry, or
* if `factory` cannot open files of type `fileType`, this will throw
* an error.
*/
setDefaultWidgetFactory(fileType: string, factory: string | undefined): void;
/**
* Create an iterator over the widget factories that have been registered.
*
* @returns A new iterator of widget factories.
*/
widgetFactories(): IIterator<DocumentRegistry.WidgetFactory>;
/**
* Create an iterator over the model factories that have been registered.
*
* @returns A new iterator of model factories.
*/
modelFactories(): IIterator<DocumentRegistry.ModelFactory>;
/**
* Create an iterator over the registered extensions for a given widget.
*
* @param widgetName - The name of the widget factory.
*
* @returns A new iterator over the widget extensions.
*/
widgetExtensions(widgetName: string): IIterator<DocumentRegistry.WidgetExtension>;
/**
* Create an iterator over the file types that have been registered.
*
* @returns A new iterator of file types.
*/
fileTypes(): IIterator<DocumentRegistry.IFileType>;
/**
* Get a widget factory by name.
*
* @param widgetName - The name of the widget factory.
*
* @returns A widget factory instance.
*/
getWidgetFactory(widgetName: string): DocumentRegistry.WidgetFactory | undefined;
/**
* Get a model factory by name.
*
* @param name - The name of the model factory.
*
* @returns A model factory instance.
*/
getModelFactory(name: string): DocumentRegistry.ModelFactory | undefined;
/**
* Get a file type by name.
*/
getFileType(name: string): DocumentRegistry.IFileType | undefined;
/**
* Get a kernel preference.
*
* @param path - The file path.
*
* @param widgetName - The name of the widget factory.
*
* @param kernel - An optional existing kernel model.
*
* @returns A kernel preference.
*/
getKernelPreference(path: string, widgetName: string, kernel?: Partial<Kernel.IModel>): ISessionContext.IKernelPreference | undefined;
/**
* Get the best file type given a contents model.
*
* @param model - The contents model of interest.
*
* @returns The best matching file type.
*/
getFileTypeForModel(model: Partial<Contents.IModel>): DocumentRegistry.IFileType;
/**
* Get the file types that match a file name.
*
* @param path - The path of the file.
*
* @returns An ordered list of matching file types.
*/
getFileTypesForPath(path: string): DocumentRegistry.IFileType[];
protected translator: ITranslator;
private _modelFactories;
private _widgetFactories;
private _defaultWidgetFactory;
private _defaultWidgetFactoryOverrides;
private _defaultWidgetFactories;
private _defaultRenderedWidgetFactories;
private _widgetFactoriesForFileType;
private _fileTypes;
private _extenders;
private _changed;
private _isDisposed;
}
/**
* The namespace for the `DocumentRegistry` class statics.
*/
export declare namespace DocumentRegistry {
/**
* The item to be added to document toolbar.
*/
interface IToolbarItem {
name: string;
widget: Widget;
}
/**
* The options used to create a document registry.
*/
interface IOptions {
/**
* The text model factory for the registry. A default instance will
* be used if not given.
*/
textModelFactory?: ModelFactory;
/**
* The initial file types for the registry.
* The [[DocumentRegistry.defaultFileTypes]] will be used if not given.
*/
initialFileTypes?: DocumentRegistry.IFileType[];
/**
* The application language translator.
*/
translator?: ITranslator;
}
/**
* The interface for a document model.
*/
interface IModel extends IDisposable {
/**
* A signal emitted when the document content changes.
*/
contentChanged: ISignal<this, void>;
/**
* A signal emitted when the model state changes.
*/
stateChanged: ISignal<this, IChangedArgsGeneric<any>>;
/**
* The dirty state of the model.
*
* #### Notes
* This should be cleared when the document is loaded from
* or saved to disk.
*/
dirty: boolean;
/**
* The read-only state of the model.
*/
readOnly: boolean;
/**
* The default kernel name of the document.
*/
readonly defaultKernelName: string;
/**
* The default kernel language of the document.
*/
readonly defaultKernelLanguage: string;
/**
* The underlying `IModelDB` instance in which model
* data is stored.
*
* ### Notes
* Making direct edits to the values stored in the`IModelDB`
* is not recommended, and may produce unpredictable results.
*/
readonly modelDB: IModelDB;
/**
* The shared notebook model.
*/
readonly sharedModel: models.ISharedDocument;
/**
* Serialize the model to a string.
*/
toString(): string;
/**
* Deserialize the model from a string.
*
* #### Notes
* Should emit a [contentChanged] signal.
*/
fromString(value: string): void;
/**
* Serialize the model to JSON.
*/
toJSON(): PartialJSONValue;
/**
* Deserialize the model from JSON.
*
* #### Notes
* Should emit a [contentChanged] signal.
*/
fromJSON(value: ReadonlyPartialJSONValue): void;
/**
* Initialize model state after initial data load.
*
* #### Notes
* This function must be called after the initial data is loaded to set up
* initial model state, such as an initial undo stack, etc.
*/
initialize(): void;
}
/**
* The interface for a document model that represents code.
*/
interface ICodeModel extends IModel, CodeEditor.IModel {
sharedModel: models.ISharedFile;
}
/**
* The document context object.
*/
interface IContext<T extends IModel> extends IDisposable {
/**
* A signal emitted when the path changes.
*/
pathChanged: ISignal<this, string>;
/**
* A signal emitted when the contentsModel changes.
*/
fileChanged: ISignal<this, Contents.IModel>;
/**
* A signal emitted on the start and end of a saving operation.
*/
saveState: ISignal<this, SaveState>;
/**
* A signal emitted when the context is disposed.
*/
disposed: ISignal<this, void>;
/**
* The data model for the document.
*/
readonly model: T;
/**
* The session context object associated with the context.
*/
readonly sessionContext: ISessionContext;
/**
* The current path associated with the document.
*/
readonly path: string;
/**
* The current local path associated with the document.
* If the document is in the default notebook file browser,
* this is the same as the path.
*/
readonly localPath: string;
/**
* The document metadata, stored as a services contents model.
*
* #### Notes
* This will be null until the context is 'ready'. Since we only store
* metadata here, the `.contents` attribute will always be empty.
*/
readonly contentsModel: Contents.IModel | null;
/**
* The url resolver for the context.
*/
readonly urlResolver: IRenderMime.IResolver;
/**
* Whether the context is ready.
*/
readonly isReady: boolean;
/**
* A promise that is fulfilled when the context is ready.
*/
readonly ready: Promise<void>;
/**
* Rename the document.
*/
rename(newName: string): Promise<void>;
/**
* Save the document contents to disk.
*/
save(): Promise<void>;
/**
* Save the document to a different path chosen by the user.
*/
saveAs(): Promise<void>;
/**
* Save the document to a different path chosen by the user.
*/
download(): Promise<void>;
/**
* Revert the document contents to disk contents.
*/
revert(): Promise<void>;
/**
* Create a checkpoint for the file.
*
* @returns A promise which resolves with the new checkpoint model when the
* checkpoint is created.
*/
createCheckpoint(): Promise<Contents.ICheckpointModel>;
/**
* Delete a checkpoint for the file.
*
* @param checkpointID - The id of the checkpoint to delete.
*
* @returns A promise which resolves when the checkpoint is deleted.
*/
deleteCheckpoint(checkpointID: string): Promise<void>;
/**
* Restore the file to a known checkpoint state.
*
* @param checkpointID - The optional id of the checkpoint to restore,
* defaults to the most recent checkpoint.
*
* @returns A promise which resolves when the checkpoint is restored.
*/
restoreCheckpoint(checkpointID?: string): Promise<void>;
/**
* List available checkpoints for the file.
*
* @returns A promise which resolves with a list of checkpoint models for
* the file.
*/
listCheckpoints(): Promise<Contents.ICheckpointModel[]>;
/**
* Add a sibling widget to the document manager.
*
* @param widget - The widget to add to the document manager.
*
* @param options - The desired options for adding the sibling.
*
* @returns A disposable used to remove the sibling if desired.
*
* #### Notes
* It is assumed that the widget has the same model and context
* as the original widget.
*/
addSibling(widget: Widget, options?: IOpenOptions): IDisposable;
}
type SaveState = 'started' | 'failed' | 'completed';
/**
* A type alias for a context.
*/
type Context = IContext<IModel>;
/**
* A type alias for a code context.
*/
type CodeContext = IContext<ICodeModel>;
/**
* The options used to initialize a widget factory.
*/
interface IWidgetFactoryOptions<T extends Widget = Widget> {
/**
* The name of the widget to display in dialogs.
*/
readonly name: string;
/**
* The file types the widget can view.
*/
readonly fileTypes: ReadonlyArray<string>;
/**
* The file types for which the factory should be the default.
*/
readonly defaultFor?: ReadonlyArray<string>;
/**
* The file types for which the factory should be the default for rendering,
* if that is different than the default factory (which may be for editing).
* If undefined, then it will fall back on the default file type.
*/
readonly defaultRendered?: ReadonlyArray<string>;
/**
* Whether the widget factory is read only.
*/
readonly readOnly?: boolean;
/**
* The registered name of the model type used to create the widgets.
*/
readonly modelName?: string;
/**
* Whether the widgets prefer having a kernel started.
*/
readonly preferKernel?: boolean;
/**
* Whether the widgets can start a kernel when opened.
*/
readonly canStartKernel?: boolean;
/**
* Whether the kernel should be shutdown when the widget is closed.
*/
readonly shutdownOnClose?: boolean;
/**
* The application language translator.
*/
readonly translator?: ITranslator;
/**
* A function producing toolbar widgets, overriding the default toolbar widgets.
*/
readonly toolbarFactory?: (widget: T) => DocumentRegistry.IToolbarItem[];
}
/**
* The options used to open a widget.
*/
interface IOpenOptions {
/**
* The reference widget id for the insert location.
*
* The default is `null`.
*/
ref?: string | null;
/**
* The supported insertion modes.
*
* An insert mode is used to specify how a widget should be added
* to the main area relative to a reference widget.
*/
mode?: DockLayout.InsertMode;
/**
* Whether to activate the widget. Defaults to `true`.
*/
activate?: boolean;
/**
* The rank order of the widget among its siblings.
*
* #### Notes
* This field may be used or ignored depending on shell implementation.
*/
rank?: number;
}
/**
* The interface for a widget factory.
*/
interface IWidgetFactory<T extends IDocumentWidget, U extends IModel> extends IDisposable, IWidgetFactoryOptions {
/**
* A signal emitted when a new widget is created.
*/
widgetCreated: ISignal<IWidgetFactory<T, U>, T>;
/**
* Create a new widget given a context.
*
* @param source - A widget to clone
*
* #### Notes
* It should emit the [widgetCreated] signal with the new widget.
*/
createNew(context: IContext<U>, source?: T): T;
}
/**
* A type alias for a standard widget factory.
*/
type WidgetFactory = IWidgetFactory<IDocumentWidget, IModel>;
/**
* An interface for a widget extension.
*/
interface IWidgetExtension<T extends Widget, U extends IModel> {
/**
* Create a new extension for a given widget.
*/
createNew(widget: T, context: IContext<U>): IDisposable | void;
}
/**
* A type alias for a standard widget extension.
*/
type WidgetExtension = IWidgetExtension<Widget, IModel>;
/**
* The interface for a model factory.
*/
interface IModelFactory<T extends IModel> extends IDisposable {
/**
* The name of the model.
*/
readonly name: string;
/**
* The content type of the file (defaults to `"file"`).
*/
readonly contentType: Contents.ContentType;
/**
* The format of the file (defaults to `"text"`).
*/
readonly fileFormat: Contents.FileFormat;
/**
* Create a new model for a given path.
*
* @param languagePreference - An optional kernel language preference.
* @param modelDB - An optional modelDB.
* @param isInitialized - An optional flag to check if the model is initialized.
*
* @returns A new document model.
*/
createNew(languagePreference?: string, modelDB?: IModelDB, isInitialized?: boolean): T;
/**
* Get the preferred kernel language given a file path.
*/
preferredLanguage(path: string): string;
}
/**
* A type alias for a standard model factory.
*/
type ModelFactory = IModelFactory<IModel>;
/**
* A type alias for a code model factory.
*/
type CodeModelFactory = IModelFactory<ICodeModel>;
/**
* An interface for a file type.
*/
interface IFileType {
/**
* The name of the file type.
*/
readonly name: string;
/**
* The mime types associated the file type.
*/
readonly mimeTypes: ReadonlyArray<string>;
/**
* The extensions of the file type (e.g. `".txt"`). Can be a compound
* extension (e.g. `".table.json`).
*/
readonly extensions: ReadonlyArray<string>;
/**
* An optional display name for the file type.
*/
readonly displayName?: string;
/**
* An optional pattern for a file name (e.g. `^Dockerfile$`).
*/
readonly pattern?: string;
/**
* The icon for the file type.
*/
readonly icon?: LabIcon;
/**
* The icon class name for the file type.
*/
readonly iconClass?: string;
/**
* The icon label for the file type.
*/
readonly iconLabel?: string;
/**
* The content type of the new file.
*/
readonly contentType: Contents.ContentType;
/**
* The format of the new file.
*/
readonly fileFormat: Contents.FileFormat;
}
/**
* An arguments object for the `changed` signal.
*/
interface IChangedArgs {
/**
* The type of the changed item.
*/
readonly type: 'widgetFactory' | 'modelFactory' | 'widgetExtension' | 'fileType';
/**
* The name of the item or the widget factory being extended.
*/
readonly name?: string;
/**
* Whether the item was added or removed.
*/
readonly change: 'added' | 'removed';
}
/**
* The defaults used for a file type.
*
* @param translator - The application language translator.
*
* @returns The default file type.
*/
function getFileTypeDefaults(translator?: ITranslator): IFileType;
/**
* The default text file type used by the document registry.
*
* @param translator - The application language translator.
*
* @returns The default text file type.
*/
function getDefaultTextFileType(translator?: ITranslator): IFileType;
/**
* The default notebook file type used by the document registry.
*
* @param translator - The application language translator.
*
* @returns The default notebook file type.
*/
function getDefaultNotebookFileType(translator?: ITranslator): IFileType;
/**
* The default directory file type used by the document registry.
*
* @param translator - The application language translator.
*
* @returns The default directory file type.
*/
function getDefaultDirectoryFileType(translator?: ITranslator): IFileType;
/**
* The default file types used by the document registry.
*
* @param translator - The application language translator.
*
* @returns The default directory file types.
*/
function getDefaultFileTypes(translator?: ITranslator): ReadonlyArray<Partial<IFileType>>;
}
/**
* An interface for a document widget.
*/
export interface IDocumentWidget<T extends Widget = Widget, U extends DocumentRegistry.IModel = DocumentRegistry.IModel> extends Widget {
/**
* The content widget.
*/
readonly content: T;
/**
* A promise resolving after the content widget is revealed.
*/
readonly revealed: Promise<void>;
/**
* The context associated with the document.
*/
readonly context: DocumentRegistry.IContext<U>;
/**
* The toolbar for the widget.
*/
readonly toolbar: Toolbar<Widget>;
/**
* Set URI fragment identifier.
*/
setFragment(fragment: string): void;
} | the_stack |
interface Structure<T extends StructureConstant = StructureConstant> extends RoomObject {
readonly prototype: Structure;
/**
* The current amount of hit points of the structure.
*/
hits: number;
/**
* The total amount of hit points of the structure.
*/
hitsMax: number;
/**
* A unique object identifier. You can use Game.getObjectById method to retrieve an object instance by its id.
*/
id: Id<this>;
/**
* If you can get an instance of a Structure, you can see it.
* If you can see the Structure, you can see the room it's in.
*/
room: Room;
/**
* One of the STRUCTURE_* constants.
*/
structureType: T;
/**
* Destroy this structure immediately.
*/
destroy(): ScreepsReturnCode;
/**
* Check whether this structure can be used. If the room controller level is not enough, then this method will return false, and the structure will be highlighted with red in the game.
*/
isActive(): boolean;
/**
* Toggle auto notification when the structure is under attack. The notification will be sent to your account email. Turned on by default.
* @param enabled Whether to enable notification or disable.
*/
notifyWhenAttacked(enabled: boolean): ScreepsReturnCode;
}
interface StructureConstructor extends _Constructor<Structure>, _ConstructorById<Structure> {}
declare const Structure: StructureConstructor;
/**
* The base prototype for a structure that has an owner. Such structures can be
* found using `FIND_MY_STRUCTURES` and `FIND_HOSTILE_STRUCTURES` constants.
*/
interface OwnedStructure<T extends StructureConstant = StructureConstant> extends Structure<T> {
readonly prototype: OwnedStructure;
/**
* Whether this is your own structure. Walls and roads don't have this property as they are considered neutral structures.
*/
my: boolean;
/**
* An object with the structure’s owner info (if present) containing the following properties: username
*/
owner: T extends STRUCTURE_CONTROLLER ? Owner | undefined : Owner;
/**
* The link to the Room object. Is always present because owned structures give visibility.
*/
room: Room;
}
interface OwnedStructureConstructor extends _Constructor<OwnedStructure>, _ConstructorById<OwnedStructure> {}
declare const OwnedStructure: OwnedStructureConstructor;
/**
* Claim this structure to take control over the room. The controller structure
* cannot be damaged or destroyed. It can be addressed by `Room.controller`
* property.
*/
interface StructureController extends OwnedStructure<STRUCTURE_CONTROLLER> {
readonly prototype: StructureController;
/**
* Whether using power is enabled in this room.
*
* Use `PowerCreep.enableRoom()` to turn powers on.
*/
isPowerEnabled: boolean;
/**
* Current controller level, from 0 to 8.
*/
level: number;
/**
* The current progress of upgrading the controller to the next level.
*/
progress: number;
/**
* The progress needed to reach the next level.
*/
progressTotal: number;
/**
* An object with the controller reservation info if present: username, ticksToEnd
*/
reservation: ReservationDefinition | undefined;
/**
* How many ticks of safe mode are remaining, or undefined.
*/
safeMode?: number;
/**
* Safe mode activations available to use.
*/
safeModeAvailable: number;
/**
* During this period in ticks new safe mode activations will be blocked, undefined if cooldown is inactive.
*/
safeModeCooldown?: number;
/**
* An object with the controller sign info if present
*/
sign: SignDefinition | undefined;
/**
* The amount of game ticks when this controller will lose one level. This timer can be reset by using Creep.upgradeController.
*/
ticksToDowngrade: number;
/**
* The amount of game ticks while this controller cannot be upgraded due to attack.
*/
upgradeBlocked: number;
/**
* Activate safe mode if available.
* @returns Result Code: OK, ERR_NOT_OWNER, ERR_BUSY, ERR_NOT_ENOUGH_RESOURCES, ERR_TIRED
*/
activateSafeMode(): ScreepsReturnCode;
/**
* Make your claimed controller neutral again.
*/
unclaim(): ScreepsReturnCode;
}
interface StructureControllerConstructor extends _Constructor<StructureController>, _ConstructorById<StructureController> {}
declare const StructureController: StructureControllerConstructor;
/**
* Contains energy which can be spent on spawning bigger creeps. Extensions can
* be placed anywhere in the room, any spawns will be able to use them regardless
* of distance.
*/
interface StructureExtension extends OwnedStructure<STRUCTURE_EXTENSION> {
readonly prototype: StructureExtension;
/**
* The amount of energy containing in the extension.
* @deprecated An alias for .store[RESOURCE_ENERGY].
*/
energy: number;
/**
* The total amount of energy the extension can contain.
* @deprecated An alias for .store.getCapacity(RESOURCE_ENERGY).
*/
energyCapacity: number;
/**
* A Store object that contains cargo of this structure.
*/
store: Store<RESOURCE_ENERGY, false>;
}
interface StructureExtensionConstructor extends _Constructor<StructureExtension>, _ConstructorById<StructureExtension> {}
declare const StructureExtension: StructureExtensionConstructor;
/**
* Remotely transfers energy to another Link in the same room.
*/
interface StructureLink extends OwnedStructure<STRUCTURE_LINK> {
readonly prototype: StructureLink;
/**
* The amount of game ticks the link has to wait until the next transfer is possible.
*/
cooldown: number;
/**
* The amount of energy containing in the link.
* @deprecated An alias for .store[RESOURCE_ENERGY].
*/
energy: number;
/**
* The total amount of energy the link can contain.
* @deprecated An alias for .store.getCapacity(RESOURCE_ENERGY).
*/
energyCapacity: number;
/**
* A Store object that contains cargo of this structure.
*/
store: Store<RESOURCE_ENERGY, false>;
/**
* Transfer energy from the link to another link or a creep.
*
* If the target is a creep, it has to be at adjacent square to the link.
*
* If the target is a link, it can be at any location in the same room.
*
* Remote transfer process implies 3% energy loss and cooldown delay depending on the distance.
* @param target The target object.
* @param amount The amount of energy to be transferred. If omitted, all the available energy is used.
*/
transferEnergy(target: Creep | StructureLink, amount?: number): ScreepsReturnCode;
}
interface StructureLinkConstructor extends _Constructor<StructureLink>, _ConstructorById<StructureLink> {}
declare const StructureLink: StructureLinkConstructor;
/**
* Non-player structure. Spawns NPC Source Keepers that guards energy sources
* and minerals in some rooms. This structure cannot be destroyed.
*/
interface StructureKeeperLair extends OwnedStructure<STRUCTURE_KEEPER_LAIR> {
readonly prototype: StructureKeeperLair;
/**
* Time to spawning of the next Source Keeper.
*/
ticksToSpawn?: number;
}
interface StructureKeeperLairConstructor extends _Constructor<StructureKeeperLair>, _ConstructorById<StructureKeeperLair> {}
declare const StructureKeeperLair: StructureKeeperLairConstructor;
/**
* Provides visibility into a distant room from your script.
*/
interface StructureObserver extends OwnedStructure<STRUCTURE_OBSERVER> {
readonly prototype: StructureObserver;
/**
* Provide visibility into a distant room from your script. The target room object will be available on the next tick. The maximum range is 5 rooms.
* @param roomName The room to observe.
*/
observeRoom(roomName: string): ScreepsReturnCode;
}
interface StructureObserverConstructor extends _Constructor<StructureObserver>, _ConstructorById<StructureObserver> {}
declare const StructureObserver: StructureObserverConstructor;
/**
* Non-player structure. Contains power resource which can be obtained by destroying the structure. Hits the attacker creep back on each attack.
*/
interface StructurePowerBank extends OwnedStructure<STRUCTURE_POWER_BANK> {
readonly prototype: StructurePowerBank;
/**
* The amount of power containing.
*/
power: number;
/**
* The amount of game ticks when this structure will disappear.
*/
ticksToDecay: number;
}
interface StructurePowerBankConstructor extends _Constructor<StructurePowerBank>, _ConstructorById<StructurePowerBank> {}
declare const StructurePowerBank: StructurePowerBankConstructor;
/**
* Non-player structure. Contains power resource which can be obtained by
* destroying the structure. Hits the attacker creep back on each attack.
*/
interface StructurePowerSpawn extends OwnedStructure<STRUCTURE_POWER_SPAWN> {
readonly prototype: StructurePowerSpawn;
/**
* The amount of energy containing in this structure.
* @deprecated An alias for .store[RESOURCE_ENERGY].
*/
energy: number;
/**
* The total amount of energy this structure can contain.
* @deprecated An alias for .store.getCapacity(RESOURCE_ENERGY).
*/
energyCapacity: number;
/**
* The amount of power containing in this structure.
* @deprecated An alias for .store[RESOURCE_POWER].
*/
power: number;
/**
* The total amount of power this structure can contain.
* @deprecated An alias for .store.getCapacity(RESOURCE_POWER).
*/
powerCapacity: number;
/**
*
*/
store: Store<RESOURCE_ENERGY | RESOURCE_POWER, false>;
/**
* Register power resource units into your account. Registered power allows to develop power creeps skills. Consumes 1 power resource unit and 50 energy resource units.
*/
processPower(): ScreepsReturnCode;
}
interface StructurePowerSpawnConstructor extends _Constructor<StructurePowerSpawn>, _ConstructorById<StructurePowerSpawn> {}
declare const StructurePowerSpawn: StructurePowerSpawnConstructor;
/**
* Blocks movement of hostile creeps, and defends your creeps and structures on
* the same tile. Can be used as a controllable gate.
*/
interface StructureRampart extends OwnedStructure<STRUCTURE_RAMPART> {
readonly prototype: StructureRampart;
/**
* The amount of game ticks when this rampart will lose some hit points.
*/
ticksToDecay: number;
/**
* If false (default), only your creeps can step on the same square. If true, any hostile creeps can pass through.
*/
isPublic: boolean;
/**
* Make this rampart public to allow other players' creeps to pass through.
* @param isPublic Whether this rampart should be public or non-public
*/
setPublic(isPublic: boolean): undefined;
}
interface StructureRampartConstructor extends _Constructor<StructureRampart>, _ConstructorById<StructureRampart> {}
declare const StructureRampart: StructureRampartConstructor;
/**
* Decreases movement cost to 1. Using roads allows creating creeps with less
* `MOVE` body parts.
*/
interface StructureRoad extends Structure<STRUCTURE_ROAD> {
readonly prototype: StructureRoad;
/**
* The amount of game ticks when this road will lose some hit points.
*/
ticksToDecay: number;
}
interface StructureRoadConstructor extends _Constructor<StructureRoad>, _ConstructorById<StructureRoad> {}
declare const StructureRoad: StructureRoadConstructor;
/**
* A structure that can store huge amount of resource units. Only one structure
* per room is allowed that can be addressed by `Room.storage` property.
*/
interface StructureStorage extends OwnedStructure<STRUCTURE_STORAGE> {
readonly prototype: StructureStorage;
/**
* An object with the storage contents.
*/
store: StoreDefinition;
/**
* The total amount of resources the storage can contain.
* @deprecated An alias for .store.getCapacity().
*/
storeCapacity: number;
}
interface StructureStorageConstructor extends _Constructor<StructureStorage>, _ConstructorById<StructureStorage> {}
declare const StructureStorage: StructureStorageConstructor;
/**
* Remotely attacks or heals creeps, or repairs structures. Can be targeted to
* any object in the room. However, its effectiveness highly depends on the
* distance. Each action consumes energy.
*/
interface StructureTower extends OwnedStructure<STRUCTURE_TOWER> {
readonly prototype: StructureTower;
/**
* The amount of energy containing in this structure.
* @deprecated An alias for .store[RESOURCE_ENERGY].
*/
energy: number;
/**
* The total amount of energy this structure can contain.
* @deprecated An alias for .store.getCapacity(RESOURCE_ENERGY).
*/
energyCapacity: number;
/**
* A Store object that contains cargo of this structure.
*/
store: Store<RESOURCE_ENERGY, false>;
/**
* Remotely attack any creep or structure in the room. Consumes 10 energy units per tick. Attack power depends on the distance to the target: from 600 hits at range 10 to 300 hits at range 40.
* @param target The target creep.
*/
attack(target: AnyCreep | Structure): ScreepsReturnCode;
/**
* Remotely heal any creep in the room. Consumes 10 energy units per tick. Heal power depends on the distance to the target: from 400 hits at range 10 to 200 hits at range 40.
* @param target The target creep.
*/
heal(target: AnyCreep): ScreepsReturnCode;
/**
* Remotely repair any structure in the room. Consumes 10 energy units per tick. Repair power depends on the distance to the target: from 600 hits at range 10 to 300 hits at range 40.
* @param target The target structure.
*/
repair(target: Structure): ScreepsReturnCode;
}
interface StructureTowerConstructor extends _Constructor<StructureTower>, _ConstructorById<StructureTower> {}
declare const StructureTower: StructureTowerConstructor;
/**
* Blocks movement of all creeps.
*/
interface StructureWall extends Structure<STRUCTURE_WALL> {
readonly prototype: StructureWall;
/**
* The amount of game ticks when the wall will disappear (only for automatically placed border walls at the start of the game).
*/
ticksToLive: number;
}
interface StructureWallConstructor extends _Constructor<StructureWall>, _ConstructorById<StructureWall> {}
declare const StructureWall: StructureWallConstructor;
/**
* Allows to harvest mineral deposits.
*/
interface StructureExtractor extends OwnedStructure<STRUCTURE_EXTRACTOR> {
readonly prototype: StructureExtractor;
/**
* The amount of game ticks until the next harvest action is possible.
*/
cooldown: number;
}
interface StructureExtractorConstructor extends _Constructor<StructureExtractor>, _ConstructorById<StructureExtractor> {}
declare const StructureExtractor: StructureExtractorConstructor;
/**
* Produces mineral compounds from base minerals and boosts creeps.
*/
interface StructureLab extends OwnedStructure<STRUCTURE_LAB> {
readonly prototype: StructureLab;
/**
* The amount of game ticks the lab has to wait until the next reaction is possible.
*/
cooldown: number;
/**
* The amount of energy containing in the lab. Energy is used for boosting creeps.
* @deprecated An alias for .store[RESOURCE_ENERGY].
*/
energy: number;
/**
* The total amount of energy the lab can contain.
* @deprecated An alias for .store.getCapacity(RESOURCE_ENERGY).
*/
energyCapacity: number;
/**
* The amount of mineral resources containing in the lab.
* @deprecated An alias for lab.store[lab.mineralType].
*/
mineralAmount: number;
/**
* The type of minerals containing in the lab. Labs can contain only one mineral type at the same time.
* Null in case there is no mineral resource in the lab.
*/
mineralType: MineralConstant | MineralCompoundConstant | null;
/**
* The total amount of minerals the lab can contain.
* @deprecated An alias for lab.store.getCapacity(lab.mineralType || yourMineral).
*/
mineralCapacity: number;
/**
* A Store object that contains cargo of this structure.
*/
store: Store<RESOURCE_ENERGY | MineralConstant | MineralCompoundConstant, false>;
/**
* Boosts creep body part using the containing mineral compound. The creep has to be at adjacent square to the lab. Boosting one body part consumes 30 mineral units and 20 energy units.
* @param creep The target creep.
* @param bodyPartsCount The number of body parts of the corresponding type to be boosted.
*
* Body parts are always counted left-to-right for TOUGH, and right-to-left for other types.
*
* If undefined, all the eligible body parts are boosted.
*/
boostCreep(creep: Creep, bodyPartsCount?: number): ScreepsReturnCode;
/**
* Immediately remove boosts from the creep and drop 50% of the mineral compounds used to boost it onto the ground regardless of the creep's remaining time to live.
* The creep has to be at adjacent square to the lab.
* Unboosting requires cooldown time equal to the total sum of the reactions needed to produce all the compounds applied to the creep.
* @param creep The target creep.
*/
unboostCreep(creep: Creep): ScreepsReturnCode;
/**
* Breaks mineral compounds back into reagents. The same output labs can be used by many source labs.
* @param lab1 The first result lab.
* @param lab2 The second result lab.
*/
reverseReaction(lab1: StructureLab, lab2: StructureLab): ScreepsReturnCode;
/**
* Produce mineral compounds using reagents from two another labs. Each lab has to be within 2 squares range. The same input labs can be used by many output labs
* @param lab1 The first source lab.
* @param lab2 The second source lab.
*/
runReaction(lab1: StructureLab, lab2: StructureLab): ScreepsReturnCode;
}
interface StructureLabConstructor extends _Constructor<StructureLab>, _ConstructorById<StructureLab> {}
declare const StructureLab: StructureLabConstructor;
/**
* Sends any resources to a Terminal in another room.
*/
interface StructureTerminal extends OwnedStructure<STRUCTURE_TERMINAL> {
readonly prototype: StructureTerminal;
/**
* The remaining amount of ticks while this terminal cannot be used to make StructureTerminal.send or Game.market.deal calls.
*/
cooldown: number;
/**
* A Store object that contains cargo of this structure.
*/
store: StoreDefinition;
/**
* The total amount of resources the storage can contain.
* @deprecated An alias for .store.getCapacity().
*/
storeCapacity: number;
/**
* Sends resource to a Terminal in another room with the specified name.
* @param resourceType One of the RESOURCE_* constants.
* @param amount The amount of resources to be sent.
* @param destination The name of the target room. You don't have to gain visibility in this room.
* @param description The description of the transaction. It is visible to the recipient. The maximum length is 100 characters.
*/
send(resourceType: ResourceConstant, amount: number, destination: string, description?: string): ScreepsReturnCode;
}
interface StructureTerminalConstructor extends _Constructor<StructureTerminal>, _ConstructorById<StructureTerminal> {}
declare const StructureTerminal: StructureTerminalConstructor;
/**
* Contains up to 2,000 resource units. Can be constructed in neutral rooms. Decays for 5,000 hits per 100 ticks.
*/
interface StructureContainer extends Structure<STRUCTURE_CONTAINER> {
readonly prototype: StructureContainer;
/**
* An object with the structure contents. Each object key is one of the RESOURCE_* constants, values are resources
* amounts. Use _.sum(structure.store) to get the total amount of contents
*/
store: StoreDefinition;
/**
* The total amount of resources the structure can contain.
* @deprecated An alias for .store.getCapacity().
*/
storeCapacity: number;
/**
* The amount of game ticks when this container will lose some hit points.
*/
ticksToDecay: number;
}
interface StructureContainerConstructor extends _Constructor<StructureContainer>, _ConstructorById<StructureContainer> {}
declare const StructureContainer: StructureContainerConstructor;
/**
* Launches a nuke to another room dealing huge damage to the landing area.
* Each launch has a cooldown and requires energy and ghodium resources. Launching
* creates a Nuke object at the target room position which is visible to any player
* until it is landed. Incoming nuke cannot be moved or cancelled. Nukes cannot
* be launched from or to novice rooms.
*/
interface StructureNuker extends OwnedStructure<STRUCTURE_NUKER> {
readonly prototype: StructureNuker;
/**
* The amount of energy contained in this structure.
* @deprecated An alias for .store[RESOURCE_ENERGY].
*/
energy: number;
/**
* The total amount of energy this structure can contain.
* @deprecated An alias for .store.getCapacity(RESOURCE_ENERGY).
*/
energyCapacity: number;
/**
* The amount of energy contained in this structure.
* @deprecated An alias for .store[RESOURCE_GHODIUM].
*/
ghodium: number;
/**
* The total amount of energy this structure can contain.
* @deprecated An alias for .store.getCapacity(RESOURCE_GHODIUM).
*/
ghodiumCapacity: number;
/**
* The amount of game ticks the link has to wait until the next transfer is possible.
*/
cooldown: number;
/**
* A Store object that contains cargo of this structure.
*/
store: Store<RESOURCE_ENERGY | RESOURCE_GHODIUM, false>;
/**
* Launch a nuke to the specified position.
* @param pos The target room position.
*/
launchNuke(pos: RoomPosition): ScreepsReturnCode;
}
interface StructureNukerConstructor extends _Constructor<StructureNuker>, _ConstructorById<StructureNuker> {}
declare const StructureNuker: StructureNukerConstructor;
/**
* A non-player structure.
* Instantly teleports your creeps to a distant room acting as a room exit tile.
* Portals appear randomly in the central room of each sector.
*/
interface StructurePortal extends Structure<STRUCTURE_PORTAL> {
readonly prototype: StructurePortal;
/**
* If this is an inter-room portal, then this property contains a RoomPosition object leading to the point in the destination room.
* If this is an inter-shard portal, then this property contains an object with shard and room string properties.
* Exact coordinates are undetermined, the creep will appear at any free spot in the destination room.
*/
destination: RoomPosition | { shard: string; room: string };
/**
* The amount of game ticks when the portal disappears, or undefined when the portal is stable.
*/
ticksToDecay: number | undefined;
}
interface StructurePortalConstructor extends _Constructor<StructurePortal>, _ConstructorById<StructurePortal> {}
declare const StructurePortal: StructurePortalConstructor;
/**
* A structure which produces trade commodities from base minerals and other commodities.
*/
interface StructureFactory extends OwnedStructure<STRUCTURE_FACTORY> {
readonly prototype: StructureFactory;
/**
* The amount of game ticks the factory has to wait until the next produce is possible.
*/
cooldown: number;
/**
* The level of the factory.
* Can be set by applying the PWR_OPERATE_FACTORY power to a newly built factory.
* Once set, the level cannot be changed.
*/
level: number;
/**
* An object with the structure contents.
*/
store: StoreDefinition;
/**
* Produces the specified commodity.
* All ingredients should be available in the factory store.
*/
produce(resource: CommodityConstant | MineralConstant | RESOURCE_ENERGY | RESOURCE_GHODIUM): ScreepsReturnCode;
}
interface StructureFactoryConstructor extends _Constructor<StructureFactory>, _ConstructorById<StructureFactory> {}
declare const StructureFactory: StructureFactoryConstructor;
/**
* A structure which is a control center of NPC Strongholds, and also rules all invaders in the sector.
*/
interface StructureInvaderCore extends OwnedStructure<STRUCTURE_INVADER_CORE> {
readonly prototype: StructureInvaderCore;
/**
* The level of the stronghold. The amount and quality of the loot depends on the level.
*/
level: number;
/**
* Shows the timer for a not yet deployed stronghold, undefined otherwise.
*/
ticksToDeploy: number;
/**
* If the core is in process of spawning a new creep, this object will contain a `StructureSpawn.Spawning` object, or `null` otherwise.
*/
spawning: Spawning | null;
}
interface StructureInvaderCoreConstructor extends _Constructor<StructureInvaderCore>, _ConstructorById<StructureInvaderCore> {}
declare const StructureInvaderCore: StructureInvaderCoreConstructor;
/**
* A discriminated union on Structure.type of all owned structure types
*/
type AnyOwnedStructure =
| StructureController
| StructureExtension
| StructureExtractor
| StructureFactory
| StructureInvaderCore
| StructureKeeperLair
| StructureLab
| StructureLink
| StructureNuker
| StructureObserver
| StructurePowerBank
| StructurePowerSpawn
| StructureRampart
| StructureSpawn
| StructureStorage
| StructureTerminal
| StructureTower;
type AnyStoreStructure =
| StructureExtension
| StructureFactory
| StructureLab
| StructureLink
| StructureNuker
| StructurePowerSpawn
| StructureSpawn
| StructureStorage
| StructureTerminal
| StructureTower
| StructureContainer;
/**
* A discriminated union on Structure.type of all structure types
*/
type AnyStructure = AnyOwnedStructure | StructureContainer | StructurePortal | StructureRoad | StructureWall;
/**
* Conditional type for all concrete implementations of Structure.
* Unlike Structure<T>, ConcreteStructure<T> gives you the actual concrete class that extends Structure<T>.
*/
type ConcreteStructure<T extends StructureConstant> = T extends STRUCTURE_EXTENSION
? StructureExtension
: T extends STRUCTURE_RAMPART
? StructureRampart
: T extends STRUCTURE_ROAD
? StructureRoad
: T extends STRUCTURE_SPAWN
? StructureSpawn
: T extends STRUCTURE_LINK
? StructureLink
: T extends STRUCTURE_WALL
? StructureWall
: T extends STRUCTURE_STORAGE
? StructureStorage
: T extends STRUCTURE_TOWER
? StructureTower
: T extends STRUCTURE_OBSERVER
? StructureObserver
: T extends STRUCTURE_POWER_SPAWN
? StructurePowerSpawn
: T extends STRUCTURE_EXTRACTOR
? StructureExtractor
: T extends STRUCTURE_LAB
? StructureLab
: T extends STRUCTURE_TERMINAL
? StructureTerminal
: T extends STRUCTURE_CONTAINER
? StructureContainer
: T extends STRUCTURE_NUKER
? StructureNuker
: T extends STRUCTURE_FACTORY
? StructureFactory
: T extends STRUCTURE_KEEPER_LAIR
? StructureKeeperLair
: T extends STRUCTURE_CONTROLLER
? StructureController
: T extends STRUCTURE_POWER_BANK
? StructurePowerBank
: T extends STRUCTURE_PORTAL
? StructurePortal
: T extends STRUCTURE_INVADER_CORE
? StructureInvaderCore
: never; | the_stack |
import fs from 'fs-extra';
import * as path from 'path';
import { expect } from 'chai';
import Helper from '../../src/e2e-helper/e2e-helper';
import { VersionNotFound } from '../../src/scope/exceptions';
import * as fixtures from '../../src/fixtures/fixtures';
import { MissingBitMapComponent } from '../../src/consumer/bit-map/exceptions';
const barFooV1 = "module.exports = function foo() { return 'got foo'; };\n";
const barFooV2 = "module.exports = function foo() { return 'got foo v2'; };\n";
const barFooV3 = "module.exports = function foo() { return 'got foo v3'; };\n";
const noDiffMessage = 'no diff for';
const successDiffMessage = 'showing diff for';
describe('bit diff command', function() {
this.timeout(0);
let helper: Helper;
before(() => {
helper = new Helper();
helper.command.setFeatures('legacy-workspace-config');
});
const barFooFile = path.join('bar', 'foo.js');
before(() => {
helper.scopeHelper.reInitLocalScope();
});
after(() => {
helper.scopeHelper.destroy();
});
describe('for non existing component', () => {
it('show an error saying the component was not found', () => {
const diffFunc = () => helper.command.runCmd('bit diff utils/non-exist');
const error = new MissingBitMapComponent('utils/non-exist');
helper.general.expectToThrow(diffFunc, error);
});
});
describe('when there are no modified components', () => {
it('show an error saying that there are no modified components', () => {
const output = helper.general.runWithTryCatch('bit diff');
expect(output).to.have.string('no modified components');
});
});
describe('after the component was created', () => {
before(() => {
helper.fixtures.createComponentBarFoo(barFooV1);
helper.fixtures.addComponentBarFoo();
});
it('before tagging it should indicate that there is no diff for that component', () => {
const output = helper.command.diff('bar/foo');
expect(output).to.have.string(noDiffMessage);
expect(output).to.have.string('bar/foo');
});
describe('after the component was tagged', () => {
before(() => {
helper.command.tagAllComponents('', '0.0.5');
});
it('should still indicate that there is no diff for that component', () => {
const output = helper.command.diff('bar/foo');
expect(output).to.have.string(noDiffMessage);
expect(output).to.have.string('bar/foo');
});
describe('and component was modified', () => {
let diffOutput;
before(() => {
helper.fixtures.createComponentBarFoo(barFooV2);
diffOutput = helper.command.diff('bar/foo');
});
it('should show a success message', () => {
expect(diffOutput).to.have.string(successDiffMessage);
});
it('should indicate the original files with ---', () => {
expect(diffOutput).to.have.string(`--- ${barFooFile} (0.0.5 original)`);
});
it('should indicate the modified files with +++', () => {
expect(diffOutput).to.have.string(`+++ ${barFooFile} (0.0.5 modified)`);
});
it('should show the deleted part with leading - (minus sign)', () => {
expect(diffOutput).to.have.string("-module.exports = function foo() { return 'got foo'; };");
});
it('should show the added part with leading + (plus sign)', () => {
expect(diffOutput).to.have.string("+module.exports = function foo() { return 'got foo v2'; };");
});
it('should show a success message also when running from an inner directory', () => {
const outputInner = helper.command.runCmd('bit diff bar/foo', path.join(helper.scopes.localPath, 'bar'));
expect(outputInner).to.have.string(successDiffMessage);
});
describe('when git path is configured incorrectly', () => {
before(() => {
helper.command.runCmd('bit config set git_path /non/exist/location');
});
after(() => {
helper.command.runCmd('bit config set git_path git');
});
it('should throw an error GitNotFound', () => {
const output = helper.general.runWithTryCatch('bit diff bar/foo');
expect(output).to.have.string('unable to run command because git executable not found');
});
});
});
});
});
describe('when there are several modified components and non modified components', () => {
before(() => {
helper.scopeHelper.reInitLocalScope();
helper.fixtures.createComponentBarFoo(barFooV1);
helper.fixtures.addComponentBarFoo();
helper.fs.createFile('utils', 'is-type.js', fixtures.isType);
helper.fixtures.addComponentUtilsIsType();
helper.fs.createFile('utils', 'is-string.js', fixtures.isString);
helper.fixtures.addComponentUtilsIsString();
helper.command.tagAllComponents();
// modify only bar/foo and utils/is-type, not utils/is-string
helper.fixtures.createComponentBarFoo(barFooV2);
helper.fs.createFile('utils', 'is-type.js', fixtures.isTypeV2);
});
describe('running bit diff with no ids', () => {
let output;
before(() => {
output = helper.command.diff();
});
it('should show diff for all modified components', () => {
expect(output).to.have.string('bar/foo');
expect(output).to.have.string('utils/is-type');
expect(output).to.have.string(barFooV1);
expect(output).to.have.string(barFooV2);
expect(output).to.have.string(fixtures.isType);
expect(output).to.have.string(fixtures.isTypeV2);
});
it('should not show non modified components', () => {
expect(output).to.not.have.string('utils/is-string');
});
});
describe('running bit diff with multiple ids', () => {
let output;
before(() => {
output = helper.command.diff('utils/is-type utils/is-string');
});
it('should show diff for the modified components only', () => {
expect(output).to.have.string(fixtures.isType);
expect(output).to.have.string(fixtures.isTypeV2);
});
it('should not show diff for non modified components', () => {
expect(output).to.not.have.string(fixtures.isString);
});
it('should mention the components with no diff', () => {
expect(output).to.have.string('utils/is-string');
expect(output).to.have.string(noDiffMessage);
});
});
});
describe('when a file is deleted and another is added', () => {
let output;
before(() => {
helper.scopeHelper.reInitLocalScope();
helper.fixtures.createComponentBarFoo(barFooV1);
helper.fixtures.addComponentBarFoo();
helper.command.tagAllComponents();
helper.fs.createFile('bar', 'foo2.js', barFooV2);
fs.removeSync(path.join(helper.scopes.localPath, 'bar/foo.js'));
helper.command.addComponent('bar/foo2.js', { i: 'bar/foo', m: 'bar/foo2.js' });
helper.command.runCmd('bit status'); // to clean bitmap file
output = helper.command.diff('bar/foo');
});
it('should indicate the deleted files as deleted', () => {
expect(output).to.have.string(`--- ${barFooFile} (0.0.1 original)`);
expect(output).to.have.string(`+++ ${barFooFile} (0.0.1 modified)`);
// notice the leading minus sign
expect(output).to.have.string(`-${barFooV1}`);
});
it('should indicate the added files as added', () => {
const barFoo2File = path.join('bar', 'foo2.js');
expect(output).to.have.string(`--- ${barFoo2File} (0.0.1 original)`);
expect(output).to.have.string(`+++ ${barFoo2File} (0.0.1 modified)`);
// notice the leading plus sign
expect(output).to.have.string(`+${barFooV2}`);
});
describe('other fields diff', () => {
it('should indicate that the mainFile was changed', () => {
expect(output).to.have.string('--- Main File (0.0.1 original)');
expect(output).to.have.string('+++ Main File (0.0.1 modified)');
expect(output).to.have.string('- bar/foo.js');
expect(output).to.have.string('+ bar/foo2.js');
});
it('should indicate that the files array were changed', () => {
expect(output).to.have.string('--- Files (0.0.1 original)');
expect(output).to.have.string('+++ Files (0.0.1 modified)');
expect(output).to.have.string('- [ bar/foo.js ]');
expect(output).to.have.string('+ [ bar/foo2.js ]');
});
});
describe('running bit diff between the previous version and the last version', () => {
before(() => {
helper.command.tagAllComponents();
output = helper.command.diff('bar/foo 0.0.1 0.0.2');
});
it('should indicate the deleted files as deleted', () => {
expect(output).to.have.string(`--- ${barFooFile} (0.0.1)`);
expect(output).to.have.string(`+++ ${barFooFile} (0.0.2)`);
expect(output).to.have.string(`-${barFooV1}`);
});
it('should indicate the added files as added', () => {
const barFoo2File = path.join('bar', 'foo2.js');
expect(output).to.have.string(`--- ${barFoo2File} (0.0.1)`);
expect(output).to.have.string(`+++ ${barFoo2File} (0.0.2)`);
expect(output).to.have.string(`+${barFooV2}`);
});
describe('other fields diff', () => {
it('should indicate that the mainFile was changed', () => {
expect(output).to.have.string('--- Main File (0.0.1)');
expect(output).to.have.string('+++ Main File (0.0.2)');
expect(output).to.have.string('- bar/foo.js');
expect(output).to.have.string('+ bar/foo2.js');
});
it('should indicate that the files array were changed', () => {
expect(output).to.have.string('--- Files (0.0.1)');
expect(output).to.have.string('+++ Files (0.0.2)');
expect(output).to.have.string('- [ bar/foo.js ]');
expect(output).to.have.string('+ [ bar/foo2.js ]');
});
});
it('should have the same output as running diff of the previous version', () => {
const diffOfVersionOutput = helper.command.diff('bar/foo 0.0.1');
expect(diffOfVersionOutput).to.be.equal(output);
});
});
describe('running bit diff between current version and version 0.0.1', () => {
before(() => {
helper.command.tagAllComponents(undefined, undefined, false);
output = helper.command.diff('bar/foo 0.0.1');
});
it('should indicate the deleted files as deleted', () => {
expect(output).to.have.string(`--- ${barFooFile} (0.0.1)`);
expect(output).to.have.string(`+++ ${barFooFile} (0.0.2)`);
expect(output).to.have.string(`-${barFooV1}`);
});
it('should indicate the added files as added', () => {
const barFoo2File = path.join('bar', 'foo2.js');
expect(output).to.have.string(`--- ${barFoo2File} (0.0.1)`);
expect(output).to.have.string(`+++ ${barFoo2File} (0.0.2)`);
expect(output).to.have.string(`+${barFooV2}`);
});
describe('other fields diff', () => {
it('should indicate that the mainFile was changed', () => {
expect(output).to.have.string('--- Main File (0.0.1)');
expect(output).to.have.string('+++ Main File (0.0.2)');
expect(output).to.have.string('- bar/foo.js');
expect(output).to.have.string('+ bar/foo2.js');
});
it('should indicate that the files array were changed', () => {
expect(output).to.have.string('--- Files (0.0.1)');
expect(output).to.have.string('+++ Files (0.0.2)');
expect(output).to.have.string('- [ bar/foo.js ]');
expect(output).to.have.string('+ [ bar/foo2.js ]');
});
});
it('should have the same output as running diff of the previous version', () => {
const diffOfVersionOutput = helper.command.diff('bar/foo 0.0.1');
expect(diffOfVersionOutput).to.be.equal(output);
});
});
});
describe('component with multiple versions', () => {
before(() => {
helper.scopeHelper.reInitLocalScope();
helper.fixtures.createComponentBarFoo(barFooV1);
helper.fixtures.addComponentBarFoo();
helper.fixtures.tagComponentBarFoo(); // 0.0.1
helper.fixtures.createComponentBarFoo(barFooV2);
helper.fixtures.tagComponentBarFoo(); // 0.0.2
helper.fixtures.createComponentBarFoo(barFooV3);
helper.fixtures.tagComponentBarFoo(); // 0.0.3
});
describe('diff between a non-exist version and current version', () => {
it('should throw an VersionNotFound error', () => {
const error = new VersionNotFound('1.0.6');
const diffFunc = () => helper.command.diff('bar/foo 1.0.6');
helper.general.expectToThrow(diffFunc, error);
});
});
describe('diff between an earlier version and current version', () => {
let output;
before(() => {
output = helper.command.diff('bar/foo 0.0.1');
});
it('should show the earlier version with leading - (minus sign)', () => {
expect(output).to.have.string(`--- ${barFooFile} (0.0.1)`);
expect(output).to.have.string(`-${barFooV1}`);
});
it('should show the current version with leading + (plus sign)', () => {
expect(output).to.have.string(`+++ ${barFooFile} (0.0.3)`);
expect(output).to.have.string(`+${barFooV3}`);
});
});
describe('diff between two different versions', () => {
let output;
before(() => {
output = helper.command.diff('bar/foo 0.0.1 0.0.2');
});
it('should show the first version with leading - (minus sign)', () => {
expect(output).to.have.string(`--- ${barFooFile} (0.0.1)`);
expect(output).to.have.string(`-${barFooV1}`);
});
it('should show the second version with leading + (plus sign)', () => {
expect(output).to.have.string(`+++ ${barFooFile} (0.0.2)`);
expect(output).to.have.string(`+${barFooV2}`);
});
});
describe('diff between two versions with multiple ids (not supported)', () => {
it('should throw an error', () => {
const output = helper.general.runWithTryCatch('bit diff bar/foo bar/foo2 0.0.1 0.0.2');
expect(output).to.have.string(
'bit diff [id] [version] [to_version] syntax was used, however, 4 arguments were given instead of 3'
);
});
});
describe('diff of a certain version with multiple ids (not supported)', () => {
it('should throw an error', () => {
const output = helper.general.runWithTryCatch('bit diff bar/foo bar/foo2 0.0.1');
expect(output).to.have.string(
'bit diff [id] [version] syntax was used, however, 3 arguments were given instead of 2'
);
});
});
});
describe('component with dependencies', () => {
before(() => {
helper.scopeHelper.reInitLocalScope();
helper.fs.createFile('utils', 'is-string.js');
helper.fixtures.createComponentBarFoo('import isString from "../utils/is-string"');
helper.fixtures.addComponentUtilsIsString();
helper.fixtures.addComponentBarFoo();
helper.command.tagAllComponents();
helper.command.runCmd('bit move utils utility');
helper.fixtures.createComponentBarFoo('import isString from "../utility/is-string"');
});
it('should not indicate relativePaths changes when --verbose is not used', () => {
const output = helper.command.diff('bar/foo');
expect(output).to.not.have.string('sourceRelativePath');
expect(output).to.not.have.string('destinationRelativePath');
});
it('should indicate relativePaths changes when --verbose is used', () => {
const output = helper.command.diff('bar/foo --verbose');
expect(output).to.have.string('- "sourceRelativePath": "utils/is-string.js",');
expect(output).to.have.string('+ "sourceRelativePath": "utility/is-string.js",');
});
});
}); | the_stack |
var cubeRotation = 0.0;
// will set to true when video can be copied to texture
var copyVideo = false;
import * as glMatrix from './gl-matrix';
const mat4 = glMatrix.mat4;
import { Video } from '@nativescript/canvas-media';
//
// Start here
//
export function handleVideo(canvas) {
const gl = canvas.getContext('webgl2') as WebGLRenderingContext;
// If we don't have a GL context, give up now
if (!gl) {
alert('Unable to initialize WebGL. Your browser or machine may not support it.');
return;
}
// Vertex shader program
const vsSource = `
attribute vec4 aVertexPosition;
attribute vec3 aVertexNormal;
attribute vec2 aTextureCoord;
uniform mat4 uNormalMatrix;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
varying highp vec2 vTextureCoord;
varying highp vec3 vLighting;
void main(void) {
gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
vTextureCoord = aTextureCoord;
// Apply lighting effect
highp vec3 ambientLight = vec3(0.3, 0.3, 0.3);
highp vec3 directionalLightColor = vec3(1, 1, 1);
highp vec3 directionalVector = normalize(vec3(0.85, 0.8, 0.75));
highp vec4 transformedNormal = uNormalMatrix * vec4(aVertexNormal, 1.0);
highp float directional = max(dot(transformedNormal.xyz, directionalVector), 0.0);
vLighting = ambientLight + (directionalLightColor * directional);
}
`;
// Fragment shader program
const fsSource = `
varying highp vec2 vTextureCoord;
varying highp vec3 vLighting;
uniform sampler2D uSampler;
void main(void) {
highp vec4 texelColor = texture2D(uSampler, vTextureCoord);
gl_FragColor = vec4(texelColor.rgb * vLighting, texelColor.a);
}
`;
// Initialize a shader program; this is where all the lighting
// for the vertices and so forth is established.
const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
// Collect all the info needed to use the shader program.
// Look up which attributes our shader program is using
// for aVertexPosition, aVertexNormal, aTextureCoord,
// and look up uniform locations.
const programInfo = {
program: shaderProgram,
attribLocations: {
vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
vertexNormal: gl.getAttribLocation(shaderProgram, 'aVertexNormal'),
textureCoord: gl.getAttribLocation(shaderProgram, 'aTextureCoord'),
},
uniformLocations: {
projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),
modelViewMatrix: gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'),
normalMatrix: gl.getUniformLocation(shaderProgram, 'uNormalMatrix'),
uSampler: gl.getUniformLocation(shaderProgram, 'uSampler'),
},
};
// Here's where we call the routine that builds all the
// objects we'll be drawing.
const buffers = initBuffers(gl);
const texture = initTexture(gl);
//https://github.com/mdn/webgl-examples/raw/gh-pages/tutorial/sample8/Firefox.mp4
const video = setupVideo('~/assets/file-assets/webgl/Firefox.mp4');
var then = 0;
// Draw the scene repeatedly
function render(now) {
now *= 0.001; // convert to seconds
const deltaTime = now - then;
then = now;
if (copyVideo) {
updateTexture(gl, texture, video);
}
drawScene(gl, programInfo, buffers, texture, deltaTime);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
function setupVideo(url) {
// @ts-ignore
const video = document.createElement('video');
video.width = 128;
video.height = 128;
var playing = false;
var timeupdate = false;
video.autoplay = false;
//video.muted = true;
video.loop = true;
// Waiting for these 2 events ensures
// there is data in the video
video.addEventListener(
'playing',
function () {
playing = true;
checkReady();
},
true
);
video.addEventListener(
'timeupdate',
function () {
timeupdate = true;
checkReady();
},
true
);
video.src = url;
video.play();
function checkReady() {
if (playing && timeupdate) {
copyVideo = true;
}
}
return video;
}
//
// initBuffers
//
// Initialize the buffers we'll need. For this demo, we just
// have one object -- a simple three-dimensional cube.
//
function initBuffers(gl) {
// Create a buffer for the cube's vertex positions.
const positionBuffer = gl.createBuffer();
// Select the positionBuffer as the one to apply buffer
// operations to from here out.
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
// Now create an array of positions for the cube.
const positions = [
// Front face
-1.0,
-1.0,
1.0,
1.0,
-1.0,
1.0,
1.0,
1.0,
1.0,
-1.0,
1.0,
1.0,
// Back face
-1.0,
-1.0,
-1.0,
-1.0,
1.0,
-1.0,
1.0,
1.0,
-1.0,
1.0,
-1.0,
-1.0,
// Top face
-1.0,
1.0,
-1.0,
-1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
-1.0,
// Bottom face
-1.0,
-1.0,
-1.0,
1.0,
-1.0,
-1.0,
1.0,
-1.0,
1.0,
-1.0,
-1.0,
1.0,
// Right face
1.0,
-1.0,
-1.0,
1.0,
1.0,
-1.0,
1.0,
1.0,
1.0,
1.0,
-1.0,
1.0,
// Left face
-1.0,
-1.0,
-1.0,
-1.0,
-1.0,
1.0,
-1.0,
1.0,
1.0,
-1.0,
1.0,
-1.0,
];
// Now pass the list of positions into WebGL to build the
// shape. We do this by creating a Float32Array from the
// JavaScript array, then use it to fill the current buffer.
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
// Set up the normals for the vertices, so that we can compute lighting.
const normalBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer);
const vertexNormals = [
// Front
0.0,
0.0,
1.0,
0.0,
0.0,
1.0,
0.0,
0.0,
1.0,
0.0,
0.0,
1.0,
// Back
0.0,
0.0,
-1.0,
0.0,
0.0,
-1.0,
0.0,
0.0,
-1.0,
0.0,
0.0,
-1.0,
// Top
0.0,
1.0,
0.0,
0.0,
1.0,
0.0,
0.0,
1.0,
0.0,
0.0,
1.0,
0.0,
// Bottom
0.0,
-1.0,
0.0,
0.0,
-1.0,
0.0,
0.0,
-1.0,
0.0,
0.0,
-1.0,
0.0,
// Right
1.0,
0.0,
0.0,
1.0,
0.0,
0.0,
1.0,
0.0,
0.0,
1.0,
0.0,
0.0,
// Left
-1.0,
0.0,
0.0,
-1.0,
0.0,
0.0,
-1.0,
0.0,
0.0,
-1.0,
0.0,
0.0,
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertexNormals), gl.STATIC_DRAW);
// Now set up the texture coordinates for the faces.
const textureCoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, textureCoordBuffer);
const textureCoordinates = [
// Front
0.0,
0.0,
1.0,
0.0,
1.0,
1.0,
0.0,
1.0,
// Back
0.0,
0.0,
1.0,
0.0,
1.0,
1.0,
0.0,
1.0,
// Top
0.0,
0.0,
1.0,
0.0,
1.0,
1.0,
0.0,
1.0,
// Bottom
0.0,
0.0,
1.0,
0.0,
1.0,
1.0,
0.0,
1.0,
// Right
0.0,
0.0,
1.0,
0.0,
1.0,
1.0,
0.0,
1.0,
// Left
0.0,
0.0,
1.0,
0.0,
1.0,
1.0,
0.0,
1.0,
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(textureCoordinates), gl.STATIC_DRAW);
// Build the element array buffer; this specifies the indices
// into the vertex arrays for each face's vertices.
const indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
// This array defines each face as two triangles, using the
// indices into the vertex array to specify each triangle's
// position.
const indices = [
0,
1,
2,
0,
2,
3, // front
4,
5,
6,
4,
6,
7, // back
8,
9,
10,
8,
10,
11, // top
12,
13,
14,
12,
14,
15, // bottom
16,
17,
18,
16,
18,
19, // right
20,
21,
22,
20,
22,
23, // left
];
// Now send the element array to GL
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
return {
position: positionBuffer,
normal: normalBuffer,
textureCoord: textureCoordBuffer,
indices: indexBuffer,
};
}
//
// Initialize a texture.
//
function initTexture(gl, url?) {
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
// Because video havs to be download over the internet
// they might take a moment until it's ready so
// put a single pixel in the texture so we can
// use it immediately.
const level = 0;
const internalFormat = gl.RGBA;
const width = 1;
const height = 1;
const border = 0;
const srcFormat = gl.RGBA;
const srcType = gl.UNSIGNED_BYTE;
const pixel = new Uint8Array([0, 0, 255, 255]); // opaque blue
gl.texImage2D(gl.TEXTURE_2D, level, internalFormat, width, height, border, srcFormat, srcType, pixel);
// Turn off mips and set wrapping to clamp to edge so it
// will work regardless of the dimensions of the video.
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
return texture;
}
//
// copy the video texture
//
function updateTexture(gl: WebGLRenderingContext, texture, video) {
const level = 0;
const internalFormat = gl.RGBA;
const srcFormat = gl.RGBA;
const srcType = gl.UNSIGNED_BYTE;
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, level, internalFormat, srcFormat, srcType, video);
}
function isPowerOf2(value) {
return (value & (value - 1)) == 0;
}
//
// Draw the scene.
//
function drawScene(gl, programInfo, buffers, texture, deltaTime) {
gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear to black, fully opaque
gl.clearDepth(1.0); // Clear everything
gl.enable(gl.DEPTH_TEST); // Enable depth testing
gl.depthFunc(gl.LEQUAL); // Near things obscure far things
// Clear the canvas before we start drawing on it.
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// Create a perspective matrix, a special matrix that is
// used to simulate the distortion of perspective in a camera.
// Our field of view is 45 degrees, with a width/height
// ratio that matches the display size of the canvas
// and we only want to see objects between 0.1 units
// and 100 units away from the camera.
const fieldOfView = (45 * Math.PI) / 180; // in radians
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const zNear = 0.1;
const zFar = 100.0;
const projectionMatrix = mat4.create();
// note: glmatrix.js always has the first argument
// as the destination to receive the result.
mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar);
// Set the drawing position to the "identity" point, which is
// the center of the scene.
const modelViewMatrix = mat4.create();
// Now move the drawing position a bit to where we want to
// start drawing the square.
mat4.translate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to translate
[-0.0, 0.0, -6.0]
); // amount to translate
mat4.rotate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to rotate
cubeRotation, // amount to rotate in radians
[0, 0, 1]
); // axis to rotate around (Z)
mat4.rotate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to rotate
cubeRotation * 0.7, // amount to rotate in radians
[0, 1, 0]
); // axis to rotate around (X)
const normalMatrix = mat4.create();
mat4.invert(normalMatrix, modelViewMatrix);
mat4.transpose(normalMatrix, normalMatrix);
// Tell WebGL how to pull out the positions from the position
// buffer into the vertexPosition attribute
{
const numComponents = 3;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);
gl.vertexAttribPointer(programInfo.attribLocations.vertexPosition, numComponents, type, normalize, stride, offset);
gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition);
}
// Tell WebGL how to pull out the texture coordinates from
// the texture coordinate buffer into the textureCoord attribute.
{
const numComponents = 2;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.textureCoord);
gl.vertexAttribPointer(programInfo.attribLocations.textureCoord, numComponents, type, normalize, stride, offset);
gl.enableVertexAttribArray(programInfo.attribLocations.textureCoord);
}
// Tell WebGL how to pull out the normals from
// the normal buffer into the vertexNormal attribute.
{
const numComponents = 3;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.normal);
gl.vertexAttribPointer(programInfo.attribLocations.vertexNormal, numComponents, type, normalize, stride, offset);
gl.enableVertexAttribArray(programInfo.attribLocations.vertexNormal);
}
// Tell WebGL which indices to use to index the vertices
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices);
// Tell WebGL to use our program when drawing
gl.useProgram(programInfo.program);
// Set the shader uniforms
gl.uniformMatrix4fv(programInfo.uniformLocations.projectionMatrix, false, projectionMatrix);
gl.uniformMatrix4fv(programInfo.uniformLocations.modelViewMatrix, false, modelViewMatrix);
gl.uniformMatrix4fv(programInfo.uniformLocations.normalMatrix, false, normalMatrix);
// Specify the texture to map onto the faces.
// Tell WebGL we want to affect texture unit 0
gl.activeTexture(gl.TEXTURE0);
// Bind the texture to texture unit 0
gl.bindTexture(gl.TEXTURE_2D, texture);
// Tell the shader we bound the texture to texture unit 0
gl.uniform1i(programInfo.uniformLocations.uSampler, 0);
{
const vertexCount = 36;
const type = gl.UNSIGNED_SHORT;
const offset = 0;
gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);
}
// Update the rotation for the next draw
cubeRotation += deltaTime;
}
//
// Initialize a shader program, so WebGL knows how to draw our data
//
function initShaderProgram(gl, vsSource, fsSource) {
const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
// Create the shader program
const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
// If creating the shader program failed, alert
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert('Unable to initialize the shader program: ' + gl.getProgramInfoLog(shaderProgram));
return null;
}
return shaderProgram;
}
//
// creates a shader of the given type, uploads the source and
// compiles it.
//
function loadShader(gl, type, source) {
const shader = gl.createShader(type);
// Send the source to the shader object
gl.shaderSource(shader, source);
// Compile the shader program
gl.compileShader(shader);
// See if it compiled successfully
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert('An error occurred compiling the shaders: ' + gl.getShaderInfoLog(shader));
gl.deleteShader(shader);
return null;
}
return shader;
} | the_stack |
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
// firebase
// import * as firebase from 'firebase/app';
import firebase from "firebase/app";
import 'firebase/messaging';
import 'firebase/database';
import 'firebase/auth';
import 'firebase/storage';
// models
import { ConversationModel } from '../../models/conversation';
// services
import { ConversationsHandlerService } from '../abstract/conversations-handler.service';
import { LoggerService } from '../abstract/logger.service';
import { LoggerInstance } from '../logger/loggerInstance';
import { AppConfigProvider } from 'src/app/services/app-config';
//import { DatabaseProvider } from '../database';
// utils
import { avatarPlaceholder, getColorBck } from '../../utils/utils-user';
import { compareValues, getFromNow, conversationsPathForUserId, searchIndexInArrayForUid, isGroup } from '../../utils/utils';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
// @Injectable({ providedIn: 'root' })
@Injectable()
export class FirebaseConversationsHandler extends ConversationsHandlerService {
// BehaviorSubject
BSConversationDetail: BehaviorSubject<ConversationModel>;
// readAllMessages: BehaviorSubject<string>;
conversationAdded: BehaviorSubject<ConversationModel>;
conversationChanged: BehaviorSubject<ConversationModel>;
conversationRemoved: BehaviorSubject<ConversationModel>;
loadedConversationsStorage: BehaviorSubject<ConversationModel[]>;
// public params
conversations: Array<ConversationModel> = [];
uidConvSelected: string;
tenant: string;
// imageRepo: ImageRepoService = new FirebaseImageRepoService();
// private params
private loggedUserId: string;
private translationMap: Map<string, string>;
private isConversationClosingMap: Map<string, boolean>;
private logger: LoggerService = LoggerInstance.getInstance()
private ref: firebase.database.Query;
private BASE_URL: string;
// private audio: any;
// private setTimeoutSound: any;
constructor(
//public databaseProvider: DatabaseProvider
public http: HttpClient,
public appConfig: AppConfigProvider
) {
super();
}
/**
* inizializzo conversations handler
*/
initialize(
tenant: string,
userId: string,
translationMap: Map<string, string>
) {
this.tenant = tenant;
this.loggedUserId = userId;
this.translationMap = translationMap;
this.conversations = [];
this.isConversationClosingMap = new Map();
//this.databaseProvider.initialize(userId, this.tenant);
//this.getConversationsFromStorage();
this.BASE_URL = this.appConfig.getConfig().firebaseConfig.chat21ApiUrl;
}
/**
* mi connetto al nodo conversations
* creo la reference
* mi sottoscrivo a change, removed, added
*/
// connect() {
// const that = this;
// const urlNodeFirebase = conversationsPathForUserId(this.tenant, this.loggedUserId);
// this.logger.printDebug('connect -------> conversations::ACTIVE', urlNodeFirebase)
// this.ref = firebase.database().ref(urlNodeFirebase).orderByChild('timestamp').limitToLast(200);
// this.ref.on('child_changed', (childSnapshot) => {
// that.changed(childSnapshot);
// });
// this.ref.on('child_removed', (childSnapshot) => {
// that.removed(childSnapshot);
// });
// this.ref.on('child_added', (childSnapshot) => {
// that.added(childSnapshot);
// });
// // SET AUDIO
// // this.audio = new Audio();
// // this.audio.src = URL_SOUND;
// // this.audio.load();
// }
/**
* mi connetto al nodo conversations
* creo la reference
* mi sottoscrivo a change, removed, added
*/
// ---------------------------------------------------------------------------------
// New connect - renamed subscribeToConversation
//----------------------------------------------------------------------------------
subscribeToConversations(callback) {
const that = this;
const urlNodeFirebase = conversationsPathForUserId(this.tenant, this.loggedUserId);
this.logger.debug('[FIREBASEConversationsHandlerSERVICE] SubscribeToConversations conversations::ACTIVE urlNodeFirebase', urlNodeFirebase)
this.ref = firebase.database().ref(urlNodeFirebase).orderByChild('timestamp').limitToLast(200);
this.ref.on('child_changed', (childSnapshot) => {
that.changed(childSnapshot);
});
this.ref.on('child_removed', (childSnapshot) => {
that.removed(childSnapshot);
});
this.ref.on('child_added', (childSnapshot) => {
that.added(childSnapshot);
});
setTimeout(() => {
callback()
}, 2000);
// SET AUDIO
// this.audio = new Audio();
// this.audio.src = URL_SOUND;
// this.audio.load();
}
/**
* restituisce il numero di conversazioni nuove
*/
countIsNew(): number {
let num = 0;
this.conversations.forEach((element) => {
if (element.is_new === true) {
num++;
}
});
return num;
}
setConversationRead(conversationrecipient): void {
this.logger.log('[CONVS-DETAIL][FB-ACTIVE] updateConversationBadge: ');
const urlUpdate = conversationsPathForUserId(this.tenant, this.loggedUserId) + '/' + conversationrecipient;
const update = {};
update['/is_new'] = false;
firebase.database().ref(urlUpdate).update(update);
}
/**
* Returns the status of the conversations with conversationId from isConversationClosingMap
* @param conversationId the conversation id
* @returns true if the conversation is waiting to be closed, false otherwise
*/
getClosingConversation(conversationId: string) {
return this.isConversationClosingMap[conversationId];
}
/**
* Add the conversation with conversationId to the isConversationClosingMap
* @param conversationId the id of the conversation of which it wants to save the state
* @param status true if the conversation is waiting to be closed, false otherwise
*/
setClosingConversation(conversationId: string, status: boolean) {
this.isConversationClosingMap[conversationId] = status;
}
/**
* Delete the conversation with conversationId from the isConversationClosingMap
* @param conversationId the id of the conversation of which is wants to delete
*/
deleteClosingConversation(conversationId: string) {
this.isConversationClosingMap.delete(conversationId);
}
// -------->>>> ARCHIVE CONVERSATION SECTION START <<<<---------------//
archiveConversation(conversationId: string) {
const that = this
this.setClosingConversation(conversationId, true);
const index = searchIndexInArrayForUid(this.conversations, conversationId);
// if (index > -1) {
// this.conversations.splice(index, 1);
// fare chiamata delete per rimuoverle la conversazione da remoto
this.deleteConversation(conversationId, function (response) {
that.logger.debug('[FIREBASEConversationsHandlerSERVICE] ARCHIVE-CONV', response)
if (response === 'success') {
if (index > -1) {
that.conversations.splice(index, 1);
}
} else if (response === 'error') {
that.setClosingConversation(conversationId, false);
}
})
// }
}
deleteConversation(conversationId, callback) {
this.logger.debug('[FIREBASEConversationsHandlerSERVICE] DELETE CONV conversationId', conversationId)
// let queryString = ''
// let isSupportConversation = conversationId.startsWith("support-group");
// if (isSupportConversation) {
// queryString = '?forall=true'
// }
this.getFirebaseToken((error, idToken) => {
this.logger.debug('[FIREBASEConversationsHandlerSERVICE] DELETE CONV idToken', idToken)
this.logger.debug('F[FIREBASEConversationsHandlerSERVICE] DELETE CONV error', error)
if (idToken) {
const httpOptions = {
headers: new HttpHeaders({
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + idToken,
})
}
const url = this.BASE_URL + '/api/' + this.tenant + '/conversations/' + conversationId // + queryString;
this.http.delete(url, httpOptions).subscribe(res => {
this.logger.debug('[FIREBASEConversationsHandlerSERVICE] DELETE CONV - RES', res);
callback('success')
}, (error) => {
this.logger.error('[FIREBASEConversationsHandlerSERVICE] DELETE CONV ERROR ', error);
callback('error')
}, () => {
this.logger.debug('[FIREBASEConversationsHandlerSERVICE] DELETE CONV * COMPLETE *');
});
} else {
callback('error')
}
});
}
getFirebaseToken(callback) {
const firebase_currentUser = firebase.auth().currentUser;
this.logger.debug(' // firebase current user ', firebase_currentUser);
if (firebase_currentUser) {
firebase_currentUser.getIdToken(/* forceRefresh */ true)
.then(function (idToken) {
// qui richiama la callback
callback(null, idToken);
}).catch(function (error) {
// Handle error
callback(error, null);
});
}
}
// -------->>>> ARCHIVE CONVERSATION SECTION END <<<<---------------//
public getConversationDetail(conversationId: string, callback: (conv: ConversationModel) => void): void {
// fare promise o callback ??
this.logger.log('[FIREBASEConversationsHandlerSERVICE] getConversationDetail *****: ', conversationId)
const conversation = this.conversations.find(item => item.uid === conversationId);
this.logger.log('[FIREBASEConversationsHandlerSERVICE] conversations *****: ', this.conversations)
this.logger.log('[FIREBASEConversationsHandlerSERVICE] getConversationDetail *****: ', conversation)
if (conversation) {
callback(conversation)
// return conversationSelected
// this.BSConversationDetail.next(conversationSelected);
} else {
this.logger.log('[FIREBASEConversationsHandlerSERVICE] getConversationDetail ***** ELSE')
// const urlNodeFirebase = '/apps/' + this.tenant + '/users/' + this.loggedUserId + '/conversations/' + conversationId;
const urlNodeFirebase = conversationsPathForUserId(this.tenant, this.loggedUserId) + '/' + conversationId;
this.logger.log('[FIREBASEConversationsHandlerSERVICE] conversationDetail urlNodeFirebase *****', urlNodeFirebase)
const firebaseMessages = firebase.database().ref(urlNodeFirebase);
firebaseMessages.on('value', (childSnapshot) => {
const childData: ConversationModel = childSnapshot.val();
this.logger.log('[FIREBASEConversationsHandlerSERVICE] conversationDetail childSnapshot.val() *****', childSnapshot.val());
this.logger.log('[FIREBASEConversationsHandlerSERVICE] conversationDetail childSnapshot *****', childSnapshot)
// && childData.uid
if (childSnapshot && childSnapshot.key && childData) {
childData.uid = childSnapshot.key;
const conversation = this.completeConversation(childData);
if (conversation) {
callback(conversation)
} else {
callback(null)
}
}
// this.BSConversationDetail.next(conversation);
});
}
}
/**
* dispose reference di conversations
*/
dispose() {
this.conversations = [];
this.uidConvSelected = '';
//this.ref.off();
// this.ref.off("child_changed");
// this.ref.off("child_removed");
// this.ref.off("child_added");
this.logger.debug('[FIREBASEConversationsHandlerSERVICE] DISPOSE::: ', this.ref)
}
// ---------------------------------------------------------- //
// BEGIN PRIVATE FUNCTIONS
// ---------------------------------------------------------- //
/**
*
*/
// private getConversationsFromStorage() {
// const that = this;
// this.databaseProvider.getConversations()
// .then((conversations: [ConversationModel]) => {
// that.loadedConversationsStorage.next(conversations);
// })
// .catch((e) => {
// this.logger.error('error: ', e);
// });
// }
// /**
// *
// * @param childSnapshot
// */
private conversationGenerate(childSnapshot: any): boolean {
const childData: ConversationModel = childSnapshot.val();
childData.uid = childSnapshot.key;
const conversation = this.completeConversation(childData);
if (this.isValidConversation(conversation)) {
this.setClosingConversation(childSnapshot.key, false);
const index = searchIndexInArrayForUid(this.conversations, conversation.uid);
if (index > -1) {
this.conversations.splice(index, 1, conversation);
} else {
this.conversations.splice(0, 0, conversation);
}
//this.databaseProvider.setConversation(conversation);
this.conversations.sort(compareValues('timestamp', 'desc'));
return true;
} else {
return false;
}
}
/**
*
* @param childSnapshot
*/
// private conversationGenerate(childSnapshot: any): ConversationModel {
// this.logger.debug('conversationGenerate: ', childSnapshot.val());
// const childData: ConversationModel = childSnapshot.val();
// childData.uid = childSnapshot.key;
// const conversation = this.completeConversation(childData);
// if (this.isValidConversation(conversation)) {
// this.setClosingConversation(childSnapshot.key, false);
// const index = searchIndexInArrayForUid(this.conversations, conversation.uid);
// if (index > -1) {
// this.conversations.splice(index, 1, conversation);
// } else {
// this.conversations.splice(0, 0, conversation);
// }
// //this.databaseProvider.setConversation(conversation);
// this.conversations.sort(compareValues('timestamp', 'desc'));
// if (conversation.is_new) {
// this.soundMessage();
// }
// return conversation;
// } else {
// return null;
// }
// }
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
/**
* 1 - completo la conversazione con i parametri mancanti
* 2 - verifico che sia una conversazione valida
* 3 - salvo stato conversazione (false) nell'array delle conversazioni chiuse
* 4 - aggiungo alla pos 0 la nuova conversazione all'array di conversazioni
* o sostituisco la conversazione con quella preesistente
* 5 - salvo la conversazione nello storage
* 6 - ordino l'array per timestamp
* 7 - pubblico conversations:update
*/
//TODO-GAB: ora emit singola conversation e non dell'intero array di conversations
private added(childSnapshot: any) {
if (this.conversationGenerate(childSnapshot)) {
const index = searchIndexInArrayForUid(this.conversations, childSnapshot.key);
if (index > -1) {
const conversationAdded = this.conversations[index]
this.conversationAdded.next(conversationAdded);
}
} else {
this.logger.log('[FIREBASEConversationsHandlerSERVICE]ADDED::conversations with conversationId: ', childSnapshot.key, 'is not valid')
}
}
/**
* 1 - completo la conversazione con i parametri mancanti
* 2 - verifico che sia una conversazione valida
* 3 - aggiungo alla pos 0 la nuova conversazione all'array di conversazioni
* 4 - salvo la conversazione nello storage
* 5 - ordino l'array per timestamp
* 6 - pubblico conversations:update
* 7 - attivo sound se è un msg nuovo
*/
//TODO-GAB: ora emit singola conversation e non dell'intero array di conversations
private changed(childSnapshot: any) {
if (this.conversationGenerate(childSnapshot)) {
const index = searchIndexInArrayForUid(this.conversations, childSnapshot.key);
if (index > -1) {
const conversationChanged = this.conversations[index]
this.conversationChanged.next(conversationChanged);
}
} else {
this.logger.error('[FIREBASEConversationsHandlerSERVICE]CHANGED::conversations with conversationId: ', childSnapshot.key, 'is not valid')
}
}
/**
* 1 - cerco indice conversazione da eliminare
* 2 - elimino conversazione da array conversations
* 3 - elimino la conversazione dallo storage
* 4 - pubblico conversations:update
* 5 - elimino conversazione dall'array delle conversazioni chiuse
*/
//TODO-GAB: ora emit singola conversation e non dell'intero array di conversations
private removed(childSnapshot: any) {
const index = searchIndexInArrayForUid(this.conversations, childSnapshot.key);
if (index > -1) {
const conversationRemoved = this.conversations[index]
this.conversations.splice(index, 1);
// this.conversations.sort(compareValues('timestamp', 'desc'));
//this.databaseProvider.removeConversation(childSnapshot.key);
this.conversationRemoved.next(conversationRemoved);
}
// remove the conversation from the isConversationClosingMap
this.deleteClosingConversation(childSnapshot.key);
}
/**
* Completo conversazione aggiungendo:
* 1 - nel caso in cui sender_fullname e recipient_fullname sono vuoti, imposto i rispettivi id come fullname,
* in modo da avere sempre il campo fullname popolato
* 2 - imposto conversation_with e conversation_with_fullname con i valori del sender o al recipient,
* a seconda che il sender corrisponda o meno all'utente loggato. Aggiungo 'tu:' se il sender coincide con il loggedUser
* Se il sender NON è l'utente loggato, ma è una conversazione di tipo GROUP, il conversation_with_fullname
* sarà uguale al recipient_fullname
* 3 - imposto stato conversazione, che indica se ci sono messaggi non letti nella conversazione
* 4 - imposto il tempo trascorso tra l'ora attuale e l'invio dell'ultimo messaggio
* 5 - imposto avatar, colore e immagine
* @param conv
*/
private completeConversation(conv): ConversationModel {
conv.selected = false;
if (!conv.sender_fullname || conv.sender_fullname === 'undefined' || conv.sender_fullname.trim() === '') {
conv.sender_fullname = conv.sender;
}
if (!conv.recipient_fullname || conv.recipient_fullname === 'undefined' || conv.recipient_fullname.trim() === '') {
conv.recipient_fullname = conv.recipient;
}
let conversation_with_fullname = conv.sender_fullname;
let conversation_with = conv.sender;
if (conv.sender === this.loggedUserId) {
conversation_with = conv.recipient;
conversation_with_fullname = conv.recipient_fullname;
conv.sender_fullname = this.translationMap.get('YOU')
// conv.last_message_text = YOU + conv.last_message_text;
// } else if (conv.channel_type === TYPE_GROUP) {
} else if (isGroup(conv)) {
// conversation_with_fullname = conv.sender_fullname;
// conv.last_message_text = conv.last_message_text;
conversation_with = conv.recipient;
conversation_with_fullname = conv.recipient_fullname;
}
conv.conversation_with = conversation_with;
conv.conversation_with_fullname = conversation_with_fullname;
conv.status = this.setStatusConversation(conv.sender, conv.uid);
// conv.time_last_message = this.getTimeLastMessage(conv.timestamp); // evaluate if is used
conv.avatar = avatarPlaceholder(conversation_with_fullname);
conv.color = getColorBck(conversation_with_fullname);
//conv.image = this.imageRepo.getImagePhotoUrl(conversation_with);
// getImageUrlThumbFromFirebasestorage(conversation_with, this.FIREBASESTORAGE_BASE_URL_IMAGE, this.urlStorageBucket);
return conv;
}
/** */
private setStatusConversation(sender: string, uid: string): string {
let status = '0'; // letto
if (sender === this.loggedUserId || uid === this.uidConvSelected) {
status = '0';
} else {
status = '1'; // non letto
}
return status;
}
/**
* calcolo il tempo trascorso da ora al timestamp passato
* @param timestamp
*/
private getTimeLastMessage(timestamp: string) {
const timestampNumber = parseInt(timestamp, 10) / 1000;
const time = getFromNow(timestampNumber);
return time;
}
/**
* check if the conversations is valid or not
*/
private isValidConversation(convToCheck: ConversationModel): boolean {
if (!this.isValidField(convToCheck.uid)) {
return false;
}
if (!this.isValidField(convToCheck.is_new)) {
return false;
}
if (!this.isValidField(convToCheck.last_message_text)) {
return false;
}
if (!this.isValidField(convToCheck.recipient)) {
return false;
}
if (!this.isValidField(convToCheck.recipient_fullname)) {
return false;
}
if (!this.isValidField(convToCheck.sender)) {
return false;
}
if (!this.isValidField(convToCheck.sender_fullname)) {
return false;
}
if (!this.isValidField(convToCheck.status)) {
return false;
}
if (!this.isValidField(convToCheck.timestamp)) {
return false;
}
if (!this.isValidField(convToCheck.channel_type)) {
return false;
}
return true;
}
/**
*
* @param field
*/
private isValidField(field: any): boolean {
return (field === null || field === undefined) ? false : true;
}
// ---------------------------------------------------------- //
// END PRIVATE FUNCTIONS
// ---------------------------------------------------------- //
} | the_stack |
'use strict';
import {IStream} from 'vs/editor/common/modes';
export class LineStream implements IStream {
static STRING_TO_ARRAY_CACHE:{ [key:string]:boolean[]; } = {};
/*protected*/ _source:string;
private sourceLength:number;
/*protected*/ _pos:number;
private whitespace:string;
private whitespaceArr:boolean[];
private separators:string;
private separatorsArr:boolean[];
private tokenStart:number;
private tokenEnd:number;
constructor(source:string) {
this._source = source;
this.sourceLength = source.length;
this._pos = 0;
this.whitespace = '\t \u00a0';
this.whitespaceArr = this.stringToArray(this.whitespace);
this.separators = '';
this.separatorsArr = this.stringToArray(this.separators);
this.tokenStart = -1;
this.tokenEnd = -1;
}
private stringToArray(str:string):boolean[] {
if (!LineStream.STRING_TO_ARRAY_CACHE.hasOwnProperty(str)) {
LineStream.STRING_TO_ARRAY_CACHE[str] = this.actualStringToArray(str);
}
return LineStream.STRING_TO_ARRAY_CACHE[str];
}
private actualStringToArray(str:string):boolean[] {
let maxCharCode = 0;
for (let i = 0; i < str.length; i++) {
maxCharCode = Math.max(maxCharCode, str.charCodeAt(i));
}
let r:boolean[] = [];
for (let i = 0; i <= maxCharCode; i++) {
r[i] = false;
}
for (let i = 0; i < str.length; i++) {
r[str.charCodeAt(i)] = true;
}
return r;
}
public pos():number {
return this._pos;
}
public eos() {
return this._pos >= this.sourceLength;
}
public peek():string {
// Check EOS
if (this._pos >= this.sourceLength) {
throw new Error('Stream is at the end');
}
return this._source[this._pos];
}
public next():string {
// Check EOS
if (this._pos >= this.sourceLength) {
throw new Error('Stream is at the end');
}
// Reset peeked token
this.tokenStart = -1;
this.tokenEnd = -1;
return this._source[this._pos++];
}
public next2(): void {
// Check EOS
if (this._pos >= this.sourceLength) {
throw new Error('Stream is at the end');
}
// Reset peeked token
this.tokenStart = -1;
this.tokenEnd = -1;
this._pos++;
}
public advance(n: number): string {
if (n === 0) {
return '';
}
var oldPos = this._pos;
this._pos += n;
// Reset peeked token
this.tokenStart = -1;
this.tokenEnd = -1;
return this._source.substring(oldPos, this._pos);
}
private _advance2(n: number): number {
if (n === 0) {
return n;
}
this._pos += n;
// Reset peeked token
this.tokenStart = -1;
this.tokenEnd = -1;
return n;
}
public advanceToEOS():string {
var oldPos = this._pos;
this._pos = this.sourceLength;
this.resetPeekedToken();
return this._source.substring(oldPos, this._pos);
}
public goBack(n:number) {
this._pos -= n;
this.resetPeekedToken();
}
private createPeeker(condition:any):()=>number {
if (condition instanceof RegExp) {
return () => {
var result = condition.exec(this._source.substr(this._pos));
if (result === null) {
return 0;
} else if (result.index !== 0) {
throw new Error('Regular expression must begin with the character "^"');
}
return result[0].length;
};
} else if ((condition instanceof String || (typeof condition) === 'string') && condition) {
return () => {
var len = (<String> condition).length, match = this._pos + len <= this.sourceLength;
for (var i = 0; match && i < len; i++) {
match = this._source.charCodeAt(this._pos + i) === (<String> condition).charCodeAt(i);
}
return match ? len : 0;
};
}
throw new Error('Condition must be either a regular expression, function or a non-empty string');
}
// --- BEGIN `_advanceIfStringCaseInsensitive`
private _advanceIfStringCaseInsensitive(condition:string): number {
var oldPos = this._pos,
source = this._source,
len = condition.length,
i:number;
if (len < 1 || oldPos + len > this.sourceLength) {
return 0;
}
for (i = 0; i < len; i++) {
if (source.charAt(oldPos + i).toLowerCase() !== condition.charAt(i).toLowerCase()) {
return 0;
}
}
return len;
}
public advanceIfStringCaseInsensitive(condition: string): string {
return this.advance(this._advanceIfStringCaseInsensitive(condition));
}
public advanceIfStringCaseInsensitive2(condition: string): number {
return this._advance2(this._advanceIfStringCaseInsensitive(condition));
}
// --- END
// --- BEGIN `advanceIfString`
private _advanceIfString(condition: string): number {
var oldPos = this._pos,
source = this._source,
len = condition.length,
i:number;
if (len < 1 || oldPos + len > this.sourceLength) {
return 0;
}
for (i = 0; i < len; i++) {
if (source.charCodeAt(oldPos + i) !== condition.charCodeAt(i)) {
return 0;
}
}
return len;
}
public advanceIfString(condition:string): string {
return this.advance(this._advanceIfString(condition));
}
public advanceIfString2(condition: string): number {
return this._advance2(this._advanceIfString(condition));
}
// --- END
// --- BEGIN `advanceIfString`
private _advanceIfCharCode(charCode:number): number {
if (this._pos < this.sourceLength && this._source.charCodeAt(this._pos) === charCode) {
return 1;
}
return 0;
}
public advanceIfCharCode(charCode: number): string {
return this.advance(this._advanceIfCharCode(charCode));
}
public advanceIfCharCode2(charCode: number): number {
return this._advance2(this._advanceIfCharCode(charCode));
}
// --- END
// --- BEGIN `advanceIfRegExp`
private _advanceIfRegExp(condition:RegExp): number {
if (this._pos >= this.sourceLength) {
return 0;
}
if (!condition.test(this._source.substr(this._pos))) {
return 0;
}
return RegExp.lastMatch.length;
}
public advanceIfRegExp(condition: RegExp): string {
return this.advance(this._advanceIfRegExp(condition));
}
public advanceIfRegExp2(condition: RegExp): number {
return this._advance2(this._advanceIfRegExp(condition));
}
// --- END
private advanceLoop(condition:any, isWhile:boolean, including:boolean):string {
if (this.eos()) {
return '';
}
var peeker = this.createPeeker(condition);
var oldPos = this._pos;
var n = 0;
var f = null;
if (isWhile) {
f = (n) => {
return n > 0;
};
} else {
f = (n) => {
return n === 0;
};
}
while (!this.eos() && f(n = peeker())) {
if (n > 0) {
this.advance(n);
} else {
this.next();
}
}
if (including && !this.eos()) {
this.advance(n);
}
return this._source.substring(oldPos, this._pos);
}
public advanceWhile(condition:any):string {
return this.advanceLoop(condition, true, false);
}
public advanceUntil(condition:any, including:boolean):string {
return this.advanceLoop(condition, false, including);
}
// --- BEGIN `advanceUntilString`
private _advanceUntilString(condition: string, including: boolean): number {
if (this.eos() || condition.length === 0) {
return 0;
}
var oldPos = this._pos;
var index = this._source.indexOf(condition, oldPos);
if (index === -1) {
// String was not found => advanced to `eos`
return (this.sourceLength - oldPos);
}
if (including) {
// String was found => advance to include `condition`
return (index + condition.length - oldPos);
}
// String was found => advance right before `condition`
return (index - oldPos);
}
public advanceUntilString(condition: string, including: boolean): string {
return this.advance(this._advanceUntilString(condition, including));
}
public advanceUntilString2(condition: string, including: boolean): number {
return this._advance2(this._advanceUntilString(condition, including));
}
// --- END
private resetPeekedToken() {
this.tokenStart = -1;
this.tokenEnd = -1;
}
public setTokenRules(separators:string, whitespace:string):void {
if (this.separators !== separators || this.whitespace !== whitespace) {
this.separators = separators;
this.separatorsArr = this.stringToArray(this.separators);
this.whitespace = whitespace;
this.whitespaceArr = this.stringToArray(this.whitespace);
this.resetPeekedToken();
}
}
// --- tokens
public peekToken():string {
if (this.tokenStart !== -1) {
return this._source.substring(this.tokenStart, this.tokenEnd);
}
var source = this._source,
sourceLength = this.sourceLength,
whitespaceArr = this.whitespaceArr,
separatorsArr = this.separatorsArr,
tokenStart = this._pos;
// Check EOS
if (tokenStart >= sourceLength) {
throw new Error('Stream is at the end');
}
// Skip whitespace
while (whitespaceArr[source.charCodeAt(tokenStart)] && tokenStart < sourceLength) {
tokenStart++;
}
var tokenEnd = tokenStart;
// If a separator is hit, it is a token
if (separatorsArr[source.charCodeAt(tokenEnd)] && tokenEnd < sourceLength) {
tokenEnd++;
} else {
// Advance until a separator or a whitespace is hit
while (!separatorsArr[source.charCodeAt(tokenEnd)] && !whitespaceArr[source.charCodeAt(tokenEnd)] && tokenEnd < sourceLength) {
tokenEnd++;
}
}
// Cache peeked token
this.tokenStart = tokenStart;
this.tokenEnd = tokenEnd;
return source.substring(tokenStart, tokenEnd);
}
public nextToken():string {
// Check EOS
if (this._pos >= this.sourceLength) {
throw new Error('Stream is at the end');
}
// Peek token if necessary
var result:string;
if (this.tokenStart === -1) {
result = this.peekToken();
} else {
result = this._source.substring(this.tokenStart, this.tokenEnd);
}
// Advance to tokenEnd
this._pos = this.tokenEnd;
// Reset peeked token
this.tokenStart = -1;
this.tokenEnd = -1;
return result;
}
// -- whitespace
public peekWhitespace():string {
var source = this._source,
sourceLength = this.sourceLength,
whitespaceArr = this.whitespaceArr,
peek = this._pos;
while (whitespaceArr[source.charCodeAt(peek)] && peek < sourceLength) {
peek++;
}
return source.substring(this._pos, peek);
}
// --- BEGIN `advanceIfRegExp`
private _skipWhitespace(): number {
var source = this._source,
sourceLength = this.sourceLength,
whitespaceArr = this.whitespaceArr,
oldPos = this._pos,
peek = this._pos;
while (whitespaceArr[source.charCodeAt(peek)] && peek < sourceLength) {
peek++;
}
return (peek - oldPos);
}
public skipWhitespace(): string {
return this.advance(this._skipWhitespace());
}
public skipWhitespace2(): number {
return this._advance2(this._skipWhitespace());
}
// --- END
} | the_stack |
* @module models/room-member
*/
import { EventEmitter } from "events";
import { getHttpUriForMxc } from "../content-repo";
import * as utils from "../utils";
import { User } from "./user";
import { MatrixEvent } from "./event";
import { RoomState } from "./room-state";
export class RoomMember extends EventEmitter {
private _isOutOfBand = false;
private _modified: number;
public _requestedProfileInfo: boolean; // used by sync.ts
// XXX these should be read-only
public typing = false;
public name: string;
public rawDisplayName: string;
public powerLevel = 0;
public powerLevelNorm = 0;
public user?: User = null;
public membership: string = null;
public disambiguate = false;
public events: {
member?: MatrixEvent;
} = {
member: null,
};
/**
* Construct a new room member.
*
* @constructor
* @alias module:models/room-member
*
* @param {string} roomId The room ID of the member.
* @param {string} userId The user ID of the member.
* @prop {string} roomId The room ID for this member.
* @prop {string} userId The user ID of this member.
* @prop {boolean} typing True if the room member is currently typing.
* @prop {string} name The human-readable name for this room member. This will be
* disambiguated with a suffix of " (@user_id:matrix.org)" if another member shares the
* same displayname.
* @prop {string} rawDisplayName The ambiguous displayname of this room member.
* @prop {Number} powerLevel The power level for this room member.
* @prop {Number} powerLevelNorm The normalised power level (0-100) for this
* room member.
* @prop {User} user The User object for this room member, if one exists.
* @prop {string} membership The membership state for this room member e.g. 'join'.
* @prop {Object} events The events describing this RoomMember.
* @prop {MatrixEvent} events.member The m.room.member event for this RoomMember.
* @prop {boolean} disambiguate True if the member's name is disambiguated.
*/
constructor(public readonly roomId: string, public readonly userId: string) {
super();
this.name = userId;
this.rawDisplayName = userId;
this.updateModifiedTime();
}
/**
* Mark the member as coming from a channel that is not sync
*/
public markOutOfBand(): void {
this._isOutOfBand = true;
}
/**
* @return {boolean} does the member come from a channel that is not sync?
* This is used to store the member seperately
* from the sync state so it available across browser sessions.
*/
public isOutOfBand(): boolean {
return this._isOutOfBand;
}
/**
* Update this room member's membership event. May fire "RoomMember.name" if
* this event updates this member's name.
* @param {MatrixEvent} event The <code>m.room.member</code> event
* @param {RoomState} roomState Optional. The room state to take into account
* when calculating (e.g. for disambiguating users with the same name).
* @fires module:client~MatrixClient#event:"RoomMember.name"
* @fires module:client~MatrixClient#event:"RoomMember.membership"
*/
public setMembershipEvent(event: MatrixEvent, roomState?: RoomState): void {
const displayName = event.getDirectionalContent().displayname;
if (event.getType() !== "m.room.member") {
return;
}
this._isOutOfBand = false;
this.events.member = event;
const oldMembership = this.membership;
this.membership = event.getDirectionalContent().membership;
this.disambiguate = shouldDisambiguate(
this.userId,
displayName,
roomState,
);
const oldName = this.name;
this.name = calculateDisplayName(
this.userId,
displayName,
roomState,
this.disambiguate,
);
// not quite raw: we strip direction override chars so it can safely be inserted into
// blocks of text without breaking the text direction
this.rawDisplayName = utils.removeDirectionOverrideChars(event.getDirectionalContent().displayname);
if (!this.rawDisplayName || !utils.removeHiddenChars(this.rawDisplayName)) {
this.rawDisplayName = this.userId;
}
if (oldMembership !== this.membership) {
this.updateModifiedTime();
this.emit("RoomMember.membership", event, this, oldMembership);
}
if (oldName !== this.name) {
this.updateModifiedTime();
this.emit("RoomMember.name", event, this, oldName);
}
}
/**
* Update this room member's power level event. May fire
* "RoomMember.powerLevel" if this event updates this member's power levels.
* @param {MatrixEvent} powerLevelEvent The <code>m.room.power_levels</code>
* event
* @fires module:client~MatrixClient#event:"RoomMember.powerLevel"
*/
public setPowerLevelEvent(powerLevelEvent: MatrixEvent): void {
if (powerLevelEvent.getType() !== "m.room.power_levels") {
return;
}
const evContent = powerLevelEvent.getDirectionalContent();
let maxLevel = evContent.users_default || 0;
const users = evContent.users || {};
Object.values(users).forEach(function(lvl: number) {
maxLevel = Math.max(maxLevel, lvl);
});
const oldPowerLevel = this.powerLevel;
const oldPowerLevelNorm = this.powerLevelNorm;
if (users[this.userId] !== undefined && Number.isInteger(users[this.userId])) {
this.powerLevel = users[this.userId];
} else if (evContent.users_default !== undefined) {
this.powerLevel = evContent.users_default;
} else {
this.powerLevel = 0;
}
this.powerLevelNorm = 0;
if (maxLevel > 0) {
this.powerLevelNorm = (this.powerLevel * 100) / maxLevel;
}
// emit for changes in powerLevelNorm as well (since the app will need to
// redraw everyone's level if the max has changed)
if (oldPowerLevel !== this.powerLevel || oldPowerLevelNorm !== this.powerLevelNorm) {
this.updateModifiedTime();
this.emit("RoomMember.powerLevel", powerLevelEvent, this);
}
}
/**
* Update this room member's typing event. May fire "RoomMember.typing" if
* this event changes this member's typing state.
* @param {MatrixEvent} event The typing event
* @fires module:client~MatrixClient#event:"RoomMember.typing"
*/
public setTypingEvent(event: MatrixEvent): void {
if (event.getType() !== "m.typing") {
return;
}
const oldTyping = this.typing;
this.typing = false;
const typingList = event.getContent().user_ids;
if (!Array.isArray(typingList)) {
// malformed event :/ bail early. TODO: whine?
return;
}
if (typingList.indexOf(this.userId) !== -1) {
this.typing = true;
}
if (oldTyping !== this.typing) {
this.updateModifiedTime();
this.emit("RoomMember.typing", event, this);
}
}
/**
* Update the last modified time to the current time.
*/
private updateModifiedTime() {
this._modified = Date.now();
}
/**
* Get the timestamp when this RoomMember was last updated. This timestamp is
* updated when properties on this RoomMember are updated.
* It is updated <i>before</i> firing events.
* @return {number} The timestamp
*/
public getLastModifiedTime(): number {
return this._modified;
}
public isKicked(): boolean {
return this.membership === "leave" &&
this.events.member.getSender() !== this.events.member.getStateKey();
}
/**
* If this member was invited with the is_direct flag set, return
* the user that invited this member
* @return {string} user id of the inviter
*/
public getDMInviter(): string {
// when not available because that room state hasn't been loaded in,
// we don't really know, but more likely to not be a direct chat
if (this.events.member) {
// TODO: persist the is_direct flag on the member as more member events
// come in caused by displayName changes.
// the is_direct flag is set on the invite member event.
// This is copied on the prev_content section of the join member event
// when the invite is accepted.
const memberEvent = this.events.member;
let memberContent = memberEvent.getContent();
let inviteSender = memberEvent.getSender();
if (memberContent.membership === "join") {
memberContent = memberEvent.getPrevContent();
inviteSender = memberEvent.getUnsigned().prev_sender;
}
if (memberContent.membership === "invite" && memberContent.is_direct) {
return inviteSender;
}
}
}
/**
* Get the avatar URL for a room member.
* @param {string} baseUrl The base homeserver URL See
* {@link module:client~MatrixClient#getHomeserverUrl}.
* @param {Number} width The desired width of the thumbnail.
* @param {Number} height The desired height of the thumbnail.
* @param {string} resizeMethod The thumbnail resize method to use, either
* "crop" or "scale".
* @param {Boolean} allowDefault (optional) Passing false causes this method to
* return null if the user has no avatar image. Otherwise, a default image URL
* will be returned. Default: true. (Deprecated)
* @param {Boolean} allowDirectLinks (optional) If true, the avatar URL will be
* returned even if it is a direct hyperlink rather than a matrix content URL.
* If false, any non-matrix content URLs will be ignored. Setting this option to
* true will expose URLs that, if fetched, will leak information about the user
* to anyone who they share a room with.
* @return {?string} the avatar URL or null.
*/
public getAvatarUrl(
baseUrl: string,
width: number,
height: number,
resizeMethod: string,
allowDefault = true,
allowDirectLinks: boolean,
): string | null {
const rawUrl = this.getMxcAvatarUrl();
if (!rawUrl && !allowDefault) {
return null;
}
const httpUrl = getHttpUriForMxc(baseUrl, rawUrl, width, height, resizeMethod, allowDirectLinks);
if (httpUrl) {
return httpUrl;
}
return null;
}
/**
* get the mxc avatar url, either from a state event, or from a lazily loaded member
* @return {string} the mxc avatar url
*/
public getMxcAvatarUrl(): string | null {
if (this.events.member) {
return this.events.member.getDirectionalContent().avatar_url;
} else if (this.user) {
return this.user.avatarUrl;
}
return null;
}
}
const MXID_PATTERN = /@.+:.+/;
const LTR_RTL_PATTERN = /[\u200E\u200F\u202A-\u202F]/;
function shouldDisambiguate(selfUserId: string, displayName: string, roomState?: RoomState): boolean {
if (!displayName || displayName === selfUserId) return false;
// First check if the displayname is something we consider truthy
// after stripping it of zero width characters and padding spaces
if (!utils.removeHiddenChars(displayName)) return false;
if (!roomState) return false;
// Next check if the name contains something that look like a mxid
// If it does, it may be someone trying to impersonate someone else
// Show full mxid in this case
if (MXID_PATTERN.test(displayName)) return true;
// Also show mxid if the display name contains any LTR/RTL characters as these
// make it very difficult for us to find similar *looking* display names
// E.g "Mark" could be cloned by writing "kraM" but in RTL.
if (LTR_RTL_PATTERN.test(displayName)) return true;
// Also show mxid if there are other people with the same or similar
// displayname, after hidden character removal.
const userIds = roomState.getUserIdsWithDisplayName(displayName);
if (userIds.some((u) => u !== selfUserId)) return true;
return false;
}
function calculateDisplayName(
selfUserId: string,
displayName: string,
roomState: RoomState,
disambiguate: boolean,
): string {
if (disambiguate) return utils.removeDirectionOverrideChars(displayName) + " (" + selfUserId + ")";
if (!displayName || displayName === selfUserId) return selfUserId;
// First check if the displayname is something we consider truthy
// after stripping it of zero width characters and padding spaces
if (!utils.removeHiddenChars(displayName)) return selfUserId;
// We always strip the direction override characters (LRO and RLO).
// These override the text direction for all subsequent characters
// in the paragraph so if display names contained these, they'd
// need to be wrapped in something to prevent this from leaking out
// (which we can do in HTML but not text) or we'd need to add
// control characters to the string to reset any overrides (eg.
// adding PDF characters at the end). As far as we can see,
// there should be no reason these would be necessary - rtl display
// names should flip into the correct direction automatically based on
// the characters, and you can still embed rtl in ltr or vice versa
// with the embed chars or marker chars.
return utils.removeDirectionOverrideChars(displayName);
}
/**
* Fires whenever any room member's name changes.
* @event module:client~MatrixClient#"RoomMember.name"
* @param {MatrixEvent} event The matrix event which caused this event to fire.
* @param {RoomMember} member The member whose RoomMember.name changed.
* @param {string?} oldName The previous name. Null if the member didn't have a
* name previously.
* @example
* matrixClient.on("RoomMember.name", function(event, member){
* var newName = member.name;
* });
*/
/**
* Fires whenever any room member's membership state changes.
* @event module:client~MatrixClient#"RoomMember.membership"
* @param {MatrixEvent} event The matrix event which caused this event to fire.
* @param {RoomMember} member The member whose RoomMember.membership changed.
* @param {string?} oldMembership The previous membership state. Null if it's a
* new member.
* @example
* matrixClient.on("RoomMember.membership", function(event, member, oldMembership){
* var newState = member.membership;
* });
*/
/**
* Fires whenever any room member's typing state changes.
* @event module:client~MatrixClient#"RoomMember.typing"
* @param {MatrixEvent} event The matrix event which caused this event to fire.
* @param {RoomMember} member The member whose RoomMember.typing changed.
* @example
* matrixClient.on("RoomMember.typing", function(event, member){
* var isTyping = member.typing;
* });
*/
/**
* Fires whenever any room member's power level changes.
* @event module:client~MatrixClient#"RoomMember.powerLevel"
* @param {MatrixEvent} event The matrix event which caused this event to fire.
* @param {RoomMember} member The member whose RoomMember.powerLevel changed.
* @example
* matrixClient.on("RoomMember.powerLevel", function(event, member){
* var newPowerLevel = member.powerLevel;
* var newNormPowerLevel = member.powerLevelNorm;
* });
*/ | the_stack |
import localVarRequest = require('request');
import http = require('http');
let defaultBasePath = 'https://virtserver.swaggerhub.com/ohanlon/AdvancedTypeScript3CRM/1.0';
// ===============================================
// This file is autogenerated - Please do not edit
// ===============================================
/* tslint:disable:no-unused-variable */
let primitives = [
"string",
"boolean",
"double",
"integer",
"long",
"float",
"number",
"any"
];
class ObjectSerializer {
public static findCorrectType(data: any, expectedType: string) {
if (data == undefined) {
return expectedType;
} else if (primitives.indexOf(expectedType.toLowerCase()) !== -1) {
return expectedType;
} else if (expectedType === "Date") {
return expectedType;
} else {
if (enumsMap[expectedType]) {
return expectedType;
}
if (!typeMap[expectedType]) {
return expectedType; // w/e we don't know the type
}
// Check the discriminator
let discriminatorProperty = typeMap[expectedType].discriminator;
if (discriminatorProperty == null) {
return expectedType; // the type does not have a discriminator. use it.
} else {
if (data[discriminatorProperty]) {
return data[discriminatorProperty]; // use the type given in the discriminator
} else {
return expectedType; // discriminator was not present (or an empty string)
}
}
}
}
public static serialize(data: any, type: string) {
if (data == undefined) {
return data;
} else if (primitives.indexOf(type.toLowerCase()) !== -1) {
return data;
} else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6
let subType: string = type.replace("Array<", ""); // Array<Type> => Type>
subType = subType.substring(0, subType.length - 1); // Type> => Type
let transformedData: any[] = [];
for (let index in data) {
let date = data[index];
transformedData.push(ObjectSerializer.serialize(date, subType));
}
return transformedData;
} else if (type === "Date") {
return data.toString();
} else {
if (enumsMap[type]) {
return data;
}
if (!typeMap[type]) { // in case we dont know the type
return data;
}
// get the map for the correct type.
let attributeTypes = typeMap[type].getAttributeTypeMap();
let instance: {[index: string]: any} = {};
for (let index in attributeTypes) {
let attributeType = attributeTypes[index];
instance[attributeType.baseName] = ObjectSerializer.serialize(data[attributeType.name], attributeType.type);
}
return instance;
}
}
public static deserialize(data: any, type: string) {
// polymorphism may change the actual type.
type = ObjectSerializer.findCorrectType(data, type);
if (data == undefined) {
return data;
} else if (primitives.indexOf(type.toLowerCase()) !== -1) {
return data;
} else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6
let subType: string = type.replace("Array<", ""); // Array<Type> => Type>
subType = subType.substring(0, subType.length - 1); // Type> => Type
let transformedData: any[] = [];
for (let index in data) {
let date = data[index];
transformedData.push(ObjectSerializer.deserialize(date, subType));
}
return transformedData;
} else if (type === "Date") {
return new Date(data);
} else {
if (enumsMap[type]) {// is Enum
return data;
}
if (!typeMap[type]) { // dont know the type
return data;
}
let instance = new typeMap[type]();
let attributeTypes = typeMap[type].getAttributeTypeMap();
for (let index in attributeTypes) {
let attributeType = attributeTypes[index];
instance[attributeType.name] = ObjectSerializer.deserialize(data[attributeType.baseName], attributeType.type);
}
return instance;
}
}
}
export class InlineResponse200 {
'serverID'?: string;
'firstName'?: string;
'lastName'?: string;
'address'?: PeopleAddress;
static discriminator: string | undefined = undefined;
static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [
{
"name": "serverID",
"baseName": "ServerID",
"type": "string"
},
{
"name": "firstName",
"baseName": "FirstName",
"type": "string"
},
{
"name": "lastName",
"baseName": "LastName",
"type": "string"
},
{
"name": "address",
"baseName": "Address",
"type": "PeopleAddress"
} ];
static getAttributeTypeMap() {
return InlineResponse200.attributeTypeMap;
}
}
export class InlineResponse400 {
'message'?: string;
static discriminator: string | undefined = undefined;
static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [
{
"name": "message",
"baseName": "message",
"type": "string"
} ];
static getAttributeTypeMap() {
return InlineResponse400.attributeTypeMap;
}
}
export class PeopleAddress {
'line1'?: string;
'line2'?: string;
'line3'?: string;
'line4'?: string;
'postalCode'?: string;
'serverID'?: string;
static discriminator: string | undefined = undefined;
static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [
{
"name": "line1",
"baseName": "Line1",
"type": "string"
},
{
"name": "line2",
"baseName": "Line2",
"type": "string"
},
{
"name": "line3",
"baseName": "Line3",
"type": "string"
},
{
"name": "line4",
"baseName": "Line4",
"type": "string"
},
{
"name": "postalCode",
"baseName": "PostalCode",
"type": "string"
},
{
"name": "serverID",
"baseName": "ServerID",
"type": "string"
} ];
static getAttributeTypeMap() {
return PeopleAddress.attributeTypeMap;
}
}
let enumsMap: {[index: string]: any} = {
}
let typeMap: {[index: string]: any} = {
"InlineResponse200": InlineResponse200,
"InlineResponse400": InlineResponse400,
"PeopleAddress": PeopleAddress,
}
export interface Authentication {
/**
* Apply authentication settings to header and query params.
*/
applyToRequest(requestOptions: localVarRequest.Options): void;
}
export class HttpBasicAuth implements Authentication {
public username: string = '';
public password: string = '';
applyToRequest(requestOptions: localVarRequest.Options): void {
requestOptions.auth = {
username: this.username, password: this.password
}
}
}
export class ApiKeyAuth implements Authentication {
public apiKey: string = '';
constructor(private location: string, private paramName: string) {
}
applyToRequest(requestOptions: localVarRequest.Options): void {
if (this.location == "query") {
(<any>requestOptions.qs)[this.paramName] = this.apiKey;
} else if (this.location == "header" && requestOptions && requestOptions.headers) {
requestOptions.headers[this.paramName] = this.apiKey;
}
}
}
export class OAuth implements Authentication {
public accessToken: string = '';
applyToRequest(requestOptions: localVarRequest.Options): void {
if (requestOptions && requestOptions.headers) {
requestOptions.headers["Authorization"] = "Bearer " + this.accessToken;
}
}
}
export class VoidAuth implements Authentication {
public username: string = '';
public password: string = '';
applyToRequest(_: localVarRequest.Options): void {
// Do nothing
}
}
export enum DefaultApiApiKeys {
}
export class DefaultApi {
protected _basePath = defaultBasePath;
protected defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications = {
'default': <Authentication>new VoidAuth(),
'UserSecurity': new HttpBasicAuth(),
}
constructor(basePath?: string);
constructor(username: string, password: string, basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
this.username = basePathOrUsername;
this.password = password
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
set basePath(basePath: string) {
this._basePath = basePath;
}
get basePath() {
return this._basePath;
}
public setDefaultAuthentication(auth: Authentication) {
this.authentications.default = auth;
}
public setApiKey(key: DefaultApiApiKeys, value: string) {
(this.authentications as any)[DefaultApiApiKeys[key]].apiKey = value;
}
set username(username: string) {
this.authentications.UserSecurity.username = username;
}
set password(password: string) {
this.authentications.UserSecurity.password = password;
}
/**
* Returns a list of people
* @summary Retrieves the list of people from Firebase
* @param {*} [options] Override http request options.
*/
public peopleGet (options: any = {}) : Promise<{ response: http.IncomingMessage; body: Array<any>; }> {
const localVarPath = this.basePath + '/people';
let localVarQueryParameters: any = {};
let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders);
let localVarFormParams: any = {};
(<any>Object).assign(localVarHeaderParams, options.headers);
let localVarUseFormData = false;
let localVarRequestOptions: localVarRequest.Options = {
method: 'GET',
qs: localVarQueryParameters,
headers: localVarHeaderParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
this.authentications.UserSecurity.applyToRequest(localVarRequestOptions);
this.authentications.default.applyToRequest(localVarRequestOptions);
if (Object.keys(localVarFormParams).length) {
if (localVarUseFormData) {
(<any>localVarRequestOptions).formData = localVarFormParams;
} else {
localVarRequestOptions.form = localVarFormParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: Array<any>; }>((resolve, reject) => {
localVarRequest(localVarRequestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
body = ObjectSerializer.deserialize(body, "Array<any>");
if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject({ response: response, body: body });
}
}
});
});
}
} | the_stack |
import * as React from 'react';
import { composeEventHandlers } from '@radix-ui/primitive';
import { createContextScope } from '@radix-ui/react-context';
import { Primitive } from '@radix-ui/react-primitive';
import * as MenuPrimitive from '@radix-ui/react-menu';
import { createMenuScope } from '@radix-ui/react-menu';
import { useCallbackRef } from '@radix-ui/react-use-callback-ref';
import type * as Radix from '@radix-ui/react-primitive';
import type { Scope } from '@radix-ui/react-context';
type Direction = 'ltr' | 'rtl';
type Point = { x: number; y: number };
/* -------------------------------------------------------------------------------------------------
* ContextMenu
* -----------------------------------------------------------------------------------------------*/
const CONTEXT_MENU_NAME = 'ContextMenu';
type ScopedProps<P> = P & { __scopeContextMenu?: Scope };
const [createContextMenuContext, createContextMenuScope] = createContextScope(CONTEXT_MENU_NAME, [
createMenuScope,
]);
const useMenuScope = createMenuScope();
type ContextMenuContextValue = {
isRootMenu: boolean;
open: boolean;
onOpenChange(open: boolean): void;
modal: boolean;
};
const [ContextMenuProvider, useContextMenuContext] =
createContextMenuContext<ContextMenuContextValue>(CONTEXT_MENU_NAME);
interface ContextMenuProps {
onOpenChange?(open: boolean): void;
dir?: Direction;
modal?: boolean;
children?: React.ReactNode;
}
const ContextMenu: React.FC<ContextMenuProps> = (props: ScopedProps<ContextMenuProps>) => {
const { __scopeContextMenu, children, onOpenChange, dir, modal = true } = props;
const [open, setOpen] = React.useState(false);
const contentContext = useContentContext(CONTEXT_MENU_NAME, __scopeContextMenu);
const menuScope = useMenuScope(__scopeContextMenu);
const handleOpenChangeProp = useCallbackRef(onOpenChange);
const handleOpenChange = React.useCallback(
(open) => {
setOpen(open);
handleOpenChangeProp(open);
},
[handleOpenChangeProp]
);
return contentContext.isInsideContent ? (
<ContextMenuProvider
scope={__scopeContextMenu}
isRootMenu={false}
open={open}
onOpenChange={handleOpenChange}
modal={modal}
>
<MenuPrimitive.Sub {...menuScope} open={open} onOpenChange={handleOpenChange}>
{children}
</MenuPrimitive.Sub>
</ContextMenuProvider>
) : (
<ContextMenuProvider
scope={__scopeContextMenu}
isRootMenu={true}
open={open}
onOpenChange={handleOpenChange}
modal={modal}
>
<MenuPrimitive.Root
{...menuScope}
dir={dir}
open={open}
onOpenChange={handleOpenChange}
modal={modal}
>
{children}
</MenuPrimitive.Root>
</ContextMenuProvider>
);
};
ContextMenu.displayName = CONTEXT_MENU_NAME;
/* -------------------------------------------------------------------------------------------------
* ContextMenuTrigger
* -----------------------------------------------------------------------------------------------*/
const TRIGGER_NAME = 'ContextMenuTrigger';
type ContextMenuTriggerElement = React.ElementRef<typeof Primitive.span>;
type PrimitiveSpanProps = Radix.ComponentPropsWithoutRef<typeof Primitive.span>;
interface ContextMenuTriggerProps extends PrimitiveSpanProps {}
const ContextMenuTrigger = React.forwardRef<ContextMenuTriggerElement, ContextMenuTriggerProps>(
(props: ScopedProps<ContextMenuTriggerProps>, forwardedRef) => {
const { __scopeContextMenu, ...triggerProps } = props;
const context = useContextMenuContext(TRIGGER_NAME, __scopeContextMenu);
const menuScope = useMenuScope(__scopeContextMenu);
const pointRef = React.useRef<Point>({ x: 0, y: 0 });
const virtualRef = React.useRef({
getBoundingClientRect: () => DOMRect.fromRect({ width: 0, height: 0, ...pointRef.current }),
});
const longPressTimerRef = React.useRef(0);
const clearLongPress = React.useCallback(
() => window.clearTimeout(longPressTimerRef.current),
[]
);
const handleOpen = (event: React.MouseEvent | React.PointerEvent) => {
pointRef.current = { x: event.clientX, y: event.clientY };
context.onOpenChange(true);
};
React.useEffect(() => clearLongPress, [clearLongPress]);
return (
<ContentProvider scope={__scopeContextMenu} isInsideContent={false}>
<MenuPrimitive.Anchor {...menuScope} virtualRef={virtualRef} />
<Primitive.span
{...triggerProps}
ref={forwardedRef}
// prevent iOS context menu from appearing
style={{ WebkitTouchCallout: 'none', ...props.style }}
onContextMenu={composeEventHandlers(props.onContextMenu, (event) => {
// clearing the long press here because some platforms already support
// long press to trigger a `contextmenu` event
clearLongPress();
event.preventDefault();
handleOpen(event);
})}
onPointerDown={composeEventHandlers(
props.onPointerDown,
whenTouchOrPen((event) => {
// clear the long press here in case there's multiple touch points
clearLongPress();
longPressTimerRef.current = window.setTimeout(() => handleOpen(event), 700);
})
)}
onPointerMove={composeEventHandlers(props.onPointerMove, whenTouchOrPen(clearLongPress))}
onPointerCancel={composeEventHandlers(
props.onPointerCancel,
whenTouchOrPen(clearLongPress)
)}
onPointerUp={composeEventHandlers(props.onPointerUp, whenTouchOrPen(clearLongPress))}
/>
</ContentProvider>
);
}
);
ContextMenuTrigger.displayName = TRIGGER_NAME;
/* -------------------------------------------------------------------------------------------------
* ContextMenuContent
* -----------------------------------------------------------------------------------------------*/
const CONTENT_NAME = 'ContextMenuContent';
const [ContentProvider, useContentContext] = createContextMenuContext(CONTENT_NAME, {
isInsideContent: false,
});
type ContextMenuContentElement = React.ElementRef<typeof MenuPrimitive.Content>;
type MenuContentProps = Radix.ComponentPropsWithoutRef<typeof MenuPrimitive.Content>;
interface ContextMenuContentProps extends Omit<MenuContentProps, 'portalled' | 'side' | 'align'> {}
const ContextMenuContent = React.forwardRef<ContextMenuContentElement, ContextMenuContentProps>(
(props: ScopedProps<ContextMenuContentProps>, forwardedRef) => {
const { __scopeContextMenu, ...contentProps } = props;
const context = useContextMenuContext(CONTENT_NAME, __scopeContextMenu);
const menuScope = useMenuScope(__scopeContextMenu);
const commonProps = {
...contentProps,
style: {
...props.style,
// re-namespace exposed content custom property
['--radix-context-menu-content-transform-origin' as any]:
'var(--radix-popper-transform-origin)',
},
};
return (
<ContentProvider scope={__scopeContextMenu} isInsideContent={true}>
{context.isRootMenu ? (
<ContextMenuRootContent
__scopeContextMenu={__scopeContextMenu}
{...commonProps}
ref={forwardedRef}
/>
) : (
<MenuPrimitive.Content {...menuScope} {...commonProps} ref={forwardedRef} />
)}
</ContentProvider>
);
}
);
ContextMenuContent.displayName = CONTENT_NAME;
/* ---------------------------------------------------------------------------------------------- */
type ContextMenuRootContentElement = React.ElementRef<typeof MenuPrimitive.Content>;
interface ContextMenuRootContentProps extends ScopedProps<MenuContentProps> {}
const ContextMenuRootContent = React.forwardRef<
ContextMenuRootContentElement,
ContextMenuRootContentProps
>((props, forwardedRef) => {
const { __scopeContextMenu, ...contentProps } = props;
const context = useContextMenuContext(CONTENT_NAME, __scopeContextMenu);
const menuScope = useMenuScope(__scopeContextMenu);
const hasInteractedOutsideRef = React.useRef(false);
return (
<MenuPrimitive.Content
{...menuScope}
{...contentProps}
ref={forwardedRef}
portalled
side="right"
sideOffset={2}
align="start"
onCloseAutoFocus={(event) => {
props.onCloseAutoFocus?.(event);
if (!event.defaultPrevented && hasInteractedOutsideRef.current) {
event.preventDefault();
}
hasInteractedOutsideRef.current = false;
}}
onInteractOutside={(event) => {
props.onInteractOutside?.(event);
if (!event.defaultPrevented && !context.modal) hasInteractedOutsideRef.current = true;
}}
/>
);
});
/* -------------------------------------------------------------------------------------------------
* ContextMenuGroup
* -----------------------------------------------------------------------------------------------*/
const GROUP_NAME = 'ContextMenuGroup';
type ContextMenuGroupElement = React.ElementRef<typeof MenuPrimitive.Group>;
type MenuGroupProps = Radix.ComponentPropsWithoutRef<typeof MenuPrimitive.Group>;
interface ContextMenuGroupProps extends MenuGroupProps {}
const ContextMenuGroup = React.forwardRef<ContextMenuGroupElement, ContextMenuGroupProps>(
(props: ScopedProps<ContextMenuGroupProps>, forwardedRef) => {
const { __scopeContextMenu, ...groupProps } = props;
const menuScope = useMenuScope(__scopeContextMenu);
return <MenuPrimitive.Group {...menuScope} {...groupProps} ref={forwardedRef} />;
}
);
ContextMenuGroup.displayName = GROUP_NAME;
/* -------------------------------------------------------------------------------------------------
* ContextMenuLabel
* -----------------------------------------------------------------------------------------------*/
const LABEL_NAME = 'ContextMenuLabel';
type ContextMenuLabelElement = React.ElementRef<typeof MenuPrimitive.Label>;
type MenuLabelProps = Radix.ComponentPropsWithoutRef<typeof MenuPrimitive.Label>;
interface ContextMenuLabelProps extends MenuLabelProps {}
const ContextMenuLabel = React.forwardRef<ContextMenuLabelElement, ContextMenuLabelProps>(
(props: ScopedProps<ContextMenuLabelProps>, forwardedRef) => {
const { __scopeContextMenu, ...labelProps } = props;
const menuScope = useMenuScope(__scopeContextMenu);
return <MenuPrimitive.Label {...menuScope} {...labelProps} ref={forwardedRef} />;
}
);
ContextMenuLabel.displayName = LABEL_NAME;
/* -------------------------------------------------------------------------------------------------
* ContextMenuItem
* -----------------------------------------------------------------------------------------------*/
const ITEM_NAME = 'ContextMenuItem';
type ContextMenuItemElement = React.ElementRef<typeof MenuPrimitive.Item>;
type MenuItemProps = Radix.ComponentPropsWithoutRef<typeof MenuPrimitive.Item>;
interface ContextMenuItemProps extends MenuItemProps {}
const ContextMenuItem = React.forwardRef<ContextMenuItemElement, ContextMenuItemProps>(
(props: ScopedProps<ContextMenuItemProps>, forwardedRef) => {
const { __scopeContextMenu, ...itemProps } = props;
const menuScope = useMenuScope(__scopeContextMenu);
return <MenuPrimitive.Item {...menuScope} {...itemProps} ref={forwardedRef} />;
}
);
ContextMenuItem.displayName = ITEM_NAME;
/* -------------------------------------------------------------------------------------------------
* ContextMenuTriggerItem
* -----------------------------------------------------------------------------------------------*/
const TRIGGER_ITEM_NAME = 'ContextMenuTriggerItem';
type ContextMenuTriggerItemElement = React.ElementRef<typeof MenuPrimitive.SubTrigger>;
type MenuSubTriggerProps = Radix.ComponentPropsWithoutRef<typeof MenuPrimitive.SubTrigger>;
interface ContextMenuTriggerItemProps extends MenuSubTriggerProps {}
const ContextMenuTriggerItem = React.forwardRef<
ContextMenuTriggerItemElement,
ContextMenuTriggerItemProps
>((props: ScopedProps<ContextMenuTriggerItemProps>, forwardedRef) => {
const { __scopeContextMenu, ...triggerItemProps } = props;
const menuScope = useMenuScope(__scopeContextMenu);
return <MenuPrimitive.SubTrigger {...menuScope} {...triggerItemProps} ref={forwardedRef} />;
});
ContextMenuTriggerItem.displayName = TRIGGER_ITEM_NAME;
/* -------------------------------------------------------------------------------------------------
* ContextMenuCheckboxItem
* -----------------------------------------------------------------------------------------------*/
const CHECKBOX_ITEM_NAME = 'ContextMenuCheckboxItem';
type ContextMenuCheckboxItemElement = React.ElementRef<typeof MenuPrimitive.CheckboxItem>;
type MenuCheckboxItemProps = Radix.ComponentPropsWithoutRef<typeof MenuPrimitive.CheckboxItem>;
interface ContextMenuCheckboxItemProps extends MenuCheckboxItemProps {}
const ContextMenuCheckboxItem = React.forwardRef<
ContextMenuCheckboxItemElement,
ContextMenuCheckboxItemProps
>((props: ScopedProps<ContextMenuCheckboxItemProps>, forwardedRef) => {
const { __scopeContextMenu, ...checkboxItemProps } = props;
const menuScope = useMenuScope(__scopeContextMenu);
return <MenuPrimitive.CheckboxItem {...menuScope} {...checkboxItemProps} ref={forwardedRef} />;
});
ContextMenuCheckboxItem.displayName = CHECKBOX_ITEM_NAME;
/* -------------------------------------------------------------------------------------------------
* ContextMenuRadioGroup
* -----------------------------------------------------------------------------------------------*/
const RADIO_GROUP_NAME = 'ContextMenuRadioGroup';
type ContextMenuRadioGroupElement = React.ElementRef<typeof MenuPrimitive.RadioGroup>;
type MenuRadioGroupProps = Radix.ComponentPropsWithoutRef<typeof MenuPrimitive.RadioGroup>;
interface ContextMenuRadioGroupProps extends MenuRadioGroupProps {}
const ContextMenuRadioGroup = React.forwardRef<
ContextMenuRadioGroupElement,
ContextMenuRadioGroupProps
>((props: ScopedProps<ContextMenuRadioGroupProps>, forwardedRef) => {
const { __scopeContextMenu, ...radioGroupProps } = props;
const menuScope = useMenuScope(__scopeContextMenu);
return <MenuPrimitive.RadioGroup {...menuScope} {...radioGroupProps} ref={forwardedRef} />;
});
ContextMenuRadioGroup.displayName = RADIO_GROUP_NAME;
/* -------------------------------------------------------------------------------------------------
* ContextMenuRadioItem
* -----------------------------------------------------------------------------------------------*/
const RADIO_ITEM_NAME = 'ContextMenuRadioItem';
type ContextMenuRadioItemElement = React.ElementRef<typeof MenuPrimitive.RadioItem>;
type MenuRadioItemProps = Radix.ComponentPropsWithoutRef<typeof MenuPrimitive.RadioItem>;
interface ContextMenuRadioItemProps extends MenuRadioItemProps {}
const ContextMenuRadioItem = React.forwardRef<
ContextMenuRadioItemElement,
ContextMenuRadioItemProps
>((props: ScopedProps<ContextMenuRadioItemProps>, forwardedRef) => {
const { __scopeContextMenu, ...radioItemProps } = props;
const menuScope = useMenuScope(__scopeContextMenu);
return <MenuPrimitive.RadioItem {...menuScope} {...radioItemProps} ref={forwardedRef} />;
});
ContextMenuRadioItem.displayName = RADIO_ITEM_NAME;
/* -------------------------------------------------------------------------------------------------
* ContextMenuItemIndicator
* -----------------------------------------------------------------------------------------------*/
const INDICATOR_NAME = 'ContextMenuItemIndicator';
type ContextMenuItemIndicatorElement = React.ElementRef<typeof MenuPrimitive.ItemIndicator>;
type MenuItemIndicatorProps = Radix.ComponentPropsWithoutRef<typeof MenuPrimitive.ItemIndicator>;
interface ContextMenuItemIndicatorProps extends MenuItemIndicatorProps {}
const ContextMenuItemIndicator = React.forwardRef<
ContextMenuItemIndicatorElement,
ContextMenuItemIndicatorProps
>((props: ScopedProps<ContextMenuItemIndicatorProps>, forwardedRef) => {
const { __scopeContextMenu, ...itemIndicatorProps } = props;
const menuScope = useMenuScope(__scopeContextMenu);
return <MenuPrimitive.ItemIndicator {...menuScope} {...itemIndicatorProps} ref={forwardedRef} />;
});
ContextMenuItemIndicator.displayName = INDICATOR_NAME;
/* -------------------------------------------------------------------------------------------------
* ContextMenuSeparator
* -----------------------------------------------------------------------------------------------*/
const SEPARATOR_NAME = 'ContextMenuSeparator';
type ContextMenuSeparatorElement = React.ElementRef<typeof MenuPrimitive.Separator>;
type MenuSeparatorProps = Radix.ComponentPropsWithoutRef<typeof MenuPrimitive.Separator>;
interface ContextMenuSeparatorProps extends MenuSeparatorProps {}
const ContextMenuSeparator = React.forwardRef<
ContextMenuSeparatorElement,
ContextMenuSeparatorProps
>((props: ScopedProps<ContextMenuSeparatorProps>, forwardedRef) => {
const { __scopeContextMenu, ...separatorProps } = props;
const menuScope = useMenuScope(__scopeContextMenu);
return <MenuPrimitive.Separator {...menuScope} {...separatorProps} ref={forwardedRef} />;
});
ContextMenuSeparator.displayName = SEPARATOR_NAME;
/* -------------------------------------------------------------------------------------------------
* ContextMenuArrow
* -----------------------------------------------------------------------------------------------*/
const ARROW_NAME = 'ContextMenuArrow';
type ContextMenuArrowElement = React.ElementRef<typeof MenuPrimitive.Arrow>;
type MenuArrowProps = Radix.ComponentPropsWithoutRef<typeof MenuPrimitive.Arrow>;
interface ContextMenuArrowProps extends MenuArrowProps {}
const ContextMenuArrow = React.forwardRef<ContextMenuArrowElement, ContextMenuArrowProps>(
(props: ScopedProps<ContextMenuArrowProps>, forwardedRef) => {
const { __scopeContextMenu, ...arrowProps } = props;
const menuScope = useMenuScope(__scopeContextMenu);
return <MenuPrimitive.Arrow {...menuScope} {...arrowProps} ref={forwardedRef} />;
}
);
ContextMenuArrow.displayName = ARROW_NAME;
/* -----------------------------------------------------------------------------------------------*/
function whenTouchOrPen<E>(handler: React.PointerEventHandler<E>): React.PointerEventHandler<E> {
return (event) => (event.pointerType !== 'mouse' ? handler(event) : undefined);
}
const Root = ContextMenu;
const Trigger = ContextMenuTrigger;
const Content = ContextMenuContent;
const Group = ContextMenuGroup;
const Label = ContextMenuLabel;
const Item = ContextMenuItem;
const TriggerItem = ContextMenuTriggerItem;
const CheckboxItem = ContextMenuCheckboxItem;
const RadioGroup = ContextMenuRadioGroup;
const RadioItem = ContextMenuRadioItem;
const ItemIndicator = ContextMenuItemIndicator;
const Separator = ContextMenuSeparator;
const Arrow = ContextMenuArrow;
export {
createContextMenuScope,
//
ContextMenu,
ContextMenuTrigger,
ContextMenuContent,
ContextMenuGroup,
ContextMenuLabel,
ContextMenuItem,
ContextMenuTriggerItem,
ContextMenuCheckboxItem,
ContextMenuRadioGroup,
ContextMenuRadioItem,
ContextMenuItemIndicator,
ContextMenuSeparator,
ContextMenuArrow,
//
Root,
Trigger,
Content,
Group,
Label,
Item,
TriggerItem,
CheckboxItem,
RadioGroup,
RadioItem,
ItemIndicator,
Separator,
Arrow,
};
export type {
ContextMenuProps,
ContextMenuTriggerProps,
ContextMenuContentProps,
ContextMenuGroupProps,
ContextMenuLabelProps,
ContextMenuItemProps,
ContextMenuTriggerItemProps,
ContextMenuCheckboxItemProps,
ContextMenuRadioGroupProps,
ContextMenuRadioItemProps,
ContextMenuItemIndicatorProps,
ContextMenuSeparatorProps,
ContextMenuArrowProps,
}; | the_stack |
import { GraphQLFieldExtensions } from 'https://cdn.skypack.dev/graphql?dts';
import type { InputFieldMap, InputShapeFromFields, Resolver, Subscriber } from '../builder-options.ts';
import { SchemaTypes } from '../schema-types.ts';
import { FieldNullability, FieldRequiredness, InputShapeFromTypeParam, InputType, ShapeFromTypeParam, TypeParam, } from '../type-params.ts';
declare global {
export namespace PothosSchemaTypes {
export interface FieldOptions<Types extends SchemaTypes = SchemaTypes, ParentShape = unknown, Type extends TypeParam<Types> = TypeParam<Types>, Nullable extends FieldNullability<Type> = FieldNullability<Type>, Args extends InputFieldMap = InputFieldMap, ResolveShape = unknown, ResolveReturnShape = unknown> {
/** The type for this field */
type: Type;
/** arguments for this field (created via `t.args`) */
args?: Args;
/** determins if this field can return null */
nullable?: Nullable;
/** text description for this field. This will be added into your schema file and visable in tools like graphql-playground */
description?: string;
/** When present marks this field as deprecated */
deprecationReason?: string;
/** extensions for this field for use by directives, server plugins or other tools that depend on extensions */
extensions?: GraphQLFieldExtensions<ParentShape, Types["Context"], InputShapeFromFields<Args>>;
/**
* Resolver function for this field
* @param parent - The parent object for the current type
* @param {object} args - args object based on the args defined for this field
* @param {object} context - the context object for the current query, based on `Context` type provided to the SchemaBuilder
* @param {GraphQLResolveInfo} info - info about how this field was queried
*/
resolve?: Resolver<ResolveShape, InputShapeFromFields<Args>, Types["Context"], ShapeFromTypeParam<Types, Type, Nullable>, ResolveReturnShape>;
}
export interface ObjectFieldOptions<Types extends SchemaTypes, ParentShape, Type extends TypeParam<Types>, Nullable extends FieldNullability<Type>, Args extends InputFieldMap, ResolveReturnShape> extends FieldOptions<Types, ParentShape, Type, Nullable, Args, ParentShape, ResolveReturnShape> {
/**
* Resolver function for this field
* @param parent - The parent object for the current type
* @param {object} args - args object based on the args defined for this field
* @param {object} context - the context object for the current query, based on `Context` type provided to the SchemaBuilder
* @param {GraphQLResolveInfo} info - info about how this field was queried
*/
resolve: Resolver<ParentShape, InputShapeFromFields<Args>, Types["Context"], ShapeFromTypeParam<Types, Type, Nullable>, ResolveReturnShape>;
}
export interface QueryFieldOptions<Types extends SchemaTypes, Type extends TypeParam<Types>, Nullable extends FieldNullability<Type>, Args extends InputFieldMap, ResolveReturnShape> extends FieldOptions<Types, Types["Root"], Type, Nullable, Args, Types["Root"], ResolveReturnShape> {
/**
* Resolver function for this field
* @param root - The root object for this request
* @param {object} args - args object based on the args defined for this field
* @param {object} context - the context object for the current query, based on `Context` type provided to the SchemaBuilder
* @param {GraphQLResolveInfo} info - info about how this field was queried
*/
resolve: Resolver<Types["Root"], InputShapeFromFields<Args>, Types["Context"], ShapeFromTypeParam<Types, Type, Nullable>, ResolveReturnShape>;
}
export interface MutationFieldOptions<Types extends SchemaTypes, Type extends TypeParam<Types>, Nullable extends FieldNullability<Type>, Args extends InputFieldMap, ResolveReturnShape> extends FieldOptions<Types, Types["Root"], Type, Nullable, Args, Types["Root"], ResolveReturnShape> {
/**
* Resolver function for this field
* @param root - The root object for this request
* @param {object} args - args object based on the args defined for this field
* @param {object} context - the context object for the current query, based on `Context` type provided to the SchemaBuilder
* @param {GraphQLResolveInfo} info - info about how this field was queried
*/
resolve: Resolver<Types["Root"], InputShapeFromFields<Args>, Types["Context"], ShapeFromTypeParam<Types, Type, Nullable>, ResolveReturnShape>;
}
export interface InterfaceFieldOptions<Types extends SchemaTypes, ParentShape, Type extends TypeParam<Types>, Nullable extends FieldNullability<Type>, Args extends InputFieldMap, ResolveReturnShape> extends FieldOptions<Types, ParentShape, Type, Nullable, Args, ParentShape, ResolveReturnShape> {
/**
* Resolver function for this field
* @param root - The root object for this request
* @param {object} args - args object based on the args defined for this field
* @param {object} context - the context object for the current query, based on `Context` type provided to the SchemaBuilder
* @param {GraphQLResolveInfo} info - info about how this field was queried
*/
resolve?: Resolver<ParentShape, InputShapeFromFields<Args>, Types["Context"], ShapeFromTypeParam<Types, Type, Nullable>, ResolveReturnShape>;
}
export interface SubscriptionFieldOptions<Types extends SchemaTypes, Type extends TypeParam<Types>, Nullable extends FieldNullability<Type>, Args extends InputFieldMap, ResolveShape, ResolveReturnShape> extends FieldOptions<Types, Types["Root"], Type, Nullable, Args, ResolveShape, ResolveReturnShape> {
/**
* Resolver function for this field
* @param parent - The parent object for this subscription (yielded by subscribe)
* @param {object} args - args object based on the args defined for this field
* @param {object} context - the context object for the current query, based on `Context` type provided to the SchemaBuilder
* @param {GraphQLResolveInfo} info - info about how this field was queried
*/
resolve: Resolver<ResolveShape, InputShapeFromFields<Args>, Types["Context"], ShapeFromTypeParam<Types, Type, Nullable>, ResolveReturnShape>;
/**
* Resolver function for this field
* @param root - The root object for this request
* @param {object} args - args object based on the args defined for this field
* @param {object} context - the context object for the current query, based on `Context` type provided to the SchemaBuilder
* @param {GraphQLResolveInfo} info - info about how this field was queried
*/
subscribe: Subscriber<Types["Root"], InputShapeFromFields<Args>, Types["Context"], ResolveShape>;
}
export interface FieldOptionsByKind<Types extends SchemaTypes, ParentShape, Type extends TypeParam<Types>, Nullable extends FieldNullability<Type>, Args extends InputFieldMap, ResolveShape, ResolveReturnShape> {
Query: QueryFieldOptions<Types, Type, Nullable, Args, ResolveReturnShape>;
Mutation: MutationFieldOptions<Types, Type, Nullable, Args, ResolveReturnShape>;
Subscription: SubscriptionFieldOptions<Types, Type, Nullable, Args, ResolveShape, ResolveReturnShape>;
Object: ObjectFieldOptions<Types, ParentShape, Type, Nullable, Args, ResolveReturnShape>;
Interface: InterfaceFieldOptions<Types, ParentShape, Type, Nullable, Args, ResolveReturnShape>;
}
export interface InputFieldOptions<Types extends SchemaTypes = SchemaTypes, Type extends InputType<Types> | [
InputType<Types>
] = InputType<Types> | [
InputType<Types>
], Req extends FieldRequiredness<Type> = FieldRequiredness<Type>> {
/** The type for this field */
type: Type;
/** text description for this field. This will be added into your schema file and visable in tools like graphql-playground */
description?: string;
/** When present marks this field as deprecated */
deprecationReason?: string;
/** etermins if this field can be omitted (or set as null) */
required?: Req;
/** default value if this field is not included in the query */
defaultValue?: NonNullable<InputShapeFromTypeParam<Types, Type, Req>>;
/** extensions for this field for use by directives, server plugins or other tools that depend on extensions */
extensions?: Readonly<Record<string, unknown>>;
}
export interface ArgFieldOptions<Types extends SchemaTypes = SchemaTypes, Type extends InputType<Types> | [
InputType<Types>
] = InputType<Types> | [
InputType<Types>
], Req extends FieldRequiredness<Type> = FieldRequiredness<Type>> extends InputFieldOptions<Types, Type, Req> {
}
export interface InputObjectFieldOptions<Types extends SchemaTypes = SchemaTypes, Type extends InputType<Types> | [
InputType<Types>
] = InputType<Types> | [
InputType<Types>
], Req extends FieldRequiredness<Type> = FieldRequiredness<Type>> extends InputFieldOptions<Types, Type, Req> {
}
export interface InputFieldOptionsByKind<Types extends SchemaTypes = SchemaTypes, Type extends InputType<Types> | [
InputType<Types>
] = InputType<Types> | [
InputType<Types>
], Req extends FieldRequiredness<Type> = FieldRequiredness<Type>> {
Arg: ArgFieldOptions<Types, Type, Req>;
InputObject: InputObjectFieldOptions<Types, Type, Req>;
}
}
} | the_stack |
import React from "react";
import { View } from "react-native";
import styled from "@emotion/native";
import RView, { MediaRule } from "emotion-native-media-query";
import {
STANFORD_COLORS,
FOCUS_STATES,
BREAKPOINTS,
FONTS,
LINKS,
} from "helpers/constants";
import { Category } from "helpers/wpapi";
import Link from "./Link";
import { SECTION_PADDING } from "./Section";
import { CategoryLink } from "./CategoryLink";
import css from "@emotion/css";
type CategoryWithChildren = Category & {
children: { [slug: string]: CategoryWithChildren };
};
// List of links that appears at bottom of any page on the site;
// note the difference between this component and TopBarLinks;
// make sure to change links in desired place(s) when updating
export const FooterContent: React.ElementType = ({ style }: any) => {
// https://www.stanforddaily.com/wp-json/tsd/json/v1/nav
const categoryList: {
[slug: string]: CategoryWithChildren;
} = {
news: {
id: 3,
name: "News",
slug: "news",
url: "/category/news/",
children: {
"academics-news": {
id: 4408,
name: "Academics",
slug: "academics-news",
url: "/category/news/academics-news/",
children: {},
},
"local-news": {
id: 4412,
name: "Local",
slug: "local-news",
url: "/category/news/local-news/",
children: {},
},
"research-news": {
id: 4414,
name: "Research",
slug: "research-news",
url: "/category/news/research-news/",
children: {},
},
"technology-news": {
id: 16821,
name: "Science & Tech",
slug: "technology-news",
url: "/category/news/technology-news/",
children: {},
},
"speakers-events-news": {
id: 4421,
name: "Speakers & Events",
slug: "speakers-events-news",
url: "/category/news/speakers-events-news/",
children: {},
},
"student-government-news": {
id: 4422,
name: "Student Government",
slug: "student-government-news",
url: "/category/news/student-government-news/",
children: {},
},
"student-life-news": {
id: 4423,
name: "Student Life",
slug: "student-life-news",
url: "/category/news/student-life-news/",
children: {},
},
"university-news": {
id: 4424,
name: "University",
slug: "university-news",
url: "/category/news/university-news/",
children: {},
},
},
},
// magazine: {
// id: 53462,
// name: "Magazine",
// slug: "magazine",
// url: "/category/magazine/",
// children: {},
// },
sports: {
id: 23,
name: "SPORTS",
slug: "sports",
url: "/category/sports/",
children: {
"fall-sports": {
id: 45417,
name: "Fall Sports",
slug: "fall-sports",
url: "/category/sports/fall-sports/",
children: {},
},
"winter-sports": {
id: 45418,
name: "Winter Sports",
slug: "winter-sports",
url: "/category/sports/winter-sports/",
children: {},
},
"spring-sports": {
id: 45419,
name: "Spring Sports",
slug: "spring-sports",
url: "/category/sports/spring-sports/",
children: {},
},
"sports-features": {
id: 57510,
name: "Sports Features",
slug: "sports-features",
url: "/category/sports/sports-features/",
children: {},
},
},
},
opinions: {
id: 24,
name: "OPINIONS",
slug: "opinions",
url: "/category/opinions/",
children: {
columnists: {
id: 13181,
name: "Columnists",
slug: "columnists",
url: "/category/opinions/columnists/",
children: {},
},
editorials: {
id: 13183,
name: "Editorials",
slug: "editorials",
url: "/category/opinions/editorials/",
children: {},
},
"letters-to-the-community": {
id: 38657,
name: "Letters to the Community",
slug: "letters-to-the-community",
url: "/category/opinions/letters-to-the-community/",
children: {},
},
"letters-to-the-editor": {
id: 13182,
name: "Letters to the Editor",
slug: "letters-to-the-editor",
url: "/category/opinions/letters-to-the-editor/",
children: {},
},
"op-eds": {
id: 27142,
name: "Op-Eds",
slug: "op-eds",
url: "/category/opinions/op-eds/",
children: {},
},
},
},
"arts-life": {
id: 25,
name: "ARTS & LIFE",
slug: "arts-life",
url: "/category/arts-life/",
children: {
"comedy-intermission": {
id: 26817,
name: "Comedy",
slug: "comedy-intermission",
url: "/category/arts-life/comedy-intermission/",
children: {},
},
"critics-pick": {
id: 26681,
name: "Critic's Pick",
slug: "critics-pick",
url: "/category/arts-life/critics-pick/",
children: {},
},
culture: {
id: 40678,
name: "Culture",
slug: "culture",
url: "/category/arts-life/culture/",
children: {},
},
"fashion-intermission": {
id: 23854,
name: "Fashion",
slug: "fashion-intermission",
url: "/category/arts-life/fashion-intermission/",
children: {},
},
"film-intermission": {
id: 23850,
name: "Film",
slug: "film-intermission",
url: "/category/arts-life/film-intermission/",
children: {},
},
food: {
id: 23853,
name: "Food",
slug: "food",
url: "/category/arts-life/food/",
children: {},
},
"music-intermission": {
id: 23848,
name: "Music",
slug: "music-intermission",
url: "/category/arts-life/music-intermission/",
children: {},
},
reads: {
id: 40679,
name: "Reads",
slug: "reads",
url: "/category/arts-life/reads/",
children: {},
},
reviews: {
id: 40680,
name: "Reviews",
slug: "reviews",
url: "/category/arts-life/reviews/",
children: {},
},
screen: {
id: 40640,
name: "Screen",
slug: "screen",
url: "/category/arts-life/screen/",
children: {},
},
"television-intermission": {
id: 23849,
name: "Television",
slug: "television-intermission",
url: "/category/arts-life/television-intermission/",
children: {},
},
"theater-intermission": {
id: 23851,
name: "Theater",
slug: "theater-intermission",
url: "/category/arts-life/theater-intermission/",
children: {},
},
"video-games": {
id: 66235,
name: "Video Games",
slug: "video-games",
url: "/category/arts-life/video-games/",
children: {},
},
"visual-arts-intermission": {
id: 23867,
name: "Visual Arts",
slug: "visual-arts-intermission",
url: "/category/arts-life/visual-arts-intermission/",
children: {},
},
},
},
thegrind: {
id: 32278,
name: "The Grind",
slug: "thegrind",
url: "/category/thegrind/",
children: {},
// "social-life": {
// id: 66231,
// name: "Social Life",
// slug: "social-life",
// url: "/category/thegrind/social-life/",
// children: {},
// },
// "campus-quirks": {
// id: 66225,
// name: "Campus Quirks",
// slug: "campus-quirks",
// url: "/category/thegrind/campus-quirks/",
// children: {},
// },
// "reflections-advice": {
// id: 66227,
// name: "Reflections & Advice",
// slug: "reflections-advice",
// url: "/category/thegrind/reflections-advice/",
// children: {},
// },
// "classes-declassified": {
// id: 66232,
// name: "Classes Declassified",
// slug: "classes-declassified",
// url: "/category/thegrind/classes-declassified/",
// children: {},
// },
// },
},
humor: {
id: 55796,
name: "Humor",
slug: "humor",
url: "/category/humor/",
children: {},
},
magazine: {
id: 53462,
name: "Magazine",
slug: "magazine",
url: "/category/magazine/",
children: {},
},
"@94305": {
id: 58277,
name: "Data",
slug: "94305",
url: "/category/@94305/",
children: {},
},
// TODO: use `LinkLink` type
podcasts: {
id: null,
name: "Podcasts",
slug: "podcasts",
url: LINKS.THE_DAILY_BREW_SPOTIFY,
children: {},
},
video: {
id: null,
name: "Video",
slug: "video",
url: LINKS.YOUTUBE,
children: {},
},
cartoons: {
id: 41527,
name: "Cartoons",
slug: "cartoons",
url: "/category/cartoons/",
children: {},
},
dei: {
id: 74524,
name: "DEI",
slug: "dei",
url: "/category/dei/",
children: {},
},
resources: {
id: null,
name: "Resources",
slug: "resources",
url: "/campus-resources/",
children: {},
},
aboutUs: {
id: null,
name: "About us",
slug: "about-us",
url: "/about/",
children: {},
},
masthead: {
id: null,
name: "Masthead",
slug: "masthead",
url: "/masthead/",
children: {},
},
alumni: {
id: null,
name: "Alumni",
slug: "alumni",
url: "https://alumni.stanforddaily.com/",
children: {},
},
advertise: {
id: null,
name: "Advertise",
slug: "advertise",
url: "/advertise/",
children: {},
},
archives: {
id: null,
name: "Archives",
slug: "archives",
url: "https://archives.stanforddaily.com/",
children: {},
},
};
const BottomText = styled.Text({
...FONTS.AUXILIARY,
color: STANFORD_COLORS.WHITE,
});
const BottomLine: React.ElementType = props => (
<RView
style={{
textAlign: "center",
}}
rStyle={{
[MediaRule.MinWidth]: {
[BREAKPOINTS.DESKTOP]: {
justifyContent: "space-between",
flexDirection: "row",
},
},
}}
{...props}
/>
);
const bottomLinkStyle = {
color: "inherit",
textDecoration: "underline",
};
return (
<RView
style={style}
css={css`
a {
line-height: 1.5em;
}
@media print {
display: none;
}
`}
rStyle={{
[MediaRule.MinWidth]: {
[BREAKPOINTS.TABLET]: {
padding: SECTION_PADDING,
},
},
}}
>
<RView
rStyle={{
[MediaRule.MinWidth]: {
[BREAKPOINTS.TABLET]: {
marginTop: SECTION_PADDING,
height: 300,
flexWrap: "wrap",
},
},
}}
>
{Object.values(categoryList).map(category => {
return (
<View
key={category.url}
style={{
marginBottom: SECTION_PADDING,
}}
>
<CategoryLink
category={category}
style={{
color: STANFORD_COLORS.WHITE,
fontSize: 16,
fontWeight: "bold",
}}
hasCustomOutline={true}
isInNav={true}
/>
{Object.values(category.children).map(subCategory => {
return (
<CategoryLink
key={subCategory.id}
category={subCategory}
style={{
color: STANFORD_COLORS.WHITE,
textTransform: "none",
}}
hasCustomOutline={true}
isInNav={true}
/>
);
})}
</View>
);
})}
</RView>
<View>
<BottomLine>
<BottomText style={{ fontWeight: "bold" }}>
© 2021 The Stanford Daily Publishing Corporation
</BottomText>
<BottomText style={{ fontWeight: "bold" }}>
<a
style={bottomLinkStyle}
href={LINKS.ACCESSIBILITY_STATEMENT}
title="Accessibility"
css={css`
${FOCUS_STATES.YELLOW_OUTLINE}
`}
>
Accessibility
</a>{" "}
|{" "}
<Link href="/[year]/" as="/privacy-policy/">
<a
style={bottomLinkStyle}
title="Privacy Policy"
css={css`
${FOCUS_STATES.YELLOW_OUTLINE}
`}
>
Privacy Policy
</a>
</Link>{" "}
|{" "}
<a
style={bottomLinkStyle}
href="https://apps.apple.com/us/app/stanford-daily/id1341270063" // add to constants
title="iOS App"
css={css`
${FOCUS_STATES.YELLOW_OUTLINE}
`}
>
iOS App
</a>{" "}
|{" "}
<a
style={bottomLinkStyle}
href="https://play.google.com/store/apps/details?id=com.Stanford.Daily.App&hl=en_US"
title="Google Play App"
css={css`
${FOCUS_STATES.YELLOW_OUTLINE}
`}
>
Google Play App
</a>
</BottomText>
</BottomLine>
<BottomLine>
<BottomText style={{ textTransform: "none" }}>
Proudly powered by{" "}
<a
style={bottomLinkStyle}
href="https://wordpress.org/"
title="WordPress"
css={css`
${FOCUS_STATES.YELLOW_OUTLINE}
`}
>
WordPress
</a>{" "}
and{" "}
<a
style={bottomLinkStyle}
href="https://expo.io/"
title="Expo"
css={css`
${FOCUS_STATES.YELLOW_OUTLINE}
`}
>
Expo
</a>{" "}
| Theme by{" "}
<a
style={bottomLinkStyle}
href="https://github.com/TheStanfordDaily/"
title="The Stanford Daily Tech Team"
css={css`
${FOCUS_STATES.YELLOW_OUTLINE}
`}
>
TSD Tech Team
</a>
</BottomText>
<BottomText style={{ textTransform: "none" }}>
<a
style={bottomLinkStyle}
href="/donate/"
title="Donate"
css={css`
${FOCUS_STATES.YELLOW_OUTLINE}
`}
>
Donate
</a>{" "}
and support The Daily when you shop on{" "}
<a
style={bottomLinkStyle}
href="https://smile.amazon.com/"
title="Amazon Smile"
css={css`
${FOCUS_STATES.YELLOW_OUTLINE}
`}
>
Amazon
</a>
</BottomText>
</BottomLine>
</View>
</RView>
);
}; | the_stack |
import type { ValidationRule } from 'ant-design-vue/lib/form/Form';
import {
IField,
IFieldBeetWeen,
IFieldContains,
IFieldLength,
IFieldRange,
IFieldMatch,
IFieldRegular,
IFieldValidator,
} from './typing';
import { useLocalization } from './useLocalization';
import { isEmail, isPhone } from '/@/utils/is';
export enum ValidationEnum {
DoNotMatch = "'{0}' and '{1}' do not match.",
FieldInvalid = 'The field {0} is invalid.',
FieldIsNotValid = '{0} is not valid.',
FieldMustBeStringOrArrayWithMaximumLength = "The field {0} must be a string or array type with a maximum length of '{1}'.",
FieldMustBeStringOrArrayWithMinimumLength = "The field {0} must be a string or array type with a minimum length of '{1}'.",
FieldMustBeStringWithMaximumLength = 'The field {0} must be a string with a maximum length of {1}.',
FieldMustBeStringWithMinimumLengthAndMaximumLength = 'The field {0} must be a string with a minimum length of {2} and a maximum length of {1}.',
FieldMustBeetWeen = 'The field {0} must be between {1} and {2}.',
FieldMustMatchRegularExpression = "The field {0} must match the regular expression '{1}'.",
FieldDoNotValidCreditCardNumber = 'The {0} field is not a valid credit card number.',
FieldDoNotValidEmailAddress = 'The {0} field is not a valid e-mail address.',
FieldDoNotValidFullyQualifiedUrl = 'The {0} field is not a valid fully-qualified http, https, or ftp URL.',
FieldDoNotValidPhoneNumber = 'The {0} field is not a valid phone number.',
FieldRequired = 'The {0} field is required.',
FieldOnlyAcceptsFilesExtensions = 'The {0} field only accepts files with the following extensions: {1}',
ThisFieldIsInvalid = 'ThisFieldIsInvalid.',
ThisFieldIsNotAValidCreditCardNumber = 'ThisFieldIsNotAValidCreditCardNumber.',
ThisFieldIsNotAValidEmailAddress = 'ThisFieldIsNotAValidEmailAddress.',
ThisFieldIsNotAValidFullyQualifiedHttpHttpsOrFtpUrl = 'ThisFieldIsNotAValidFullyQualifiedHttpHttpsOrFtpUrl',
ThisFieldIsNotAValidPhoneNumber = 'ThisFieldIsNotAValidPhoneNumber.',
ThisFieldIsNotValid = 'ThisFieldIsNotValid.',
ThisFieldIsRequired = 'ThisFieldIsRequired.',
ThisFieldMustBeAStringOrArrayTypeWithAMaximumLength = 'ThisFieldMustBeAStringOrArrayTypeWithAMaximumLengthOf{0}',
ThisFieldMustBeAStringOrArrayTypeWithAMinimumLength = 'ThisFieldMustBeAStringOrArrayTypeWithAMinimumLengthOf{0}',
ThisFieldMustBeAStringWithAMaximumLength = 'ThisFieldMustBeAStringWithAMaximumLengthOf{0}',
ThisFieldMustBeAStringWithAMinimumLengthAndAMaximumLength = 'ThisFieldMustBeAStringWithAMinimumLengthOf{1}AndAMaximumLengthOf{0}',
ThisFieldMustBeBetween = 'ThisFieldMustBeBetween{0}And{1}',
ThisFieldMustMatchTheRegularExpression = 'ThisFieldMustMatchTheRegularExpression{0}',
ThisFieldOnlyAcceptsFilesWithTheFollowingExtensions = 'ThisFieldOnlyAcceptsFilesWithTheFollowingExtensions:{0}',
}
/** 规则创建器 */
interface IRuleCreator {
/** input 与 value 是否匹配 */
doNotMatch(field: IFieldMatch): ValidationRule[];
/** 字段是无效值 */
fieldInvalid(field: IFieldValidator): ValidationRule[];
/** 验证未通过 */
fieldIsNotValid(field: IFieldValidator): ValidationRule[];
/** 字段{0}必须是最大长度为'{1}'的字符串或数组 */
fieldMustBeStringOrArrayWithMaximumLength(field: IFieldLength): ValidationRule[];
/** 字段{0}必须是最小长度为'{1}'的字符串或数组 */
fieldMustBeStringOrArrayWithMinimumLength(field: IFieldLength): ValidationRule[];
/** 字段{0}必须是最大长度为{1}的字符串 */
fieldMustBeStringWithMaximumLength(field: IFieldLength): ValidationRule[];
/** 字段{0}必须是最小长度为{2}并且最大长度{1}的字符串 */
fieldMustBeStringWithMinimumLengthAndMaximumLength(field: IFieldRange): ValidationRule[];
/** 字段{0}值必须在{1}和{2}范围内 */
fieldMustBeetWeen(field: IFieldBeetWeen): ValidationRule[];
/** 字段{0}与正则表达式不匹配 */
fieldMustMatchRegularExpression(field: IFieldRegular): ValidationRule[];
/** 字段{0}不是有效的信用卡号码 */
fieldDoNotValidCreditCardNumber(field: IField): ValidationRule[];
/** 字段{0}不是有效的邮箱地址 */
fieldDoNotValidEmailAddress(field: IField): ValidationRule[];
/** 字段{0}不是有效的完全限定的http,https或ftp URL. */
fieldDoNotValidFullyQualifiedUrl(field: IField): ValidationRule[];
/** 字段{0}不是有效的手机号码 */
fieldDoNotValidPhoneNumber(field: IField): ValidationRule[];
/** 字段{0}不可为空 */
fieldRequired(field: IField): ValidationRule[];
/** {0}字段只允许以下扩展名的文件: {1} */
fieldOnlyAcceptsFilesExtensions(field: IFieldContains): ValidationRule[];
}
export function useValidation() {
const { L } = useLocalization('AbpValidation');
function _getFieldName(field: IField) {
return __getFieldName(field.name ?? '', field.resourceName, field.prefix, field.connector);
}
function __getFieldName(
fieldName: string,
resourceName?: string,
prefix?: string,
connector?: string,
) {
if (fieldName && resourceName) {
fieldName = prefix ? `${prefix}${connector ?? ':'}${fieldName}` : fieldName;
const { L: l } = useLocalization(resourceName);
return l(fieldName);
}
return fieldName;
}
function _createRule(options: {
message?: string;
type?: string;
required?: boolean;
len?: number;
min?: number;
max?: number;
trigger?: string;
validator?: (rule: any, value: any, callback: any, source?: any, options?: any) => any;
}): ValidationRule[] {
return [
{
message: options.message,
type: options.type,
required: options.required,
len: options.len,
min: options.min,
max: options.max,
validator: options.validator,
trigger: options.trigger,
},
];
}
function _createValidator(
field: IField,
useNameEnum: string,
notNameEnum: string,
required?: boolean,
): ValidationRule {
const message = field.name ? L(useNameEnum, _getFieldName(field)) : L(notNameEnum);
return {
required: required,
message: message,
type: field.type,
trigger: field.trigger,
};
}
function _createLengthValidator(
field: IFieldLength,
checkMaximum: boolean,
useNameEnum: string,
notNameEnum: string,
required?: boolean,
): ValidationRule {
const message = field.name
? L(useNameEnum, _getFieldName(field), field.length)
: L(notNameEnum, field.length);
function checkLength(value: string | any[]) {
return checkMaximum ? field.length > value.length : value.length > field.length;
}
return {
required: required,
message: message,
type: field.type,
trigger: field.trigger,
validator: (_, value: string) => {
if (!checkLength(value)) {
return Promise.reject(message);
}
return Promise.resolve();
},
};
}
function _createLengthRangValidator(
field: IFieldRange,
useNameEnum: string,
notNameEnum: string,
required?: boolean,
): ValidationRule {
const message = field.name
? L(useNameEnum, _getFieldName(field), field.minimum, field.maximum)
: L(notNameEnum, field.minimum, field.maximum);
return {
required: required,
message: message,
type: field.type,
trigger: field.trigger,
validator: (_, value: string) => {
if (value.length < field.minimum || value.length > field.maximum) {
return Promise.reject(message);
}
return Promise.resolve();
},
};
}
function _createBeetWeenValidator(field: IFieldBeetWeen): ValidationRule {
const message = field.name
? L(ValidationEnum.FieldMustBeetWeen, _getFieldName(field), field.start, field.end)
: L(ValidationEnum.ThisFieldMustBeBetween, field.start, field.end);
return {
message: message,
trigger: field.trigger,
validator: (_, value) => {
// beetween不在进行必输检查, 改为数字有效性检查
if (isNaN(value)) {
return Promise.reject(message);
}
if (value < field.start || value > field.end) {
return Promise.reject(message);
} else {
return Promise.resolve();
}
},
};
}
function _createRegularExpressionValidator(
field: IFieldRegular,
required?: boolean,
): ValidationRule {
const message = field.name
? L(ValidationEnum.FieldMustMatchRegularExpression, _getFieldName(field), field.expression)
: L(ValidationEnum.ThisFieldMustMatchTheRegularExpression, field.expression);
return {
required: required,
message: message,
type: field.type,
trigger: field.trigger,
pattern: new RegExp(field.expression),
};
}
function _createEmailValidator(field: IField, required?: boolean): ValidationRule {
const message = field.name
? L(ValidationEnum.FieldDoNotValidEmailAddress, _getFieldName(field))
: L(ValidationEnum.ThisFieldIsNotAValidEmailAddress);
return {
required: required,
message: message,
type: field.type,
trigger: field.trigger,
validator: (_, value: string) => {
if (!isEmail(value)) {
return Promise.reject(message);
}
return Promise.resolve();
},
};
}
function _createPhoneValidator(field: IField, required?: boolean): ValidationRule {
const message = field.name
? L(ValidationEnum.FieldDoNotValidPhoneNumber, _getFieldName(field))
: L(ValidationEnum.ThisFieldIsNotAValidPhoneNumber);
return {
required: required,
message: message,
type: field.type,
trigger: field.trigger,
validator: (_, value: string) => {
if (!isPhone(value)) {
return Promise.reject(message);
}
return Promise.resolve();
},
};
}
const ruleCreator: IRuleCreator = {
doNotMatch(field: IFieldMatch) {
const message = L(
ValidationEnum.DoNotMatch,
__getFieldName(field.name, field.resourceName, field.prefix),
__getFieldName(field.matchField, field.resourceName, field.prefix),
);
return _createRule({
required: field.required,
message: message,
type: field.type,
trigger: field.trigger,
validator: (_, value: string) => {
if (value !== field.matchValue) {
return Promise.reject(message);
}
return Promise.resolve();
},
});
},
fieldInvalid(field: IFieldValidator) {
const message = field.name
? L(ValidationEnum.FieldInvalid, _getFieldName(field))
: L(ValidationEnum.ThisFieldIsInvalid);
return _createRule({
required: field.required,
message: message,
type: field.type,
trigger: field.trigger,
validator: (_, value: any) => {
if (!field.validator(value)) {
return Promise.reject(message);
}
return Promise.resolve();
},
});
},
fieldIsNotValid(field: IFieldValidator) {
const message = field.name
? L(ValidationEnum.FieldIsNotValid, _getFieldName(field))
: L(ValidationEnum.ThisFieldIsNotValid);
return _createRule({
required: field.required,
message: message,
type: field.type,
trigger: field.trigger,
validator: (_, value: any) => {
if (field.validator(value)) {
return Promise.reject(message);
}
return Promise.resolve();
},
});
},
fieldMustBeStringOrArrayWithMaximumLength(field: IFieldLength) {
return [
_createLengthValidator(
field,
true,
ValidationEnum.FieldMustBeStringOrArrayWithMaximumLength,
ValidationEnum.ThisFieldMustBeAStringOrArrayTypeWithAMaximumLength,
),
];
},
fieldMustBeStringOrArrayWithMinimumLength(field: IFieldLength) {
return [
_createLengthValidator(
field,
false,
ValidationEnum.FieldMustBeStringOrArrayWithMinimumLength,
ValidationEnum.ThisFieldMustBeAStringOrArrayTypeWithAMinimumLength,
),
];
},
fieldMustBeStringWithMaximumLength(field: IFieldLength) {
return [
_createLengthValidator(
field,
true,
ValidationEnum.FieldMustBeStringWithMaximumLength,
ValidationEnum.ThisFieldMustBeAStringWithAMaximumLength,
),
];
},
fieldMustBeStringWithMinimumLengthAndMaximumLength(field: IFieldRange) {
return [
_createLengthRangValidator(
field,
ValidationEnum.FieldMustBeStringWithMinimumLengthAndMaximumLength,
ValidationEnum.ThisFieldMustBeAStringWithAMinimumLengthAndAMaximumLength,
),
];
},
fieldMustBeetWeen(field: IFieldBeetWeen) {
return [_createBeetWeenValidator(field)];
},
fieldMustMatchRegularExpression(field: IFieldRegular) {
return [_createRegularExpressionValidator(field)];
},
fieldDoNotValidCreditCardNumber(field: IField) {
if (field.name) {
return _createRule({
message: L(ValidationEnum.FieldDoNotValidCreditCardNumber, _getFieldName(field)),
type: field.type,
trigger: field.trigger,
});
}
return _createRule({
message: L(ValidationEnum.ThisFieldIsNotAValidCreditCardNumber),
type: field.type,
trigger: field.trigger,
});
},
fieldDoNotValidEmailAddress(field: IField) {
return [_createEmailValidator(field)];
},
fieldDoNotValidFullyQualifiedUrl(field: IField) {
if (field.name) {
return _createRule({
message: L(ValidationEnum.FieldDoNotValidFullyQualifiedUrl, _getFieldName(field)),
type: field.type,
trigger: field.trigger,
});
}
return _createRule({
message: L(ValidationEnum.ThisFieldIsNotAValidFullyQualifiedHttpHttpsOrFtpUrl),
type: field.type,
trigger: field.trigger,
});
},
fieldDoNotValidPhoneNumber(field: IField) {
return [_createPhoneValidator(field)];
},
fieldRequired(field: IField) {
return [
_createValidator(
field,
ValidationEnum.FieldRequired,
ValidationEnum.ThisFieldIsRequired,
true,
),
];
},
fieldOnlyAcceptsFilesExtensions(field: IFieldContains) {
const message = field.name
? L(ValidationEnum.FieldOnlyAcceptsFilesExtensions, _getFieldName(field), field.value)
: L(ValidationEnum.ThisFieldMustMatchTheRegularExpression, field.value);
return _createRule({
message: message,
type: field.type,
trigger: field.trigger,
validator: (_, value: string) => {
if (!field.value.includes(value)) {
return Promise.reject(message);
}
return Promise.resolve();
},
});
},
};
return {
ruleCreator,
};
} | the_stack |
import * as tf from '../../dist/tfjs.esm.js';
import * as fxImage from './imagefx';
import type { Tensor } from '../tfjs/types';
import type { Config } from '../config';
import { env } from '../util/env';
import { log, now } from '../util/util';
export type Input = Tensor | ImageData | ImageBitmap | HTMLImageElement | HTMLMediaElement | HTMLVideoElement | HTMLCanvasElement | OffscreenCanvas | typeof Image | typeof env.Canvas;
export type AnyCanvas = HTMLCanvasElement | OffscreenCanvas;
const maxSize = 2048;
// internal temp canvases
let inCanvas: AnyCanvas | null = null; // use global variable to avoid recreating canvas on each frame
let outCanvas: AnyCanvas | null = null; // use global variable to avoid recreating canvas on each frame
let tmpCanvas: AnyCanvas | null = null; // use global variable to avoid recreating canvas on each frame
// @ts-ignore // imagefx is js module that should be converted to a class
let fx: fxImage.GLImageFilter | null; // instance of imagefx
export function canvas(width, height): AnyCanvas {
let c;
if (env.browser) {
if (env.offscreen) {
c = new OffscreenCanvas(width, height);
} else {
if (typeof document === 'undefined') throw new Error('attempted to run in web worker but offscreenCanvas is not supported');
c = document.createElement('canvas');
c.width = width;
c.height = height;
}
} else {
// @ts-ignore // env.canvas is an external monkey-patch
if (typeof env.Canvas !== 'undefined') c = new env.Canvas(width, height);
else if (typeof globalThis.Canvas !== 'undefined') c = new globalThis.Canvas(width, height);
}
// if (!c) throw new Error('cannot create canvas');
return c;
}
export function copy(input: AnyCanvas, output?: AnyCanvas) {
const outputCanvas = output || canvas(input.width, input.height);
const ctx = outputCanvas.getContext('2d') as CanvasRenderingContext2D;
ctx.drawImage(input, 0, 0);
return outputCanvas;
}
// process input image and return tensor
// input can be tensor, imagedata, htmlimageelement, htmlvideoelement
// input is resized and run through imagefx filter
export function process(input: Input, config: Config, getTensor: boolean = true): { tensor: Tensor | null, canvas: AnyCanvas | null } {
if (!input) {
// throw new Error('input is missing');
if (config.debug) log('input is missing');
return { tensor: null, canvas: null }; // video may become temporarily unavailable due to onresize
}
// sanity checks since different browsers do not implement all dom elements
if (
!(input instanceof tf.Tensor)
&& !(typeof Image !== 'undefined' && input instanceof Image)
&& !(typeof env.Canvas !== 'undefined' && input instanceof env.Canvas)
&& !(typeof globalThis.Canvas !== 'undefined' && input instanceof globalThis.Canvas)
&& !(typeof ImageData !== 'undefined' && input instanceof ImageData)
&& !(typeof ImageBitmap !== 'undefined' && input instanceof ImageBitmap)
&& !(typeof HTMLImageElement !== 'undefined' && input instanceof HTMLImageElement)
&& !(typeof HTMLMediaElement !== 'undefined' && input instanceof HTMLMediaElement)
&& !(typeof HTMLVideoElement !== 'undefined' && input instanceof HTMLVideoElement)
&& !(typeof HTMLCanvasElement !== 'undefined' && input instanceof HTMLCanvasElement)
&& !(typeof OffscreenCanvas !== 'undefined' && input instanceof OffscreenCanvas)
) {
throw new Error('input type is not recognized');
}
if (input instanceof tf.Tensor) {
// if input is tensor, use as-is
if ((input)['isDisposedInternal']) {
throw new Error('input tensor is disposed');
} else if (!(input as Tensor).shape || (input as Tensor).shape.length !== 4 || (input as Tensor).shape[0] !== 1 || (input as Tensor).shape[3] !== 3) {
throw new Error(`input tensor shape must be [1, height, width, 3] and instead was ${input['shape']}`);
} else {
return { tensor: tf.clone(input), canvas: (config.filter.return ? outCanvas : null) };
}
} else {
// check if resizing will be needed
if (typeof input['readyState'] !== 'undefined' && input['readyState'] <= 2) {
if (config.debug) log('input stream is not ready');
return { tensor: null, canvas: inCanvas }; // video may become temporarily unavailable due to onresize
}
const originalWidth = input['naturalWidth'] || input['videoWidth'] || input['width'] || (input['shape'] && (input['shape'][1] > 0));
const originalHeight = input['naturalHeight'] || input['videoHeight'] || input['height'] || (input['shape'] && (input['shape'][2] > 0));
if (!originalWidth || !originalHeight) {
if (config.debug) log('cannot determine input dimensions');
return { tensor: null, canvas: inCanvas }; // video may become temporarily unavailable due to onresize
}
let targetWidth = originalWidth;
let targetHeight = originalHeight;
if (targetWidth > maxSize) {
targetWidth = maxSize;
targetHeight = Math.trunc(targetWidth * originalHeight / originalWidth);
}
if (targetHeight > maxSize) {
targetHeight = maxSize;
targetWidth = Math.trunc(targetHeight * originalWidth / originalHeight);
}
// create our canvas and resize it if needed
if ((config.filter.width || 0) > 0) targetWidth = config.filter.width;
else if ((config.filter.height || 0) > 0) targetWidth = originalWidth * ((config.filter.height || 0) / originalHeight);
if ((config.filter.height || 0) > 0) targetHeight = config.filter.height;
else if ((config.filter.width || 0) > 0) targetHeight = originalHeight * ((config.filter.width || 0) / originalWidth);
if (!targetWidth || !targetHeight) throw new Error('input cannot determine dimension');
if (!inCanvas || (inCanvas?.width !== targetWidth) || (inCanvas?.height !== targetHeight)) inCanvas = canvas(targetWidth, targetHeight);
// draw input to our canvas
const inCtx = inCanvas.getContext('2d') as CanvasRenderingContext2D;
if ((typeof ImageData !== 'undefined') && (input instanceof ImageData)) {
inCtx.putImageData(input, 0, 0);
} else {
if (config.filter.flip && typeof inCtx.translate !== 'undefined') {
inCtx.translate(originalWidth, 0);
inCtx.scale(-1, 1);
inCtx.drawImage(input as AnyCanvas, 0, 0, originalWidth, originalHeight, 0, 0, inCanvas?.width, inCanvas?.height);
inCtx.setTransform(1, 0, 0, 1, 0, 0); // resets transforms to defaults
} else {
inCtx.drawImage(input as AnyCanvas, 0, 0, originalWidth, originalHeight, 0, 0, inCanvas?.width, inCanvas?.height);
}
}
if (!outCanvas || (inCanvas.width !== outCanvas.width) || (inCanvas?.height !== outCanvas?.height)) outCanvas = canvas(inCanvas.width, inCanvas.height); // init output canvas
// imagefx transforms using gl from input canvas to output canvas
if (config.filter.enabled && env.webgl.supported) {
if (!fx) fx = env.browser ? new fxImage.GLImageFilter() : null; // && (typeof document !== 'undefined')
env.filter = !!fx;
if (!fx) return { tensor: null, canvas: inCanvas };
fx.reset();
if (config.filter.brightness !== 0) fx.add('brightness', config.filter.brightness);
if (config.filter.contrast !== 0) fx.add('contrast', config.filter.contrast);
if (config.filter.sharpness !== 0) fx.add('sharpen', config.filter.sharpness);
if (config.filter.blur !== 0) fx.add('blur', config.filter.blur);
if (config.filter.saturation !== 0) fx.add('saturation', config.filter.saturation);
if (config.filter.hue !== 0) fx.add('hue', config.filter.hue);
if (config.filter.negative) fx.add('negative');
if (config.filter.sepia) fx.add('sepia');
if (config.filter.vintage) fx.add('brownie');
if (config.filter.sepia) fx.add('sepia');
if (config.filter.kodachrome) fx.add('kodachrome');
if (config.filter.technicolor) fx.add('technicolor');
if (config.filter.polaroid) fx.add('polaroid');
if (config.filter.pixelate !== 0) fx.add('pixelate', config.filter.pixelate);
if (fx.get() > 0) outCanvas = fx.apply(inCanvas);
else outCanvas = fx.draw(inCanvas);
} else {
copy(inCanvas, outCanvas); // if no filters applied, output canvas is input canvas
if (fx) fx = null;
env.filter = !!fx;
}
if (!getTensor) return { tensor: null, canvas: outCanvas }; // just canvas was requested
if (!outCanvas) throw new Error('cannot create output canvas');
// create tensor from image unless input was a tensor already
let pixels;
let depth = 3;
if ((typeof ImageData !== 'undefined' && input instanceof ImageData) || (input['data'] && input['width'] && input['height'])) { // if input is imagedata, just use it
if (env.browser && tf.browser) {
pixels = tf.browser ? tf.browser.fromPixels(input) : null;
} else {
depth = input['data'].length / input['height'] / input['width'];
// const arr = Uint8Array.from(input['data']);
const arr = new Uint8Array(input['data']['buffer']);
pixels = tf.tensor(arr, [input['height'], input['width'], depth], 'int32');
}
} else {
if (!tmpCanvas || (outCanvas.width !== tmpCanvas.width) || (outCanvas?.height !== tmpCanvas?.height)) tmpCanvas = canvas(outCanvas.width, outCanvas.height); // init output canvas
if (tf.browser && env.browser) {
if (config.backend === 'webgl' || config.backend === 'humangl' || config.backend === 'webgpu') {
pixels = tf.browser.fromPixels(outCanvas); // safe to reuse since both backend and context are gl based
} else {
tmpCanvas = copy(outCanvas); // cannot use output canvas as it already has gl context so we do a silly one more canvas
pixels = tf.browser.fromPixels(tmpCanvas);
}
} else {
const tempCanvas = copy(outCanvas); // cannot use output canvas as it already has gl context so we do a silly one more canvas
const tempCtx = tempCanvas.getContext('2d') as CanvasRenderingContext2D;
const tempData = tempCtx.getImageData(0, 0, targetWidth, targetHeight);
depth = tempData.data.length / targetWidth / targetHeight;
const arr = new Uint8Array(tempData.data.buffer);
pixels = tf.tensor(arr, [targetWidth, targetHeight, depth]);
}
}
if (depth === 4) { // rgba to rgb
const rgb = tf.slice3d(pixels, [0, 0, 0], [-1, -1, 3]); // strip alpha channel
tf.dispose(pixels);
pixels = rgb;
/*
const channels = tf.split(pixels, 4, 2); // split rgba to channels
tf.dispose(pixels);
const rgb = tf.stack([channels[0], channels[1], channels[2]], 2); // stack channels back to rgb and ignore alpha
pixels = tf.reshape(rgb, [rgb.shape[0], rgb.shape[1], 3]); // move extra dim from the end of tensor and use it as batch number instead
tf.dispose([rgb, ...channels]);
*/
}
if (!pixels) throw new Error('cannot create tensor from input');
const casted = tf.cast(pixels, 'float32');
const tensor = tf.expandDims(casted, 0);
tf.dispose([pixels, casted]);
return { tensor, canvas: (config.filter.return ? outCanvas : null) };
}
}
let lastInputSum = 0;
let lastCacheDiff = 1;
let benchmarked = 0;
const checksum = async (input: Tensor): Promise<number> => { // use tf sum or js based sum loop depending on which is faster
const resizeFact = 48;
const reduced: Tensor = tf.image.resizeBilinear(input, [Math.trunc((input.shape[1] || 1) / resizeFact), Math.trunc((input.shape[2] || 1) / resizeFact)]);
const tfSum = async (): Promise<number> => {
const sumT = tf.sum(reduced);
const sum0 = await sumT.data();
tf.dispose(sumT);
return sum0[0];
};
const jsSum = async (): Promise<number> => {
const reducedData = await reduced.data(); // raw image rgb array
let sum0 = 0;
for (let i = 0; i < reducedData.length / 3; i++) sum0 += reducedData[3 * i + 2]; // look only at green value of each pixel
return sum0;
};
if (benchmarked === 0) {
const t0 = now();
await jsSum();
const t1 = now();
await tfSum();
const t2 = now();
benchmarked = t1 - t0 < t2 - t1 ? 1 : 2;
}
const res = benchmarked === 1 ? await jsSum() : await tfSum();
tf.dispose(reduced);
return res;
};
export async function skip(config, input: Tensor) {
if (config.cacheSensitivity === 0) return false;
const sum = await checksum(input);
const diff = 100 * (Math.max(sum, lastInputSum) / Math.min(sum, lastInputSum) - 1);
lastInputSum = sum;
// if previous frame was skipped, skip this frame if changed more than cacheSensitivity
// if previous frame was not skipped, then look for cacheSensitivity or difference larger than one in previous frame to avoid resetting cache in subsequent frames unnecessarily
let skipFrame = diff < Math.max(config.cacheSensitivity, lastCacheDiff);
// if difference is above 10x threshold, don't use last value to force reset cache for significant change of scenes or images
lastCacheDiff = diff > 10 * config.cacheSensitivity ? 0 : diff;
skipFrame = skipFrame && (lastCacheDiff > 0); // if no cached diff value then force no skip
return skipFrame;
} | the_stack |
import { GlobalProps } from 'ojs/ojvcomponent';
import { ComponentChildren } from 'preact';
import Color = require('../ojcolor');
import { editableValue, editableValueEventMap, editableValueSettableProperties } from '../ojeditablevalue';
import { JetElement, JetSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..';
export interface ojColorSpectrum extends editableValue<Color, ojColorSpectrumSettableProperties> {
displayOptions?: {
converterHint?: 'display' | 'none';
helpInstruction?: Array<'notewindow' | 'none'> | 'notewindow' | 'none';
messages?: 'display' | 'none';
validatorHint?: 'display' | 'none';
};
labelledBy: string | null;
readonly transientValue: Color;
value: Color;
translations: {
labelHue?: string;
labelOpacity?: string;
labelSatLum?: string;
labelThumbDesc?: string;
};
addEventListener<T extends keyof ojColorSpectrumEventMap>(type: T, listener: (this: HTMLElement, ev: ojColorSpectrumEventMap[T]) => any, options?: (boolean | AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojColorSpectrumSettableProperties>(property: T): ojColorSpectrum[T];
getProperty(property: string): any;
setProperty<T extends keyof ojColorSpectrumSettableProperties>(property: T, value: ojColorSpectrumSettableProperties[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojColorSpectrumSettableProperties>): void;
setProperties(properties: ojColorSpectrumSettablePropertiesLenient): void;
}
export namespace ojColorSpectrum {
interface ojAnimateEnd extends CustomEvent<{
action: string;
element: Element;
[propName: string]: any;
}> {
}
interface ojAnimateStart extends CustomEvent<{
action: string;
element: Element;
endCallback: (() => void);
[propName: string]: any;
}> {
}
// tslint:disable-next-line interface-over-type-literal
type displayOptionsChanged = JetElementCustomEvent<ojColorSpectrum["displayOptions"]>;
// tslint:disable-next-line interface-over-type-literal
type labelledByChanged = JetElementCustomEvent<ojColorSpectrum["labelledBy"]>;
// tslint:disable-next-line interface-over-type-literal
type transientValueChanged = JetElementCustomEvent<ojColorSpectrum["transientValue"]>;
// tslint:disable-next-line interface-over-type-literal
type valueChanged = JetElementCustomEvent<ojColorSpectrum["value"]>;
//------------------------------------------------------------
// Start: generated events for inherited properties
//------------------------------------------------------------
// tslint:disable-next-line interface-over-type-literal
type describedByChanged = editableValue.describedByChanged<Color, ojColorSpectrumSettableProperties>;
// tslint:disable-next-line interface-over-type-literal
type disabledChanged = editableValue.disabledChanged<Color, ojColorSpectrumSettableProperties>;
// tslint:disable-next-line interface-over-type-literal
type helpChanged = editableValue.helpChanged<Color, ojColorSpectrumSettableProperties>;
// tslint:disable-next-line interface-over-type-literal
type helpHintsChanged = editableValue.helpHintsChanged<Color, ojColorSpectrumSettableProperties>;
// tslint:disable-next-line interface-over-type-literal
type labelEdgeChanged = editableValue.labelEdgeChanged<Color, ojColorSpectrumSettableProperties>;
// tslint:disable-next-line interface-over-type-literal
type labelHintChanged = editableValue.labelHintChanged<Color, ojColorSpectrumSettableProperties>;
// tslint:disable-next-line interface-over-type-literal
type messagesCustomChanged = editableValue.messagesCustomChanged<Color, ojColorSpectrumSettableProperties>;
// tslint:disable-next-line interface-over-type-literal
type userAssistanceDensityChanged = editableValue.userAssistanceDensityChanged<Color, ojColorSpectrumSettableProperties>;
// tslint:disable-next-line interface-over-type-literal
type validChanged = editableValue.validChanged<Color, ojColorSpectrumSettableProperties>;
//------------------------------------------------------------
// End: generated events for inherited properties
//------------------------------------------------------------
}
export interface ojColorSpectrumEventMap extends editableValueEventMap<Color, ojColorSpectrumSettableProperties> {
'ojAnimateEnd': ojColorSpectrum.ojAnimateEnd;
'ojAnimateStart': ojColorSpectrum.ojAnimateStart;
'displayOptionsChanged': JetElementCustomEvent<ojColorSpectrum["displayOptions"]>;
'labelledByChanged': JetElementCustomEvent<ojColorSpectrum["labelledBy"]>;
'transientValueChanged': JetElementCustomEvent<ojColorSpectrum["transientValue"]>;
'valueChanged': JetElementCustomEvent<ojColorSpectrum["value"]>;
'describedByChanged': JetElementCustomEvent<ojColorSpectrum["describedBy"]>;
'disabledChanged': JetElementCustomEvent<ojColorSpectrum["disabled"]>;
'helpChanged': JetElementCustomEvent<ojColorSpectrum["help"]>;
'helpHintsChanged': JetElementCustomEvent<ojColorSpectrum["helpHints"]>;
'labelEdgeChanged': JetElementCustomEvent<ojColorSpectrum["labelEdge"]>;
'labelHintChanged': JetElementCustomEvent<ojColorSpectrum["labelHint"]>;
'messagesCustomChanged': JetElementCustomEvent<ojColorSpectrum["messagesCustom"]>;
'userAssistanceDensityChanged': JetElementCustomEvent<ojColorSpectrum["userAssistanceDensity"]>;
'validChanged': JetElementCustomEvent<ojColorSpectrum["valid"]>;
}
export interface ojColorSpectrumSettableProperties extends editableValueSettableProperties<Color> {
displayOptions?: {
converterHint?: 'display' | 'none';
helpInstruction?: Array<'notewindow' | 'none'> | 'notewindow' | 'none';
messages?: 'display' | 'none';
validatorHint?: 'display' | 'none';
};
labelledBy: string | null;
readonly transientValue: Color;
value: Color;
translations: {
labelHue?: string;
labelOpacity?: string;
labelSatLum?: string;
labelThumbDesc?: string;
};
}
export interface ojColorSpectrumSettablePropertiesLenient extends Partial<ojColorSpectrumSettableProperties> {
[key: string]: any;
}
export type ColorSpectrumElement = ojColorSpectrum;
export namespace ColorSpectrumElement {
interface ojAnimateEnd extends CustomEvent<{
action: string;
element: Element;
[propName: string]: any;
}> {
}
interface ojAnimateStart extends CustomEvent<{
action: string;
element: Element;
endCallback: (() => void);
[propName: string]: any;
}> {
}
// tslint:disable-next-line interface-over-type-literal
type displayOptionsChanged = JetElementCustomEvent<ojColorSpectrum["displayOptions"]>;
// tslint:disable-next-line interface-over-type-literal
type labelledByChanged = JetElementCustomEvent<ojColorSpectrum["labelledBy"]>;
// tslint:disable-next-line interface-over-type-literal
type transientValueChanged = JetElementCustomEvent<ojColorSpectrum["transientValue"]>;
// tslint:disable-next-line interface-over-type-literal
type valueChanged = JetElementCustomEvent<ojColorSpectrum["value"]>;
//------------------------------------------------------------
// Start: generated events for inherited properties
//------------------------------------------------------------
// tslint:disable-next-line interface-over-type-literal
type describedByChanged = editableValue.describedByChanged<Color, ojColorSpectrumSettableProperties>;
// tslint:disable-next-line interface-over-type-literal
type disabledChanged = editableValue.disabledChanged<Color, ojColorSpectrumSettableProperties>;
// tslint:disable-next-line interface-over-type-literal
type helpChanged = editableValue.helpChanged<Color, ojColorSpectrumSettableProperties>;
// tslint:disable-next-line interface-over-type-literal
type helpHintsChanged = editableValue.helpHintsChanged<Color, ojColorSpectrumSettableProperties>;
// tslint:disable-next-line interface-over-type-literal
type labelEdgeChanged = editableValue.labelEdgeChanged<Color, ojColorSpectrumSettableProperties>;
// tslint:disable-next-line interface-over-type-literal
type labelHintChanged = editableValue.labelHintChanged<Color, ojColorSpectrumSettableProperties>;
// tslint:disable-next-line interface-over-type-literal
type messagesCustomChanged = editableValue.messagesCustomChanged<Color, ojColorSpectrumSettableProperties>;
// tslint:disable-next-line interface-over-type-literal
type userAssistanceDensityChanged = editableValue.userAssistanceDensityChanged<Color, ojColorSpectrumSettableProperties>;
// tslint:disable-next-line interface-over-type-literal
type validChanged = editableValue.validChanged<Color, ojColorSpectrumSettableProperties>;
//------------------------------------------------------------
// End: generated events for inherited properties
//------------------------------------------------------------
}
export interface ColorSpectrumIntrinsicProps extends Partial<Readonly<ojColorSpectrumSettableProperties>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
onojAnimateEnd?: (value: ojColorSpectrumEventMap['ojAnimateEnd']) => void;
onojAnimateStart?: (value: ojColorSpectrumEventMap['ojAnimateStart']) => void;
ondisplayOptionsChanged?: (value: ojColorSpectrumEventMap['displayOptionsChanged']) => void;
onlabelledByChanged?: (value: ojColorSpectrumEventMap['labelledByChanged']) => void;
ontransientValueChanged?: (value: ojColorSpectrumEventMap['transientValueChanged']) => void;
onvalueChanged?: (value: ojColorSpectrumEventMap['valueChanged']) => void;
ondescribedByChanged?: (value: ojColorSpectrumEventMap['describedByChanged']) => void;
ondisabledChanged?: (value: ojColorSpectrumEventMap['disabledChanged']) => void;
onhelpChanged?: (value: ojColorSpectrumEventMap['helpChanged']) => void;
onhelpHintsChanged?: (value: ojColorSpectrumEventMap['helpHintsChanged']) => void;
onlabelEdgeChanged?: (value: ojColorSpectrumEventMap['labelEdgeChanged']) => void;
onlabelHintChanged?: (value: ojColorSpectrumEventMap['labelHintChanged']) => void;
onmessagesCustomChanged?: (value: ojColorSpectrumEventMap['messagesCustomChanged']) => void;
onuserAssistanceDensityChanged?: (value: ojColorSpectrumEventMap['userAssistanceDensityChanged']) => void;
onvalidChanged?: (value: ojColorSpectrumEventMap['validChanged']) => void;
children?: ComponentChildren;
}
declare global {
namespace preact.JSX {
interface IntrinsicElements {
"oj-color-spectrum": ColorSpectrumIntrinsicProps;
}
}
} | the_stack |
/* eslint-disable @typescript-eslint/class-name-casing */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-empty-interface */
/* eslint-disable @typescript-eslint/no-namespace */
/* eslint-disable no-irregular-whitespace */
import {
OAuth2Client,
JWT,
Compute,
UserRefreshClient,
BaseExternalAccountClient,
GaxiosPromise,
GoogleConfigurable,
createAPIRequest,
MethodOptions,
StreamMethodOptions,
GlobalOptions,
GoogleAuth,
BodyResponseCallback,
APIRequestContext,
} from 'googleapis-common';
import {Readable} from 'stream';
export namespace mybusinesslodging_v1 {
export interface Options extends GlobalOptions {
version: 'v1';
}
interface StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?:
| string
| OAuth2Client
| JWT
| Compute
| UserRefreshClient
| BaseExternalAccountClient
| GoogleAuth;
/**
* V1 error format.
*/
'$.xgafv'?: string;
/**
* OAuth access token.
*/
access_token?: string;
/**
* Data format for response.
*/
alt?: string;
/**
* JSONP
*/
callback?: string;
/**
* Selector specifying which fields to include in a partial response.
*/
fields?: string;
/**
* API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
*/
key?: string;
/**
* OAuth 2.0 token for the current user.
*/
oauth_token?: string;
/**
* Returns response with indentations and line breaks.
*/
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
*/
quotaUser?: string;
/**
* Legacy upload protocol for media (e.g. "media", "multipart").
*/
uploadType?: string;
/**
* Upload protocol for media (e.g. "raw", "multipart").
*/
upload_protocol?: string;
}
/**
* My Business Lodging API
*
* The My Business Lodging API enables managing lodging business information on Google.
*
* @example
* ```js
* const {google} = require('googleapis');
* const mybusinesslodging = google.mybusinesslodging('v1');
* ```
*/
export class Mybusinesslodging {
context: APIRequestContext;
locations: Resource$Locations;
constructor(options: GlobalOptions, google?: GoogleConfigurable) {
this.context = {
_options: options || {},
google,
};
this.locations = new Resource$Locations(this.context);
}
}
/**
* Physical adaptations made to the property in consideration of varying levels of human physical ability.
*/
export interface Schema$Accessibility {
/**
* Mobility accessible. Throughout the property there are physical adaptations to ease the stay of a person in a wheelchair, such as auto-opening doors, wide elevators, wide bathrooms or ramps.
*/
mobilityAccessible?: boolean | null;
/**
* Mobility accessible elevator. A lift that transports people from one level to another and is built to accommodate a wheelchair-using passenger owing to the width of its doors and placement of call buttons.
*/
mobilityAccessibleElevator?: boolean | null;
/**
* Mobility accessible elevator exception.
*/
mobilityAccessibleElevatorException?: string | null;
/**
* Mobility accessible exception.
*/
mobilityAccessibleException?: string | null;
/**
* Mobility accessible parking. The presence of a marked, designated area of prescribed size in which only registered, labeled vehicles transporting a person with physical challenges may park.
*/
mobilityAccessibleParking?: boolean | null;
/**
* Mobility accessible parking exception.
*/
mobilityAccessibleParkingException?: string | null;
/**
* Mobility accessible pool. A swimming pool equipped with a mechanical chair that can be lowered and raised for the purpose of moving physically challenged guests into and out of the pool. May be powered by electricity or water. Also known as pool lift.
*/
mobilityAccessiblePool?: boolean | null;
/**
* Mobility accessible pool exception.
*/
mobilityAccessiblePoolException?: string | null;
}
/**
* Amenities and features related to leisure and play.
*/
export interface Schema$Activities {
/**
* Beach access. The hotel property is in close proximity to a beach and offers a way to get to that beach. This can include a route to the beach such as stairs down if hotel is on a bluff, or a short trail. Not the same as beachfront (with beach access, the hotel's proximity is close to but not right on the beach).
*/
beachAccess?: boolean | null;
/**
* Beach access exception.
*/
beachAccessException?: string | null;
/**
* Breach front. The hotel property is physically located on the beach alongside an ocean, sea, gulf, or bay. It is not on a lake, river, stream, or pond. The hotel is not separated from the beach by a public road allowing vehicular, pedestrian, or bicycle traffic.
*/
beachFront?: boolean | null;
/**
* Beach front exception.
*/
beachFrontException?: string | null;
/**
* Bicycle rental. The hotel owns bicycles that it permits guests to borrow and use. Can be free or for a fee.
*/
bicycleRental?: boolean | null;
/**
* Bicycle rental exception.
*/
bicycleRentalException?: string | null;
/**
* Boutique stores. There are stores selling clothing, jewelry, art and decor either on hotel premises or very close by. Does not refer to the hotel gift shop or convenience store.
*/
boutiqueStores?: boolean | null;
/**
* Boutique stores exception.
*/
boutiqueStoresException?: string | null;
/**
* Casino. A space designated for gambling and gaming featuring croupier-run table and card games, as well as electronic slot machines. May be on hotel premises or located nearby.
*/
casino?: boolean | null;
/**
* Casino exception.
*/
casinoException?: string | null;
/**
* Free bicycle rental. The hotel owns bicycles that it permits guests to borrow and use for free.
*/
freeBicycleRental?: boolean | null;
/**
* Free bicycle rental exception.
*/
freeBicycleRentalException?: string | null;
/**
* Free watercraft rental. The hotel owns watercraft that it permits guests to borrow and use for free.
*/
freeWatercraftRental?: boolean | null;
/**
* Free Watercraft rental exception.
*/
freeWatercraftRentalException?: string | null;
/**
* Game room. There is a room at the hotel containing electronic machines for play such as pinball, prize machines, driving simulators, and other items commonly found at a family fun center or arcade. May also include non-electronic games like pool, foosball, darts, and more. May or may not be designed for children. Also known as arcade, fun room, or family fun center.
*/
gameRoom?: boolean | null;
/**
* Game room exception.
*/
gameRoomException?: string | null;
/**
* Golf. There is a golf course on hotel grounds or there is a nearby, independently run golf course that allows use by hotel guests. Can be free or for a fee.
*/
golf?: boolean | null;
/**
* Golf exception.
*/
golfException?: string | null;
/**
* Horseback riding. The hotel has a horse barn onsite or an affiliation with a nearby barn to allow for guests to sit astride a horse and direct it to walk, trot, cantor, gallop and/or jump. Can be in a riding ring, on designated paths, or in the wilderness. May or may not involve instruction.
*/
horsebackRiding?: boolean | null;
/**
* Horseback riding exception.
*/
horsebackRidingException?: string | null;
/**
* Nightclub. There is a room at the hotel with a bar, a dance floor, and seating where designated staffers play dance music. There may also be a designated area for the performance of live music, singing and comedy acts.
*/
nightclub?: boolean | null;
/**
* Nightclub exception.
*/
nightclubException?: string | null;
/**
* Private beach. The beach which is in close proximity to the hotel is open only to guests.
*/
privateBeach?: boolean | null;
/**
* Private beach exception.
*/
privateBeachException?: string | null;
/**
* Scuba. The provision for guests to dive under naturally occurring water fitted with a self-contained underwater breathing apparatus (SCUBA) for the purpose of exploring underwater life. Apparatus consists of a tank providing oxygen to the diver through a mask. Requires certification of the diver and supervision. The hotel may have the activity at its own waterfront or have an affiliation with a nearby facility. Required equipment is most often supplied to guests. Can be free or for a fee. Not snorkeling. Not done in a swimming pool.
*/
scuba?: boolean | null;
/**
* Scuba exception.
*/
scubaException?: string | null;
/**
* Snorkeling. The provision for guests to participate in a recreational water activity in which swimmers wear a diving mask, a simple, shaped breathing tube and flippers/swim fins for the purpose of exploring below the surface of an ocean, gulf or lake. Does not usually require user certification or professional supervision. Equipment may or may not be available for rent or purchase. Not scuba diving.
*/
snorkeling?: boolean | null;
/**
* Snorkeling exception.
*/
snorkelingException?: string | null;
/**
* Tennis. The hotel has the requisite court(s) on site or has an affiliation with a nearby facility for the purpose of providing guests with the opportunity to play a two-sided court-based game in which players use a stringed racquet to hit a ball across a net to the side of the opposing player. The court can be indoors or outdoors. Instructors, racquets and balls may or may not be provided.
*/
tennis?: boolean | null;
/**
* Tennis exception.
*/
tennisException?: string | null;
/**
* Watercraft rental. The hotel owns water vessels that it permits guests to borrow and use. Can be free or for a fee. Watercraft may include boats, pedal boats, rowboats, sailboats, powerboats, canoes, kayaks, or personal watercraft (such as a Jet Ski).
*/
watercraftRental?: boolean | null;
/**
* Watercraft rental exception.
*/
watercraftRentalException?: string | null;
/**
* Water skiing. The provision of giving guests the opportunity to be pulled across naturally occurring water while standing on skis and holding a tow rope attached to a motorboat. Can occur on hotel premises or at a nearby waterfront. Most often performed in a lake or ocean.
*/
waterSkiing?: boolean | null;
/**
* Water skiing exception.
*/
waterSkiingException?: string | null;
}
/**
* Features of the property of specific interest to the business traveler.
*/
export interface Schema$Business {
/**
* Business center. A designated room at the hotel with one or more desks and equipped with guest-use computers, printers, fax machines and/or photocopiers. May or may not be open 24/7. May or may not require a key to access. Not a meeting room or conference room.
*/
businessCenter?: boolean | null;
/**
* Business center exception.
*/
businessCenterException?: string | null;
/**
* Meeting rooms. Rooms at the hotel designated for business-related gatherings. Rooms are usually equipped with tables or desks, office chairs and audio/visual facilities to allow for presentations and conference calls. Also known as conference rooms.
*/
meetingRooms?: boolean | null;
/**
* Meeting rooms count. The number of meeting rooms at the property.
*/
meetingRoomsCount?: number | null;
/**
* Meeting rooms count exception.
*/
meetingRoomsCountException?: string | null;
/**
* Meeting rooms exception.
*/
meetingRoomsException?: string | null;
}
/**
* The ways in which the property provides guests with the ability to access the internet.
*/
export interface Schema$Connectivity {
/**
* Free wifi. The hotel offers guests wifi for free.
*/
freeWifi?: boolean | null;
/**
* Free wifi exception.
*/
freeWifiException?: string | null;
/**
* Public area wifi available. Guests have the ability to wirelessly connect to the internet in the areas of the hotel accessible to anyone. Can be free or for a fee.
*/
publicAreaWifiAvailable?: boolean | null;
/**
* Public area wifi available exception.
*/
publicAreaWifiAvailableException?: string | null;
/**
* Public internet terminal. An area of the hotel supplied with computers and designated for the purpose of providing guests with the ability to access the internet.
*/
publicInternetTerminal?: boolean | null;
/**
* Public internet terminal exception.
*/
publicInternetTerminalException?: string | null;
/**
* Wifi available. The hotel provides the ability for guests to wirelessly connect to the internet. Can be in the public areas of the hotel and/or in the guest rooms. Can be free or for a fee.
*/
wifiAvailable?: boolean | null;
/**
* Wifi available exception.
*/
wifiAvailableException?: string | null;
}
/**
* An eco certificate awarded to the hotel.
*/
export interface Schema$EcoCertification {
/**
* Whether the eco certificate was awarded or not.
*/
awarded?: boolean | null;
/**
* Awarded exception.
*/
awardedException?: string | null;
/**
* Required. The eco certificate.
*/
ecoCertificate?: string | null;
}
/**
* Energy efficiency practices implemented at the hotel.
*/
export interface Schema$EnergyEfficiency {
/**
* Carbon free energy sources. Property sources carbon-free electricity via at least one of the following methods: on-site clean energy generation, power purchase agreement(s) with clean energy generators, green power provided by electricity supplier, or purchases of Energy Attribute Certificates (such as Renewable Energy Certificates or Guarantees of Origin).
*/
carbonFreeEnergySources?: boolean | null;
/**
* Carbon free energy sources exception.
*/
carbonFreeEnergySourcesException?: string | null;
/**
* Energy conservation program. The property tracks corporate-level Scope 1 and 2 GHG emissions, and Scope 3 emissions if available. The property has a commitment to implement initiatives that reduce GHG emissions year over year. The property has shown an absolute reduction in emissions for at least 2 years. Emissions are either verfied by a third-party and/or published in external communications.
*/
energyConservationProgram?: boolean | null;
/**
* Energy conservation program exception.
*/
energyConservationProgramException?: string | null;
/**
* Energy efficient heating and cooling systems. The property doesn't use chlorofluorocarbon (CFC)-based refrigerants in heating, ventilating, and air-conditioning systems unless a third-party audit shows it's not economically feasible. The CFC-based refrigerants which are used should have a Global Warming Potential (GWP) ≤ 10. The property uses occupancy sensors on HVAC systems in back-of-house spaces, meeting rooms, and other low-traffic areas.
*/
energyEfficientHeatingAndCoolingSystems?: boolean | null;
/**
* Energy efficient heating and cooling systems exception.
*/
energyEfficientHeatingAndCoolingSystemsException?: string | null;
/**
* Energy efficient lighting. At least 75% of the property's lighting is energy efficient, using lighting that is more than 45 lumens per watt – typically LED or CFL lightbulbs.
*/
energyEfficientLighting?: boolean | null;
/**
* Energy efficient lighting exception.
*/
energyEfficientLightingException?: string | null;
/**
* Energy saving thermostats. The property installed energy-saving thermostats throughout the building to conserve energy when rooms or areas are not in use. Energy-saving thermostats are devices that control heating/cooling in the building by learning temperature preferences and automatically adjusting to energy-saving temperatures as the default. The thermostats are automatically set to a temperature between 68-78 degrees F (20-26 °C), depending on seasonality. In the winter, set the thermostat to 68°F (20°C) when the room is occupied, lowering room temperature when unoccupied. In the summer, set the thermostat to 78°F (26°C) when the room is occupied.
*/
energySavingThermostats?: boolean | null;
/**
* Energy saving thermostats exception.
*/
energySavingThermostatsException?: string | null;
/**
* Output only. Green building design. True if BREEAM-* or LEED-* certified.
*/
greenBuildingDesign?: boolean | null;
/**
* Output only. Green building design exception.
*/
greenBuildingDesignException?: string | null;
/**
* Independent organization audits energy use. The property conducts an energy audit at least every 5 years, the results of which are either verified by a third-party and/or published in external communications. An energy audit is a detailed assessment of the facility which provides recommendations to existing operations and procedures to improve energy efficiency, available incentives or rebates,and opportunities for improvements through renovations or upgrades. Examples of organizations that conduct credible third party audits include: Engie Impact, DNV GL (EU), Dexma, and local utility providers (they often provide energy and water audits).
*/
independentOrganizationAuditsEnergyUse?: boolean | null;
/**
* Independent organization audits energy use exception.
*/
independentOrganizationAuditsEnergyUseException?: string | null;
}
/**
* Enhanced cleaning measures implemented by the hotel during COVID-19.
*/
export interface Schema$EnhancedCleaning {
/**
* Commercial-grade disinfectant used to clean the property.
*/
commercialGradeDisinfectantCleaning?: boolean | null;
/**
* Commercial grade disinfectant cleaning exception.
*/
commercialGradeDisinfectantCleaningException?: string | null;
/**
* Enhanced cleaning of common areas.
*/
commonAreasEnhancedCleaning?: boolean | null;
/**
* Common areas enhanced cleaning exception.
*/
commonAreasEnhancedCleaningException?: string | null;
/**
* Employees trained in COVID-19 cleaning procedures.
*/
employeesTrainedCleaningProcedures?: boolean | null;
/**
* Employees trained cleaning procedures exception.
*/
employeesTrainedCleaningProceduresException?: string | null;
/**
* Employees trained in thorough hand-washing.
*/
employeesTrainedThoroughHandWashing?: boolean | null;
/**
* Employees trained thorough hand washing exception.
*/
employeesTrainedThoroughHandWashingException?: string | null;
/**
* Employees wear masks, face shields, and/or gloves.
*/
employeesWearProtectiveEquipment?: boolean | null;
/**
* Employees wear protective equipment exception.
*/
employeesWearProtectiveEquipmentException?: string | null;
/**
* Enhanced cleaning of guest rooms.
*/
guestRoomsEnhancedCleaning?: boolean | null;
/**
* Guest rooms enhanced cleaning exception.
*/
guestRoomsEnhancedCleaningException?: string | null;
}
/**
* Services and amenities for families and young guests.
*/
export interface Schema$Families {
/**
* Babysitting. Child care that is offered by hotel staffers or coordinated by hotel staffers with local child care professionals. Can be free or for a fee.
*/
babysitting?: boolean | null;
/**
* Babysitting exception.
*/
babysittingException?: string | null;
/**
* Kids activities. Recreational options such as sports, films, crafts and games designed for the enjoyment of children and offered at the hotel. May or may not be supervised. May or may not be at a designated time or place. Cab be free or for a fee.
*/
kidsActivities?: boolean | null;
/**
* Kids activities exception.
*/
kidsActivitiesException?: string | null;
/**
* Kids club. An organized program of group activities held at the hotel and designed for the enjoyment of children. Facilitated by hotel staff (or staff procured by the hotel) in an area(s) designated for the purpose of entertaining children without their parents. May include games, outings, water sports, team sports, arts and crafts, and films. Usually has set hours. Can be free or for a fee. Also known as Kids Camp or Kids program.
*/
kidsClub?: boolean | null;
/**
* Kids club exception.
*/
kidsClubException?: string | null;
}
/**
* Meals, snacks, and beverages available at the property.
*/
export interface Schema$FoodAndDrink {
/**
* Bar. A designated room, lounge or area of an on-site restaurant with seating at a counter behind which a hotel staffer takes the guest's order and provides the requested alcoholic drink. Can be indoors or outdoors. Also known as Pub.
*/
bar?: boolean | null;
/**
* Bar exception.
*/
barException?: string | null;
/**
* Breakfast available. The morning meal is offered to all guests. Can be free or for a fee.
*/
breakfastAvailable?: boolean | null;
/**
* Breakfast available exception.
*/
breakfastAvailableException?: string | null;
/**
* Breakfast buffet. Breakfast meal service where guests serve themselves from a variety of dishes/foods that are put out on a table.
*/
breakfastBuffet?: boolean | null;
/**
* Breakfast buffet exception.
*/
breakfastBuffetException?: string | null;
/**
* Buffet. A type of meal where guests serve themselves from a variety of dishes/foods that are put out on a table. Includes lunch and/or dinner meals. A breakfast-only buffet is not sufficient.
*/
buffet?: boolean | null;
/**
* Buffet exception.
*/
buffetException?: string | null;
/**
* Dinner buffet. Dinner meal service where guests serve themselves from a variety of dishes/foods that are put out on a table.
*/
dinnerBuffet?: boolean | null;
/**
* Dinner buffet exception.
*/
dinnerBuffetException?: string | null;
/**
* Free breakfast. Breakfast is offered for free to all guests. Does not apply if limited to certain room packages.
*/
freeBreakfast?: boolean | null;
/**
* Free breakfast exception.
*/
freeBreakfastException?: string | null;
/**
* Restaurant. A business onsite at the hotel that is open to the public as well as guests, and offers meals and beverages to consume at tables or counters. May or may not include table service. Also known as cafe, buffet, eatery. A "breakfast room" where the hotel serves breakfast only to guests (not the general public) does not count as a restaurant.
*/
restaurant?: boolean | null;
/**
* Restaurant exception.
*/
restaurantException?: string | null;
/**
* Restaurants count. The number of restaurants at the hotel.
*/
restaurantsCount?: number | null;
/**
* Restaurants count exception.
*/
restaurantsCountException?: string | null;
/**
* Room service. A hotel staffer delivers meals prepared onsite to a guest's room as per their request. May or may not be available during specific hours. Services should be available to all guests (not based on rate/room booked/reward program, etc).
*/
roomService?: boolean | null;
/**
* Room service exception.
*/
roomServiceException?: string | null;
/**
* Table service. A restaurant in which a staff member is assigned to a guest's table to take their order, deliver and clear away food, and deliver the bill, if applicable. Also known as sit-down restaurant.
*/
tableService?: boolean | null;
/**
* Table service exception.
*/
tableServiceException?: string | null;
/**
* 24hr room service. Room service is available 24 hours a day.
*/
twentyFourHourRoomService?: boolean | null;
/**
* 24hr room service exception.
*/
twentyFourHourRoomServiceException?: string | null;
/**
* Vending machine. A glass-fronted mechanized cabinet displaying and dispensing snacks and beverages for purchase by coins, paper money and/or credit cards.
*/
vendingMachine?: boolean | null;
/**
* Vending machine exception.
*/
vendingMachineException?: string | null;
}
/**
* Response message for LodgingService.GetGoogleUpdatedLodging
*/
export interface Schema$GetGoogleUpdatedLodgingResponse {
/**
* Required. The fields in the Lodging that have been updated by Google. Repeated field items are not individually specified.
*/
diffMask?: string | null;
/**
* Required. The Google updated Lodging.
*/
lodging?: Schema$Lodging;
}
/**
* Features and available amenities in the guest unit.
*/
export interface Schema$GuestUnitFeatures {
/**
* Bungalow or villa. An independent structure that is part of a hotel or resort that is rented to one party for a vacation stay. The hotel or resort may be completely comprised of bungalows or villas, or they may be one of several guestroom options. Guests in the bungalows or villas most often have the same, if not more, amenities and services offered to guests in other guestroom types.
*/
bungalowOrVilla?: boolean | null;
/**
* Bungalow or villa exception.
*/
bungalowOrVillaException?: string | null;
/**
* Connecting unit available. A guestroom type that features access to an adjacent guestroom for the purpose of booking both rooms. Most often used by families who need more than one room to accommodate the number of people in their group.
*/
connectingUnitAvailable?: boolean | null;
/**
* Connecting unit available exception.
*/
connectingUnitAvailableException?: string | null;
/**
* Executive floor. A floor of the hotel where the guestrooms are only bookable by members of the hotel's frequent guest membership program. Benefits of this room class include access to a designated lounge which may or may not feature free breakfast, cocktails or other perks specific to members of the program.
*/
executiveFloor?: boolean | null;
/**
* Executive floor exception.
*/
executiveFloorException?: string | null;
/**
* Max adult occupants count. The total number of adult guests allowed to stay overnight in the guestroom.
*/
maxAdultOccupantsCount?: number | null;
/**
* Max adult occupants count exception.
*/
maxAdultOccupantsCountException?: string | null;
/**
* Max child occupants count. The total number of children allowed to stay overnight in the room.
*/
maxChildOccupantsCount?: number | null;
/**
* Max child occupants count exception.
*/
maxChildOccupantsCountException?: string | null;
/**
* Max occupants count. The total number of guests allowed to stay overnight in the guestroom.
*/
maxOccupantsCount?: number | null;
/**
* Max occupants count exception.
*/
maxOccupantsCountException?: string | null;
/**
* Private home. A privately owned home (house, townhouse, apartment, cabin, bungalow etc) that may or not serve as the owner's residence, but is rented out in its entirety or by the room(s) to paying guest(s) for vacation stays. Not for lease-based, long-term residency.
*/
privateHome?: boolean | null;
/**
* Private home exception.
*/
privateHomeException?: string | null;
/**
* Suite. A guestroom category that implies both a bedroom area and a separate living area. There may or may not be full walls and doors separating the two areas, but regardless, they are very distinct. Does not mean a couch or chair in a bedroom.
*/
suite?: boolean | null;
/**
* Suite exception.
*/
suiteException?: string | null;
/**
* Tier. Classification of the unit based on available features/amenities. A non-standard tier is only permitted if at least one other unit type falls under the standard tier.
*/
tier?: string | null;
/**
* Tier exception.
*/
tierException?: string | null;
/**
* Features available in the living areas in the guest unit.
*/
totalLivingAreas?: Schema$LivingArea;
/**
* Views available from the guest unit itself.
*/
views?: Schema$ViewsFromUnit;
}
/**
* A specific type of unit primarily defined by its features.
*/
export interface Schema$GuestUnitType {
/**
* Required. Unit or room code identifiers for a single GuestUnitType. Each code must be unique within a Lodging instance.
*/
codes?: string[] | null;
/**
* Features and available amenities of the GuestUnitType.
*/
features?: Schema$GuestUnitFeatures;
/**
* Required. Short, English label or name of the GuestUnitType. Target <50 chars.
*/
label?: string | null;
}
/**
* Health and safety measures implemented by the hotel during COVID-19.
*/
export interface Schema$HealthAndSafety {
/**
* Enhanced cleaning measures implemented by the hotel during COVID-19.
*/
enhancedCleaning?: Schema$EnhancedCleaning;
/**
* Increased food safety measures implemented by the hotel during COVID-19.
*/
increasedFoodSafety?: Schema$IncreasedFoodSafety;
/**
* Minimized contact measures implemented by the hotel during COVID-19.
*/
minimizedContact?: Schema$MinimizedContact;
/**
* Personal protection measures implemented by the hotel during COVID-19.
*/
personalProtection?: Schema$PersonalProtection;
/**
* Physical distancing measures implemented by the hotel during COVID-19.
*/
physicalDistancing?: Schema$PhysicalDistancing;
}
/**
* Conveniences provided in guest units to facilitate an easier, more comfortable stay.
*/
export interface Schema$Housekeeping {
/**
* Daily housekeeping. Guest units are cleaned by hotel staff daily during guest's stay.
*/
dailyHousekeeping?: boolean | null;
/**
* Daily housekeeping exception.
*/
dailyHousekeepingException?: string | null;
/**
* Housekeeping available. Guest units are cleaned by hotel staff during guest's stay. Schedule may vary from daily, weekly, or specific days of the week.
*/
housekeepingAvailable?: boolean | null;
/**
* Housekeeping available exception.
*/
housekeepingAvailableException?: string | null;
/**
* Turndown service. Hotel staff enters guest units to prepare the bed for sleep use. May or may not include some light housekeeping. May or may not include an evening snack or candy. Also known as evening service.
*/
turndownService?: boolean | null;
/**
* Turndown service exception.
*/
turndownServiceException?: string | null;
}
/**
* Increased food safety measures implemented by the hotel during COVID-19.
*/
export interface Schema$IncreasedFoodSafety {
/**
* Additional sanitation in dining areas.
*/
diningAreasAdditionalSanitation?: boolean | null;
/**
* Dining areas additional sanitation exception.
*/
diningAreasAdditionalSanitationException?: string | null;
/**
* Disposable flatware.
*/
disposableFlatware?: boolean | null;
/**
* Disposable flatware exception.
*/
disposableFlatwareException?: string | null;
/**
* Additional safety measures during food prep and serving.
*/
foodPreparationAndServingAdditionalSafety?: boolean | null;
/**
* Food preparation and serving additional safety exception.
*/
foodPreparationAndServingAdditionalSafetyException?: string | null;
/**
* Individually-packaged meals.
*/
individualPackagedMeals?: boolean | null;
/**
* Individual packaged meals exception.
*/
individualPackagedMealsException?: string | null;
/**
* Single-use menus.
*/
singleUseFoodMenus?: boolean | null;
/**
* Single use food menus exception.
*/
singleUseFoodMenusException?: string | null;
}
/**
* Language spoken by at least one staff member.
*/
export interface Schema$LanguageSpoken {
/**
* Required. The BCP-47 language code for the spoken language. Currently accepted codes: ar, de, en, es, fil, fr, hi, id, it, ja, ko, nl, pt, ru, vi, yue, zh.
*/
languageCode?: string | null;
/**
* At least one member of the staff can speak the language.
*/
spoken?: boolean | null;
/**
* Spoken exception.
*/
spokenException?: string | null;
}
/**
* An individual room, such as kitchen, bathroom, bedroom, within a bookable guest unit.
*/
export interface Schema$LivingArea {
/**
* Accessibility features of the living area.
*/
accessibility?: Schema$LivingAreaAccessibility;
/**
* Information about eating features in the living area.
*/
eating?: Schema$LivingAreaEating;
/**
* Features in the living area.
*/
features?: Schema$LivingAreaFeatures;
/**
* Information about the layout of the living area.
*/
layout?: Schema$LivingAreaLayout;
/**
* Information about sleeping features in the living area.
*/
sleeping?: Schema$LivingAreaSleeping;
}
/**
* Accessibility features of the living area.
*/
export interface Schema$LivingAreaAccessibility {
/**
* ADA compliant unit. A guestroom designed to accommodate the physical challenges of a guest with mobility and/or auditory and/or visual issues, as determined by legislative policy. Usually features enlarged doorways, roll-in showers with seats, bathroom grab bars, and communication equipment for the hearing and sight challenged.
*/
adaCompliantUnit?: boolean | null;
/**
* ADA compliant unit exception.
*/
adaCompliantUnitException?: string | null;
/**
* Hearing-accessible doorbell. A visual indicator(s) of a knock or ring at the door.
*/
hearingAccessibleDoorbell?: boolean | null;
/**
* Hearing-accessible doorbell exception.
*/
hearingAccessibleDoorbellException?: string | null;
/**
* Hearing-accessible fire alarm. A device that gives warning of a fire through flashing lights.
*/
hearingAccessibleFireAlarm?: boolean | null;
/**
* Hearing-accessible fire alarm exception.
*/
hearingAccessibleFireAlarmException?: string | null;
/**
* Hearing-accessible unit. A guestroom designed to accommodate the physical challenges of a guest with auditory issues.
*/
hearingAccessibleUnit?: boolean | null;
/**
* Hearing-accessible unit exception.
*/
hearingAccessibleUnitException?: string | null;
/**
* Mobility-accessible bathtub. A bathtub that accomodates the physically challenged with additional railings or hand grips, a transfer seat or lift, and/or a door to enable walking into the tub.
*/
mobilityAccessibleBathtub?: boolean | null;
/**
* Mobility-accessible bathtub exception.
*/
mobilityAccessibleBathtubException?: string | null;
/**
* Mobility-accessible shower. A shower with an enlarged door or access point to accommodate a wheelchair or a waterproof seat for the physically challenged.
*/
mobilityAccessibleShower?: boolean | null;
/**
* Mobility-accessible shower exception.
*/
mobilityAccessibleShowerException?: string | null;
/**
* Mobility-accessible toilet. A toilet with a higher seat, grab bars, and/or a larger area around it to accommodate the physically challenged.
*/
mobilityAccessibleToilet?: boolean | null;
/**
* Mobility-accessible toilet exception.
*/
mobilityAccessibleToiletException?: string | null;
/**
* Mobility-accessible unit. A guestroom designed to accommodate the physical challenges of a guest with mobility and/or auditory and/or visual issues. Usually features enlarged doorways, roll-in showers with seats, bathroom grab bars, and communication equipment for the hearing and sight challenged.
*/
mobilityAccessibleUnit?: boolean | null;
/**
* Mobility-accessible unit exception.
*/
mobilityAccessibleUnitException?: string | null;
}
/**
* Information about eating features in the living area.
*/
export interface Schema$LivingAreaEating {
/**
* Coffee maker. An electric appliance that brews coffee by heating and forcing water through ground coffee.
*/
coffeeMaker?: boolean | null;
/**
* Coffee maker exception.
*/
coffeeMakerException?: string | null;
/**
* Cookware. Kitchen pots, pans and utensils used in connection with the preparation of food.
*/
cookware?: boolean | null;
/**
* Cookware exception.
*/
cookwareException?: string | null;
/**
* Dishwasher. A counter-height electrical cabinet containing racks for dirty dishware, cookware and cutlery, and a dispenser for soap built into the pull-down door. The cabinet is attached to the plumbing system to facilitate the automatic cleaning of its contents.
*/
dishwasher?: boolean | null;
/**
* Dishwasher exception.
*/
dishwasherException?: string | null;
/**
* Indoor grill. Metal grates built into an indoor cooktop on which food is cooked over an open flame or electric heat source.
*/
indoorGrill?: boolean | null;
/**
* Indoor grill exception.
*/
indoorGrillException?: string | null;
/**
* Kettle. A covered container with a handle and a spout used for boiling water.
*/
kettle?: boolean | null;
/**
* Kettle exception.
*/
kettleException?: string | null;
/**
* Kitchen available. An area of the guestroom designated for the preparation and storage of food via the presence of a refrigerator, cook top, oven and sink, as well as cutlery, dishes and cookware. Usually includes small appliances such a coffee maker and a microwave. May or may not include an automatic dishwasher.
*/
kitchenAvailable?: boolean | null;
/**
* Kitchen available exception.
*/
kitchenAvailableException?: string | null;
/**
* Microwave. An electric oven that quickly cooks and heats food by microwave energy. Smaller than a standing or wall mounted oven. Usually placed on a kitchen counter, a shelf or tabletop or mounted above a cooktop.
*/
microwave?: boolean | null;
/**
* Microwave exception.
*/
microwaveException?: string | null;
/**
* Minibar. A small refrigerated cabinet in the guestroom containing bottles/cans of soft drinks, mini bottles of alcohol, and snacks. The items are most commonly available for a fee.
*/
minibar?: boolean | null;
/**
* Minibar exception.
*/
minibarException?: string | null;
/**
* Outdoor grill. Metal grates on which food is cooked over an open flame or electric heat source. Part of an outdoor apparatus that supports the grates. Also known as barbecue grill or barbecue.
*/
outdoorGrill?: boolean | null;
/**
* Outdoor grill exception.
*/
outdoorGrillException?: string | null;
/**
* Oven. A temperature controlled, heated metal cabinet powered by gas or electricity in which food is placed for the purpose of cooking or reheating.
*/
oven?: boolean | null;
/**
* Oven exception.
*/
ovenException?: string | null;
/**
* Refrigerator. A large, climate-controlled electrical cabinet with vertical doors. Built for the purpose of chilling and storing perishable foods.
*/
refrigerator?: boolean | null;
/**
* Refrigerator exception.
*/
refrigeratorException?: string | null;
/**
* Sink. A basin with a faucet attached to a water source and used for the purpose of washing and rinsing.
*/
sink?: boolean | null;
/**
* Sink exception.
*/
sinkException?: string | null;
/**
* Snackbar. A small cabinet in the guestroom containing snacks. The items are most commonly available for a fee.
*/
snackbar?: boolean | null;
/**
* Snackbar exception.
*/
snackbarException?: string | null;
/**
* Stove. A kitchen appliance powered by gas or electricity for the purpose of creating a flame or hot surface on which pots of food can be cooked. Also known as cooktop or hob.
*/
stove?: boolean | null;
/**
* Stove exception.
*/
stoveException?: string | null;
/**
* Tea station. A small area with the supplies needed to heat water and make tea.
*/
teaStation?: boolean | null;
/**
* Tea station exception.
*/
teaStationException?: string | null;
/**
* Toaster. A small, temperature controlled electric appliance with rectangular slots at the top that are lined with heated coils for the purpose of browning slices of bread products.
*/
toaster?: boolean | null;
/**
* Toaster exception.
*/
toasterException?: string | null;
}
/**
* Features in the living area.
*/
export interface Schema$LivingAreaFeatures {
/**
* Air conditioning. An electrical machine used to cool the temperature of the guestroom.
*/
airConditioning?: boolean | null;
/**
* Air conditioning exception.
*/
airConditioningException?: string | null;
/**
* Bathtub. A fixed plumbing feature set on the floor and consisting of a large container that accommodates the body of an adult for the purpose of seated bathing. Includes knobs or fixtures to control the temperature of the water, a faucet through which the water flows, and a drain that can be closed for filling and opened for draining.
*/
bathtub?: boolean | null;
/**
* Bathtub exception.
*/
bathtubException?: string | null;
/**
* Bidet. A plumbing fixture attached to a toilet or a low, fixed sink designed for the purpose of washing after toilet use.
*/
bidet?: boolean | null;
/**
* Bidet exception.
*/
bidetException?: string | null;
/**
* Dryer. An electrical machine designed to dry clothing.
*/
dryer?: boolean | null;
/**
* Dryer exception.
*/
dryerException?: string | null;
/**
* Electronic room key. A card coded by the check-in computer that is read by the lock on the hotel guestroom door to allow for entry.
*/
electronicRoomKey?: boolean | null;
/**
* Electronic room key exception.
*/
electronicRoomKeyException?: string | null;
/**
* Fireplace. A framed opening (aka hearth) at the base of a chimney in which logs or an electrical fire feature are burned to provide a relaxing ambiance or to heat the room. Often made of bricks or stone.
*/
fireplace?: boolean | null;
/**
* Fireplace exception.
*/
fireplaceException?: string | null;
/**
* Hairdryer. A handheld electric appliance that blows temperature-controlled air for the purpose of drying wet hair. Can be mounted to a bathroom wall or a freestanding device stored in the guestroom's bathroom or closet.
*/
hairdryer?: boolean | null;
/**
* Hairdryer exception.
*/
hairdryerException?: string | null;
/**
* Heating. An electrical machine used to warm the temperature of the guestroom.
*/
heating?: boolean | null;
/**
* Heating exception.
*/
heatingException?: string | null;
/**
* In-unit safe. A strong fireproof cabinet with a programmable lock, used for the protected storage of valuables in a guestroom. Often built into a closet.
*/
inunitSafe?: boolean | null;
/**
* In-unit safe exception.
*/
inunitSafeException?: string | null;
/**
* In-unit Wifi available. Guests can wirelessly connect to the Internet in the guestroom. Can be free or for a fee.
*/
inunitWifiAvailable?: boolean | null;
/**
* In-unit Wifi available exception.
*/
inunitWifiAvailableException?: string | null;
/**
* Ironing equipment. A device, usually with a flat metal base, that is heated to smooth, finish, or press clothes and a flat, padded, cloth-covered surface on which the clothes are worked.
*/
ironingEquipment?: boolean | null;
/**
* Ironing equipment exception.
*/
ironingEquipmentException?: string | null;
/**
* Pay per view movies. Televisions with channels that offer films that can be viewed for a fee, and have an interface to allow the viewer to accept the terms and approve payment.
*/
payPerViewMovies?: boolean | null;
/**
* Pay per view movies exception.
*/
payPerViewMoviesException?: string | null;
/**
* Private bathroom. A bathroom designated for the express use of the guests staying in a specific guestroom.
*/
privateBathroom?: boolean | null;
/**
* Private bathroom exception.
*/
privateBathroomException?: string | null;
/**
* Shower. A fixed plumbing fixture for standing bathing that features a tall spray spout or faucet through which water flows, a knob or knobs that control the water's temperature, and a drain in the floor.
*/
shower?: boolean | null;
/**
* Shower exception.
*/
showerException?: string | null;
/**
* Toilet. A fixed bathroom feature connected to a sewer or septic system and consisting of a water-flushed bowl with a seat, as well as a device that elicites the water-flushing action. Used for the process and disposal of human waste.
*/
toilet?: boolean | null;
/**
* Toilet exception.
*/
toiletException?: string | null;
/**
* TV. A television is available in the guestroom.
*/
tv?: boolean | null;
/**
* TV casting. A television equipped with a device through which the video entertainment accessed on a personal computer, phone or tablet can be wirelessly delivered to and viewed on the guestroom's television.
*/
tvCasting?: boolean | null;
/**
* TV exception.
*/
tvCastingException?: string | null;
/**
* TV exception.
*/
tvException?: string | null;
/**
* TV streaming. Televisions that embed a range of web-based apps to allow for watching media from those apps.
*/
tvStreaming?: boolean | null;
/**
* TV streaming exception.
*/
tvStreamingException?: string | null;
/**
* Universal power adapters. A power supply for electronic devices which plugs into a wall for the purpose of converting AC to a single DC voltage. Also know as AC adapter or charger.
*/
universalPowerAdapters?: boolean | null;
/**
* Universal power adapters exception.
*/
universalPowerAdaptersException?: string | null;
/**
* Washer. An electrical machine connected to a running water source designed to launder clothing.
*/
washer?: boolean | null;
/**
* Washer exception.
*/
washerException?: string | null;
}
/**
* Information about the layout of the living area.
*/
export interface Schema$LivingAreaLayout {
/**
* Balcony. An outdoor platform attached to a building and surrounded by a short wall, fence or other safety railing. The balcony is accessed through a door in a guestroom or suite and is for use by the guest staying in that room. May or may not include seating or outdoor furniture. Is not located on the ground floor. Also lanai.
*/
balcony?: boolean | null;
/**
* Balcony exception.
*/
balconyException?: string | null;
/**
* Living area sq meters. The measurement in meters of the area of a guestroom's living space.
*/
livingAreaSqMeters?: number | null;
/**
* Living area sq meters exception.
*/
livingAreaSqMetersException?: string | null;
/**
* Loft. A three-walled upper area accessed by stairs or a ladder that overlooks the lower area of a room.
*/
loft?: boolean | null;
/**
* Loft exception.
*/
loftException?: string | null;
/**
* Non smoking. A guestroom in which the smoking of cigarettes, cigars and pipes is prohibited.
*/
nonSmoking?: boolean | null;
/**
* Non smoking exception.
*/
nonSmokingException?: string | null;
/**
* Patio. A paved, outdoor area with seating attached to and accessed through a ground-floor guestroom for use by the occupants of the guestroom.
*/
patio?: boolean | null;
/**
* Patio exception.
*/
patioException?: string | null;
/**
* Stairs. There are steps leading from one level or story to another in the unit.
*/
stairs?: boolean | null;
/**
* Stairs exception.
*/
stairsException?: string | null;
}
/**
* Information about sleeping features in the living area.
*/
export interface Schema$LivingAreaSleeping {
/**
* Beds count. The number of permanent beds present in a guestroom. Does not include rollaway beds, cribs or sofabeds.
*/
bedsCount?: number | null;
/**
* Beds count exception.
*/
bedsCountException?: string | null;
/**
* Bunk beds count. The number of furniture pieces in which one framed mattress is fixed directly above another by means of a physical frame. This allows one person(s) to sleep in the bottom bunk and one person(s) to sleep in the top bunk. Also known as double decker bed.
*/
bunkBedsCount?: number | null;
/**
* Bunk beds count exception.
*/
bunkBedsCountException?: string | null;
/**
* Cribs count. The number of small beds for an infant or toddler that the guestroom can obtain. The bed is surrounded by a high railing to prevent the child from falling or climbing out of the bed
*/
cribsCount?: number | null;
/**
* Cribs count exception.
*/
cribsCountException?: string | null;
/**
* Double beds count. The number of medium beds measuring 53"W x 75"L (135cm x 191cm). Also known as full size bed.
*/
doubleBedsCount?: number | null;
/**
* Double beds count exception.
*/
doubleBedsCountException?: string | null;
/**
* Feather pillows. The option for guests to obtain bed pillows that are stuffed with the feathers and down of ducks or geese.
*/
featherPillows?: boolean | null;
/**
* Feather pillows exception.
*/
featherPillowsException?: string | null;
/**
* Hypoallergenic bedding. Bedding such as linens, pillows, mattress covers and/or mattresses that are made of materials known to be resistant to allergens such as mold, dust and dander.
*/
hypoallergenicBedding?: boolean | null;
/**
* Hypoallergenic bedding exception.
*/
hypoallergenicBeddingException?: string | null;
/**
* King beds count. The number of large beds measuring 76"W x 80"L (193cm x 102cm). Most often meant to accompany two people. Includes California king and super king.
*/
kingBedsCount?: number | null;
/**
* King beds count exception.
*/
kingBedsCountException?: string | null;
/**
* Memory foam pillows. The option for guests to obtain bed pillows that are stuffed with a man-made foam that responds to body heat by conforming to the body closely, and then recovers its shape when the pillow cools down.
*/
memoryFoamPillows?: boolean | null;
/**
* Memory foam pillows exception.
*/
memoryFoamPillowsException?: string | null;
/**
* Other beds count. The number of beds that are not standard mattress and boxspring setups such as Japanese tatami mats, trundle beds, air mattresses and cots.
*/
otherBedsCount?: number | null;
/**
* Other beds count exception.
*/
otherBedsCountException?: string | null;
/**
* Queen beds count. The number of medium-large beds measuring 60"W x 80"L (152cm x 102cm).
*/
queenBedsCount?: number | null;
/**
* Queen beds count exception.
*/
queenBedsCountException?: string | null;
/**
* Roll away beds count. The number of mattresses on wheeled frames that can be folded in half and rolled away for easy storage that the guestroom can obtain upon request.
*/
rollAwayBedsCount?: number | null;
/**
* Roll away beds count exception.
*/
rollAwayBedsCountException?: string | null;
/**
* Single or twin count beds. The number of smaller beds measuring 38"W x 75"L (97cm x 191cm) that can accommodate one adult.
*/
singleOrTwinBedsCount?: number | null;
/**
* Single or twin beds count exception.
*/
singleOrTwinBedsCountException?: string | null;
/**
* Sofa beds count. The number of specially designed sofas that can be made to serve as a bed by lowering its hinged upholstered back to horizontal position or by pulling out a concealed mattress.
*/
sofaBedsCount?: number | null;
/**
* Sofa beds count exception.
*/
sofaBedsCountException?: string | null;
/**
* Synthetic pillows. The option for guests to obtain bed pillows stuffed with polyester material crafted to reproduce the feel of a pillow stuffed with down and feathers.
*/
syntheticPillows?: boolean | null;
/**
* Synthetic pillows exception.
*/
syntheticPillowsException?: string | null;
}
/**
* Lodging of a location that provides accomodations.
*/
export interface Schema$Lodging {
/**
* Physical adaptations made to the property in consideration of varying levels of human physical ability.
*/
accessibility?: Schema$Accessibility;
/**
* Amenities and features related to leisure and play.
*/
activities?: Schema$Activities;
/**
* Output only. All units on the property have at least these attributes.
*/
allUnits?: Schema$GuestUnitFeatures;
/**
* Features of the property of specific interest to the business traveler.
*/
business?: Schema$Business;
/**
* Features of the shared living areas available in this Lodging.
*/
commonLivingArea?: Schema$LivingArea;
/**
* The ways in which the property provides guests with the ability to access the internet.
*/
connectivity?: Schema$Connectivity;
/**
* Services and amenities for families and young guests.
*/
families?: Schema$Families;
/**
* Meals, snacks, and beverages available at the property.
*/
foodAndDrink?: Schema$FoodAndDrink;
/**
* Individual GuestUnitTypes that are available in this Lodging.
*/
guestUnits?: Schema$GuestUnitType[];
/**
* Health and safety measures implemented by the hotel during COVID-19.
*/
healthAndSafety?: Schema$HealthAndSafety;
/**
* Conveniences provided in guest units to facilitate an easier, more comfortable stay.
*/
housekeeping?: Schema$Housekeeping;
/**
* Required. Metadata for the lodging.
*/
metadata?: Schema$LodgingMetadata;
/**
* Required. Google identifier for this location in the form: `locations/{location_id\}/lodging`
*/
name?: string | null;
/**
* Parking options at the property.
*/
parking?: Schema$Parking;
/**
* Policies regarding guest-owned animals.
*/
pets?: Schema$Pets;
/**
* Property rules that impact guests.
*/
policies?: Schema$Policies;
/**
* Swimming pool or recreational water facilities available at the hotel.
*/
pools?: Schema$Pools;
/**
* General factual information about the property's physical structure and important dates.
*/
property?: Schema$Property;
/**
* Conveniences or help provided by the property to facilitate an easier, more comfortable stay.
*/
services?: Schema$Services;
/**
* Output only. Some units on the property have as much as these attributes.
*/
someUnits?: Schema$GuestUnitFeatures;
/**
* Sustainability practices implemented at the hotel.
*/
sustainability?: Schema$Sustainability;
/**
* Vehicles or vehicular services facilitated or owned by the property.
*/
transportation?: Schema$Transportation;
/**
* Guest facilities at the property to promote or maintain health, beauty, and fitness.
*/
wellness?: Schema$Wellness;
}
/**
* Metadata for the Lodging.
*/
export interface Schema$LodgingMetadata {
/**
* Required. The latest time at which the Lodging data is asserted to be true in the real world. This is not necessarily the time at which the request is made.
*/
updateTime?: string | null;
}
/**
* Minimized contact measures implemented by the hotel during COVID-19.
*/
export interface Schema$MinimizedContact {
/**
* No-contact check-in and check-out.
*/
contactlessCheckinCheckout?: boolean | null;
/**
* Contactless check-in check-out exception.
*/
contactlessCheckinCheckoutException?: string | null;
/**
* Keyless mobile entry to guest rooms.
*/
digitalGuestRoomKeys?: boolean | null;
/**
* Digital guest room keys exception.
*/
digitalGuestRoomKeysException?: string | null;
/**
* Housekeeping scheduled by request only.
*/
housekeepingScheduledRequestOnly?: boolean | null;
/**
* Housekeeping scheduled request only exception.
*/
housekeepingScheduledRequestOnlyException?: string | null;
/**
* High-touch items, such as magazines, removed from common areas.
*/
noHighTouchItemsCommonAreas?: boolean | null;
/**
* No high touch items common areas exception.
*/
noHighTouchItemsCommonAreasException?: string | null;
/**
* High-touch items, such as decorative pillows, removed from guest rooms.
*/
noHighTouchItemsGuestRooms?: boolean | null;
/**
* No high touch items guest rooms exception.
*/
noHighTouchItemsGuestRoomsException?: string | null;
/**
* Plastic key cards are disinfected or discarded.
*/
plasticKeycardsDisinfected?: boolean | null;
/**
* Plastic keycards disinfected exception.
*/
plasticKeycardsDisinfectedException?: string | null;
/**
* Buffer maintained between room bookings.
*/
roomBookingsBuffer?: boolean | null;
/**
* Room bookings buffer exception.
*/
roomBookingsBufferException?: string | null;
}
/**
* Parking options at the property.
*/
export interface Schema$Parking {
/**
* Electric car charging stations. Electric power stations, usually located outdoors, into which guests plug their electric cars to receive a charge.
*/
electricCarChargingStations?: boolean | null;
/**
* Electric car charging stations exception.
*/
electricCarChargingStationsException?: string | null;
/**
* Free parking. The hotel allows the cars of guests to be parked for free. Parking facility may be an outdoor lot or an indoor garage, but must be onsite. Nearby parking does not apply. Parking may be performed by the guest or by hotel staff. Free parking must be available to all guests (limited conditions does not apply).
*/
freeParking?: boolean | null;
/**
* Free parking exception.
*/
freeParkingException?: string | null;
/**
* Free self parking. Guests park their own cars for free. Parking facility may be an outdoor lot or an indoor garage, but must be onsite. Nearby parking does not apply.
*/
freeSelfParking?: boolean | null;
/**
* Free self parking exception.
*/
freeSelfParkingException?: string | null;
/**
* Free valet parking. Hotel staff member parks the cars of guests. Parking with this service is free.
*/
freeValetParking?: boolean | null;
/**
* Free valet parking exception.
*/
freeValetParkingException?: string | null;
/**
* Parking available. The hotel allows the cars of guests to be parked. Can be free or for a fee. Parking facility may be an outdoor lot or an indoor garage, but must be onsite. Nearby parking does not apply. Parking may be performed by the guest or by hotel staff.
*/
parkingAvailable?: boolean | null;
/**
* Parking available exception.
*/
parkingAvailableException?: string | null;
/**
* Self parking available. Guests park their own cars. Parking facility may be an outdoor lot or an indoor garage, but must be onsite. Nearby parking does not apply. Can be free or for a fee.
*/
selfParkingAvailable?: boolean | null;
/**
* Self parking available exception.
*/
selfParkingAvailableException?: string | null;
/**
* Valet parking available. Hotel staff member parks the cars of guests. Parking with this service can be free or for a fee.
*/
valetParkingAvailable?: boolean | null;
/**
* Valet parking available exception.
*/
valetParkingAvailableException?: string | null;
}
/**
* Forms of payment accepted at the property.
*/
export interface Schema$PaymentOptions {
/**
* Cash. The hotel accepts payment by paper/coin currency.
*/
cash?: boolean | null;
/**
* Cash exception.
*/
cashException?: string | null;
/**
* Cheque. The hotel accepts a printed document issued by the guest's bank in the guest's name as a form of payment.
*/
cheque?: boolean | null;
/**
* Cheque exception.
*/
chequeException?: string | null;
/**
* Credit card. The hotel accepts payment by a card issued by a bank or credit card company. Also known as charge card, debit card, bank card, or charge plate.
*/
creditCard?: boolean | null;
/**
* Credit card exception.
*/
creditCardException?: string | null;
/**
* Debit card. The hotel accepts a bank-issued card that immediately deducts the charged funds from the guest's bank account upon processing.
*/
debitCard?: boolean | null;
/**
* Debit card exception.
*/
debitCardException?: string | null;
/**
* Mobile nfc. The hotel has the compatible computer hardware terminal that reads and charges a payment app on the guest's smartphone without requiring the two devices to make physical contact. Also known as Apple Pay, Google Pay, Samsung Pay.
*/
mobileNfc?: boolean | null;
/**
* Mobile nfc exception.
*/
mobileNfcException?: string | null;
}
/**
* Personal protection measures implemented by the hotel during COVID-19.
*/
export interface Schema$PersonalProtection {
/**
* Hand-sanitizer and/or sanitizing wipes are offered in common areas.
*/
commonAreasOfferSanitizingItems?: boolean | null;
/**
* Common areas offer sanitizing items exception.
*/
commonAreasOfferSanitizingItemsException?: string | null;
/**
* Masks required on the property.
*/
faceMaskRequired?: boolean | null;
/**
* Face mask required exception.
*/
faceMaskRequiredException?: string | null;
/**
* In-room hygiene kits with masks, hand sanitizer, and/or antibacterial wipes.
*/
guestRoomHygieneKitsAvailable?: boolean | null;
/**
* Guest room hygiene kits available exception.
*/
guestRoomHygieneKitsAvailableException?: string | null;
/**
* Masks and/or gloves available for guests.
*/
protectiveEquipmentAvailable?: boolean | null;
/**
* Protective equipment available exception.
*/
protectiveEquipmentAvailableException?: string | null;
}
/**
* Policies regarding guest-owned animals.
*/
export interface Schema$Pets {
/**
* Cats allowed. Domesticated felines are permitted at the property and allowed to stay in the guest room of their owner. May or may not require a fee.
*/
catsAllowed?: boolean | null;
/**
* Cats allowed exception.
*/
catsAllowedException?: string | null;
/**
* Dogs allowed. Domesticated canines are permitted at the property and allowed to stay in the guest room of their owner. May or may not require a fee.
*/
dogsAllowed?: boolean | null;
/**
* Dogs allowed exception.
*/
dogsAllowedException?: string | null;
/**
* Pets allowed. Household animals are allowed at the property and in the specific guest room of their owner. May or may not include dogs, cats, reptiles and/or fish. May or may not require a fee. Service animals are not considered to be pets, so not governed by this policy.
*/
petsAllowed?: boolean | null;
/**
* Pets allowed exception.
*/
petsAllowedException?: string | null;
/**
* Pets allowed free. Household animals are allowed at the property and in the specific guest room of their owner for free. May or may not include dogs, cats, reptiles, and/or fish.
*/
petsAllowedFree?: boolean | null;
/**
* Pets allowed free exception.
*/
petsAllowedFreeException?: string | null;
}
/**
* Physical distancing measures implemented by the hotel during COVID-19.
*/
export interface Schema$PhysicalDistancing {
/**
* Common areas arranged to maintain physical distancing.
*/
commonAreasPhysicalDistancingArranged?: boolean | null;
/**
* Common areas physical distancing arranged exception.
*/
commonAreasPhysicalDistancingArrangedException?: string | null;
/**
* Physical distancing required.
*/
physicalDistancingRequired?: boolean | null;
/**
* Physical distancing required exception.
*/
physicalDistancingRequiredException?: string | null;
/**
* Safety dividers at front desk and other locations.
*/
safetyDividers?: boolean | null;
/**
* Safety dividers exception.
*/
safetyDividersException?: string | null;
/**
* Guest occupancy limited within shared facilities.
*/
sharedAreasLimitedOccupancy?: boolean | null;
/**
* Shared areas limited occupancy exception.
*/
sharedAreasLimitedOccupancyException?: string | null;
/**
* Private spaces designated in spa and wellness areas.
*/
wellnessAreasHavePrivateSpaces?: boolean | null;
/**
* Wellness areas have private spaces exception.
*/
wellnessAreasHavePrivateSpacesException?: string | null;
}
/**
* Property rules that impact guests.
*/
export interface Schema$Policies {
/**
* All inclusive available. The hotel offers a rate option that includes the cost of the room, meals, activities, and other amenities that might otherwise be charged separately.
*/
allInclusiveAvailable?: boolean | null;
/**
* All inclusive available exception.
*/
allInclusiveAvailableException?: string | null;
/**
* All inclusive only. The only rate option offered by the hotel is a rate that includes the cost of the room, meals, activities and other amenities that might otherwise be charged separately.
*/
allInclusiveOnly?: boolean | null;
/**
* All inclusive only exception.
*/
allInclusiveOnlyException?: string | null;
/**
* Check-in time. The time of the day at which the hotel begins providing guests access to their unit at the beginning of their stay.
*/
checkinTime?: Schema$TimeOfDay;
/**
* Check-in time exception.
*/
checkinTimeException?: string | null;
/**
* Check-out time. The time of the day on the last day of a guest's reserved stay at which the guest must vacate their room and settle their bill. Some hotels may offer late or early check out for a fee.
*/
checkoutTime?: Schema$TimeOfDay;
/**
* Check-out time exception.
*/
checkoutTimeException?: string | null;
/**
* Kids stay free. The children of guests are allowed to stay in the room/suite of a parent or adult without an additional fee. The policy may or may not stipulate a limit of the child's age or the overall number of children allowed.
*/
kidsStayFree?: boolean | null;
/**
* Kids stay free exception.
*/
kidsStayFreeException?: string | null;
/**
* Max child age. The hotel allows children up to a certain age to stay in the room/suite of a parent or adult without an additional fee.
*/
maxChildAge?: number | null;
/**
* Max child age exception.
*/
maxChildAgeException?: string | null;
/**
* Max kids stay free count. The hotel allows a specific, defined number of children to stay in the room/suite of a parent or adult without an additional fee.
*/
maxKidsStayFreeCount?: number | null;
/**
* Max kids stay free count exception.
*/
maxKidsStayFreeCountException?: string | null;
/**
* Forms of payment accepted at the property.
*/
paymentOptions?: Schema$PaymentOptions;
/**
* Smoke free property. Smoking is not allowed inside the building, on balconies, or in outside spaces. Hotels that offer a designated area for guests to smoke are not considered smoke-free properties.
*/
smokeFreeProperty?: boolean | null;
/**
* Smoke free property exception.
*/
smokeFreePropertyException?: string | null;
}
/**
* Swimming pool or recreational water facilities available at the hotel.
*/
export interface Schema$Pools {
/**
* Adult pool. A pool restricted for use by adults only. Can be indoors or outdoors.
*/
adultPool?: boolean | null;
/**
* Adult pool exception.
*/
adultPoolException?: string | null;
/**
* Hot tub. A man-made pool containing bubbling water maintained at a higher temperature and circulated by aerating jets for the purpose of soaking, relaxation and hydrotherapy. Can be indoors or outdoors. Not used for active swimming. Also known as Jacuzzi. Hot tub must be in a common area where all guests can access it. Does not apply to room-specific hot tubs that are only accessible to guest occupying that room.
*/
hotTub?: boolean | null;
/**
* Hot tub exception.
*/
hotTubException?: string | null;
/**
* Indoor pool. A pool located inside the hotel and available for guests to use for swimming and/or soaking. Use may or may not be restricted to adults and/or children.
*/
indoorPool?: boolean | null;
/**
* Indoor pool exception.
*/
indoorPoolException?: string | null;
/**
* Indoor pools count. The sum of all indoor pools at the hotel.
*/
indoorPoolsCount?: number | null;
/**
* Indoor pools count exception.
*/
indoorPoolsCountException?: string | null;
/**
* Lazy river. A man-made pool or several interconnected recreational pools built to mimic the shape and current of a winding river where guests float in the water on inflated rubber tubes. Can be indoors or outdoors.
*/
lazyRiver?: boolean | null;
/**
* Lazy river exception.
*/
lazyRiverException?: string | null;
/**
* Lifeguard. A trained member of the hotel staff stationed by the hotel's indoor or outdoor swimming area and responsible for the safety of swimming guests.
*/
lifeguard?: boolean | null;
/**
* Lifeguard exception.
*/
lifeguardException?: string | null;
/**
* Outdoor pool. A pool located outside on the grounds of the hotel and available for guests to use for swimming, soaking or recreation. Use may or may not be restricted to adults and/or children.
*/
outdoorPool?: boolean | null;
/**
* Outdoor pool exception.
*/
outdoorPoolException?: string | null;
/**
* Outdoor pools count. The sum of all outdoor pools at the hotel.
*/
outdoorPoolsCount?: number | null;
/**
* Outdoor pools count exception.
*/
outdoorPoolsCountException?: string | null;
/**
* Pool. The presence of a pool, either indoors or outdoors, for guests to use for swimming and/or soaking. Use may or may not be restricted to adults and/or children.
*/
pool?: boolean | null;
/**
* Pool exception.
*/
poolException?: string | null;
/**
* Pools count. The sum of all pools at the hotel.
*/
poolsCount?: number | null;
/**
* Pools count exception.
*/
poolsCountException?: string | null;
/**
* Wading pool. A shallow pool designed for small children to play in. Can be indoors or outdoors. Also known as kiddie pool.
*/
wadingPool?: boolean | null;
/**
* Wading pool exception.
*/
wadingPoolException?: string | null;
/**
* Water park. An aquatic recreation area with a large pool or series of pools that has features such as a water slide or tube, wavepool, fountains, rope swings, and/or obstacle course. Can be indoors or outdoors. Also known as adventure pool.
*/
waterPark?: boolean | null;
/**
* Water park exception.
*/
waterParkException?: string | null;
/**
* Waterslide. A continuously wetted chute positioned by an indoor or outdoor pool which people slide down into the water.
*/
waterslide?: boolean | null;
/**
* Waterslide exception.
*/
waterslideException?: string | null;
/**
* Wave pool. A large indoor or outdoor pool with a machine that produces water currents to mimic the ocean's crests.
*/
wavePool?: boolean | null;
/**
* Wave pool exception.
*/
wavePoolException?: string | null;
}
/**
* General factual information about the property's physical structure and important dates.
*/
export interface Schema$Property {
/**
* Built year. The year that construction of the property was completed.
*/
builtYear?: number | null;
/**
* Built year exception.
*/
builtYearException?: string | null;
/**
* Floors count. The number of stories the building has from the ground floor to the top floor that are accessible to guests.
*/
floorsCount?: number | null;
/**
* Floors count exception.
*/
floorsCountException?: string | null;
/**
* Last renovated year. The year when the most recent renovation of the property was completed. Renovation may include all or any combination of the following: the units, the public spaces, the exterior, or the interior.
*/
lastRenovatedYear?: number | null;
/**
* Last renovated year exception.
*/
lastRenovatedYearException?: string | null;
/**
* Rooms count. The total number of rooms and suites bookable by guests for an overnight stay. Does not include event space, public spaces, conference rooms, fitness rooms, business centers, spa, salon, restaurants/bars, or shops.
*/
roomsCount?: number | null;
/**
* Rooms count exception.
*/
roomsCountException?: string | null;
}
/**
* Conveniences or help provided by the property to facilitate an easier, more comfortable stay.
*/
export interface Schema$Services {
/**
* Baggage storage. A provision for guests to leave their bags at the hotel when they arrive for their stay before the official check-in time. May or may not apply for guests who wish to leave their bags after check-out and before departing the locale. Also known as bag dropoff.
*/
baggageStorage?: boolean | null;
/**
* Baggage storage exception.
*/
baggageStorageException?: string | null;
/**
* Concierge. Hotel staff member(s) responsible for facilitating an easy, comfortable stay through making reservations for meals, sourcing theater tickets, arranging tours, finding a doctor, making recommendations, and answering questions.
*/
concierge?: boolean | null;
/**
* Concierge exception.
*/
conciergeException?: string | null;
/**
* Convenience store. A shop at the hotel primarily selling snacks, drinks, non-prescription medicines, health and beauty aids, magazines and newspapers.
*/
convenienceStore?: boolean | null;
/**
* Convenience store exception.
*/
convenienceStoreException?: string | null;
/**
* Currency exchange. A staff member or automated machine tasked with the transaction of providing the native currency of the hotel's locale in exchange for the foreign currency provided by a guest.
*/
currencyExchange?: boolean | null;
/**
* Currency exchange exception.
*/
currencyExchangeException?: string | null;
/**
* Elevator. A passenger elevator that transports guests from one story to another. Also known as lift.
*/
elevator?: boolean | null;
/**
* Elevator exception.
*/
elevatorException?: string | null;
/**
* Front desk. A counter or desk in the lobby or the immediate interior of the hotel where a member of the staff greets guests and processes the information related to their stay (including check-in and check-out). May or may not be manned and open 24/7.
*/
frontDesk?: boolean | null;
/**
* Front desk exception.
*/
frontDeskException?: string | null;
/**
* Full service laundry. Laundry and dry cleaning facilitated and handled by the hotel on behalf of the guest. Does not include the provision for guests to do their own laundry in on-site machines.
*/
fullServiceLaundry?: boolean | null;
/**
* Full service laundry exception.
*/
fullServiceLaundryException?: string | null;
/**
* Gift shop. An on-site store primarily selling souvenirs, mementos and other gift items. May or may not also sell sundries, magazines and newspapers, clothing, or snacks.
*/
giftShop?: boolean | null;
/**
* Gift shop exception.
*/
giftShopException?: string | null;
/**
* Languages spoken by at least one staff member.
*/
languagesSpoken?: Schema$LanguageSpoken[];
/**
* Self service laundry. On-site clothes washers and dryers accessible to guests for the purpose of washing and drying their own clothes. May or may not require payment to use the machines.
*/
selfServiceLaundry?: boolean | null;
/**
* Self service laundry exception.
*/
selfServiceLaundryException?: string | null;
/**
* Social hour. A reception with complimentary soft drinks, tea, coffee, wine and/or cocktails in the afternoon or evening. Can be hosted by hotel staff or guests may serve themselves. Also known as wine hour. The availability of coffee/tea in the lobby throughout the day does not constitute a social or wine hour.
*/
socialHour?: boolean | null;
/**
* Social hour exception.
*/
socialHourException?: string | null;
/**
* 24hr front desk. Front desk is staffed 24 hours a day.
*/
twentyFourHourFrontDesk?: boolean | null;
/**
* 24hr front desk exception.
*/
twentyFourHourFrontDeskException?: string | null;
/**
* Wake up calls. By direction of the guest, a hotel staff member will phone the guest unit at the requested hour. Also known as morning call.
*/
wakeUpCalls?: boolean | null;
/**
* Wake up calls exception.
*/
wakeUpCallsException?: string | null;
}
/**
* Sustainability practices implemented at the hotel.
*/
export interface Schema$Sustainability {
/**
* Energy efficiency practices implemented at the hotel.
*/
energyEfficiency?: Schema$EnergyEfficiency;
/**
* Sustainability certifications the hotel has been awarded.
*/
sustainabilityCertifications?: Schema$SustainabilityCertifications;
/**
* Sustainable sourcing practices implemented at the hotel.
*/
sustainableSourcing?: Schema$SustainableSourcing;
/**
* Waste reduction practices implemented at the hotel.
*/
wasteReduction?: Schema$WasteReduction;
/**
* Water conservation practices implemented at the hotel.
*/
waterConservation?: Schema$WaterConservation;
}
/**
* Sustainability certifications the hotel has been awarded.
*/
export interface Schema$SustainabilityCertifications {
/**
* BREEAM certification.
*/
breeamCertification?: string | null;
/**
* BREEAM certification exception.
*/
breeamCertificationException?: string | null;
/**
* The eco certificates awarded to the hotel.
*/
ecoCertifications?: Schema$EcoCertification[];
/**
* LEED certification.
*/
leedCertification?: string | null;
/**
* LEED certification exception.
*/
leedCertificationException?: string | null;
}
/**
* Sustainable sourcing practices implemented at the hotel.
*/
export interface Schema$SustainableSourcing {
/**
* Eco friendly toiletries. Soap, shampoo, lotion, and other toiletries provided for guests have a nationally or internationally recognized sustainability certification, such as USDA Organic, EU Organic, or cruelty-free.
*/
ecoFriendlyToiletries?: boolean | null;
/**
* Eco friendly toiletries exception.
*/
ecoFriendlyToiletriesException?: string | null;
/**
* Locally sourced food and beverages. Property sources locally in order to lower the environmental footprint from reduced transportation and to stimulate the local economy. Products produced less than 62 miles from the establishment are normally considered as locally produced.
*/
locallySourcedFoodAndBeverages?: boolean | null;
/**
* Locally sourced food and beverages exception.
*/
locallySourcedFoodAndBeveragesException?: string | null;
/**
* Organic cage free eggs. The property sources 100% certified organic and cage-free eggs (shell, liquid, and egg products). Cage-free means hens are able to walk, spread their wings and lay their eggs in nests).
*/
organicCageFreeEggs?: boolean | null;
/**
* Organic cage free eggs exception.
*/
organicCageFreeEggsException?: string | null;
/**
* Organic food and beverages. At least 25% of food and beverages, by spend, are certified organic. Organic means products that are certified to one of the organic standard listed in the IFOAM family of standards. Qualifying certifications include USDA Organic and EU Organic, among others.
*/
organicFoodAndBeverages?: boolean | null;
/**
* Organic food and beverages exception.
*/
organicFoodAndBeveragesException?: string | null;
/**
* Responsible purchasing policy. The property has a responsible procurement policy in place. Responsible means integration of social, ethical, and/or environmental performance factors into the procurement process when selecting suppliers.
*/
responsiblePurchasingPolicy?: boolean | null;
/**
* Responsible purchasing policy exception.
*/
responsiblePurchasingPolicyException?: string | null;
/**
* Responsibly sources seafood. The property does not source seafood from the Monterey Bay Aquarium Seafood Watch "avoid" list, and must sustainably source seafood listed as "good alternative," "eco-certified," and "best choice". The property has a policy outlining a commitment to source Marine Stewardship Council (MSC) and/or Aquaculture Stewardship Council (ASC) Chain of Custody certified seafood.
*/
responsiblySourcesSeafood?: boolean | null;
/**
* Responsibly sources seafood exception.
*/
responsiblySourcesSeafoodException?: string | null;
/**
* Vegan meals. The property provides vegan menu options for guests. Vegan food does not contain animal products or byproducts.
*/
veganMeals?: boolean | null;
/**
* Vegan meals exception.
*/
veganMealsException?: string | null;
/**
* Vegetarian meals. The property provides vegetarian menu options for guests. Vegetarian food does not contain meat, poultry, fish, or seafood.
*/
vegetarianMeals?: boolean | null;
/**
* Vegetarian meals exception.
*/
vegetarianMealsException?: string | null;
}
/**
* Represents a time of day. The date and time zone are either not significant or are specified elsewhere. An API may choose to allow leap seconds. Related types are google.type.Date and `google.protobuf.Timestamp`.
*/
export interface Schema$TimeOfDay {
/**
* Hours of day in 24 hour format. Should be from 0 to 23. An API may choose to allow the value "24:00:00" for scenarios like business closing time.
*/
hours?: number | null;
/**
* Minutes of hour of day. Must be from 0 to 59.
*/
minutes?: number | null;
/**
* Fractions of seconds in nanoseconds. Must be from 0 to 999,999,999.
*/
nanos?: number | null;
/**
* Seconds of minutes of the time. Must normally be from 0 to 59. An API may allow the value 60 if it allows leap-seconds.
*/
seconds?: number | null;
}
/**
* Vehicles or vehicular services facilitated or owned by the property.
*/
export interface Schema$Transportation {
/**
* Airport shuttle. The hotel provides guests with a chauffeured van or bus to and from the airport. Can be free or for a fee. Guests may share the vehicle with other guests unknown to them. Applies if the hotel has a third-party shuttle service (office/desk etc.) within the hotel. As long as hotel provides this service, it doesn't matter if it's directly with them or a third party they work with. Does not apply if guest has to coordinate with an entity outside/other than the hotel.
*/
airportShuttle?: boolean | null;
/**
* Airport shuttle exception.
*/
airportShuttleException?: string | null;
/**
* Car rental on property. A branch of a rental car company with a processing desk in the hotel. Available cars for rent may be awaiting at the hotel or in a nearby lot.
*/
carRentalOnProperty?: boolean | null;
/**
* Car rental on property exception.
*/
carRentalOnPropertyException?: string | null;
/**
* Free airport shuttle. Airport shuttle is free to guests. Must be free to all guests without any conditions.
*/
freeAirportShuttle?: boolean | null;
/**
* Free airport shuttle exception.
*/
freeAirportShuttleException?: string | null;
/**
* Free private car service. Private chauffeured car service is free to guests.
*/
freePrivateCarService?: boolean | null;
/**
* Free private car service exception.
*/
freePrivateCarServiceException?: string | null;
/**
* Local shuttle. A car, van or bus provided by the hotel to transport guests to destinations within a specified range of distance around the hotel. Usually shopping and/or convention centers, downtown districts, or beaches. Can be free or for a fee.
*/
localShuttle?: boolean | null;
/**
* Local shuttle exception.
*/
localShuttleException?: string | null;
/**
* Private car service. Hotel provides a private chauffeured car to transport guests to destinations. Passengers in the car are either alone or are known to one another and have requested the car together. Service can be free or for a fee and travel distance is usually limited to a specific range. Not a taxi.
*/
privateCarService?: boolean | null;
/**
* Private car service exception.
*/
privateCarServiceException?: string | null;
/**
* Transfer. Hotel provides a shuttle service or car service to take guests to and from the nearest airport or train station. Can be free or for a fee. Guests may share the vehicle with other guests unknown to them.
*/
transfer?: boolean | null;
/**
* Transfer exception.
*/
transferException?: string | null;
}
/**
* Views available from the guest unit itself.
*/
export interface Schema$ViewsFromUnit {
/**
* Beach view. A guestroom that features a window through which guests can see the beach.
*/
beachView?: boolean | null;
/**
* Beach view exception.
*/
beachViewException?: string | null;
/**
* City view. A guestroom that features a window through which guests can see the buildings, parks and/or streets of the city.
*/
cityView?: boolean | null;
/**
* City view exception.
*/
cityViewException?: string | null;
/**
* Garden view. A guestroom that features a window through which guests can see a garden.
*/
gardenView?: boolean | null;
/**
* Garden view exception.
*/
gardenViewException?: string | null;
/**
* Lake view.
*/
lakeView?: boolean | null;
/**
* Lake view exception.
*/
lakeViewException?: string | null;
/**
* Landmark view. A guestroom that features a window through which guests can see a landmark such as the countryside, a golf course, the forest, a park, a rain forst, a mountain or a slope.
*/
landmarkView?: boolean | null;
/**
* Landmark view exception.
*/
landmarkViewException?: string | null;
/**
* Ocean view. A guestroom that features a window through which guests can see the ocean.
*/
oceanView?: boolean | null;
/**
* Ocean view exception.
*/
oceanViewException?: string | null;
/**
* Pool view. A guestroom that features a window through which guests can see the hotel's swimming pool.
*/
poolView?: boolean | null;
/**
* Pool view exception.
*/
poolViewException?: string | null;
/**
* Valley view. A guestroom that features a window through which guests can see over a valley.
*/
valleyView?: boolean | null;
/**
* Valley view exception.
*/
valleyViewException?: string | null;
}
/**
* Waste reduction practices implemented at the hotel.
*/
export interface Schema$WasteReduction {
/**
* Compostable food containers and cutlery. 100% of food service containers and to-go cutlery are compostable, and reusable utensils are offered wherever possible. Compostable materials are capable of undergoing biological decomposition in a compost site, such that material is not visually distinguishable and breaks down into carbon dioxide, water, inorganic compounds, and biomass.
*/
compostableFoodContainersAndCutlery?: boolean | null;
/**
* Compostable food containers and cutlery exception.
*/
compostableFoodContainersAndCutleryException?: string | null;
/**
* Composts excess food. The property has a program and/or policy for diverting waste from landfill by composting food and yard waste, either through compost collection and off-site processing or on-site compost processing.
*/
compostsExcessFood?: boolean | null;
/**
* Composts excess food exception.
*/
compostsExcessFoodException?: string | null;
/**
* Donates excess food. The property has a program and/or policy for diverting waste from landfill that may include efforts to donate for human consumption or divert food for animal feed.
*/
donatesExcessFood?: boolean | null;
/**
* Donates excess food exception.
*/
donatesExcessFoodException?: string | null;
/**
* Food waste reduction program. The property has established a food waste reduction and donation program, aiming to reduce food waste by half. These programs typically use tools such as the Hotel Kitchen Toolkit and others to track waste and measure progress.
*/
foodWasteReductionProgram?: boolean | null;
/**
* Food waste reduction program exception.
*/
foodWasteReductionProgramException?: string | null;
/**
* No single use plastic straws. The property bans single-use plastic straws.
*/
noSingleUsePlasticStraws?: boolean | null;
/**
* No single use plastic straws exception.
*/
noSingleUsePlasticStrawsException?: string | null;
/**
* No single use plastic water bottles. The property bans single-use plastic water bottles.
*/
noSingleUsePlasticWaterBottles?: boolean | null;
/**
* No single use plastic water bottles exception.
*/
noSingleUsePlasticWaterBottlesException?: string | null;
/**
* No styrofoam food containers. The property eliminates the use of Styrofoam in disposable food service items.
*/
noStyrofoamFoodContainers?: boolean | null;
/**
* No styrofoam food containers exception.
*/
noStyrofoamFoodContainersException?: string | null;
/**
* Recycling program. The property has a recycling program, aligned with LEED waste requirements, and a policy outlining efforts to send less than 50% of waste to landfill. The recycling program includes storage locations for recyclable materials, including mixed paper, corrugated cardboard, glass, plastics, and metals.
*/
recyclingProgram?: boolean | null;
/**
* Recycling program exception.
*/
recyclingProgramException?: string | null;
/**
* Refillable toiletry containers. The property has replaced miniature individual containers with refillable amenity dispensers for shampoo, conditioner, soap, and lotion.
*/
refillableToiletryContainers?: boolean | null;
/**
* Refillable toiletry containers exception.
*/
refillableToiletryContainersException?: string | null;
/**
* Safely disposes batteries. The property safely stores and disposes batteries.
*/
safelyDisposesBatteries?: boolean | null;
/**
* Safely disposes batteries exception.
*/
safelyDisposesBatteriesException?: string | null;
/**
* Safely disposes electronics. The property has a reputable recycling program that keeps hazardous electronic parts and chemical compounds out of landfills, dumps and other unauthorized abandonment sites, and recycles/reuses applicable materials. (e.g. certified electronics recyclers).
*/
safelyDisposesElectronics?: boolean | null;
/**
* Safely disposes electronics exception.
*/
safelyDisposesElectronicsException?: string | null;
/**
* Safely disposes lightbulbs. The property safely stores and disposes lightbulbs.
*/
safelyDisposesLightbulbs?: boolean | null;
/**
* Safely disposes lightbulbs exception.
*/
safelyDisposesLightbulbsException?: string | null;
/**
* Safely handles hazardous substances. The property has a hazardous waste management program aligned wit GreenSeal and LEED requirements, and meets all regulatory requirements for hazardous waste disposal and recycling. Hazardous means substances that are classified as "hazardous" by an authoritative body (such as OSHA or DOT), are labeled with signal words such as "Danger," "Caution," "Warning," or are flammable, corrosive, or ignitable. Requirements include: - The property shall maintain records of the efforts it has made to replace the hazardous substances it uses with less hazardous alternatives. - An inventory of the hazardous materials stored on-site. - Products intended for cleaning, dishwashing, laundry, and pool maintenance shall be stored in clearly labeled containers. These containers shall be checked regularly for leaks, and replaced a necessary. - Spill containment devices shall be installed to collect spills, drips, or leaching of chemicals.
*/
safelyHandlesHazardousSubstances?: boolean | null;
/**
* Safely handles hazardous substances exception.
*/
safelyHandlesHazardousSubstancesException?: string | null;
/**
* Soap donation program. The property participates in a soap donation program such as Clean the World or something similar.
*/
soapDonationProgram?: boolean | null;
/**
* Soap donation program exception.
*/
soapDonationProgramException?: string | null;
/**
* Toiletry donation program. The property participates in a toiletry donation program such as Clean the World or something similar.
*/
toiletryDonationProgram?: boolean | null;
/**
* Toiletry donation program exception.
*/
toiletryDonationProgramException?: string | null;
/**
* Water bottle filling stations. The property offers water stations throughout the building for guest use.
*/
waterBottleFillingStations?: boolean | null;
/**
* Water bottle filling stations exception.
*/
waterBottleFillingStationsException?: string | null;
}
/**
* Water conservation practices implemented at the hotel.
*/
export interface Schema$WaterConservation {
/**
* Independent organization audits water use. The property conducts a water conservation audit every 5 years, the results of which are either verified by a third-party and/or published in external communications. A water conservation audit is a detailed assessment of the facility, providing recommendations to existing operations and procedures to improve water efficiency, available incentives or rebates, and opportunities for improvements through renovations or upgrades. Examples of organizations who conduct credible third party audits include: Engie Impact, and local utility providers (they often provide energy and water audits).
*/
independentOrganizationAuditsWaterUse?: boolean | null;
/**
* Independent organization audits water use exception.
*/
independentOrganizationAuditsWaterUseException?: string | null;
/**
* Linen reuse program. The property offers a linen reuse program.
*/
linenReuseProgram?: boolean | null;
/**
* Linen reuse program exception.
*/
linenReuseProgramException?: string | null;
/**
* Towel reuse program. The property offers a towel reuse program.
*/
towelReuseProgram?: boolean | null;
/**
* Towel reuse program exception.
*/
towelReuseProgramException?: string | null;
/**
* Water saving showers. All of the property's guest rooms have shower heads that use no more than 2.0 gallons per minute (gpm).
*/
waterSavingShowers?: boolean | null;
/**
* Water saving showers exception.
*/
waterSavingShowersException?: string | null;
/**
* Water saving sinks. All of the property's guest rooms have bathroom faucets that use a maximum of 1.5 gallons per minute (gpm), public restroom faucets do not exceed 0.5 gpm, and kitchen faucets (excluding faucets used exclusively for filling operations) do not exceed 2.2 gpm.
*/
waterSavingSinks?: boolean | null;
/**
* Water saving sinks exception.
*/
waterSavingSinksException?: string | null;
/**
* Water saving toilets. All of the property's toilets use 1.6 gallons per flush, or less.
*/
waterSavingToilets?: boolean | null;
/**
* Water saving toilets exception.
*/
waterSavingToiletsException?: string | null;
}
/**
* Guest facilities at the property to promote or maintain health, beauty, and fitness.
*/
export interface Schema$Wellness {
/**
* Doctor on call. The hotel has a contract with a medical professional who provides services to hotel guests should they fall ill during their stay. The doctor may or may not have an on-site office or be at the hotel at all times.
*/
doctorOnCall?: boolean | null;
/**
* Doctor on call exception.
*/
doctorOnCallException?: string | null;
/**
* Elliptical machine. An electric, stationary fitness machine with pedals that simulates climbing, walking or running and provides a user-controlled range of speeds and tensions. May not have arm-controlled levers to work out the upper body as well. Commonly found in a gym, fitness room, health center, or health club.
*/
ellipticalMachine?: boolean | null;
/**
* Elliptical machine exception.
*/
ellipticalMachineException?: string | null;
/**
* Fitness center. A room or building at the hotel containing equipment to promote physical activity, such as treadmills, elliptical machines, stationary bikes, weight machines, free weights, and/or stretching mats. Use of the fitness center can be free or for a fee. May or may not be staffed. May or may not offer instructor-led classes in various styles of physical conditioning. May or may not be open 24/7. May or may not include locker rooms and showers. Also known as health club, gym, fitness room, health center.
*/
fitnessCenter?: boolean | null;
/**
* Fitness center exception.
*/
fitnessCenterException?: string | null;
/**
* Free fitness center. Guests may use the fitness center for free.
*/
freeFitnessCenter?: boolean | null;
/**
* Free fitness center exception.
*/
freeFitnessCenterException?: string | null;
/**
* Free weights. Individual handheld fitness equipment of varied weights used for upper body strength training or bodybuilding. Also known as barbells, dumbbells, or kettlebells. Often stored on a rack with the weights arranged from light to heavy. Commonly found in a gym, fitness room, health center, or health club.
*/
freeWeights?: boolean | null;
/**
* Free weights exception.
*/
freeWeightsException?: string | null;
/**
* Massage. A service provided by a trained massage therapist involving the physical manipulation of a guest's muscles in order to achieve relaxation or pain relief.
*/
massage?: boolean | null;
/**
* Massage exception.
*/
massageException?: string | null;
/**
* Salon. A room at the hotel where professionals provide hair styling services such as shampooing, blow drying, hair dos, hair cutting and hair coloring. Also known as hairdresser or beauty salon.
*/
salon?: boolean | null;
/**
* Salon exception.
*/
salonException?: string | null;
/**
* Sauna. A wood-paneled room heated to a high temperature where guests sit on built-in wood benches for the purpose of perspiring and relaxing their muscles. Can be dry or slightly wet heat. Not a steam room.
*/
sauna?: boolean | null;
/**
* Sauna exception.
*/
saunaException?: string | null;
/**
* Spa. A designated area, room or building at the hotel offering health and beauty treatment through such means as steam baths, exercise equipment, and massage. May also offer facials, nail care, and hair care. Services are usually available by appointment and for an additional fee. Does not apply if hotel only offers a steam room; must offer other beauty and/or health treatments as well.
*/
spa?: boolean | null;
/**
* Spa exception.
*/
spaException?: string | null;
/**
* Treadmill. An electric stationary fitness machine that simulates a moving path to promote walking or running within a range of user-controlled speeds and inclines. Also known as running machine. Commonly found in a gym, fitness room, health center, or health club.
*/
treadmill?: boolean | null;
/**
* Treadmill exception.
*/
treadmillException?: string | null;
/**
* Weight machine. Non-electronic fitness equipment designed for the user to target the exertion of different muscles. Usually incorporates a padded seat, a stack of flat weights and various bars and pulleys. May be designed for toning a specific part of the body or may involve different user-controlled settings, hardware and pulleys so as to provide an overall workout in one machine. Commonly found in a gym, fitness center, fitness room, or health club.
*/
weightMachine?: boolean | null;
/**
* Weight machine exception.
*/
weightMachineException?: string | null;
}
export class Resource$Locations {
context: APIRequestContext;
lodging: Resource$Locations$Lodging;
constructor(context: APIRequestContext) {
this.context = context;
this.lodging = new Resource$Locations$Lodging(this.context);
}
/**
* Returns the Lodging of a specific location.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/mybusinesslodging.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const mybusinesslodging = google.mybusinesslodging('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: [],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await mybusinesslodging.locations.getLodging({
* // Required. Google identifier for this location in the form: `locations/{location_id\}/lodging`
* name: 'locations/my-location/lodging',
* // Required. The specific fields to return. Use "*" to include all fields. Repeated field items cannot be individually specified.
* readMask: 'placeholder-value',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "accessibility": {},
* // "activities": {},
* // "allUnits": {},
* // "business": {},
* // "commonLivingArea": {},
* // "connectivity": {},
* // "families": {},
* // "foodAndDrink": {},
* // "guestUnits": [],
* // "healthAndSafety": {},
* // "housekeeping": {},
* // "metadata": {},
* // "name": "my_name",
* // "parking": {},
* // "pets": {},
* // "policies": {},
* // "pools": {},
* // "property": {},
* // "services": {},
* // "someUnits": {},
* // "sustainability": {},
* // "transportation": {},
* // "wellness": {}
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
getLodging(
params: Params$Resource$Locations$Getlodging,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
getLodging(
params?: Params$Resource$Locations$Getlodging,
options?: MethodOptions
): GaxiosPromise<Schema$Lodging>;
getLodging(
params: Params$Resource$Locations$Getlodging,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
getLodging(
params: Params$Resource$Locations$Getlodging,
options: MethodOptions | BodyResponseCallback<Schema$Lodging>,
callback: BodyResponseCallback<Schema$Lodging>
): void;
getLodging(
params: Params$Resource$Locations$Getlodging,
callback: BodyResponseCallback<Schema$Lodging>
): void;
getLodging(callback: BodyResponseCallback<Schema$Lodging>): void;
getLodging(
paramsOrCallback?:
| Params$Resource$Locations$Getlodging
| BodyResponseCallback<Schema$Lodging>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$Lodging>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$Lodging>
| BodyResponseCallback<Readable>
): void | GaxiosPromise<Schema$Lodging> | GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Locations$Getlodging;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Locations$Getlodging;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://mybusinesslodging.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'),
method: 'GET',
},
options
),
params,
requiredParams: ['name'],
pathParams: ['name'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$Lodging>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$Lodging>(parameters);
}
}
/**
* Updates the Lodging of a specific location.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/mybusinesslodging.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const mybusinesslodging = google.mybusinesslodging('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: [],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await mybusinesslodging.locations.updateLodging({
* // Required. Google identifier for this location in the form: `locations/{location_id\}/lodging`
* name: 'locations/my-location/lodging',
* // Required. The specific fields to update. Use "*" to update all fields, which may include unsetting empty fields in the request. Repeated field items cannot be individually updated.
* updateMask: 'placeholder-value',
*
* // Request body metadata
* requestBody: {
* // request body parameters
* // {
* // "accessibility": {},
* // "activities": {},
* // "allUnits": {},
* // "business": {},
* // "commonLivingArea": {},
* // "connectivity": {},
* // "families": {},
* // "foodAndDrink": {},
* // "guestUnits": [],
* // "healthAndSafety": {},
* // "housekeeping": {},
* // "metadata": {},
* // "name": "my_name",
* // "parking": {},
* // "pets": {},
* // "policies": {},
* // "pools": {},
* // "property": {},
* // "services": {},
* // "someUnits": {},
* // "sustainability": {},
* // "transportation": {},
* // "wellness": {}
* // }
* },
* });
* console.log(res.data);
*
* // Example response
* // {
* // "accessibility": {},
* // "activities": {},
* // "allUnits": {},
* // "business": {},
* // "commonLivingArea": {},
* // "connectivity": {},
* // "families": {},
* // "foodAndDrink": {},
* // "guestUnits": [],
* // "healthAndSafety": {},
* // "housekeeping": {},
* // "metadata": {},
* // "name": "my_name",
* // "parking": {},
* // "pets": {},
* // "policies": {},
* // "pools": {},
* // "property": {},
* // "services": {},
* // "someUnits": {},
* // "sustainability": {},
* // "transportation": {},
* // "wellness": {}
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
updateLodging(
params: Params$Resource$Locations$Updatelodging,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
updateLodging(
params?: Params$Resource$Locations$Updatelodging,
options?: MethodOptions
): GaxiosPromise<Schema$Lodging>;
updateLodging(
params: Params$Resource$Locations$Updatelodging,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
updateLodging(
params: Params$Resource$Locations$Updatelodging,
options: MethodOptions | BodyResponseCallback<Schema$Lodging>,
callback: BodyResponseCallback<Schema$Lodging>
): void;
updateLodging(
params: Params$Resource$Locations$Updatelodging,
callback: BodyResponseCallback<Schema$Lodging>
): void;
updateLodging(callback: BodyResponseCallback<Schema$Lodging>): void;
updateLodging(
paramsOrCallback?:
| Params$Resource$Locations$Updatelodging
| BodyResponseCallback<Schema$Lodging>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$Lodging>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$Lodging>
| BodyResponseCallback<Readable>
): void | GaxiosPromise<Schema$Lodging> | GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Locations$Updatelodging;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Locations$Updatelodging;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://mybusinesslodging.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'),
method: 'PATCH',
},
options
),
params,
requiredParams: ['name'],
pathParams: ['name'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$Lodging>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$Lodging>(parameters);
}
}
}
export interface Params$Resource$Locations$Getlodging
extends StandardParameters {
/**
* Required. Google identifier for this location in the form: `locations/{location_id\}/lodging`
*/
name?: string;
/**
* Required. The specific fields to return. Use "*" to include all fields. Repeated field items cannot be individually specified.
*/
readMask?: string;
}
export interface Params$Resource$Locations$Updatelodging
extends StandardParameters {
/**
* Required. Google identifier for this location in the form: `locations/{location_id\}/lodging`
*/
name?: string;
/**
* Required. The specific fields to update. Use "*" to update all fields, which may include unsetting empty fields in the request. Repeated field items cannot be individually updated.
*/
updateMask?: string;
/**
* Request body metadata
*/
requestBody?: Schema$Lodging;
}
export class Resource$Locations$Lodging {
context: APIRequestContext;
constructor(context: APIRequestContext) {
this.context = context;
}
/**
* Returns the Google updated Lodging of a specific location.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/mybusinesslodging.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const mybusinesslodging = google.mybusinesslodging('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: [],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await mybusinesslodging.locations.lodging.getGoogleUpdated({
* // Required. Google identifier for this location in the form: `accounts/{account_id\}/locations/{location_id\}/lodging`
* name: 'locations/my-location/lodging',
* // Required. The specific fields to return. Use "*" to include all fields. Repeated field items cannot be individually specified.
* readMask: 'placeholder-value',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "diffMask": "my_diffMask",
* // "lodging": {}
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
getGoogleUpdated(
params: Params$Resource$Locations$Lodging$Getgoogleupdated,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
getGoogleUpdated(
params?: Params$Resource$Locations$Lodging$Getgoogleupdated,
options?: MethodOptions
): GaxiosPromise<Schema$GetGoogleUpdatedLodgingResponse>;
getGoogleUpdated(
params: Params$Resource$Locations$Lodging$Getgoogleupdated,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
getGoogleUpdated(
params: Params$Resource$Locations$Lodging$Getgoogleupdated,
options:
| MethodOptions
| BodyResponseCallback<Schema$GetGoogleUpdatedLodgingResponse>,
callback: BodyResponseCallback<Schema$GetGoogleUpdatedLodgingResponse>
): void;
getGoogleUpdated(
params: Params$Resource$Locations$Lodging$Getgoogleupdated,
callback: BodyResponseCallback<Schema$GetGoogleUpdatedLodgingResponse>
): void;
getGoogleUpdated(
callback: BodyResponseCallback<Schema$GetGoogleUpdatedLodgingResponse>
): void;
getGoogleUpdated(
paramsOrCallback?:
| Params$Resource$Locations$Lodging$Getgoogleupdated
| BodyResponseCallback<Schema$GetGoogleUpdatedLodgingResponse>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$GetGoogleUpdatedLodgingResponse>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$GetGoogleUpdatedLodgingResponse>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$GetGoogleUpdatedLodgingResponse>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Locations$Lodging$Getgoogleupdated;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Locations$Lodging$Getgoogleupdated;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://mybusinesslodging.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v1/{+name}:getGoogleUpdated').replace(
/([^:]\/)\/+/g,
'$1'
),
method: 'GET',
},
options
),
params,
requiredParams: ['name'],
pathParams: ['name'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$GetGoogleUpdatedLodgingResponse>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$GetGoogleUpdatedLodgingResponse>(
parameters
);
}
}
}
export interface Params$Resource$Locations$Lodging$Getgoogleupdated
extends StandardParameters {
/**
* Required. Google identifier for this location in the form: `accounts/{account_id\}/locations/{location_id\}/lodging`
*/
name?: string;
/**
* Required. The specific fields to return. Use "*" to include all fields. Repeated field items cannot be individually specified.
*/
readMask?: string;
}
} | the_stack |
import * as _ from 'lodash';
import { callable } from './callable';
import {
ComponentSlotStyle,
ComponentSlotStylesInput,
ComponentSlotStylesPrepared,
ComponentVariablesInput,
ComponentVariablesPrepared,
FontFace,
SiteVariablesInput,
SiteVariablesPrepared,
StaticStyle,
ThemeAnimation,
ThemeComponentStylesInput,
ThemeComponentStylesPrepared,
ThemeComponentVariablesInput,
ThemeComponentVariablesPrepared,
ThemeInput,
ThemePrepared,
} from './types';
import { isEnabled as isDebugEnabled } from './debugEnabled';
import { deepmerge } from './deepmerge';
import { objectKeyToValues } from './objectKeysToValues';
import { toCompactArray } from './toCompactArray';
import { withDebugId } from './withDebugId';
export const emptyTheme: ThemePrepared = {
siteVariables: {
fontSizes: {},
},
componentVariables: {},
componentStyles: {},
fontFaces: [],
staticStyles: [],
animations: {},
};
// ----------------------------------------
// Component level merge functions
// ----------------------------------------
/**
* Merges a single component's styles (keyed by component part) with another component's styles.
*/
export const mergeComponentStyles__PROD: typeof mergeComponentStyles = (stylesA, stylesB) => {
const result = {};
if (stylesA) {
Object.keys(stylesA).forEach(partName => {
const slotA = stylesA[partName];
const slotB = stylesB?.[partName];
// if there is no source, merging is a no-op, skip it
if (typeof slotA === 'undefined' || slotA === null) {
return;
}
// no target means source doesn't need to merge onto anything
// just ensure source is callable (prepared format)
if (typeof slotB === 'undefined' || slotB === null) {
result[partName] = typeof slotA === 'function' ? slotA : () => slotA;
return;
}
if (slotA === slotB) {
result[partName] = typeof slotA === 'function' ? slotA : () => slotA;
}
});
}
if (stylesB) {
Object.keys(stylesB).forEach(partName => {
const slotA = stylesA?.[partName];
const slotB = stylesB[partName];
// if there is no source, merging is a no-op, skip it
if (typeof slotB === 'undefined' || slotB === null) {
return;
}
// no target means source doesn't need to merge onto anything
// just ensure source is callable (prepared format)
if (typeof slotA === 'undefined' || slotA === null) {
result[partName] = typeof slotB === 'function' ? slotB : () => slotB;
return;
}
if (slotA === slotB) {
return;
}
// We have both target and source, replace with merge fn
result[partName] = function mergedStyleFunction(styleParam) {
// originalTarget is always prepared, fn is guaranteed
return _.merge(
typeof slotA === 'function' ? slotA(styleParam) : slotA,
typeof slotB === 'function' ? slotB(styleParam) : slotB,
);
};
});
}
return result;
};
export const mergeComponentStyles__DEV: typeof mergeComponentStyles = (stylesA, stylesB) => {
if (!isDebugEnabled) {
return mergeComponentStyles__PROD(stylesA, stylesB);
}
const mergedKeys = [...(stylesA ? Object.keys(stylesA) : []), ...(stylesB ? Object.keys(stylesB) : [])];
const result = {};
mergedKeys.forEach(slotName => {
const slotA = styleParam => {
const { _debug = undefined, ...styles } = callable(stylesA?.[slotName])(styleParam) || {};
// new object required to prevent circular JSON structure error in <Debug />
return {
...styles,
_debug: _debug || [{ styles: { ...styles }, debugId: stylesA._debugId }],
};
};
const slotB = styleParam => {
const { _debug = undefined, ...styles } = callable(stylesB?.[slotName])(styleParam) || {};
// new object required to prevent circular JSON structure error in <Debug />
return {
...styles,
_debug: _debug || [{ styles: { ...styles }, debugId: stylesB._debugId }],
};
};
if (stylesA?.[slotName] && stylesB?.[slotName]) {
// We have both, replace with merge fn
result[slotName] = styleParam => {
// slot* are always prepared, fn is guaranteed, _debug always exists
const { _debug: debugA, ...resolvedStylesA } = slotA(styleParam);
const { _debug: debugB, ...resolvedStylesB } = slotB(styleParam);
const merged = _.merge(resolvedStylesA, resolvedStylesB);
merged._debug = debugA.concat(debugB || { styles: resolvedStylesB, debugId: resolvedStylesB._debugId });
return merged;
};
} else if (stylesA?.[slotName]) {
result[slotName] = slotA;
} else if (stylesB?.[slotName]) {
result[slotName] = slotB;
}
});
return result;
};
export const mergeComponentStyles: (
stylesA: ComponentSlotStylesInput | null | undefined,
stylesB: ComponentSlotStylesInput | null | undefined,
) => ComponentSlotStylesPrepared =
process.env.NODE_ENV === 'production' ? mergeComponentStyles__PROD : mergeComponentStyles__DEV;
/**
* Merges a single component's variables with another component's variables.
*/
export const mergeComponentVariables__PROD = (...sources: ComponentVariablesInput[]): ComponentVariablesPrepared => {
const initial = () => ({});
// filtering is required as some arguments can be undefined
const filteredSources = sources.filter(Boolean);
// a short circle to avoid calls of deepmerge()
if (filteredSources.length === 1) {
return typeof filteredSources[0] === 'function' ? filteredSources[0] : callable(filteredSources[0]);
}
return filteredSources.reduce<ComponentVariablesPrepared>((acc, next) => {
return function mergeComponentVariables(...args) {
const accumulatedVariables = acc(...args);
const fn = typeof next === 'function' ? next : callable(next);
const computedComponentVariables = fn(...args);
return deepmerge(accumulatedVariables, computedComponentVariables);
};
}, initial);
};
export const mergeComponentVariables__DEV = (...sources: ComponentVariablesInput[]): ComponentVariablesPrepared => {
if (!isDebugEnabled) {
return mergeComponentVariables__PROD(...sources);
}
const initial = () => ({});
return sources.reduce<ComponentVariablesPrepared>((acc, next) => {
return siteVariables => {
const { _debug = [], ...accumulatedVariables } = acc(siteVariables);
const { _debug: computedDebug = undefined, _debugId = undefined, ...computedComponentVariables } =
callable(next)(siteVariables) || {};
const merged = deepmerge(accumulatedVariables, computedComponentVariables);
merged._debug = _debug.concat(
computedDebug || {
resolved: computedComponentVariables,
debugId: _debugId,
input: siteVariables
? siteVariables._invertedKeys && callable(next)(siteVariables._invertedKeys)
: callable(next)(),
},
);
return merged;
};
}, initial);
};
export const mergeComponentVariables =
process.env.NODE_ENV === 'production' ? mergeComponentVariables__PROD : mergeComponentVariables__DEV;
// ----------------------------------------
// Theme level merge functions
// ----------------------------------------
/**
* Site variables can safely be merged at each Provider in the tree.
* They are flat objects and do not depend on render-time values, such as props.
*/
export const mergeSiteVariables__PROD = (
...sources: (SiteVariablesInput | null | undefined)[]
): SiteVariablesPrepared => {
const initial: SiteVariablesPrepared = {
fontSizes: {},
};
return deepmerge(initial, ...sources);
};
export const mergeSiteVariables__DEV = (
...sources: (SiteVariablesInput | null | undefined)[]
): SiteVariablesPrepared => {
if (!isDebugEnabled) {
return mergeSiteVariables__PROD(...sources);
}
const initial: SiteVariablesPrepared = {
fontSizes: {},
};
return sources.reduce<SiteVariablesPrepared>((acc, next) => {
const { _debug = [], ...accumulatedSiteVariables } = acc;
const { _debug: computedDebug = undefined, _invertedKeys = undefined, _debugId = undefined, ...nextSiteVariables } =
next || {};
const merged = deepmerge({ ...accumulatedSiteVariables, _invertedKeys: undefined }, nextSiteVariables);
merged._debug = _debug.concat(computedDebug || { resolved: nextSiteVariables, debugId: _debugId });
merged._invertedKeys = _invertedKeys || objectKeyToValues(merged, key => `siteVariables.${key}`);
return merged;
}, initial);
};
export const mergeSiteVariables =
process.env.NODE_ENV === 'production' ? mergeSiteVariables__PROD : mergeSiteVariables__DEV;
/**
* Component variables can be objects, functions, or an array of these.
* The functions must be called with the final result of siteVariables, otherwise
* the component variable objects would have no ability to apply siteVariables.
* Therefore, componentVariables must be resolved by the component at render time.
* We instead pass down call stack of component variable functions to be resolved later.
*/
export const mergeThemeVariables__PROD = (
...sources: (ThemeComponentVariablesInput | null | undefined)[]
): ThemeComponentVariablesPrepared => {
const displayNames = _.union(..._.map(sources, _.keys));
return displayNames.reduce((componentVariables, displayName) => {
componentVariables[displayName] = mergeComponentVariables(..._.map(sources, displayName));
return componentVariables;
}, {});
};
export const mergeThemeVariables__DEV = (
...sources: (ThemeComponentVariablesInput | null | undefined)[]
): ThemeComponentVariablesPrepared => {
if (!isDebugEnabled) {
return mergeThemeVariables__PROD(...sources);
}
const displayNames = _.union(..._.map(sources, _.keys));
return displayNames.reduce((componentVariables, displayName) => {
componentVariables[displayName] = mergeComponentVariables(
..._.map(sources, source => source && withDebugId(source[displayName], source._debugId)),
);
return componentVariables;
}, {});
};
export const mergeThemeVariables =
process.env.NODE_ENV === 'production' ? mergeThemeVariables__PROD : mergeThemeVariables__DEV;
/**
* See mergeThemeVariables() description.
* Component styles adhere to the same pattern as component variables, except
* that they return style objects.
*/
export const mergeThemeStyles = (
...sources: (ThemeComponentStylesInput | null | undefined)[]
): ThemeComponentStylesPrepared => {
const initial: ThemeComponentStylesPrepared = {};
return sources.reduce<ThemeComponentStylesPrepared>((themeComponentStyles, next) => {
_.forEach(next, (stylesByPart, displayName) => {
themeComponentStyles[displayName] = mergeComponentStyles(
themeComponentStyles[displayName],
withDebugId(stylesByPart, (next as ThemeComponentStylesPrepared & { _debugId: string })._debugId),
);
});
return themeComponentStyles;
}, initial);
};
export const mergeFontFaces = (...sources: FontFace[]) => {
return toCompactArray<FontFace>(...sources);
};
export const mergeStaticStyles = (...sources: StaticStyle[]) => {
return toCompactArray<StaticStyle>(...sources);
};
export const mergeAnimations = (...sources: { [key: string]: ThemeAnimation }[]): { [key: string]: ThemeAnimation } => {
return Object.assign({}, ...sources);
};
export const mergeStyles = (...sources: ComponentSlotStyle[]) => {
return (...args) => {
return sources.reduce((acc, next) => {
return _.merge(acc, callable(next)(...args));
}, {});
};
};
export const mergeThemes = (...themes: ThemeInput[]): ThemePrepared => {
return themes.reduce<ThemePrepared>(
(acc: ThemePrepared, next: ThemeInput) => {
if (!next) return acc;
const nextDebugId = next['_debugId'];
acc.siteVariables = mergeSiteVariables(acc.siteVariables, withDebugId(next.siteVariables, nextDebugId));
acc.componentVariables = mergeThemeVariables(
acc.componentVariables,
withDebugId(next.componentVariables, nextDebugId),
);
acc.componentStyles = mergeThemeStyles(acc.componentStyles, withDebugId(next.componentStyles, nextDebugId));
acc.fontFaces = mergeFontFaces(...acc.fontFaces, ...(next.fontFaces || []));
acc.staticStyles = mergeStaticStyles(...acc.staticStyles, ...(next.staticStyles || []));
acc.animations = mergeAnimations(acc.animations, next.animations);
return acc;
},
// .reduce() will modify "emptyTheme" object, so we should clone it before actual usage
{ ...emptyTheme },
);
}; | the_stack |
* @module WebGL
*/
import { assert } from "@itwin/core-bentley";
import { DrawParams } from "../DrawCommand";
import { UniformHandle } from "../UniformHandle";
import { Matrix4 } from "../Matrix";
import { Pass, TextureUnit } from "../RenderFlags";
import { IsInstanced, PositionType } from "../TechniqueFlags";
import { VariableType, VertexShaderBuilder } from "../ShaderBuilder";
import { System } from "../System";
import { decode3Float32, decodeUint16, decodeUint24 } from "./Decode";
import { addInstanceOverrides } from "./Instancing";
import { addLookupTable } from "./LookupTable";
const initializeVertLUTCoords = `
g_vertexLUTIndex = decodeUInt24(qpos);
g_vertexBaseCoords = compute_vert_coords(g_vertexLUTIndex);
`;
/** @internal */
export const unquantizePosition = `
vec4 unquantizePosition(vec3 pos, vec3 origin, vec3 scale) { return vec4(origin + scale * pos, 1.0); }
`;
const computeQuantizedPosition = `
vec4 computeVertexPosition(vec3 pos) { return unquantizePosition(pos, u_qOrigin, u_qScale); }
`;
// Need to read 2 rgba values to obtain 6 16-bit integers for position
const computeVertexPositionFromLUT = `
vec4 computeVertexPosition(vec3 encodedIndex) {
vec3 qpos = vec3(decodeUInt16(g_vertLutData0.xy), decodeUInt16(g_vertLutData0.zw), decodeUInt16(g_vertLutData1.xy));
g_featureAndMaterialIndex = g_vertLutData2;
return unquantizePosition(qpos, u_qOrigin, u_qScale);
}
`;
const computeUnquantizedPosition1 = `
vec4 computeVertexPosition(vec3 encodedIndex) {
vec3 pf[4];
pf[0] = g_vertLutData0.xyz;
g_featureAndMaterialIndex.x = g_vertLutData0.w;
pf[1] = g_vertLutData1.xyz;
g_featureAndMaterialIndex.y = g_vertLutData1.w;
pf[2] = g_vertLutData2.xyz;
g_featureAndMaterialIndex.z = g_vertLutData2.w;
pf[3] = g_vertLutData3.xyz;
g_featureAndMaterialIndex.w = g_vertLutData3.w;
return vec4(decode3Float32(pf), 1.0);
}
`;
const computeUnquantizedPosition2 = `
vec4 computeVertexPosition(vec3 encodedIndex) {
uvec3 vux = uvec3(g_vertLutData0.xyz);
g_featureAndMaterialIndex.x = g_vertLutData0.w;
uvec3 vuy = uvec3(g_vertLutData1.xyz);
g_featureAndMaterialIndex.y = g_vertLutData1.w;
uvec3 vuz = uvec3(g_vertLutData2.xyz);
g_featureAndMaterialIndex.z = g_vertLutData2.w;
uvec3 vuw = uvec3(g_vertLutData3.xyz);
g_featureAndMaterialIndex.w = g_vertLutData3.w;
uvec3 u = (vuw << 24) | (vuz << 16) | (vuy << 8) | vux;
return vec4(uintBitsToFloat(u), 1.0);
}
`;
const computeLineWeight = "\nfloat computeLineWeight() { return g_lineWeight; }\n";
const computeLineCode = "\nfloat computeLineCode() { return g_lineCode; }\n";
export function addSamplePosition(vert: VertexShaderBuilder): void {
vert.addFunction(getSamplePosition(vert.positionType));
}
function getSamplePosition(type: PositionType): string {
const prelude = `
vec4 samplePosition(float index) {
vec2 tc = compute_vert_coords(index);`;
if ("quantized" === type) {
return `
${prelude}
vec4 e0 = floor(TEXTURE(u_vertLUT, tc) * 255.0 + 0.5);
tc.x += g_vert_stepX;
vec4 e1 = floor(TEXTURE(u_vertLUT, tc) * 255.0 + 0.5);
vec3 qpos = vec3(decodeUInt16(e0.xy), decodeUInt16(e0.zw), decodeUInt16(e1.xy));
return unquantizePosition(qpos, u_qOrigin, u_qScale);
}
`;
}
if (System.instance.capabilities.isWebGL2) {
return `
${prelude}
uvec3 vux = uvec3(floor(TEXTURE(u_vertLUT, tc).xyz * 255.0 + 0.5));
tc.x += g_vert_stepX;
uvec3 vuy = uvec3(floor(TEXTURE(u_vertLUT, tc).xyz * 255.0 + 0.5));
tc.x += g_vert_stepX;
uvec3 vuz = uvec3(floor(TEXTURE(u_vertLUT, tc).xyz * 255.0 + 0.5));
tc.x += g_vert_stepX;
uvec3 vuw = uvec3(floor(TEXTURE(u_vertLUT, tc).xyz * 255.0 + 0.5));
uvec3 u = (vuw << 24) | (vuz << 16) | (vuy << 8) | vux;
return vec4(uintBitsToFloat(u), 1.0);
}`;
}
return `
${prelude}
vec3 pf[4];
pf[0] = floor(TEXTURE(u_vertLUT, tc).xyz * 255.0 + 0.5);
tc.x += g_vert_stepX;
pf[1] = floor(TEXTURE(u_vertLUT, tc).xyz * 255.0 + 0.5);
tc.x += g_vert_stepX;
pf[2] = floor(TEXTURE(u_vertLUT, tc).xyz * 255.0 + 0.5);
tc.x += g_vert_stepX;
pf[3] = floor(TEXTURE(u_vertLUT, tc).xyz * 255.0 + 0.5);
return vec4(decode3Float32(pf), 1.0);
}`;
}
/** @internal */
export function addModelViewProjectionMatrix(vert: VertexShaderBuilder): void {
if (vert.usesInstancedGeometry) {
addModelViewMatrix(vert);
addProjectionMatrix(vert);
vert.addGlobal("g_mvp", VariableType.Mat4);
vert.addInitializer("g_mvp = u_proj * g_mv;");
} else {
vert.addUniform("u_mvp", VariableType.Mat4, (prog) => {
prog.addGraphicUniform("u_mvp", (uniform, params) => {
params.target.uniforms.branch.bindModelViewProjectionMatrix(uniform, params.geometry, params.isViewCoords);
});
});
}
}
/** @internal */
export function addProjectionMatrix(vert: VertexShaderBuilder): void {
vert.addUniform("u_proj", VariableType.Mat4, (prog) => {
prog.addProgramUniform("u_proj", (uniform, params) => {
params.bindProjectionMatrix(uniform);
});
});
}
const computeInstancedRtcMatrix = `
g_instancedRtcMatrix = u_instanced_rtc * g_modelMatrixRTC;
`;
/** @internal */
export function addInstancedRtcMatrix(vert: VertexShaderBuilder): void {
if (!vert.usesInstancedGeometry)
return;
assert(undefined !== vert.find("g_modelMatrixRTC")); // set up in VertexShaderBuilder constructor...
vert.addUniform("u_instanced_rtc", VariableType.Mat4, (prog) => {
prog.addGraphicUniform("u_instanced_rtc", (uniform, params) => {
const modelt = params.geometry.asInstanced!.getRtcOnlyTransform();
uniform.setMatrix4(Matrix4.fromTransform(modelt));
});
});
vert.addGlobal("g_instancedRtcMatrix", VariableType.Mat4);
vert.addInitializer(computeInstancedRtcMatrix);
}
/** @internal */
export function addModelViewMatrix(vert: VertexShaderBuilder): void {
const bind = (uniform: UniformHandle, params: DrawParams) => {
params.target.uniforms.branch.bindModelViewMatrix(uniform, params.geometry, params.isViewCoords);
};
if (vert.usesInstancedGeometry) {
vert.addUniform("u_instanced_modelView", VariableType.Mat4, (prog) => {
prog.addGraphicUniform("u_instanced_modelView", bind);
});
vert.addGlobal("g_mv", VariableType.Mat4);
vert.addInitializer("g_mv = u_instanced_modelView * g_modelMatrixRTC;");
} else {
vert.addUniform("u_mv", VariableType.Mat4, (prog) => {
// ###TODO: We only need 3 rows, not 4...
prog.addGraphicUniform("u_mv", bind);
});
}
}
const computeNormalMatrix = `
g_nmx = mat3(u_modelViewN);
g_nmx[0][0] *= u_frustumScale.x;
g_nmx[1][1] *= u_frustumScale.y;
`;
const computeNormalMatrix2 = `
g_nmx = transpose(inverse(mat3(MAT_MV)));
g_nmx[0][0] *= u_frustumScale.x;
g_nmx[1][1] *= u_frustumScale.y;
`;
const computeNormalMatrix1Inst = `
g_nmx = mat3(MAT_MV);
g_nmx[0][0] *= u_frustumScale.x;
g_nmx[1][1] *= u_frustumScale.y;
`;
/** @internal */
export function addNormalMatrix(vert: VertexShaderBuilder, instanced: IsInstanced) {
vert.addGlobal("g_nmx", VariableType.Mat3);
vert.addUniform("u_frustumScale", VariableType.Vec2, (prog) => {
prog.addGraphicUniform("u_frustumScale", (uniform, params) => {
const scale = params.target.uniforms.branch.top.frustumScale;
uniform.setUniform2fv([scale.x, scale.y]);
});
});
if (System.instance.capabilities.isWebGL2) {
vert.addInitializer(computeNormalMatrix2);
} else if (IsInstanced.Yes === instanced) {
vert.addInitializer(computeNormalMatrix1Inst);
} else {
vert.addUniform("u_modelViewN", VariableType.Mat3, (prog) => {
prog.addGraphicUniform("u_modelViewN", (uniform, params) => {
params.target.uniforms.branch.bindModelViewNTransform(uniform, params.geometry, false);
});
});
vert.addInitializer(computeNormalMatrix);
}
}
function readVertexData(index: number): string {
return `g_vertLutData${index} = floor(TEXTURE(u_vertLUT, tc) * 255.0 + 0.5);`;
}
const nextVertexData = "tc.x += g_vert_stepX;";
function readNextVertexData(index: number): string {
return `
${nextVertexData}
${readVertexData(index)}`;
}
const prereadVertexDataPrelude = `
vec2 tc = g_vertexBaseCoords;
${readVertexData(0)}
${readNextVertexData(1)}
${readNextVertexData(2)}
`;
const prereadQuantizedVertexData = `${prereadVertexDataPrelude}
if (3.0 < u_vertParams.z) {
${readNextVertexData(3)}
}
`;
const prereadUnquantizedVertexData = `${prereadVertexDataPrelude}
${readNextVertexData(3)}
${readNextVertexData(4)}
if (5.0 < u_vertParams.z) {
${readNextVertexData(5)}
}
`;
const scratchLutParams = new Float32Array(4);
function addPositionFromLUT(vert: VertexShaderBuilder) {
vert.addGlobal("g_vertexLUTIndex", VariableType.Float);
vert.addGlobal("g_vertexBaseCoords", VariableType.Vec2);
const unquantized = "unquantized" === vert.positionType;
const maxRgbaPerVert = unquantized ? 6 : 4;
for (let i = 0; i < maxRgbaPerVert; i++)
vert.addGlobal(`g_vertLutData${i}`, VariableType.Vec4);
vert.addFunction(decodeUint24);
vert.addFunction(decodeUint16);
if (unquantized) {
if (System.instance.capabilities.isWebGL2) {
vert.addFunction(computeUnquantizedPosition2);
} else {
vert.addFunction(decode3Float32);
vert.addFunction(computeUnquantizedPosition1);
}
} else {
vert.addFunction(computeVertexPositionFromLUT);
}
vert.addUniform("u_vertLUT", VariableType.Sampler2D, (prog) => {
prog.addGraphicUniform("u_vertLUT", (uniform, params) => {
(params.geometry.asLUT!).lut.texture.bindSampler(uniform, TextureUnit.VertexLUT);
});
});
vert.addUniform("u_vertParams", VariableType.Vec4, (prog) => {
prog.addGraphicUniform("u_vertParams", (uniform, params) => {
assert(undefined !== params.geometry.asLUT);
const lut = params.geometry.asLUT.lut;
const lutParams = scratchLutParams;
lutParams[0] = lut.texture.width;
lutParams[1] = lut.texture.height;
lutParams[2] = lut.numRgbaPerVertex;
lutParams[3] = lut.numVertices;
uniform.setUniform4fv(lutParams);
});
});
addLookupTable(vert, "vert", "u_vertParams.z");
vert.addInitializer(initializeVertLUTCoords);
vert.addGlobal("g_featureAndMaterialIndex", VariableType.Vec4);
// Read the vertex data from the vertex table up front. Yields a consistent (if unexplainable) small performance boost.
vert.addInitializer(unquantized ? prereadUnquantizedVertexData : prereadQuantizedVertexData);
}
/** @internal */
export function addPosition(vert: VertexShaderBuilder, fromLUT: boolean) {
if (!fromLUT || "quantized" === vert.positionType) {
vert.addFunction(unquantizePosition);
vert.addUniform("u_qScale", VariableType.Vec3, (prog) => {
prog.addGraphicUniform("u_qScale", (uniform, params) => {
assert(params.geometry.usesQuantizedPositions);
uniform.setUniform3fv(params.geometry.qScale);
});
});
vert.addUniform("u_qOrigin", VariableType.Vec3, (prog) => {
prog.addGraphicUniform("u_qOrigin", (uniform, params) => {
assert(params.geometry.usesQuantizedPositions);
uniform.setUniform3fv(params.geometry.qOrigin);
});
});
}
if (!fromLUT) {
vert.addFunction(computeQuantizedPosition);
} else {
addPositionFromLUT(vert);
}
}
/** @internal */
export function addAlpha(vert: VertexShaderBuilder): void {
vert.addUniform("u_hasAlpha", VariableType.Float, (prog) => {
prog.addGraphicUniform("u_hasAlpha", (uniform, params) => {
uniform.setUniform1f(Pass.rendersTranslucent(params.geometry.getPass(params.target)) ? 1 : 0);
});
});
}
/** @internal */
export function addLineWeight(vert: VertexShaderBuilder): void {
vert.addUniform("u_lineWeight", VariableType.Float, (prog) => {
prog.addGraphicUniform("u_lineWeight", (attr, params) => {
attr.setUniform1f(params.geometry.getLineWeight(params.programParams));
});
});
vert.addGlobal("g_lineWeight", VariableType.Float);
if (vert.usesInstancedGeometry) {
addInstanceOverrides(vert);
vert.addInitializer("g_lineWeight = mix(u_lineWeight, a_instanceOverrides.g, extractInstanceBit(kOvrBit_Weight));");
} else {
vert.addInitializer("g_lineWeight = u_lineWeight;");
}
vert.addFunction(computeLineWeight);
}
/** @internal */
export function replaceLineWeight(vert: VertexShaderBuilder, func: string): void {
vert.replaceFunction(computeLineWeight, func);
}
/** @internal */
export function addLineCode(vert: VertexShaderBuilder): void {
vert.addUniform("u_lineCode", VariableType.Float, (prog) => {
prog.addGraphicUniform("u_lineCode", (attr, params) => {
attr.setUniform1f(params.geometry.getLineCode(params.programParams));
});
});
vert.addGlobal("g_lineCode", VariableType.Float);
if (vert.usesInstancedGeometry) {
addInstanceOverrides(vert);
vert.addInitializer("g_lineCode = mix(u_lineCode, a_instanceOverrides.b, extractInstanceBit(kOvrBit_LineCode));");
} else {
vert.addInitializer("g_lineCode = u_lineCode;");
}
vert.addFunction(computeLineCode);
}
/** @internal */
export function replaceLineCode(vert: VertexShaderBuilder, func: string): void {
vert.replaceFunction(computeLineCode, func);
}
// This vertex belongs to a triangle which should not be rendered. Produce a degenerate triangle.
// Also place it outside NDC range (for GL_POINTS)
const discardVertex = ` {
gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
return;
}
`;
/** @internal */
export const earlyVertexDiscard = ` if (checkForEarlyDiscard(rawPosition))${discardVertex}`;
/** @internal */
export const vertexDiscard = ` if (checkForDiscard())${discardVertex}`;
/** @internal */
export const lateVertexDiscard = ` if (checkForLateDiscard())${discardVertex}`; | the_stack |
import { fetchAddr, fetchSize, sanitizeAddr } from '../../backend/backUtils';
import { ConstraintSet } from '../../backend/constraintSet';
import { Constraint } from '../../backend/constraintType';
import { Context, ContextSet } from '../../backend/context';
import {
absExpIndexByLen,
isInstanceOf,
reluLen,
simplifyBool,
simplifyNum,
simplifyShape,
} from '../../backend/expUtils';
import {
CodeSource,
ShValue,
SVError,
SVErrorLevel,
SVNone,
SVObject,
SVSize,
SVType,
} from '../../backend/sharpValues';
import { BoolOpType, ExpBool, ExpNum, ExpShape, NumBopType, NumOpType, NumUopType } from '../../backend/symExpressions';
import { TorchBackend } from '../../backend/torchBackend';
import { LCImpl } from '..';
import { LCBase } from '../libcall';
export namespace NumpyLCImpl {
function genNdarray<T>(ctx: Context<T>, shape: ExpShape, source: CodeSource | undefined): ContextSet<ShValue> {
const newShape = simplifyShape(ctx.ctrSet, shape);
const size = SVSize.createSize(ctx, newShape, source);
return TorchBackend.libClassInit(ctx, 'numpy.ndarray', [size.retVal], source);
}
// return tuple of ExpNums from SVObject.
function getExpNumTuple(obj: SVObject, ctrSet: ConstraintSet): (number | ExpNum)[] | string {
const length = obj.getAttr('$length');
if (length === undefined || !(length.type === SVType.Int)) {
return `attribute '$length' is not an int`;
}
let len = typeof length.value === 'number' ? length.value : simplifyNum(ctrSet, length.value);
if (typeof len !== 'number' && !(len.opType === NumOpType.Const)) {
return `length is not const`;
}
len = typeof len === 'number' ? len : len.value;
const intTuple: (number | ExpNum)[] = [];
for (let i = 0; i < len; i++) {
const elem = obj.getIndice(i);
if (elem === undefined || elem.type !== SVType.Int) {
return `an element of tuple is not an int`;
}
const num = elem.value;
intTuple.push(num);
}
return intTuple;
}
export function warnNdarrayWithMsg(
ctx: Context<unknown>,
message: string,
source: CodeSource | undefined
): ContextSet<ShValue> {
const warning = SVError.create(message, SVErrorLevel.Warning, source);
const newCtx = ctx.addLogValue(warning);
const rank = newCtx.genSymInt('WarnTempRank', source);
const shape = newCtx.genSymShape('WarnTempShape', ExpNum.fromSymbol(rank), source);
return genNdarray(newCtx, ExpShape.fromSymbol(shape), source);
}
export function genInitShape(
ctx: Context<LCBase.ExplicitParams>,
source: CodeSource | undefined
): ContextSet<ShValue> {
const params = ctx.retVal.params;
if (params.length !== 2) {
return ctx
.warnSizeWithMsg(
`from 'LibCall.numpy.ndarrayInit': got insufficient number of argument: ${params.length}`,
source
)
.toSet();
}
const heap = ctx.heap;
const [selfAddr, shapeAddr] = params;
// ndarrayInit is always used in ndarray.__init__ -> force casting
const self = fetchAddr(selfAddr, heap)! as SVObject;
return ctx.parseSize(shapeAddr, source).map((ctx) => {
let shape: ExpShape;
let newCtx: Context<any> = ctx;
if (typeof ctx.retVal === 'string') {
newCtx = ctx.addLog(ctx.retVal, source).genIntGte('tempRank', 0, source);
shape = ExpShape.fromSymbol(newCtx.genSymShape('tempShape', newCtx.retVal, source));
} else {
shape = ctx.retVal;
}
const ctx2 = SVSize.createSize(newCtx, shape, source);
const newHeap = ctx2.heap.setVal(self.addr, self.setAttr('shape', ctx2.retVal));
return ctx2.setHeap(newHeap);
});
}
// implementation slice of np.ndarray.__getitem__
// axis range is already checked from ndarray.__getitem__
// params: [inputShape, axis, index]
export function ndarrayGetItem(
ctx: Context<LCBase.ExplicitParams>,
source: CodeSource | undefined
): ContextSet<ShValue> {
const params = ctx.retVal.params;
if (params.length !== 3) {
return ctx
.warnWithMsg(
`from 'LibCall.shape.tensorGetItem': got insufficient number of argument: ${params.length}`,
source
)
.toSet();
}
const { env, heap } = ctx;
const [sizeAddr, axisAddr, indexAddr] = params;
const size = fetchAddr(sizeAddr, heap);
const axis = fetchAddr(axisAddr, heap);
const index = fetchAddr(indexAddr, heap);
const mayTensorIndex = fetchSize(indexAddr, heap);
if (!(size && size instanceof SVSize)) {
return ctx.warnWithMsg(`from 'LibCall.shape.tensorGetItem': input is not a Size type`, source).toSet();
}
if (!(axis && axis.type === SVType.Int && typeof axis.value === 'number')) {
return ctx.warnWithMsg(`from 'LibCall.shape.tensorGetItem': axis is not a number`, source).toSet();
}
if (!index) {
return ctx.warnWithMsg(`from 'LibCall.shape.tensorGetItem': index is undefined`, source).toSet();
}
const slice = sanitizeAddr(ctx.env.getId('slice'), heap);
const shape = size.shape;
const axisValue = axis.value;
if (index.type === SVType.Int) {
// index is contant int
const indexNum = index.value;
const indexDim = ExpNum.index(shape, axisValue, source);
return ctx
.require(
[
ctx.genLte(ExpNum.bop(NumBopType.Sub, 0, indexDim, source), indexNum, source),
ctx.genLte(indexNum, ExpNum.bop(NumBopType.Sub, indexDim, 1, source), source),
],
`from 'LibCall.shape.tensorGetItem': index out of range`,
source
)
.map((ctx) => {
const left = ExpShape.slice(shape, undefined, axisValue, source);
const right = ExpShape.slice(
shape,
ExpNum.bop(NumBopType.Add, axisValue, 1, source),
undefined,
source
);
const result = simplifyShape(ctx.ctrSet, ExpShape.concat(left, right, source));
return SVSize.createSize(ctx, result, source);
});
} else if (index.type === SVType.Object) {
if (slice && isInstanceOf(index, slice, env, heap) === true) {
const start = fetchAddr(index.getAttr('start'), heap);
const end = fetchAddr(index.getAttr('stop'), heap);
const step = fetchAddr(index.getAttr('step'), heap);
const currDim = ExpNum.index(shape, axisValue, source);
let hasError = false;
let startN, endN, stepN: ExpNum | number | undefined;
if (start?.type === SVType.Int) startN = start.value;
else if (!(start?.type === SVType.None)) hasError = true;
if (end?.type === SVType.Int) endN = end.value;
else if (!(end?.type === SVType.None)) hasError = true;
if (step?.type === SVType.Int) stepN = step.value;
else if (!(step?.type === SVType.None)) hasError = true;
if (hasError) {
return ctx
.warnWithMsg(
`from 'LibCall.shape.tensorGetItem: slice value is not an integer or None.`,
source
)
.toSet();
}
const ctrList: Constraint[] = [];
if (startN !== undefined) {
startN = absExpIndexByLen(startN, currDim, source, ctx.ctrSet);
ctrList.push(ctx.genLte(0, startN, source));
} else {
startN = 0;
}
if (endN !== undefined) {
endN = absExpIndexByLen(endN, currDim, source, ctx.ctrSet);
ctrList.push(ctx.genLte(0, endN, source));
} else {
endN = currDim;
}
// return ceil((endN - startN) // stepN)
let newDim = reluLen(startN, endN, source, ctx.ctrSet);
if (stepN === undefined) stepN = 1;
if (typeof stepN !== 'number' || stepN !== 1) {
newDim = ExpNum.uop(NumUopType.Ceil, ExpNum.bop(NumBopType.TrueDiv, newDim, stepN, source), source);
}
const newShape = simplifyShape(ctx.ctrSet, ExpShape.setDim(shape, axisValue, newDim, source));
if (ctrList.length === 0) {
return SVSize.createSize(ctx, newShape, source).toSet();
}
return ctx
.require(ctrList, 'index out of range', source)
.map((ctx) => SVSize.createSize(ctx, newShape, source));
} else if (mayTensorIndex && mayTensorIndex instanceof SVSize) {
// TOOD: distinguish dtype of tensor
// TODO: Implement other advanced tensor indexing
// https://numpy.org/doc/stable/reference/arrays.indexing.html
// mask indexing
const sizeNumel = ExpNum.numel(shape, source);
const mask = mayTensorIndex;
const maskCtx = ctx.genIntGte('maskIndex', 0, source);
const maskNum = maskCtx.retVal;
return maskCtx
.require(
[maskCtx.genLte(maskNum, sizeNumel, source), maskCtx.genEq(shape, mask.shape, source)],
`from 'LibCall.tensor.getItem: Shape of mask must match.`,
source
)
.flatMap((ctx) => {
return genNdarray(ctx, ExpShape.fromConst(1, [maskNum], source), source);
});
}
}
return ctx
.warnWithMsg(
`from 'LibCall.tensor.getItem: only indexing by integer, slice or bool tensor is supported currently.`,
source
)
.toSet();
}
// A replica of torch.identityShape() in torch/index.ts
export function identityShape(
ctx: Context<LCBase.ExplicitParams>,
source: CodeSource | undefined
): ContextSet<ShValue> {
const params = ctx.retVal.params;
if (params.length !== 1) {
return warnNdarrayWithMsg(
ctx,
`from 'LibCall.numpy.identityShape': got insufficient number of argument: ${params.length}`,
source
);
}
const heap = ctx.heap;
const inputAddr = params[0];
const inputSize = fetchSize(inputAddr, heap);
if (typeof inputSize === 'string') {
return warnNdarrayWithMsg(ctx, `from 'LibCall.numpy.identityShape': ${inputSize}`, source);
}
const inputShape = inputSize.shape;
return genNdarray(ctx, inputShape, source);
}
// A replica of torch.broadcast() in torch/index.ts
export function broadcast(
ctx: Context<LCBase.ExplicitParams>,
source: CodeSource | undefined
): ContextSet<ShValue> {
const params = ctx.retVal.params;
if (params.length !== 2) {
return warnNdarrayWithMsg(
ctx,
`from 'LibCall.numpy.broadcast': got insufficient number of argument: ${params.length}`,
source
);
}
const heap = ctx.heap;
const [leftAddr, rightAddr] = params;
const leftSize = fetchSize(leftAddr, heap);
const rightSize = fetchSize(rightAddr, heap);
if (typeof leftSize === 'string') {
return warnNdarrayWithMsg(ctx, `from 'LibCall.numpy.broadcast': ${leftSize}`, source);
} else if (typeof rightSize === 'string') {
return warnNdarrayWithMsg(ctx, `from 'LibCall.numpy.broadcast': ${rightSize}`, source);
}
const leftShape = leftSize.shape;
const rightShape = rightSize.shape;
return ctx.shBroadcast(leftShape, rightShape, source).flatMap((ctx) => genNdarray(ctx, ctx.retVal, source));
}
// A replica of torch.matmul() in torch/index.ts
export function matmul(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> {
const params = ctx.retVal.params;
if (params.length !== 2) {
return warnNdarrayWithMsg(
ctx,
`from 'LibCall.numpy.matmul': got insufficient number of argument: ${params.length}`,
source
);
}
const heap = ctx.heap;
const [leftAddr, rightAddr] = params;
const leftSize = fetchSize(leftAddr, heap);
const rightSize = fetchSize(rightAddr, heap);
if (typeof leftSize === 'string') {
return warnNdarrayWithMsg(ctx, `from 'LibCall.numpy.matmul': ${leftSize}`, source);
} else if (typeof rightSize === 'string') {
return warnNdarrayWithMsg(ctx, `from 'LibCall.numpy.matmul': ${rightSize}`, source);
}
const leftShape = leftSize.shape;
const rightShape = rightSize.shape;
const leftRank = leftSize.rank();
const rightRank = rightSize.rank();
return ctx
.require(
[ctx.genLte(1, leftRank, source), ctx.genLte(1, rightRank, source)],
`from 'LibCall.numpy.matmul': cannot do matmul with scalar tensor`,
source
)
.flatMap((ctx) => {
const isLeftRankOne = ctx.genEq(1, leftRank, source);
const [leftOnePath, leftTwoPath] = ctx.ifThenElse(isLeftRankOne, source);
const leftPath = leftOnePath.flatMap((ctx) => {
const isRightRankOne = ctx.genEq(1, rightRank, source);
const [rightOnePath, rightTwoPath] = ctx.ifThenElse(isRightRankOne, source);
const lr11 = rightOnePath
.flatMap((ctx) => {
const sameDim = ctx.genEq(
ExpNum.index(leftShape, 0, source),
ExpNum.index(rightShape, 0, source),
source
);
return ctx.require(
[sameDim],
`from 'LibCall.numpy.matmul': dimension mismatch between rank-1 tensors`,
source
);
})
.flatMap((ctx) => genNdarray(ctx, ExpShape.fromConst(0, [], source), source));
const rightAxis = ExpNum.bop(NumBopType.Sub, rightRank, 2, source);
const lr12 = rightTwoPath
.flatMap((ctx) => {
const sameDim = ctx.genEq(
ExpNum.index(leftShape, 0, source),
ExpNum.index(rightShape, rightAxis, source),
source
);
return ctx.require(
[sameDim],
`from 'LibCall.numpy.matmul: dimension mismatch between rank-1 @ rank-n`,
source
);
})
.flatMap((ctx) => ctx.shReduce(rightShape, rightAxis, source))
.flatMap((ctx) => genNdarray(ctx, ctx.retVal, source));
return lr11.join(lr12);
});
const rightPath = leftTwoPath.flatMap((ctx) => {
const isRightRankOne = ctx.genEq(1, rightRank, source);
const [rightOnePath, rightTwoPath] = ctx.ifThenElse(isRightRankOne, source);
const leftAxis = ExpNum.bop(NumBopType.Sub, leftRank, 1, source);
const lr21 = rightOnePath
.flatMap((ctx) => {
const sameDim = ctx.genEq(
ExpNum.index(leftShape, leftAxis, source),
ExpNum.index(rightShape, 0, source),
source
);
return ctx.require(
[sameDim],
`from 'LibCall.numpy.matmul': dimension mismatch between rank-n @ rank-1`,
source
);
})
.flatMap((ctx) => ctx.shReduce(leftShape, leftAxis, source))
.flatMap((ctx) => genNdarray(ctx, ctx.retVal, source));
const lr22 = rightTwoPath
.flatMap((ctx) => ctx.shMatmul(leftShape, rightShape, source))
.flatMap((ctx) => genNdarray(ctx, ctx.retVal, source));
return lr21.join(lr22);
});
return leftPath.join(rightPath);
});
}
// Assumption: "tensors" is a constantRanked sequence, and each element is available.
// TODO: handle empty tensor.
export function concatenate(
ctx: Context<LCBase.ExplicitParams>,
source: CodeSource | undefined
): ContextSet<ShValue> {
const params = ctx.retVal.params;
if (params.length !== 2) {
return ctx
.warnWithMsg(
`from 'LibCall.numpy.concatenate': got insufficient number of argument: ${params.length}`,
source
)
.toSet();
}
const heap = ctx.heap;
const [seqAddr, axisAddr] = params;
const seq = fetchAddr(seqAddr, heap);
const axisSV = fetchAddr(axisAddr, heap);
if (seq?.type !== SVType.Object) {
return ctx.warnWithMsg(`from 'LibCall.numpy.concatenate': array sequence is not iterable`, source).toSet();
} else if (axisSV?.type !== SVType.Int) {
return ctx.warnWithMsg(`from 'LibCall.numpy.concatenate': axis is not an integer`, source).toSet();
}
// Assumption: length of "tensors" is constant.
const seqLen_ = fetchAddr(seq.getAttr('$length'), heap);
if (!(seqLen_?.type === SVType.Int && typeof seqLen_.value === 'number')) {
return ctx
.warnWithMsg(
`from 'LibCall.numpy.concatenate': length of array sequence is unknown, cannot iterate.`,
source
)
.toSet();
} else if (seqLen_.value === 0) {
return ctx
.warnWithMsg(`from 'LibCall.numpy.concatenate': length of array sequence is zero.`, source)
.toSet();
}
const seqLen = seqLen_.value;
const size0 = fetchSize(seq.getIndice(0), heap);
if (typeof size0 === 'string') {
return ctx.warnWithMsg(`from 'LibCall.numpy.concatenate': ${size0}`, source).toSet();
}
const size0shape = size0.shape;
const size0rank = size0.rank();
const axis = absExpIndexByLen(axisSV.value, size0rank, source);
const shape0Front = ExpShape.slice(size0shape, 0, axis, source);
const shape0Back = ExpShape.slice(size0shape, ExpNum.bop(NumBopType.Add, axis, 1, source), size0rank, source);
// TODO: handle negative index.
const ctrs: Constraint[] = [ctx.genLte(0, axis, source), ctx.genLt(axis, size0rank, source)];
let thickness: ExpNum = ExpNum.index(size0shape, axis, source);
for (let i = 1; i < seqLen; i++) {
const sizeI = fetchSize(seq.getIndice(i), heap);
if (typeof sizeI === 'string') {
return warnNdarrayWithMsg(ctx, `from 'LibCall.numpy.concatenate': ${sizeI}`, source);
}
const sizeIshape = sizeI.shape;
const shapeIFront = ExpShape.slice(sizeIshape, 0, axis, source);
const shapeIBack = ExpShape.slice(
sizeIshape,
ExpNum.bop(NumBopType.Add, axis, 1, source),
size0rank,
source
);
ctrs.push(ctx.genEq(shape0Front, shapeIFront, source));
ctrs.push(ctx.genEq(shape0Back, shapeIBack, source));
thickness = ExpNum.bop(NumBopType.Add, thickness, ExpNum.index(sizeIshape, axis, source), source);
}
const shapeThick = ExpShape.fromConst(1, [thickness], source);
const returnShape_ = ExpShape.concat(shape0Front, shapeThick, source);
const returnShape = ExpShape.concat(returnShape_, shape0Back, source);
return ctx
.require(ctrs, `from 'LibCall.numpy.concatenate': shapes must match, axis must be within rank`, source)
.flatMap((ctx) => {
return genNdarray(ctx, returnShape, source);
});
}
export function copyOut(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> {
const params = ctx.retVal.params;
if (params.length !== 2) {
return ctx
.warnWithMsg(
`from 'LibCall.numpy.copyOut': got insufficient number of argument: ${params.length}`,
source
)
.toSet();
}
const heap = ctx.heap;
const [arrayAddr, outAddr] = params;
const array = fetchSize(arrayAddr, heap);
if (outAddr.type === SVType.None) {
return ctx.toSetWith(outAddr);
}
const out = fetchSize(outAddr, heap);
if (typeof array === 'string') {
return ctx.warnWithMsg(`from 'LibCall.numpy.copyOut': ${array}`, source).toSet();
}
if (typeof out === 'string') {
return ctx.warnWithMsg(`from 'LibCall.numpy.copyOut': ${out}`, source).toSet();
}
return ctx
.require(
ctx.genEq(array.shape, out.shape, source),
`from 'LibCall.numpy.copyOut': shapes must be equal`,
source
)
.return(SVNone.create(source));
}
export function reduce(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> {
const params = ctx.retVal.params;
if (params.length !== 3) {
return warnNdarrayWithMsg(
ctx,
`from 'LibCall.numpy.reduce': got insufficient number of argument: ${params.length}`,
source
);
}
const heap = ctx.heap;
const [selfAddr, axisAddr, keepdimsAddr] = params;
const selfSize = fetchSize(selfAddr, heap);
if (typeof selfSize === 'string') {
return warnNdarrayWithMsg(ctx, `from 'LibCall.numpy.reduce': ${selfSize}`, source);
}
const selfShape = selfSize.shape;
const selfRank = selfSize.rank();
let rankValue: number | undefined = undefined;
if (typeof selfRank === 'number') {
rankValue = selfRank;
} else {
const selfRank_ = simplifyNum(ctx.ctrSet, selfRank);
if (selfRank_.opType === NumOpType.Const) {
rankValue = selfRank_.value;
}
}
const axisSV = fetchAddr(axisAddr, heap);
const keepdims = fetchAddr(keepdimsAddr, heap);
if (
axisSV === undefined ||
(axisSV.type !== SVType.None && axisSV.type !== SVType.Int && axisSV.type !== SVType.Object)
) {
return ctx.failWithMsg(`from 'LibCall.numpy.reduce': invalid type of axis ${axisSV?.type}`, source).toSet();
} else if (keepdims === undefined || keepdims.type !== SVType.Bool) {
return ctx
.failWithMsg(`from 'LibCall.numpy.reduce': invalid type of keepdims ${keepdims?.type}`, source)
.toSet();
}
let keepdimsVal: boolean;
if (typeof keepdims.value === 'boolean') {
keepdimsVal = keepdims.value;
} else {
const keepdims_: ExpBool = simplifyBool(ctx.ctrSet, keepdims.value);
if (keepdims_.opType !== BoolOpType.Const) {
return warnNdarrayWithMsg(
ctx,
`from 'LibCall.numpy.reduce': cannot infer value of keepdims ${keepdims.value}`,
source
);
}
keepdimsVal = keepdims_.value;
}
// 1) axis is None. return a scalar value.
if (axisSV.type === SVType.None) {
if (keepdimsVal) {
if (rankValue !== undefined) {
const dims: number[] = [];
for (let i = 0; i < rankValue; i++) {
dims.push(1);
}
const shape = ExpShape.fromConst(rankValue, dims, source);
return genNdarray(ctx, shape, source);
} else {
const dim = ctx.genSymInt('dim', source);
const ctrEq = ctx.genEq(ExpNum.fromSymbol(dim), 1, source);
// TODO: what is this requirement?
return ctx
.require(
ctx.genForall(dim, [0, selfRank], ctrEq, source),
`from 'LibCall.numpy.reduce': dimension error`,
source
)
.flatMap((ctx) => {
return ctx.genRankedShape(selfRank, source).flatMap((ctx) => {
const rankedShape = ctx.retVal;
return genNdarray(ctx, rankedShape, source);
});
});
}
} else {
// TODO: data type
return genNdarray(ctx, ExpShape.fromConst(0, [], source), source);
}
}
// 2) axis is an integer.
else if (axisSV.type === SVType.Int) {
const axis = absExpIndexByLen(axisSV.value, selfRank, source, ctx.ctrSet);
const shapeFront = ExpShape.slice(selfShape, 0, axis, source);
const shapeBack = ExpShape.slice(selfShape, ExpNum.bop(NumBopType.Add, axis, 1, source), selfRank, source);
let newShape: ExpShape;
if (keepdimsVal) {
const newDim = ExpShape.fromConst(1, [1], source);
const newShape_ = ExpShape.concat(shapeFront, newDim, source);
newShape = ExpShape.concat(newShape_, shapeBack, source);
} else {
newShape = ExpShape.concat(shapeFront, shapeBack, source);
}
return ctx
.require(
[ctx.genLte(0, axis, source), ctx.genLt(axis, selfRank, source)],
`from 'LibCall.numpy.reduce': axis must be within rank`,
source
)
.flatMap((ctx) => {
return genNdarray(ctx, newShape, source);
});
}
// 3) axis is a tuple of ints.
else {
const axes = getExpNumTuple(axisSV, ctx.ctrSet);
if (typeof axes === 'string') {
return ctx.failWithMsg(`from 'LibCall.numpy.reduce': ${axes}`, source).toSet();
}
const constAxes: number[] = [];
axes.forEach((axis) => {
const axis_ = absExpIndexByLen(axis, selfRank, source);
if (typeof axis_ === 'number') {
constAxes.push(axis_);
}
});
if (axes.length !== constAxes.length) {
return ctx.failWithMsg(`from 'LibCall.numpy.max': ${axes} has non-const axis`, source).toSet();
}
constAxes.sort();
const shapes: ExpShape[] = [];
let lastDim: number | ExpNum = -1;
for (let i = 0; i < constAxes.length; i++) {
const dim = constAxes[i];
shapes.push(ExpShape.slice(selfShape, ExpNum.bop(NumBopType.Add, lastDim, 1, source), dim, source));
if (keepdimsVal) {
shapes.push(ExpShape.fromConst(1, [1], source));
}
lastDim = dim;
}
shapes.push(ExpShape.slice(selfShape, ExpNum.bop(NumBopType.Add, lastDim, 1, source), selfRank, source));
const shape = shapes.reduce((left, right) => ExpShape.concat(left, right, source));
return ctx
.require(
[ctx.genLte(0, constAxes[0], source), ctx.genLt(constAxes[constAxes.length - 1], selfRank, source)],
`axes must be within rank`,
source
)
.flatMap((ctx) => {
return genNdarray(ctx, shape, source);
});
}
}
export function flatten(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> {
const params = ctx.retVal.params;
if (params.length < 1) {
return warnNdarrayWithMsg(
ctx,
`from 'LibCall.torch.flatten': got insufficient number of argument: ${params.length}`,
source
);
}
const heap = ctx.heap;
const [inputAddr, startDimAddr, endDimAddr] = params;
// TODO: use kwargs info.
// TODO: handle negative indexing
const inputSize = fetchSize(inputAddr, heap);
if (typeof inputSize === 'string') {
return warnNdarrayWithMsg(ctx, `from 'LibCall.torch.flatten': ${inputSize}`, source);
}
const inputShape = inputSize.shape;
// np.flatten only outputs 1-D array
const returnShape = ExpShape.fromConst(1, [ExpNum.numel(inputShape, source)], source);
return genNdarray(ctx, returnShape, source);
}
/* Integer array indexing.
* https://numpy.org/doc/stable/reference/arrays.indexing.html#advanced-indexing
* assumption: each element of index arrays has no boundary error
*
* x = np.array([[ 0, 1, 2],
* [ 3, 4, 5],
* [ 6, 7, 8],
* [ 9, 10, 11]])
* rows = np.array([[0, 0],
* [3, 3]], dtype=np.intp)
* columns = np.array([[0, 2],
* [0, 2]], dtype=np.intp)
* x[rows, columns] -> array([[ 0, 2],
* [ 9, 11]])
*/
export function indexIntarrays(
ctx: Context<LCBase.ExplicitParams>,
source: CodeSource | undefined
): ContextSet<ShValue> {
const params = ctx.retVal.params;
if (params.length !== 3) {
return warnNdarrayWithMsg(
ctx,
`from 'LibCall.ndarray.indexIntarrays': got insufficient number of argument: ${params.length}`,
source
);
}
const heap = ctx.heap;
const [sizeAddr, lenAddr, arraysAddr] = params;
const size = fetchAddr(sizeAddr, heap);
const len = fetchAddr(lenAddr, heap);
const arrays = fetchAddr(arraysAddr, heap);
if (!(size && size instanceof SVSize)) {
return ctx.warnWithMsg(`from 'LibCall.ndarray.indexIntarrays': input is not a Size type`, source).toSet();
}
if (len?.type !== SVType.Int) {
return warnNdarrayWithMsg(ctx, `from 'LibCall.ndarray.indexIntarrays': ${len}`, source);
}
if (arrays?.type !== SVType.Object) {
return warnNdarrayWithMsg(ctx, `from 'LibCall.ndarray.indexIntarrays': ${arrays}`, source);
}
// TODO: broadcasting, check all shapes of indice
const first = arrays.getIndice(0);
const firstSize = fetchSize(first, heap);
if (typeof firstSize === 'string') {
return warnNdarrayWithMsg(ctx, `from 'LibCall.ndarray.indexIntarrays': ${firstSize}`, source);
}
const elemShape = ExpShape.slice(size.shape, len.value, size.rank(), source);
const indexShape = firstSize.shape;
return ctx
.require(
[ctx.genLte(len.value, size.rank(), source)],
`from 'LibCall.ndarray.indexIntarrays: too many indices.`,
source
)
.flatMap((ctx) => {
return genNdarray(ctx, ExpShape.concat(indexShape, elemShape, source), source);
});
}
export function indexBoolarray(
ctx: Context<LCBase.ExplicitParams>,
source: CodeSource | undefined
): ContextSet<ShValue> {
const params = ctx.retVal.params;
if (params.length !== 2) {
return warnNdarrayWithMsg(
ctx,
`from 'LibCall.ndarray.indexIntarray': got insufficient number of argument: ${params.length}`,
source
);
}
const heap = ctx.heap;
const [sizeAddr, boolarrAddr] = params;
const size = fetchAddr(sizeAddr, heap);
const boolarray = fetchSize(boolarrAddr, heap);
if (!(size && size instanceof SVSize)) {
return ctx.warnWithMsg(`from 'LibCall.ndarray.indexIntarray': input is not a Size type`, source).toSet();
}
if (typeof boolarray === 'string') {
return warnNdarrayWithMsg(ctx, `from 'LibCall.ndarray.indexIntarray': ${boolarray}`, source);
}
// mask indexing
const sizeNumel = ExpNum.numel(size.shape, source);
const mask = boolarray;
const maskCtx = ctx.genIntGte('indexBoolarray', 0, source);
const maskNum = maskCtx.retVal;
return maskCtx
.require(
[maskCtx.genLte(maskNum, sizeNumel, source), maskCtx.genEq(size.shape, mask.shape, source)],
`from 'LibCall.ndarray.indexBoolarray: mask shape mismatch`,
source
)
.flatMap((ctx) => {
return genNdarray(ctx, ExpShape.fromConst(1, [maskNum], source), source);
});
}
export const libCallImpls: { [key: string]: LCImpl } = {
genInitShape,
ndarrayGetItem,
identityShape,
broadcast,
matmul,
concatenate,
copyOut,
reduce,
flatten,
indexIntarrays,
indexBoolarray,
};
}
export const libCallMap: Map<string, LCImpl> = new Map([...Object.entries(NumpyLCImpl.libCallImpls)]); | the_stack |
import { ConfigurationError } from '../errors/external-error';
import { AssertError, UnreachableCaseError } from '../errors/internal-error';
import { ItemType, JsonValue, ResponsiveMode, Side } from '../utils/types';
import {
ResolvedComponentItemConfig,
ResolvedHeaderedItemConfig,
ResolvedItemConfig,
ResolvedLayoutConfig,
ResolvedPopoutLayoutConfig,
ResolvedRootItemConfig,
ResolvedRowOrColumnItemConfig,
ResolvedStackItemConfig
} from "./resolved-config";
/** @public */
export interface ItemConfig {
/**
* The type of the item. Possible values are 'row', 'column', 'stack', 'component'.
*/
type: ItemType;
/**
* An array of configurations for items that will be created as children of this item.
*/
content?: ItemConfig[];
/**
* The width of this item, relative to the other children of its parent in percent
*/
width?: number;
/**
* The minimum width of this item in pixels
* CAUTION - Not tested - do not use
*/
minWidth?: number;
/**
* The height of this item, relative to the other children of its parent in percent
*/
height?: number;
/**
* The minimum height of this item in pixels
* CAUTION - Not tested - do not use
*/
minHeight?: number;
/**
* A string that can be used to identify a ContentItem.
* Do NOT assign an array. This only exists for legacy purposes. If an array is assigned, the first element
* will become the id.
*/
id?: string;
/**
* Determines if the item is closable. If false, the x on the items tab will be hidden and container.close()
* will return false
* Default: true
*/
isClosable?: boolean;
/**
* The title of the item as displayed on its tab and on popout windows
* Default: componentType.toString() or ''
*/
title?: string;
}
/** @public */
export namespace ItemConfig {
export function resolve(itemConfig: ItemConfig): ResolvedItemConfig {
switch (itemConfig.type) {
case ItemType.ground:
throw new ConfigurationError('ItemConfig cannot specify type ground', JSON.stringify(itemConfig));
case ItemType.row:
case ItemType.column:
return RowOrColumnItemConfig.resolve(itemConfig as RowOrColumnItemConfig);
case ItemType.stack:
return StackItemConfig.resolve(itemConfig as StackItemConfig);
case ItemType.component:
return ComponentItemConfig.resolve(itemConfig as ComponentItemConfig);
default:
throw new UnreachableCaseError('UCUICR55499', itemConfig.type);
}
}
export function resolveContent(content: ItemConfig[] | undefined): ResolvedItemConfig[] {
if (content === undefined) {
return [];
} else {
const count = content.length;
const result = new Array<ResolvedItemConfig>(count);
for (let i = 0; i < count; i++) {
result[i] = ItemConfig.resolve(content[i]);
}
return result;
}
}
export function resolveId(id: string | string[] | undefined): string {
if (id === undefined) {
return ResolvedItemConfig.defaults.id;
} else {
if (Array.isArray(id)) {
if (id.length === 0) {
return ResolvedItemConfig.defaults.id;
} else {
return id[0];
}
} else {
return id;
}
}
}
export function isGround(config: ItemConfig): config is ItemConfig {
return config.type === ItemType.ground;
}
export function isRow(config: ItemConfig): config is ItemConfig {
return config.type === ItemType.row;
}
export function isColumn(config: ItemConfig): config is ItemConfig {
return config.type === ItemType.column;
}
export function isStack(config: ItemConfig): config is ItemConfig {
return config.type === ItemType.stack;
}
export function isComponent(config: ItemConfig): config is ComponentItemConfig {
return config.type === ItemType.component;
}
}
// Stack or Component
/** @public */
export interface HeaderedItemConfig extends ItemConfig {
/** @deprecated use {@link (HeaderedItemConfig:namespace).(Header:interface).show} instead */
hasHeaders?: boolean;
header?: HeaderedItemConfig.Header;
maximised?: boolean;
}
/** @public */
export namespace HeaderedItemConfig {
const legacyMaximisedId = '__glMaximised';
export interface Header {
show?: false | Side;
popout?: false | string;
dock?: false | string;
maximise?: false | string;
close?: string;
minimise?: string;
tabDropdown?: false | string;
}
export namespace Header {
export function resolve(header: Header | undefined, hasHeaders: boolean | undefined): ResolvedHeaderedItemConfig.Header | undefined {
if (header === undefined && hasHeaders === undefined) {
return undefined;
} else {
const result: ResolvedHeaderedItemConfig.Header = {
show: header?.show ?? (hasHeaders === undefined ? undefined : hasHeaders ? ResolvedLayoutConfig.Header.defaults.show : false),
popout: header?.popout,
maximise: header?.maximise,
close: header?.close,
minimise: header?.minimise,
tabDropdown: header?.tabDropdown,
}
return result;
}
}
}
export function resolveIdAndMaximised(config: HeaderedItemConfig): { id: string, maximised: boolean} {
let id: string;
// To support legacy configs with Id saved as an array of string, assign config.id to a type which includes string array
let legacyId: string | string[] | undefined = config.id;
let legacyMaximised = false;
if (legacyId === undefined) {
id = ResolvedItemConfig.defaults.id;
} else {
if (Array.isArray(legacyId)) {
const idx = legacyId.findIndex((id) => id === legacyMaximisedId)
if (idx > 0) {
legacyMaximised = true;
legacyId = legacyId.splice(idx, 1);
}
if (legacyId.length > 0) {
id = legacyId[0];
} else {
id = ResolvedItemConfig.defaults.id;
}
} else {
id = legacyId;
}
}
let maximised: boolean;
if (config.maximised !== undefined) {
maximised = config.maximised;
} else {
maximised = legacyMaximised;
}
return { id, maximised }
}
}
/** @public */
export interface StackItemConfig extends HeaderedItemConfig {
type: 'stack';
content: ComponentItemConfig[];
/** The index of the item in content which is to be active*/
activeItemIndex?: number;
}
/** @public */
export namespace StackItemConfig {
export function resolve(itemConfig: StackItemConfig): ResolvedStackItemConfig {
const { id, maximised } = HeaderedItemConfig.resolveIdAndMaximised(itemConfig);
const result: ResolvedStackItemConfig = {
type: ItemType.stack,
content: resolveContent(itemConfig.content),
width: itemConfig.width ?? ResolvedItemConfig.defaults.width,
minWidth: itemConfig.minWidth ?? ResolvedItemConfig.defaults.minWidth,
height: itemConfig.height ?? ResolvedItemConfig.defaults.height,
minHeight: itemConfig.minHeight ?? ResolvedItemConfig.defaults.minHeight,
id,
maximised,
isClosable: itemConfig.isClosable ?? ResolvedItemConfig.defaults.isClosable,
activeItemIndex: itemConfig.activeItemIndex ?? ResolvedStackItemConfig.defaultActiveItemIndex,
header: HeaderedItemConfig.Header.resolve(itemConfig.header, itemConfig.hasHeaders),
};
return result;
}
export function resolveContent(content: ComponentItemConfig[] | undefined): ResolvedComponentItemConfig[] {
if (content === undefined) {
return [];
} else {
const count = content.length;
const result = new Array<ResolvedComponentItemConfig>(count);
for (let i = 0; i < count; i++) {
const childItemConfig = content[i];
const itemConfig = ItemConfig.resolve(childItemConfig);
if (!ResolvedItemConfig.isComponentItem(itemConfig)) {
throw new AssertError('UCUSICRC91114', JSON.stringify(itemConfig));
} else {
result[i] = itemConfig;
}
}
return result;
}
}
}
/** @public */
export interface ComponentItemConfig extends HeaderedItemConfig {
type: 'component';
readonly content?: [];
/**
* The type of the component.
* @deprecated use {@link (ComponentItemConfig:interface).componentType} instead
*/
componentName?: string;
/**
* The type of the component.
* `componentType` must be of type `string` if it is registered with any of the following functions:
* * {@link (GoldenLayout:class).registerComponent} (deprecated)
* * {@link (GoldenLayout:class).registerComponentConstructor}
* * {@link (GoldenLayout:class).registerComponentFactoryFunction}
*/
componentType: JsonValue;
/**
* The state information with which a component will be initialised with.
* Will be passed to the component constructor function and will be the value returned by
* container.initialState.
*/
componentState?: JsonValue;
/**
* Default: true
*/
reorderEnabled?: boolean; // Takes precedence over LayoutConfig.reorderEnabled.
}
/** @public */
export namespace ComponentItemConfig {
export function resolve(itemConfig: ComponentItemConfig): ResolvedComponentItemConfig {
let componentType: JsonValue | undefined = itemConfig.componentType;
if (componentType === undefined) {
componentType = itemConfig.componentName;
}
if (componentType === undefined) {
throw new Error('ComponentItemConfig.componentType is undefined');
} else {
const { id, maximised } = HeaderedItemConfig.resolveIdAndMaximised(itemConfig);
let title: string;
if (itemConfig.title === undefined || itemConfig.title === '') {
title = ComponentItemConfig.componentTypeToTitle(componentType);
} else {
title = itemConfig.title;
}
const result: ResolvedComponentItemConfig = {
type: itemConfig.type,
content: [],
width: itemConfig.width ?? ResolvedItemConfig.defaults.width,
minWidth: itemConfig.minWidth ?? ResolvedItemConfig.defaults.minWidth,
height: itemConfig.height ?? ResolvedItemConfig.defaults.height,
minHeight: itemConfig.minHeight ?? ResolvedItemConfig.defaults.minHeight,
id,
maximised,
isClosable: itemConfig.isClosable ?? ResolvedItemConfig.defaults.isClosable,
reorderEnabled: itemConfig.reorderEnabled ?? ResolvedComponentItemConfig.defaultReorderEnabled,
title,
header: HeaderedItemConfig.Header.resolve(itemConfig.header, itemConfig.hasHeaders),
componentType,
componentState: itemConfig.componentState ?? {},
};
return result;
}
}
export function componentTypeToTitle(componentType: JsonValue): string {
const componentTypeType = typeof componentType;
switch (componentTypeType) {
case 'string': return componentType as string;
case 'number': return (componentType as number).toString();
case 'boolean': return (componentType as boolean).toString();
default: return '';
}
}
}
// RowOrColumn
/** @public */
export interface RowOrColumnItemConfig extends ItemConfig {
type: 'row' | 'column';
content: (RowOrColumnItemConfig | StackItemConfig | ComponentItemConfig)[];
}
/** @public */
export namespace RowOrColumnItemConfig {
export type ChildItemConfig = RowOrColumnItemConfig | StackItemConfig | ComponentItemConfig;
export function isChildItemConfig(itemConfig: ItemConfig): itemConfig is ChildItemConfig {
switch (itemConfig.type) {
case ItemType.row:
case ItemType.column:
case ItemType.stack:
case ItemType.component:
return true;
case ItemType.ground:
return false;
default:
throw new UnreachableCaseError('UROCOSPCICIC13687', itemConfig.type);
}
}
export function resolve(itemConfig: RowOrColumnItemConfig): ResolvedRowOrColumnItemConfig {
const result: ResolvedRowOrColumnItemConfig = {
type: itemConfig.type,
content: RowOrColumnItemConfig.resolveContent(itemConfig.content),
width: itemConfig.width ?? ResolvedItemConfig.defaults.width,
minWidth: itemConfig.width ?? ResolvedItemConfig.defaults.minWidth,
height: itemConfig.height ?? ResolvedItemConfig.defaults.height,
minHeight: itemConfig.height ?? ResolvedItemConfig.defaults.minHeight,
id: ItemConfig.resolveId(itemConfig.id),
isClosable: itemConfig.isClosable ?? ResolvedItemConfig.defaults.isClosable,
}
return result;
}
export function resolveContent(content: ChildItemConfig[] | undefined): ResolvedRowOrColumnItemConfig.ChildItemConfig[] {
if (content === undefined) {
return [];
} else {
const count = content.length;
const result = new Array<ResolvedRowOrColumnItemConfig.ChildItemConfig>(count);
for (let i = 0; i < count; i++) {
const childItemConfig = content[i];
if (!RowOrColumnItemConfig.isChildItemConfig(childItemConfig)) {
throw new ConfigurationError('ItemConfig is not Row, Column or Stack', childItemConfig);
} else {
const resolvedChildItemConfig = ItemConfig.resolve(childItemConfig);
if (!ResolvedRowOrColumnItemConfig.isChildItemConfig(resolvedChildItemConfig)) {
throw new AssertError('UROCOSPIC99512', JSON.stringify(resolvedChildItemConfig));
} else {
result[i] = resolvedChildItemConfig;
}
}
}
return result;
}
}
}
/** @public */
export type RootItemConfig = RowOrColumnItemConfig | StackItemConfig | ComponentItemConfig;
/** @public */
export namespace RootItemConfig {
export function isRootItemConfig(itemConfig: ItemConfig): itemConfig is RootItemConfig {
switch (itemConfig.type) {
case ItemType.row:
case ItemType.column:
case ItemType.stack:
case ItemType.component:
return true;
case ItemType.ground:
return false;
default:
throw new UnreachableCaseError('URICIR23687', itemConfig.type);
}
}
export function resolve(itemConfig: RootItemConfig | undefined): ResolvedRootItemConfig | undefined {
if (itemConfig === undefined) {
return undefined;
} else {
const result = ItemConfig.resolve(itemConfig);
if (!ResolvedRootItemConfig.isRootItemConfig(result)) {
throw new ConfigurationError('ItemConfig is not Row, Column or Stack', JSON.stringify(itemConfig));
} else {
return result;
}
}
}
}
/** @public */
export interface LayoutConfig {
root: RootItemConfig;
/** @deprecated Use {@link (LayoutConfig:interface).root} */
content?: (RowOrColumnItemConfig | StackItemConfig | ComponentItemConfig)[];
openPopouts?: PopoutLayoutConfig[];
dimensions?: LayoutConfig.Dimensions;
settings?: LayoutConfig.Settings;
/** @deprecated use {@link (LayoutConfig:interface).header} instead */
labels?: LayoutConfig.Labels;
header?: LayoutConfig.Header;
}
/** Use to specify LayoutConfig with defaults or deserialise a LayoutConfig.
* Deserialisation will handle backwards compatibility.
* Note that LayoutConfig should be used for serialisation (not LayoutConfig)
* @public
*/
export namespace LayoutConfig {
export interface Settings {
/**
* @deprecated use ${@link (LayoutConfig:namespace).(Header:interface).show} instead
*/
hasHeaders?: boolean;
/**
* Constrains the area in which items can be dragged to the layout's container. Will be set to false
* automatically when layout.createDragSource() is called.
* Default: true
*/
constrainDragToContainer?: boolean;
/**
* If true, the user can re-arrange the layout by dragging items by their tabs to the desired location.
* Can be overridden by ItemConfig.reorderEnabled for specific ItemConfigs
* Default: true
*/
reorderEnabled?: boolean;
/**
* Decides what will be opened in a new window if the user clicks the popout icon. If true the entire stack will
* be transferred to the new window, if false only the active component will be opened.
* Default: false
*/
popoutWholeStack?: boolean;
/**
* Specifies if an error is thrown when a popout is blocked by the browser (e.g. by opening it programmatically).
* If false, the popout call will fail silently.
* Default: true
*/
blockedPopoutsThrowError?: boolean;
/**
* Specifies if all popouts should be closed when the page that created them is closed. Popouts don't have a
* strong dependency on their parent and can exist on their own, but can be quite annoying to close by hand. In
* addition, any changes made to popouts won't be stored after the parent is closed.
* Default: true
*/
closePopoutsOnUnload?: boolean;
/**
* Specifies if the popout icon should be displayed in the header-bar.
* @deprecated use {@link (LayoutConfig:namespace).(Header:interface).popout} instead
*/
showPopoutIcon?: boolean;
/**
* Specifies if the maximise icon should be displayed in the header-bar.
* @deprecated use {@link (LayoutConfig:namespace).(Header:interface).maximise} instead
*/
showMaximiseIcon?: boolean;
/**
* Specifies if the close icon should be displayed in the header-bar.
* @deprecated use {@link (LayoutConfig:namespace).(Header:interface).close} instead
*/
showCloseIcon?: boolean;
/**
* Specifies Responsive Mode (more info needed).
* Default: none
*/
responsiveMode?: ResponsiveMode;
/**
* Specifies Maximum pixel overlap per tab.
* Default: 0
*/
tabOverlapAllowance?: number;
/**
*
* Default: true
*/
reorderOnTabMenuClick?: boolean;
/**
* Default: 10
*/
tabControlOffset?: number;
/**
* Specifies whether to pop in elements when closing a popout window.
* Default: false
*/
popInOnClose?: boolean;
}
export namespace Settings {
export function resolve(settings: Settings | undefined): ResolvedLayoutConfig.Settings {
const result: ResolvedLayoutConfig.Settings = {
constrainDragToContainer: settings?.constrainDragToContainer ?? ResolvedLayoutConfig.Settings.defaults.constrainDragToContainer,
reorderEnabled: settings?.reorderEnabled ?? ResolvedLayoutConfig.Settings.defaults.reorderEnabled,
popoutWholeStack: settings?.popoutWholeStack ?? ResolvedLayoutConfig.Settings.defaults.popoutWholeStack,
blockedPopoutsThrowError: settings?.blockedPopoutsThrowError ?? ResolvedLayoutConfig.Settings.defaults.blockedPopoutsThrowError,
closePopoutsOnUnload: settings?.closePopoutsOnUnload ?? ResolvedLayoutConfig.Settings.defaults.closePopoutsOnUnload,
responsiveMode: settings?.responsiveMode ?? ResolvedLayoutConfig.Settings.defaults.responsiveMode,
tabOverlapAllowance: settings?.tabOverlapAllowance ?? ResolvedLayoutConfig.Settings.defaults.tabOverlapAllowance,
reorderOnTabMenuClick: settings?.reorderOnTabMenuClick ?? ResolvedLayoutConfig.Settings.defaults.reorderOnTabMenuClick,
tabControlOffset: settings?.tabControlOffset ?? ResolvedLayoutConfig.Settings.defaults.tabControlOffset,
popInOnClose: settings?.popInOnClose ?? ResolvedLayoutConfig.Settings.defaults.popInOnClose,
}
return result;
}
}
export interface Dimensions {
/**
* The width of the borders between the layout items in pixel. Please note: The actual draggable area is wider
* than the visible one, making it safe to set this to small values without affecting usability.
* Default: 5
*/
borderWidth?: number;
/**
* Default: 15
*/
borderGrabWidth?: number,
/**
* The minimum height an item can be resized to (in pixel).
* Default: 10
*/
minItemHeight?: number;
/**
* The minimum width an item can be resized to (in pixel).
* Default: 10
*/
minItemWidth?: number;
/**
* The height of the header elements in pixel. This can be changed, but your theme's header css needs to be
* adjusted accordingly.
* Default: 20
*/
headerHeight?: number;
/**
* The width of the element that appears when an item is dragged (in pixel).
* Default: 300
*/
dragProxyWidth?: number;
/**
* The height of the element that appears when an item is dragged (in pixel).
* Default: 200
*/
dragProxyHeight?: number;
}
export namespace Dimensions {
export function resolve(dimensions: Dimensions | undefined): ResolvedLayoutConfig.Dimensions {
const result: ResolvedLayoutConfig.Dimensions = {
borderWidth: dimensions?.borderWidth ?? ResolvedLayoutConfig.Dimensions.defaults.borderWidth,
borderGrabWidth: dimensions?.borderGrabWidth ?? ResolvedLayoutConfig.Dimensions.defaults.borderGrabWidth,
minItemHeight: dimensions?.minItemHeight ?? ResolvedLayoutConfig.Dimensions.defaults.minItemHeight,
minItemWidth: dimensions?.minItemWidth ?? ResolvedLayoutConfig.Dimensions.defaults.minItemWidth,
headerHeight: dimensions?.headerHeight ?? ResolvedLayoutConfig.Dimensions.defaults.headerHeight,
dragProxyWidth: dimensions?.dragProxyWidth ?? ResolvedLayoutConfig.Dimensions.defaults.dragProxyWidth,
dragProxyHeight: dimensions?.dragProxyHeight ?? ResolvedLayoutConfig.Dimensions.defaults.dragProxyHeight,
}
return result;
}
}
export interface Labels {
/**
* @deprecated use {@link (LayoutConfig:namespace).(Header:interface).close} instead
*/
close?: string;
/**
* @deprecated use {@link (LayoutConfig:namespace).(Header:interface).maximise} instead
*/
maximise?: string;
/**
* @deprecated use {@link (LayoutConfig:namespace).(Header:interface).minimise} instead
*/
minimise?: string;
/**
* @deprecated use {@link (LayoutConfig:namespace).(Header:interface).popin} instead
*/
popin?: string;
/**
* @deprecated use {@link (LayoutConfig:namespace).(Header:interface).popout} instead
*/
popout?: string;
/**
* @deprecated use {@link (LayoutConfig:namespace).(Header:interface).tabDropdown} instead
*/
tabDropdown?: string;
}
export interface Header {
/**
* Specifies whether header should be displayed, and if so, on which side.
* If false, the layout will be displayed with splitters only.
* Default: 'top'
*/
show?: false | Side;
/**
* The tooltip text that appears when hovering over the popout icon or false if popout button not displayed.
* Default: 'open in new window'
*/
popout?: false | string;
/**
* The tooltip text that appears when hovering over the popin icon.
* Default: 'pop in'
*/
popin?: string;
/**
* The tooltip text that appears when hovering over the maximise icon or false if maximised button not displayed.
* Default: 'maximise'
*/
maximise?: false | string;
/**
* The tooltip text that appears when hovering over the close icon.
* Default: 'close'
*/
close?: false | string;
/**
* The tooltip text that appears when hovering over the minimise icon.
* Default: 'minimise'
*/
minimise?: string;
/**
*
* Default: 'additional tabs'
*/
tabDropdown?: false | string;
}
export namespace Header {
export function resolve(header: Header | undefined,
settings: LayoutConfig.Settings | undefined, labels: LayoutConfig.Labels | undefined
): ResolvedLayoutConfig.Header {
let show: false | Side;
if (header?.show !== undefined) {
show = header.show;
} else {
if (settings !== undefined && settings.hasHeaders !== undefined) {
show = settings.hasHeaders ? ResolvedLayoutConfig.Header.defaults.show : false;
} else {
show = ResolvedLayoutConfig.Header.defaults.show;
}
}
const result: ResolvedLayoutConfig.Header = {
show,
popout: header?.popout ?? labels?.popout ??
(settings?.showPopoutIcon === false ? false : ResolvedLayoutConfig.Header.defaults.popout),
dock: header?.popin ?? labels?.popin ?? ResolvedLayoutConfig.Header.defaults.dock,
maximise: header?.maximise ?? labels?.maximise ??
(settings?.showMaximiseIcon === false ? false : ResolvedLayoutConfig.Header.defaults.maximise),
close: header?.close ?? labels?.close ??
(settings?.showCloseIcon === false ? false : ResolvedLayoutConfig.Header.defaults.close),
minimise: header?.minimise ?? labels?.minimise ?? ResolvedLayoutConfig.Header.defaults.minimise,
tabDropdown: header?.tabDropdown ?? labels?.tabDropdown ?? ResolvedLayoutConfig.Header.defaults.tabDropdown,
}
return result;
}
}
export function isPopout(config: LayoutConfig): config is PopoutLayoutConfig {
return 'parentId' in config || 'indexInParent' in config || 'window' in config;
}
export function resolve(layoutConfig: LayoutConfig): ResolvedLayoutConfig {
if (isPopout(layoutConfig)) {
return PopoutLayoutConfig.resolve(layoutConfig);
} else {
let root: RootItemConfig | undefined;
if (layoutConfig.root !== undefined) {
root = layoutConfig.root;
} else {
if (layoutConfig.content !== undefined && layoutConfig.content.length > 0) {
root = layoutConfig.content[0];
} else {
root = undefined;
}
}
const config: ResolvedLayoutConfig = {
resolved: true,
root: RootItemConfig.resolve(root),
openPopouts: LayoutConfig.resolveOpenPopouts(layoutConfig.openPopouts),
dimensions: LayoutConfig.Dimensions.resolve(layoutConfig.dimensions),
settings: LayoutConfig.Settings.resolve(layoutConfig.settings),
header: LayoutConfig.Header.resolve(layoutConfig.header, layoutConfig.settings, layoutConfig.labels),
}
return config;
}
}
export function fromResolved(config: ResolvedLayoutConfig): LayoutConfig {
const copiedConfig = ResolvedLayoutConfig.createCopy(config);
const result: LayoutConfig = {
root: copiedConfig.root as RootItemConfig,
openPopouts: copiedConfig.openPopouts as unknown as PopoutLayoutConfig[],
dimensions: copiedConfig.dimensions,
settings: copiedConfig.settings,
header: copiedConfig.header,
};
return result;
}
export function isResolved(configOrResolvedConfig: ResolvedLayoutConfig | LayoutConfig): configOrResolvedConfig is ResolvedLayoutConfig {
const config = configOrResolvedConfig as ResolvedLayoutConfig;
return config.resolved !== undefined && (config.resolved === true);
}
export function resolveOpenPopouts(popoutConfigs: PopoutLayoutConfig[] | undefined): ResolvedPopoutLayoutConfig[] {
if (popoutConfigs === undefined) {
return [];
} else {
const count = popoutConfigs.length;
const result = new Array<ResolvedPopoutLayoutConfig>(count);
for (let i = 0; i < count; i++) {
result[i] = PopoutLayoutConfig.resolve(popoutConfigs[i]);
}
return result;
}
}
}
/** @public */
export interface PopoutLayoutConfig extends LayoutConfig {
/** The id of the element the item will be appended to on popIn
* If null, append to topmost layout element
*/
parentId: string | null | undefined;
/** The position of this element within its parent
* If null, position is last
*/
indexInParent: number | null | undefined;
/** @deprecated use {@link (PopoutLayoutConfig:interface).window} */
dimensions: PopoutLayoutConfig.Dimensions | undefined; // for backwards compatibility
window: PopoutLayoutConfig.Window | undefined;
}
/** @public */
export namespace PopoutLayoutConfig {
// Previous versions kept window information in Dimensions key. Only use for backwards compatibility
/** @deprecated use {@link (PopoutLayoutConfig:namespace).(Window:interface)} */
export interface Dimensions extends LayoutConfig.Dimensions {
/** @deprecated use {@link (PopoutLayoutConfig:namespace).(Window:interface).width} */
width: number | null,
/** @deprecated use {@link (PopoutLayoutConfig:namespace).(Window:interface).height} */
height: number | null,
/** @deprecated use {@link (PopoutLayoutConfig:namespace).(Window:interface).left} */
left: number | null,
/** @deprecated use {@link (PopoutLayoutConfig:namespace).(Window:interface).top} */
top: number | null,
}
export interface Window {
width?: number,
height?: number,
left?: number,
top?: number,
}
export namespace Window {
export function resolve(window: Window | undefined,
dimensions: Dimensions | undefined): ResolvedPopoutLayoutConfig.Window
{
let result: ResolvedPopoutLayoutConfig.Window;
const defaults = ResolvedPopoutLayoutConfig.Window.defaults;
if (window !== undefined) {
result = {
width: window.width ?? defaults.width,
height: window.height ?? defaults.height,
left: window.left ?? defaults.left,
top: window.top ?? defaults.top,
}
} else {
result = {
width: dimensions?.width ?? defaults.width,
height: dimensions?.height ?? defaults.height,
left: dimensions?.left ?? defaults.left,
top: dimensions?.top ?? defaults.top,
}
}
return result;
}
}
export function resolve(popoutConfig: PopoutLayoutConfig): ResolvedPopoutLayoutConfig {
let root: RootItemConfig | undefined;
if (popoutConfig.root !== undefined) {
root = popoutConfig.root;
} else {
if (popoutConfig.content !== undefined && popoutConfig.content.length > 0) {
root = popoutConfig.content[0];
} else {
root = undefined;
}
}
const config: ResolvedPopoutLayoutConfig = {
root: RootItemConfig.resolve(root),
openPopouts: LayoutConfig.resolveOpenPopouts(popoutConfig.openPopouts),
settings: LayoutConfig.Settings.resolve(popoutConfig.settings),
dimensions: LayoutConfig.Dimensions.resolve(popoutConfig.dimensions),
header: LayoutConfig.Header.resolve(popoutConfig.header, popoutConfig.settings, popoutConfig.labels),
parentId: popoutConfig.parentId ?? null,
indexInParent: popoutConfig.indexInParent ?? null,
window: PopoutLayoutConfig.Window.resolve(popoutConfig.window, popoutConfig.dimensions),
resolved: true,
}
return config;
}
}
/** @public @deprecated - use {@link (LayoutConfig:interface)} */
export type Config = LayoutConfig; | the_stack |
import Messages = require('../messages');
import MetadataRegistry = require('./metadataRegistry');
const messages = Messages();
import * as syncCommandHelper from './syncCommandHelper';
import logger = require('../core/logApi');
import { SourceDeployApiBase } from './sourceDeployApiBase';
import { createOutputDir, cleanupOutputDir, updateSourceTracking } from './sourceUtil';
import { toArray } from './parseManifestEntriesArray';
import { SourceWorkspaceAdapter } from './sourceWorkspaceAdapter';
import { AggregateSourceElements } from './aggregateSourceElements';
import { DeployResult } from './sourceDeployApi';
import { SrcStatusApi } from './srcStatusApi';
import { RemoteSourceTrackingService } from './remoteSourceTrackingService';
import { env } from '@salesforce/kit';
import { SfdxProject } from '@salesforce/core';
interface DeployError extends Error {
outboundFiles: object[];
failures: object[];
}
interface PushOptions {
deploydir?: string;
wait?: number;
forceoverwrite?: boolean;
}
export class MdapiPushApi extends SourceDeployApiBase {
public swa: SourceWorkspaceAdapter;
public scratchOrg: any;
private metadataRegistry: MetadataRegistry;
private remoteSourceTrackingService: RemoteSourceTrackingService;
static packagesDeployed: number;
protected async init(): Promise<void> {
await super.init();
this.metadataRegistry = new MetadataRegistry();
const options: SourceWorkspaceAdapter.Options = {
org: this.orgApi,
metadataRegistryImpl: MetadataRegistry,
defaultPackagePath: this.force.getConfig().getAppConfig().defaultPackagePath,
};
this.swa = await SourceWorkspaceAdapter.create(options);
await this.swa.backupSourcePathInfos();
this.scratchOrg = options.org;
this.remoteSourceTrackingService = await RemoteSourceTrackingService.getInstance({
username: this.scratchOrg.name,
});
}
async deployPackage(options: PushOptions, packageName: string): Promise<any> {
try {
this.logger.debug(`deploying package: ${packageName}`);
const changedAggregateSourceElements = new AggregateSourceElements().set(
packageName,
this.swa.changedSourceElementsCache.get(packageName)
);
// Create a temp directory
options.deploydir = options.deploydir || (await createOutputDir('mdpkg'));
if (!changedAggregateSourceElements.isEmpty()) {
const result = await this.convertAndDeploy(options, this.swa, changedAggregateSourceElements, true);
return await this.processResults(result, changedAggregateSourceElements, packageName);
}
} catch (err) {
if (!err.outboundFiles) {
await this.swa.revertSourcePathInfos();
}
throw err;
} finally {
await cleanupOutputDir(options.deploydir);
}
}
async doDeploy(options: PushOptions): Promise<DeployResult> {
const results: DeployResult = { outboundFiles: [] };
// Remove this when push has been modified to support the new mdapi wait functionality;
if (isNaN(options.wait)) {
options.wait = this.force.config.getConfigContent().defaultSrcWaitMinutes;
}
await this.checkForConflicts(options);
MdapiPushApi.packagesDeployed = this.swa.changedSourceElementsCache.size;
// Deploy metadata in each package directory
let componentSuccessCount = 0;
let flattenedDeploySuccesses = [];
for (const pkg of SfdxProject.getInstance().getUniquePackageNames()) {
const sourceElements = this.swa.changedSourceElementsCache.get(pkg);
if (sourceElements && sourceElements.size) {
const opts = Object.assign({}, options);
const deployResult = await this.deployPackage(opts, pkg);
if (deployResult) {
if (deployResult.numberComponentsDeployed) {
componentSuccessCount += deployResult.numberComponentsDeployed;
}
if (deployResult.details && deployResult.details.componentSuccesses) {
flattenedDeploySuccesses = [...flattenedDeploySuccesses, ...deployResult.details.componentSuccesses];
}
if (deployResult.outboundFiles && deployResult.outboundFiles.length) {
results.outboundFiles = [...results.outboundFiles, ...deployResult.outboundFiles];
}
}
}
}
if (env.getBoolean('SFDX_DISABLE_SOURCE_MEMBER_POLLING', false)) {
logger.warn('Not polling for SourceMembers since SFDX_DISABLE_SOURCE_MEMBER_POLLING = true.');
return results;
}
// If more than 500 metadata components were pushed, display a message
// that we're fetching the source tracking data, which happens asynchronously.
if (componentSuccessCount > 500) {
logger.log(`Updating source tracking for ${componentSuccessCount} pushed components...`);
}
// post process after all deploys have been done to update source tracking.
await this._postProcess(flattenedDeploySuccesses);
return results;
}
private async checkForConflicts(options: PushOptions) {
if (options.forceoverwrite) {
// do not check for conflicts when doing push --forceoverwrite
return;
} else {
const statusApi = await SrcStatusApi.create({ org: this.orgApi, adapter: this.swa });
let conflicts: any[] = [];
try {
await statusApi.doStatus({ local: true, remote: true });
conflicts = statusApi.getLocalConflicts();
} catch (err) {
if (err.errorCode === 'INVALID_TYPE') {
const error = new Error(messages.getMessage('NonScratchOrgPush'));
error['name'] = 'NonScratchOrgPush';
throw error;
} else {
throw err;
}
}
if (conflicts.length > 0) {
const error: any = new Error('Conflicts found during push');
error['name'] = 'SourceConflict';
error['sourceConflictElements'] = conflicts;
throw error;
}
}
}
public commitChanges(packageName: string) {
if (this.swa.pendingSourcePathInfos.get(packageName)) {
return this.swa.commitPendingChanges(packageName);
}
return false;
}
private async processResults(result, changedAggregateSourceElements: AggregateSourceElements, packageName: string) {
try {
result = this._reinterpretResults(result);
if (result.success && !!result.details.componentFailures) {
this.removeFailedAggregates(result.details.componentFailures, changedAggregateSourceElements);
}
// Update deleted items even if the deploy fails so the worksapce is consistent
await this.swa.updateSource(changedAggregateSourceElements);
} catch (e) {
// Don't log to console
this.logger.error(false, e);
}
// We need to check both success and status because a status of 'SucceededPartial' returns success === true even though rollbackOnError is set.
if (result.success && result.status === 'Succeeded') {
await this.commitChanges(packageName);
result.outboundFiles = this.getOutboundFiles(changedAggregateSourceElements);
return result;
} else {
const deployFailed = new Error() as DeployError;
if (result.timedOut) {
deployFailed.name = 'PollingTimeout';
} else {
deployFailed.name = 'DeployFailed';
let aggregateSourceElements;
try {
// Try to get the source elements for better error messages, but still show
// deploy failures if this errors out
const packagePath = SfdxProject.getInstance().getPackagePath(packageName);
aggregateSourceElements = await this.swa.getAggregateSourceElements(false, packagePath);
} catch (e) {
// Don't log to console
this.logger.error(false, e);
}
deployFailed.failures = syncCommandHelper.getDeployFailures(
result,
aggregateSourceElements,
this.metadataRegistry,
this.logger
);
}
if (result.success && result.status === 'SucceededPartial') {
await this.commitChanges(packageName);
deployFailed.outboundFiles = this.getOutboundFiles(changedAggregateSourceElements);
}
throw deployFailed;
}
}
async _postProcess(pushSuccesses: any[]) {
await updateSourceTracking(pushSuccesses, this.remoteSourceTrackingService, this.metadataRegistry);
}
static _isDeleteFailureBecauseDoesNotExistOnServer(failure) {
return (
failure.fullName === 'destructiveChanges.xml' && syncCommandHelper.getFullNameFromDeleteFailure(failure) !== null
);
}
static _isFailureToUs(failure) {
return !MdapiPushApi._isDeleteFailureBecauseDoesNotExistOnServer(failure);
}
static _convertFailureToSuccess(failure) {
/*
* Delete of non existent entity error - that's ok for push.
* Also note the weird fullName behavior in the mdapi deploy file property.
* Fortunately we can recover the fullName from the error message text!
*/
if (MdapiPushApi._isDeleteFailureBecauseDoesNotExistOnServer(failure)) {
failure.fullName = syncCommandHelper.getFullNameFromDeleteFailure(failure);
failure.deleted = 'true';
failure.problem = null;
failure.success = 'true';
}
}
_recalculateResult(result, reinterpretedComponentSuccesses, reinterpretedComponentFailures) {
result.details.componentSuccesses = toArray(result.details.componentSuccesses);
const originalSuccessCount = result.details.componentSuccesses.length - 1; // Ignore package.xml
if (result.status === 'Failed') {
// We can only convert a failed deploy to a success if all the failures can be ignored
// *and* there were no successes reported for components that would have been deployed
// if the deploy had succeeded, but actually failed on the server (which is not fixable here).
result.status =
reinterpretedComponentFailures.length === 0 && originalSuccessCount === 0 ? 'Succeeded' : 'Failed';
} else {
result.status = reinterpretedComponentFailures.length === 0 ? 'Succeeded' : result.status;
}
result.success = result.status !== 'Failed';
if (result.success) {
reinterpretedComponentSuccesses.forEach((failure) => MdapiPushApi._convertFailureToSuccess(failure));
result.details.componentSuccesses = result.details.componentSuccesses.concat(reinterpretedComponentSuccesses);
result.details.componentFailures = reinterpretedComponentFailures;
result.numberComponentsDeployed = result.details.componentSuccesses.length - 1; // Ignore package.xml
result.numberComponentErrors = result.details.componentFailures.length;
result.numberComponentsTotal = result.numberComponentsDeployed + result.numberComponentErrors;
}
return result;
}
/*
* We'll take a look over the result to see if we want to change it to reflect the different
* perspectives of mdapi deploy and push. We might consider some errors to be successes from
* a push perspective. If we end up flipping some errors then we'll also need to recalculate
* whether we are a success, partial success, or failure.
*/
_reinterpretResults(result) {
result.details.componentSuccesses = toArray(result.details.componentSuccesses);
if (result.status === 'Succeeded') {
return result;
}
const componentFailures = toArray(result.details.componentFailures);
const reinterpretedComponentFailures = componentFailures.filter((failure) => MdapiPushApi._isFailureToUs(failure));
const reinterpretedComponentSuccesses = componentFailures.filter(
(failure) => !MdapiPushApi._isFailureToUs(failure)
);
if (reinterpretedComponentFailures.length !== componentFailures.length) {
return this._recalculateResult(result, reinterpretedComponentSuccesses, reinterpretedComponentFailures);
}
return result;
}
} | the_stack |
import * as utils from '../src/util';
import * as service from '../src/service';
import * as embed from '../src/embed';
import * as report from '../src/report';
import * as visual from '../src/visual';
import * as create from '../src/create';
import * as dashboard from '../src/dashboard';
import * as page from '../src/page';
import * as sdkConfig from '../src/config';
import * as visualDescriptor from '../src/visualDescriptor';
import * as Wpmp from 'window-post-message-proxy';
import * as Hpm from 'http-post-message';
import * as Router from 'powerbi-router';
import * as models from 'powerbi-models';
import { spyApp } from './utility/mockEmbed';
import * as factories from '../src/factories';
import { spyHpm } from './utility/mockHpm';
import { spyRouter } from './utility/mockRouter';
import { APINotSupportedForRDLError } from '../src/errors';
import { iframeSrc } from './constsants';
describe('SDK-to-HPM', function () {
let powerbi: service.Service;
let page1: page.Page;
let visual1: visualDescriptor.VisualDescriptor;
let uniqueId = 'uniqueId';
let sdkSessionId = 'sdkSessionId';
let createUniqueId = 'uniqueId';
let dashboardUniqueId = 'uniqueId';
let visualUniqueId = 'uniqueId';
let embedConfiguration: embed.IEmbedConfiguration;
let visualEmbedConfiguration: embed.IVisualEmbedConfiguration;
beforeEach(function () {
const spyHpmFactory: factories.IHpmFactory = () => {
return <Hpm.HttpPostMessage><any>spyHpm;
};
const noop: factories.IWpmpFactory = () => {
return <Wpmp.WindowPostMessageProxy>null;
};
const spyRouterFactory: factories.IRouterFactory = () => {
return <Router.Router><any>spyRouter;
};
spyOn(utils, "getTimeDiffInMilliseconds").and.callFake(() => 700); // Prevent requests from being throttled.
powerbi = new service.Service(spyHpmFactory, noop, spyRouterFactory, { wpmpName: 'SDK-to-HPM report wpmp' });
sdkSessionId = powerbi.getSdkSessionId();
});
afterEach(function () {
spyHpm.get.calls.reset();
spyHpm.post.calls.reset();
spyHpm.patch.calls.reset();
spyHpm.put.calls.reset();
spyHpm.delete.calls.reset();
spyRouter.get.calls.reset();
spyRouter.post.calls.reset();
spyRouter.patch.calls.reset();
spyRouter.put.calls.reset();
spyRouter.delete.calls.reset();
spyApp.reset();
});
describe('report', function () {
let reportElement: HTMLDivElement;
let report: report.Report;
beforeEach(async () => {
reportElement = document.createElement('div');
reportElement.className = 'powerbi-report-container';
document.body.appendChild(reportElement);
embedConfiguration = {
type: "report",
id: "fakeReportId",
accessToken: 'fakeToken',
embedUrl: iframeSrc
};
spyHpm.post.and.callFake(() => Promise.resolve({}));
report = <report.Report>powerbi.embed(reportElement, embedConfiguration);
page1 = new page.Page(report, 'xyz');
visual1 = new visualDescriptor.VisualDescriptor(page1, 'uvw', 'title', 'type', {});
uniqueId = report.config.uniqueId;
const iframe = reportElement.getElementsByTagName('iframe')[0];
await new Promise<void>((resolve, _reject) => {
iframe.addEventListener('load', () => resolve(null));
});
spyHpm.post.and.callThrough();
});
afterEach(() => {
powerbi.reset(reportElement);
reportElement.remove();
});
describe('load', function () {
it('report.load() sends POST /report/load with configuration in body', async function () {
// Arrange
const testData = {
loadConfiguration: {
id: 'fakeId',
accessToken: 'fakeToken'
},
response: {
body: null
}
};
spyHpm.post.and.returnValue(Promise.resolve(testData.response));
// Act
let expectedConfiguration = utils.assign({}, report.config, testData.loadConfiguration);
report.config = expectedConfiguration;
await report.load();
// Assert
const expectedHeaders = {
bootstrapped: undefined,
sdkVersion: sdkConfig.default.version,
uid: uniqueId,
sdkSessionId: sdkSessionId
};
expect(spyHpm.post).toHaveBeenCalledWith('/report/load', expectedConfiguration, expectedHeaders, jasmine.any(Object));
});
it('report.load() returns promise that rejects with validation error if the load configuration is invalid', async function () {
// Arrange
const testData = {
errorResponse: {
body: {
message: "invalid configuration object"
}
}
};
spyHpm.post.and.callFake(() => Promise.reject(testData.errorResponse));
try {
// Act
await report.load();
fail("load shouldn't succeed");
} catch (error) {
const expectedHeaders = {
bootstrapped: undefined,
sdkVersion: sdkConfig.default.version,
uid: uniqueId,
sdkSessionId: sdkSessionId
};
expect(spyHpm.post).toHaveBeenCalledWith('/report/load', report.config, expectedHeaders, jasmine.any(Object));
expect(error).toEqual(testData.errorResponse.body);
}
});
it('report.load() returns promise that resolves with null if the report load successful', async function () {
// Arrange
const testData = {
response: {
body: null
}
};
spyHpm.post.and.callFake(() => Promise.resolve(testData.response));
// Act
try {
const response = await report.load();
const expectedHeaders = {
bootstrapped: undefined,
sdkVersion: sdkConfig.default.version,
uid: uniqueId,
sdkSessionId: sdkSessionId
};
expect(spyHpm.post).toHaveBeenCalledWith('/report/load', report.config, expectedHeaders, jasmine.any(Object));
expect(response).toEqual(null);
} catch (error) {
console.log("report.load failed with", error);
fail("report.load failed");
}
});
it('report.load() updates the internal configuration if the load request was successful', async function () {
// Arrange
const testData = {
loadConfiguration: {
id: 'newFakeId',
accessToken: 'newFakeToken'
},
response: {
body: null
}
};
spyHpm.post.and.returnValue(Promise.resolve(testData.response));
// Act
let expectedConfiguration = { ...report.config, ...testData.loadConfiguration };
report.config = expectedConfiguration;
try {
const response = await report.load();
expect(report.config).toEqual(jasmine.objectContaining(expectedConfiguration));
expect(response).toEqual(null);
} catch (error) {
console.log("report.load failed with", error);
fail("report.load failed");
}
});
});
describe('pages', function () {
it('report.getPages() sends GET /report/pages', async function () {
// Arrange
const testData = {
response: {
body: [
{
name: 'page1'
}
]
}
};
spyHpm.get.and.returnValue(Promise.resolve(testData.response));
// Act
await report.getPages();
// Assert
expect(spyHpm.get).toHaveBeenCalledWith('/report/pages', { uid: uniqueId }, jasmine.any(Object));
});
it('report.getPages() return promise that rejects with server error if there was error getting pages', async function () {
// Arrange
const testData = {
expectedError: {
body: {
message: 'internal server error'
}
}
};
spyHpm.get.and.callFake(() => Promise.reject(testData.expectedError));
try {
// Act
await report.getPages();
fail("getPages should have failed");
} catch (error) {
// Assert
expect(spyHpm.get).toHaveBeenCalledWith('/report/pages', { uid: uniqueId }, jasmine.any(Object));
expect(error).toEqual(testData.expectedError.body);
}
});
it('report.getPages() returns promise that resolves with list of Page objects', async function () {
// Arrange
const testData = {
pages: [
'page1',
'page2'
],
expectedResponse: {
body: [
report.page('page1'),
report.page('page2')
]
}
};
spyHpm.get.and.returnValue(Promise.resolve(testData.expectedResponse));
try {
// Act
const pages = await report.getPages();
// Assert
expect(spyHpm.get).toHaveBeenCalledWith('/report/pages', { uid: uniqueId }, jasmine.any(Object));
expect(pages[0].name).toEqual(testData.expectedResponse.body[0].name);
expect(pages[1].name).toEqual(testData.expectedResponse.body[1].name);
} catch (error) {
console.log("report.getPages failed with", error);
fail("report.getPages failed");
}
});
it('report.getPageByName() returns promise that rejects if report page with given page name not found', async function () {
// Arrange
const pageName = 'page1';
const testData = {
expectedError: {
body: {
message: 'page not found'
}
}
};
spyHpm.get.and.callFake(() => Promise.reject(testData.expectedError));
try {
// Act
await report.getPageByName(pageName);
fail("report.getPages should have failed");
} catch (error) {
// Assert
expect(spyHpm.get).toHaveBeenCalledWith('/report/pages', { uid: uniqueId }, jasmine.any(Object));
expect(error).toEqual(testData.expectedError.body);
}
});
it('report.getPageByName(pageName) returns promise that resolves with page if request is successful', async function () {
// Arrange
const pageName = "page1";
const testData = {
expectedResponse:
{
report: report,
name: "page1",
displayName: "Page 1",
isActive: true
}
};
spyApp.getPageByName.and.returnValue(Promise.resolve(testData.expectedResponse));
try {
// Act
const page = await spyApp.getPageByName(pageName);
// Assert
expect(spyApp.getPageByName).toHaveBeenCalled();
expect(page.name).toEqual(testData.expectedResponse.name);
expect(page.isActive).toEqual(testData.expectedResponse.isActive);
} catch (error) {
console.log("getPageByName failed with", error);
fail("getPageByName failed");
}
});
it('report.getActivePage() sends GET /report/pages', async function () {
// Arrange
const testData = {
response: {
body: [
{
name: 'page1',
isActive: true
}
]
}
};
spyHpm.get.and.returnValue(Promise.resolve(testData.response));
// Act
try {
await report.getActivePage();
} catch (error) {
// The test only checks hpm request
}
// Assert
expect(spyHpm.get).toHaveBeenCalledWith('/report/pages', { uid: uniqueId }, jasmine.any(Object));
});
it('report.getActivePage() return promise that rejects with server error if there was error getting active page', async function () {
// Arrange
const testData = {
expectedError: {
body: {
message: 'internal server error'
}
}
};
spyHpm.get.and.callFake(() => Promise.reject(testData.expectedError));
try {
// Act
await report.getActivePage();
} catch (error) {
// Assert
expect(spyHpm.get).toHaveBeenCalledWith('/report/pages', { uid: uniqueId }, jasmine.any(Object));
expect(error).toEqual(testData.expectedError.body);
}
});
it('report.getActivePage() return promise that rejects if embedded report is an RDL report', async function () {
// Arrange
const testData = {
expectedError: {
body: {
message: APINotSupportedForRDLError
}
}
};
spyHpm.get.and.callFake(() => Promise.reject(testData.expectedError));
try {
// Act
await report.getActivePage();
} catch (error) {
// Assert
expect(spyHpm.get).toHaveBeenCalledWith('/report/pages', { uid: uniqueId }, jasmine.any(Object));
expect(error).toEqual(testData.expectedError.body);
}
});
it('report.getActivePage() returns promise that resolves with a page if request is successful', async function () {
// Arrange
const testData = {
expectedResponse:
{
report: report,
name: "page1",
displayName: "Page 1",
isActive: true
}
};
spyApp.getActivePage.and.returnValue(Promise.resolve(testData.expectedResponse));
try {
// Act
const page = await spyApp.getActivePage();
// Assert
expect(spyApp.getActivePage).toHaveBeenCalled();
expect(page.name).toEqual(testData.expectedResponse.name);
expect(page.isActive).toEqual(testData.expectedResponse.isActive);
} catch (error) {
console.log("getActivePage failed with", error);
fail("getActivePage failed");
}
});
it('report.addPage() sends POST /report/addPage with displayName', async function () {
// Arrange
const displayName = "testName";
const expectedRequest = {
displayName: displayName
};
const expectedHeaders = { uid: uniqueId };
spyHpm.post.and.returnValue(Promise.resolve({ body: page1 }));
// Act
await report.addPage(displayName);
// Assert
expect(spyHpm.post).toHaveBeenCalledWith('/report/addPage', expectedRequest, expectedHeaders, jasmine.any(Object));
});
it('report.renamePage() sends PUT /report/pages/{name} with displayName', async function () {
// Arrange
const name = "testName";
const displayName = "newName";
const expectedHeaders = { uid: uniqueId };
const expectedRequest = {
name,
displayName
};
spyHpm.put.and.returnValue(Promise.resolve({}));
// Act
await report.renamePage(name, displayName);
expect(spyHpm.put).toHaveBeenCalledWith(`/report/pages/${name}/name`, expectedRequest, expectedHeaders, jasmine.any(Object));
});
it('report.deletePage() sends DELETE /report/pages/{name}', async function () {
// Arrange
const name = "testName";
const expectedHeaders = { uid: uniqueId };
spyHpm.delete.and.returnValue(Promise.resolve({}));
// Act
await report.deletePage(name);
expect(spyHpm.delete).toHaveBeenCalledWith(`/report/pages/${name}`, {}, expectedHeaders, jasmine.any(Object));
});
});
describe('filters', function () {
it('report.getFilters() sends GET /report/filters', async function () {
// Arrange
const testData = {
response: {
body: [
(new models.BasicFilter({ table: "Cars", measure: "Make" }, "In", ["subaru", "honda"])).toJSON(),
(new models.AdvancedFilter({ table: "Cars", measure: "Make" }, "And", [{ value: "subaru", operator: "None" }, { value: "honda", operator: "Contains" }])).toJSON()
]
}
};
spyHpm.get.and.returnValue(Promise.resolve(testData.response));
// Act
await report.getFilters();
// Assert
expect(spyHpm.get).toHaveBeenCalledWith('/report/filters', { uid: uniqueId }, jasmine.any(Object));
});
it('report.getFilters() returns promise that rejects with server error if there was error getting filters', async function () {
// Arrange
const testData = {
expectedErrors: {
body: [
{
message: 'target is invalid, missing property x'
}
]
}
};
spyHpm.get.and.callFake(() => Promise.reject(testData.expectedErrors));
try {
// Act
await report.getFilters();
} catch (errors) {
// Assert
expect(spyHpm.get).toHaveBeenCalledWith('/report/filters', { uid: uniqueId }, jasmine.any(Object));
expect(errors).toEqual(jasmine.objectContaining(testData.expectedErrors.body));
}
});
it('report.getFilters() returns promise that resolves with the filters if the request is accepted', async function () {
// Arrange
const testData = {
response: {
body: [
(new models.BasicFilter({ table: "Cars", measure: "Make" }, "In", ["subaru", "honda"])).toJSON(),
(new models.AdvancedFilter({ table: "Cars", measure: "Make" }, "And", [{ value: "subaru", operator: "None" }, { value: "honda", operator: "Contains" }])).toJSON()
]
}
};
spyHpm.get.and.returnValue(Promise.resolve(testData.response));
try {
// Act
const filters = await report.getFilters();
// Assert
expect(spyHpm.get).toHaveBeenCalledWith('/report/filters', { uid: uniqueId }, jasmine.any(Object));
expect(filters).toEqual(testData.response.body);
} catch (error) {
console.log("getFilters failed with", error);
fail("getFilters failed");
}
});
it('report.setFilters(filters) sends PUT /report/filters', async function () {
// Arrange
const testData = {
filters: [
(new models.BasicFilter({ table: "Cars", measure: "Make" }, "In", ["subaru", "honda"])).toJSON(),
(new models.AdvancedFilter({ table: "Cars", measure: "Make" }, "And", [{ value: "subaru", operator: "None" }, { value: "honda", operator: "Contains" }])).toJSON()
]
};
spyHpm.put.and.returnValue(Promise.resolve({}));
// Act
await report.setFilters(testData.filters);
// Assert
expect(spyHpm.put).toHaveBeenCalledWith('/report/filters', testData.filters, { uid: uniqueId }, jasmine.any(Object));
});
it('report.setFilters(filters) returns promise that rejects with validation errors if filter is invalid', async function () {
// Arrange
const testData = {
filters: [
(new models.BasicFilter({ table: "Cars", measure: "Make" }, "In", ["subaru", "honda"])).toJSON(),
(new models.AdvancedFilter({ table: "Cars", measure: "Make" }, "And", [{ value: "subaru", operator: "None" }, { value: "honda", operator: "Contains" }])).toJSON()
],
expectedErrors: {
body: [
{
message: 'target is invalid, missing property x'
}
]
}
};
spyHpm.put.and.callFake(() => Promise.reject(testData.expectedErrors));
try {
// Act
await report.setFilters(testData.filters);
} catch (errors) {
// Assert
expect(spyHpm.put).toHaveBeenCalledWith('/report/filters', testData.filters, { uid: uniqueId }, jasmine.any(Object));
expect(errors).toEqual(jasmine.objectContaining(testData.expectedErrors.body));
}
});
it('report.setFilters(filters) returns promise that resolves with null if filter was valid and request is accepted', async function () {
// Arrange
const testData = {
filters: [
(new models.BasicFilter({ table: "Cars", measure: "Make" }, "In", ["subaru", "honda"])).toJSON(),
(new models.AdvancedFilter({ table: "Cars", measure: "Make" }, "And", [{ value: "subaru", operator: "None" }, { value: "honda", operator: "Contains" }])).toJSON()
]
};
spyHpm.put.and.returnValue(Promise.resolve(null));
try {
// Act
const response = await report.setFilters(testData.filters);
expect(spyHpm.put).toHaveBeenCalledWith('/report/filters', testData.filters, { uid: uniqueId }, jasmine.any(Object));
expect(response).toEqual(null);
} catch (error) {
console.log("setFilters failed with", error);
fail("setFilters failed");
}
});
it('report.removeFilters() sends PUT /report/filters', async function () {
// Arrange
spyHpm.post.and.callFake(() => Promise.resolve({}));
// Act
await report.removeFilters();
// Assert
expect(spyHpm.post).toHaveBeenCalledWith('/report/filters', { filtersOperation: models.FiltersOperations.RemoveAll, filters: undefined }, { uid: uniqueId }, jasmine.any(Object));
});
it('report.removeFilters() returns promise that resolves with null if request is accepted', async function () {
// Arrange
spyHpm.post.and.returnValue(Promise.resolve(null));
// Act
const response = await report.removeFilters();
// Assert
expect(spyHpm.post).toHaveBeenCalledWith('/report/filters', { filtersOperation: models.FiltersOperations.RemoveAll, filters: undefined }, { uid: uniqueId }, jasmine.any(Object));
expect(response).toEqual(null);
});
});
describe('switchMode', function () {
it('report.switchMode() sends POST /report/switchMode', async function () {
// Arrange
spyHpm.post.and.returnValue(Promise.resolve({
body: {}
}));
// Act
await report.switchMode(models.ViewMode.Edit);
// Assert
const url = '/report/switchMode/edit';
expect(spyHpm.post).toHaveBeenCalledWith(url, null, { uid: uniqueId }, jasmine.any(Object));
});
it('report.switchMode() returns promise that resolves if the request is accepted', async function () {
// Arrange
spyHpm.post.and.returnValue(Promise.resolve({
body: {}
}));
// Act
await report.switchMode(models.ViewMode.Edit);
// Assert
let url = '/report/switchMode/edit';
expect(spyHpm.post).toHaveBeenCalledWith(url, null, { uid: uniqueId }, jasmine.any(Object));
});
});
describe('save', function () {
it('report.save() sends POST /report/save', async function () {
// Arrange
spyHpm.post.and.returnValue(Promise.resolve({
body: {}
}));
// Act
await report.save();
// Assert
expect(spyHpm.post).toHaveBeenCalledWith('/report/save', null, { uid: uniqueId }, jasmine.any(Object));
});
it('report.save() returns promise that resolves if the request is accepted', async function () {
// Arrange
spyHpm.post.and.returnValue(Promise.resolve({
body: {}
}));
// Act
await report.save();
// Assert
expect(spyHpm.post).toHaveBeenCalledWith('/report/save', null, { uid: uniqueId }, jasmine.any(Object));
});
});
describe('switchLayout', function () {
it('report.switchLayout(layout) returns promise that rejects with errors if there was error if initial layout and current layout type do not match', async function () {
// Arrange
// Set initial layout to desktop layout
report.config.settings.layoutType = models.LayoutType.Master;
const layoutType = models.LayoutType.MobileLandscape;
const testData = {
expectedError: {
message: 'Switching between mobile and desktop layouts is not supported. Please reset the embed container and re-embed with required layout.'
},
settings: {
layoutType: layoutType
}
};
spyHpm.patch.and.callFake(() => Promise.reject(testData.expectedError));
try {
// Act
await report.switchLayout(layoutType);
} catch (error) {
// Assert
expect(spyHpm.patch).not.toHaveBeenCalledWith('/report/settings', testData.settings, { uid: uniqueId }, jasmine.any(Object));
expect(error).toEqual(testData.expectedError.message);
}
});
it('report.switchLayout(layout) returns promise that resolves with null if requst is valid and accepted', async function () {
// Arrange
// Set initial layout to mobile layout
report.config.settings.layoutType = models.LayoutType.MobilePortrait;
const layoutType = models.LayoutType.MobileLandscape;
spyApp.switchLayout.and.returnValue(Promise.resolve(null));
// Act
const response = await spyApp.switchLayout(layoutType);
// Assert
expect(spyApp.switchLayout).toHaveBeenCalled();
expect(response).toEqual(null);
});
});
describe('custom layout', function () {
it('visual.moveVisual() returns promise that rejects with server error if error in updating setting', async function () {
// Arrange
const x = 0;
const y = 0;
const testData = {
expectedError: {
body: {
message: 'internal server error'
}
}
};
spyHpm.get.and.callFake(() => Promise.reject(testData.expectedError));
try {
// Act
await visual1.moveVisual(x, y);
} catch (error) {
// Assert
expect(spyHpm.get).toHaveBeenCalledWith('/report/pages', { uid: uniqueId }, jasmine.any(Object));
expect(error).toEqual(testData.expectedError.body);
}
});
it('visual.moveVisual() returns promise that resolves with null if request is valid and accepted', async function () {
// Arrange
const x = 0;
const y = 0;
spyApp.moveVisual.and.returnValue(Promise.resolve(null));
// Act
const response = await spyApp.moveVisual(x, y);
// Assert
expect(spyApp.moveVisual).toHaveBeenCalled();
expect(response).toEqual(null);
});
it('visual.setVisualDisplayState(displayState) returns promise that rejects with validation error if display state is invalid', async function () {
// Arrange
const displayState = 2;
const testData = {
expectedError: {
body: {
message: 'mode property is invalid'
}
},
};
spyApp.setVisualDisplayState.and.callFake(() => Promise.reject(testData.expectedError));
try {
// Act
await spyApp.setVisualDisplayState(displayState);
fail("setVisualDisplayState should have failed");
} catch (error) {
// Assert
expect(error).toEqual(testData.expectedError);
}
});
it('visual.setVisualDisplayState(displayState) returns promise that resolves with null if requst is valid and accepted', async function () {
// Arrange
const displayState = models.VisualContainerDisplayMode.Visible;
spyApp.setVisualDisplayState.and.returnValue(Promise.resolve(null));
// Act
const response = await spyApp.setVisualDisplayState(displayState);
// Assert
expect(spyApp.setVisualDisplayState).toHaveBeenCalled();
expect(response).toEqual(null);
});
it('visual.resizeVisual returns promise that rejects with server error if error in updating setting', async function () {
// Arrange
const width = 200;
const height = 100;
const testData = {
expectedError: {
body: {
message: 'internal server error'
}
}
};
spyHpm.get.and.callFake(() => Promise.reject(testData.expectedError));
try {
// Act
await visual1.resizeVisual(width, height);
fail("resizeVisual should have failed");
} catch (error) {
// Assert
expect(spyHpm.get).toHaveBeenCalledWith('/report/pages', { uid: uniqueId }, jasmine.any(Object));
expect(error).toEqual(testData.expectedError.body);
}
});
it('visual.resizeVisual returns promise that resolves with null if request is valid and accepted', async function () {
// Arrange
const width = 200;
const height = 100;
spyApp.resizeVisual.and.returnValue(Promise.resolve(null));
// Act
const response = await spyApp.resizeVisual(width, height);
// Assert
expect(spyApp.resizeVisual).toHaveBeenCalled();
expect(response).toEqual(null);
});
});
describe('saveAs', function () {
let saveAsParameters: models.ISaveAsParameters = { name: "reportName" };
it('report.saveAs() sends POST /report/saveAs', async function () {
// Arrange
spyHpm.post.and.returnValue(Promise.resolve({
body: {}
}));
// Act
await report.saveAs(saveAsParameters);
// Assert
expect(spyHpm.post).toHaveBeenCalledWith('/report/saveAs', saveAsParameters, { uid: uniqueId }, jasmine.any(Object));
});
it('report.saveAs() returns promise that resolves if the request is accepted', async function () {
// Arrange
spyHpm.post.and.returnValue(Promise.resolve({
body: {}
}));
// Act
await report.saveAs(saveAsParameters);
// Assert
expect(spyHpm.post).toHaveBeenCalledWith('/report/saveAs', saveAsParameters, { uid: uniqueId }, jasmine.any(Object));
});
});
describe('setAccessToken', function () {
let accessToken: string = "fakeToken";
it('report.setAccessToken() sends POST /report/token', async function () {
// Arrange
spyHpm.post.and.returnValue(Promise.resolve({
body: {}
}));
// Act
await report.setAccessToken(accessToken);
// Assert
expect(spyHpm.post).toHaveBeenCalledWith('/report/token', accessToken, { uid: uniqueId }, jasmine.any(Object));
});
it('report.setAccessToken() returns promise that resolves if the request is accepted', async function () {
// Arrange
spyHpm.post.and.returnValue(Promise.resolve({
body: {}
}));
let newToken = "newToken";
// Act
await report.setAccessToken(newToken);
// Assert
expect(spyHpm.post).toHaveBeenCalledWith('/report/token', newToken, { uid: uniqueId }, jasmine.any(Object));
expect(report.service.accessToken).toEqual(newToken);
expect(report.config.accessToken).toEqual(newToken);
expect(report.element.getAttribute(embed.Embed.accessTokenAttribute)).toEqual(newToken);
});
});
describe('print', function () {
it('report.print() sends POST /report/print', async function () {
// Arrange
spyHpm.post.and.returnValue(Promise.resolve({
body: {}
}));
// Act
await report.print();
// Assert
expect(spyHpm.post).toHaveBeenCalledWith('/report/print', null, { uid: uniqueId }, jasmine.any(Object));
});
it('report.print() returns promise that resolves if the request is accepted', async function () {
// Arrange
spyHpm.post.and.returnValue(Promise.resolve({
body: {}
}));
// Act
await report.print();
// Assert
expect(spyHpm.post).toHaveBeenCalledWith('/report/print', null, { uid: uniqueId }, jasmine.any(Object));
});
});
describe('reload', function () {
it('report.reload() sends POST /report/load with configuration in body', async function () {
// Arrange
const testData = {
response: {
body: null
}
};
spyHpm.post.and.returnValue(Promise.resolve(testData.response));
try {
await report.load();
spyHpm.post.calls.reset();
// Act
try {
await report.reload();
} catch (error) {
console.log("reloaed failed wtih", error);
fail("reload failed");
}
const expectedHeaders = {
bootstrapped: undefined,
sdkVersion: sdkConfig.default.version,
uid: uniqueId,
sdkSessionId: sdkSessionId
};
// Assert
expect(spyHpm.post).toHaveBeenCalledWith('/report/load', report.config, expectedHeaders, jasmine.any(Object));
} catch (error) {
console.log("load failed with", error);
fail("load failed");
}
});
});
describe('refresh', function () {
it('report.refresh() sends POST /report/refresh', async function () {
// Arrange
spyHpm.post.and.returnValue(Promise.resolve({
body: {}
}));
// Act
await report.refresh();
// Assert
expect(spyHpm.post).toHaveBeenCalledWith('/report/refresh', null, { uid: uniqueId }, jasmine.any(Object));
});
});
describe('settings', function () {
it('report.updateSettings(settings) sends PATCH /report/settings with settings object', async function () {
// Arrange
const testData = {
settings: {
filterPaneEnabled: false
}
};
spyHpm.patch.and.returnValue(Promise.resolve({}));
// Act
try {
await report.updateSettings(testData.settings);
// Assert
expect(spyHpm.patch).toHaveBeenCalledWith('/report/settings', testData.settings, { uid: uniqueId }, jasmine.any(Object));
} catch (error) {
console.log("updateSettings failed with", error);
fail("updateSettings failed");
}
});
it('report.updateSettings(setting) returns promise that rejects with validation error if object is invalid', async function () {
// Arrange
const testData = {
settings: {
filterPaneEnabled: false
},
expectedError: {
body: [
{
message: 'settings object is invalid'
}
]
}
};
spyHpm.patch.and.callFake(() => Promise.reject(testData.expectedError));
try {
await report.updateSettings(testData.settings);
fail("updateSettings should have failed");
} catch (errors) {
// Assert
expect(spyHpm.patch).toHaveBeenCalledWith('/report/settings', testData.settings, { uid: uniqueId }, jasmine.any(Object));
expect(errors).toEqual(testData.expectedError.body);
}
});
it('report.updateSettings(settings) returns promise that resolves with null if requst is valid and accepted', async function () {
// Arrange
const testData = {
settings: {
filterPaneEnabled: false
}
};
spyHpm.patch.and.returnValue(Promise.resolve(null));
// Act
const response = await report.updateSettings(testData.settings);
// Assert
expect(spyHpm.patch).toHaveBeenCalledWith('/report/settings', testData.settings, { uid: uniqueId }, jasmine.any(Object));
expect(response).toEqual(null);
});
it('report.addContextMenuCommand(commandName, commandTitle, contextMenuTitle) returns promise that rejects with validation errors if extensions property is invalid', async function () {
// Arrange
const commandName = "name1";
const commandTitle = "title1";
const contextMenuTitle = "menu1";
const testData = {
expectedError: {
body: [
{
message: 'extensions property is invalid'
}
]
},
settings: {
extensions: {
commands: [{
name: "name1",
title: "title1",
extend: {
visualContextMenu: {
title: contextMenuTitle,
menuLocation: 0
}
}
}],
groups: []
}
}
};
spyHpm.patch.and.callFake(() => Promise.reject(testData.expectedError));
try {
// Act
await report.addContextMenuCommand(commandName, commandTitle, contextMenuTitle, 0, "", "", "");
fail("addContextMenuCommand should have failed");
} catch (error) {
// Assert
expect(spyHpm.patch).toHaveBeenCalledWith('/report/settings', testData.settings, { uid: uniqueId }, jasmine.any(Object));
expect(error).toEqual(jasmine.objectContaining(testData.expectedError.body));
}
});
it('report.addContextMenuCommand(commandName, commandTitle, contextMenuTitle) returns promise that resolves with null if requst is valid and accepted', async function () {
// Arrange
const commandName = "name2";
const commandTitle = "title2";
const contextMenuTitle = "menu2";
spyApp.addContextMenuCommand.and.returnValue(Promise.resolve(null));
// Act
const response = await spyApp.addContextMenuCommand(commandName, commandTitle, contextMenuTitle);
// Assert
expect(spyApp.addContextMenuCommand).toHaveBeenCalled();
expect(response).toEqual(null);
});
it('report.addOptionsMenuCommand(commandName, commandTitle, optionsMenuTitle) returns promise that rejects with validation errors if extensions property is invalid', async function () {
// Arrange
const commandName = "name1";
const commandTitle = "title1";
const optionsMenuTitle = "menu1";
const testData = {
expectedError: {
body: [
{
message: 'extensions property is invalid'
}
]
},
settings: {
extensions: {
commands: [{
name: "name1",
title: "title1",
extend: {
visualOptionsMenu: {
title: "menu1",
menuLocation: 0,
}
},
icon: undefined
}],
groups: []
}
}
};
spyHpm.patch.and.callFake(() => Promise.reject(testData.expectedError));
try {
// Act
await report.addOptionsMenuCommand(commandName, commandTitle, optionsMenuTitle);
fail("addOptionsMenuCommand should have failed");
} catch (error) {
// Assert
expect(spyHpm.patch).toHaveBeenCalledWith('/report/settings', testData.settings, { uid: uniqueId }, jasmine.any(Object));
expect(error).toEqual(jasmine.objectContaining(testData.expectedError.body));
}
});
it('report.addOptionsMenuCommand(commandName, commandTitle, optionsMenuTitle) returns promise that resolves with null if requst is valid and accepted', async function () {
// Arrange
const commandName = "name2";
const commandTitle = "title2";
const optionsMenuTitle = "menu2";
spyApp.addOptionsMenuCommand.and.returnValue(Promise.resolve(null));
// Act
const response = await spyApp.addOptionsMenuCommand(commandName, commandTitle, optionsMenuTitle);
// Assert
expect(spyApp.addOptionsMenuCommand).toHaveBeenCalled();
expect(response).toEqual(null);
});
it('report.removeContextMenuCommand(commandName) returns promise that rejects with validation errors if command name is invalid', async function () {
// Arrange
const commandName = "name1";
const testData = {
expectedError: {
message: 'PowerBIEntityNotFound'
},
settings: {
extensions: {
commands: [{
name: "name1",
title: "title1",
extend: {
}
}]
}
}
};
spyApp.removeContextMenuCommand.and.callFake(() => Promise.reject(testData.expectedError));
try {
// Act
await spyApp.removeContextMenuCommand(commandName);
fail("removeContextMenuCommand should have failed");
} catch (error) {
// Assert
expect(spyHpm.patch).not.toHaveBeenCalledWith('/report/settings', testData.settings, { uid: uniqueId }, jasmine.any(Object));
expect(error).toEqual(jasmine.objectContaining(testData.expectedError));
}
});
it('report.removeContextMenuCommand(commandName) returns promise that resolves with null if requst is valid and accepted', async function () {
// Arrange
const commandName = "name2";
spyApp.removeContextMenuCommand.and.returnValue(Promise.resolve(null));
// Act
const response = await spyApp.removeContextMenuCommand(commandName);
// Assert
expect(spyApp.removeContextMenuCommand).toHaveBeenCalled();
expect(response).toEqual(null);
});
it('report.removeOptionsMenuCommand(commandName) returns promise that rejects with validation errors if command name is invalid', async function () {
// Arrange
const commandName = "name1";
const testData = {
expectedError: {
message: 'PowerBIEntityNotFound'
},
settings: {
extensions: {
commands: [{
name: "name1",
title: "title1",
icon: "",
extend: {
}
}]
}
}
};
spyApp.removeOptionsMenuCommand.and.callFake(() => Promise.reject(testData.expectedError));
try {
// Act
await spyApp.removeOptionsMenuCommand(commandName);
} catch (error) {
// Assert
expect(spyHpm.patch).not.toHaveBeenCalledWith('/report/settings', testData.settings, { uid: uniqueId }, jasmine.any(Object));
expect(error).toEqual(jasmine.objectContaining(testData.expectedError));
}
});
it('report.removeOptionsMenuCommand(commandName) returns promise that resolves with null if requst is valid and accepted', async function () {
// Arrange
const commandName = "name2";
spyApp.removeOptionsMenuCommand.and.returnValue(Promise.resolve(null));
// Act
const response = await spyApp.removeOptionsMenuCommand(commandName);
// Assert
expect(spyApp.removeOptionsMenuCommand).toHaveBeenCalled();
expect(response).toEqual(null);
});
it('report.setVisualDisplayState(pageName, visualName, displayState) returns promise that rejects with validation error if display state is invalid', async function () {
// Arrange
const pageName = 'page1';
const visualName = 'visual';
const displayState = 2;
const testData = {
expectedError: {
body: {
message: 'display state is invalid'
}
}
};
spyHpm.get.and.callFake(() => Promise.reject(testData.expectedError));
try {
// Act
await report.setVisualDisplayState(pageName, visualName, displayState);
} catch (error) {
// Assert
expect(spyHpm.get).toHaveBeenCalledWith('/report/pages', { uid: uniqueId }, jasmine.any(Object));
expect(error).toEqual(testData.expectedError.body);
}
});
it('report.setVisualDisplayState(pageName, visualName, displayState) returns promise that resolves with null if requst is valid and accepted', async function () {
// Arrange
const pageName = 'page1';
const visualName = 'visual';
const displayState = models.VisualContainerDisplayMode.Visible;
spyApp.setVisualDisplayState.and.returnValue(Promise.resolve(null));
// Act
const response = await spyApp.setVisualDisplayState(pageName, visualName, displayState);
// Assert
expect(spyApp.setVisualDisplayState).toHaveBeenCalled();
expect(response).toEqual(null);
});
it('report.resizeVisual returns promise that rejects with validation error if page name is invalid', async function () {
// Arrange
const pageName = 'invalid page';
const visualName = 'visual';
const width = 200;
const height = 100;
const testData = {
expectedError: {
body: {
message: 'page name is invalid'
}
}
};
spyHpm.get.and.callFake(() => Promise.reject(testData.expectedError));
try {
// Act
await report.resizeVisual(pageName, visualName, width, height);
} catch (error) {
// Assert
expect(spyHpm.get).toHaveBeenCalledWith('/report/pages', { uid: uniqueId }, jasmine.any(Object));
expect(error).toEqual(testData.expectedError.body);
}
});
it('report.resizeVisual returns promise that resolves with null if request is valid and accepted', async function () {
// Arrange
const pageName = 'page1';
const visualName = 'visual';
const width = 200;
const height = 100;
spyApp.resizeVisual.and.returnValue(Promise.resolve(null));
// Act
const response = await spyApp.resizeVisual(pageName, visualName, width, height);
// Assert
expect(spyApp.resizeVisual).toHaveBeenCalled();
expect(response).toEqual(null);
});
it('report.resizeActivePage returns promise that rejects with validation error if page size type is invalid', async function () {
// Arrange
const pageSizeType = 5;
const width = 200;
const height = 100;
const testData = {
expectedError: {
body: {
message: 'page size type is invalid'
}
},
settings: {
layoutType: models.LayoutType.Custom,
customLayout: {
pageSize: {
type: pageSizeType,
width: width,
height: height
}
}
}
};
spyHpm.patch.and.callFake(() => Promise.reject(testData.expectedError));
try {
// Act
await report.resizeActivePage(pageSizeType, width, height);
} catch (error) {
// Assert
expect(spyHpm.patch).toHaveBeenCalledWith('/report/settings', testData.settings, { uid: uniqueId }, jasmine.any(Object));
expect(error).toEqual(testData.expectedError.body);
}
});
it('report.resizeActivePage returns promise that resolves with null if request is valid and accepted', async function () {
// Arrange
const pageSizeType = models.PageSizeType.Custom;
const width = 200;
const height = 100;
spyApp.resizeActivePage.and.returnValue(Promise.resolve(null));
// Act
const response = await spyApp.resizeActivePage(pageSizeType, width, height);
// Assert
expect(spyApp.resizeActivePage).toHaveBeenCalled();
expect(response).toEqual(null);
});
it('moveVisual returns promise that rejects with validation error if visual name is invalid', async function () {
// Arrange
const pageName = 'page1';
const visualName = 'invalid visual';
const x = 0;
const y = 0;
const testData = {
expectedError: {
body: {
message: 'visual name is invalid'
}
}
};
spyHpm.get.and.callFake(() => Promise.reject(testData.expectedError));
try {
// Act
await report.moveVisual(pageName, visualName, x, y);
} catch (error) {
// Assert
expect(spyHpm.get).toHaveBeenCalledWith('/report/pages', { uid: uniqueId }, jasmine.any(Object));
expect(error).toEqual(testData.expectedError.body);
}
});
it('moveVisual returns promise that resolves with null if requst is valid and accepted', async function () {
// Arrange
const pageName = 'page1';
const visualName = 'visual';
const x = 0;
const y = 0;
spyApp.moveVisual.and.returnValue(Promise.resolve(null));
// Act
const response = await spyApp.moveVisual(pageName, visualName, x, y);
// Assert
expect(spyApp.moveVisual).toHaveBeenCalled();
expect(response).toEqual(null);
});
});
describe('visual level filters', function () {
it('visual.getFilters() sends GET /report/pages/xyz/visuals/uvw/filters', async function () {
// Arrange
spyHpm.get.and.callFake(() => Promise.resolve({}));
// Act
await visual1.getFilters();
// Assert
expect(spyHpm.get).toHaveBeenCalledWith(`/report/pages/${page1.name}/visuals/${visual1.name}/filters`, { uid: uniqueId }, jasmine.any(Object));
});
it('visual.getFilters() return promise that rejects with server error if there was error getting filters', async function () {
// Arrange
const testData = {
expectedError: {
body: {
message: 'internal server error'
}
}
};
spyHpm.get.and.callFake(() => Promise.reject(testData.expectedError));
try {
// Act
await visual1.getFilters();
} catch (error) {
// Assert
expect(spyHpm.get).toHaveBeenCalledWith(`/report/pages/${page1.name}/visuals/${visual1.name}/filters`, { uid: uniqueId }, jasmine.any(Object));
expect(error).toEqual(testData.expectedError.body);
}
});
it('visual.getFilters() returns promise that resolves with list of filters', async function () {
// Arrange
const testData = {
expectedResponse: {
body: [
{ x: 'fakeFilter1' },
{ x: 'fakeFilter2' }
]
}
};
spyHpm.get.and.returnValue(Promise.resolve(testData.expectedResponse));
// Act
const filters = await visual1.getFilters();
// Assert
expect(spyHpm.get).toHaveBeenCalledWith(`/report/pages/${page1.name}/visuals/${visual1.name}/filters`, { uid: uniqueId }, jasmine.any(Object));
// @ts-ignore as testData is not of type IFilter
expect(filters).toEqual(testData.expectedResponse.body);
});
it('visual.setFilters(filters) sends PUT /report/pages/xyz/visuals/uvw/filters', async function () {
// Arrange
const testData = {
filters: [
(new models.BasicFilter({ table: "Cars", measure: "Make" }, "In", ["subaru", "honda"])).toJSON(),
(new models.AdvancedFilter({ table: "Cars", measure: "Make" }, "And", [{ value: "subaru", operator: "None" }, { value: "honda", operator: "Contains" }])).toJSON()
],
response: {
body: []
}
};
spyHpm.put.and.returnValue(Promise.resolve(testData.response));
// Act
await visual1.setFilters(testData.filters);
// Assert
expect(spyHpm.put).toHaveBeenCalledWith(`/report/pages/${page1.name}/visuals/${visual1.name}/filters`, testData.filters, { uid: uniqueId }, jasmine.any(Object));
});
it('visual.setFilters(filters) returns promise that rejects with validation errors if filter is invalid', async function () {
// Arrange
const testData = {
filters: [
(new models.BasicFilter({ table: "Cars", measure: "Make" }, "In", ["subaru", "honda"])).toJSON(),
(new models.AdvancedFilter({ table: "Cars", measure: "Make" }, "And", [{ value: "subaru", operator: "None" }, { value: "honda", operator: "Contains" }])).toJSON()
],
expectedErrors: {
body: [
{
message: 'target is invalid, missing property x'
}
]
}
};
spyHpm.put.and.callFake(() => Promise.reject(testData.expectedErrors));
try {
// Act
await visual1.setFilters(testData.filters);
fail("setFilters shouldn't succeed");
} catch (errors) {
// Assert
expect(spyHpm.put).toHaveBeenCalledWith(`/report/pages/${page1.name}/visuals/${visual1.name}/filters`, testData.filters, { uid: uniqueId }, jasmine.any(Object));
expect(errors).toEqual(jasmine.objectContaining(testData.expectedErrors.body));
}
});
it('visual.setFilters(filters) returns promise that resolves with null if filter was valid and request is accepted', async function () {
// Arrange
const testData = {
filters: [
(new models.BasicFilter({ table: "Cars", measure: "Make" }, "In", ["subaru", "honda"])).toJSON(),
(new models.AdvancedFilter({ table: "Cars", measure: "Make" }, "And", [{ value: "subaru", operator: "None" }, { value: "honda", operator: "Contains" }])).toJSON()
]
};
spyHpm.put.and.returnValue(Promise.resolve(null));
try {
// Act
const response = await visual1.setFilters(testData.filters);
// Assert
expect(spyHpm.put).toHaveBeenCalledWith(`/report/pages/${page1.name}/visuals/${visual1.name}/filters`, testData.filters, { uid: uniqueId }, jasmine.any(Object));
expect(response).toEqual(null);
} catch (error) {
console.log("setFilters failed with", error);
fail("setFilters failed");
}
});
it('visual.removeFilters() sends PUT /report/pages/xyz/visuals/uvw/filters', async function () {
// Arrange
// Act
await visual1.removeFilters();
// Assert
expect(spyHpm.post).toHaveBeenCalledWith(`/report/pages/${page1.name}/visuals/${visual1.name}/filters`, { filtersOperation: models.FiltersOperations.RemoveAll, filters: undefined }, { uid: uniqueId }, jasmine.any(Object));
});
it('visual.removeFilters() returns promise that resolves with null if request is accepted', async function () {
// Arrange
spyHpm.post.and.returnValue(Promise.resolve(null));
// Act
const response = await visual1.removeFilters();
// Assert
expect(spyHpm.post).toHaveBeenCalledWith(`/report/pages/${page1.name}/visuals/${visual1.name}/filters`, { filtersOperation: models.FiltersOperations.RemoveAll, filters: undefined }, { uid: uniqueId }, jasmine.any(Object));
expect(response).toEqual(null);
});
});
describe('page', function () {
describe('filters', function () {
it('page.getFilters() sends GET /report/pages/xyz/filters', async function () {
// Arrange
spyHpm.get.and.callFake(() => Promise.resolve({}));
// Act
await page1.getFilters();
// Assert
expect(spyHpm.get).toHaveBeenCalledWith(`/report/pages/${page1.name}/filters`, { uid: uniqueId }, jasmine.any(Object));
});
it('page.getFilters() return promise that rejects with server error if there was error getting filters', async function () {
// Arrange
const testData = {
expectedError: {
body: {
message: 'internal server error'
}
}
};
spyHpm.get.and.callFake(() => Promise.reject(testData.expectedError));
try {
// Act
await page1.getFilters();
} catch (error) {
// Assert
expect(spyHpm.get).toHaveBeenCalledWith(`/report/pages/${page1.name}/filters`, { uid: uniqueId }, jasmine.any(Object));
expect(error).toEqual(testData.expectedError.body);
}
});
it('page.getFilters() returns promise that resolves with list of filters', async function () {
// Arrange
const testData = {
expectedResponse: {
body: [
{ x: 'fakeFilter1' },
{ x: 'fakeFilter2' }
]
}
};
spyHpm.get.and.returnValue(Promise.resolve(testData.expectedResponse));
// Act
const filters = await page1.getFilters();
// Assert
expect(spyHpm.get).toHaveBeenCalledWith(`/report/pages/${page1.name}/filters`, { uid: uniqueId }, jasmine.any(Object));
// @ts-ignore as testData is not of type IFilter
expect(filters).toEqual(testData.expectedResponse.body);
});
it('page.setFilters(filters) sends PUT /report/pages/xyz/filters', async function () {
// Arrange
const testData = {
filters: [
(new models.BasicFilter({ table: "Cars", measure: "Make" }, "In", ["subaru", "honda"])).toJSON(),
(new models.AdvancedFilter({ table: "Cars", measure: "Make" }, "And", [{ value: "subaru", operator: "None" }, { value: "honda", operator: "Contains" }])).toJSON()
],
response: {
body: []
}
};
spyHpm.put.and.returnValue(Promise.resolve(testData.response));
// Act
await page1.setFilters(testData.filters);
// Assert
expect(spyHpm.put).toHaveBeenCalledWith(`/report/pages/${page1.name}/filters`, testData.filters, { uid: uniqueId }, jasmine.any(Object));
});
it('page.setFilters(filters) returns promise that rejects with validation errors if filter is invalid', async function () {
// Arrange
const testData = {
filters: [
(new models.BasicFilter({ table: "Cars", measure: "Make" }, "In", ["subaru", "honda"])).toJSON(),
(new models.AdvancedFilter({ table: "Cars", measure: "Make" }, "And", [{ value: "subaru", operator: "None" }, { value: "honda", operator: "Contains" }])).toJSON()
],
expectedErrors: {
body: [
{
message: 'target is invalid, missing property x'
}
]
}
};
spyHpm.put.and.callFake(() => Promise.reject(testData.expectedErrors));
try {
// Act
await page1.setFilters(testData.filters);
} catch (errors) {
// Assert
expect(spyHpm.put).toHaveBeenCalledWith(`/report/pages/${page1.name}/filters`, testData.filters, { uid: uniqueId }, jasmine.any(Object));
expect(errors).toEqual(jasmine.objectContaining(testData.expectedErrors.body));
}
});
it('page.setFilters(filters) returns promise that resolves with null if filter was valid and request is accepted', async function () {
// Arrange
const testData = {
filters: [
(new models.BasicFilter({ table: "Cars", measure: "Make" }, "In", ["subaru", "honda"])).toJSON(),
(new models.AdvancedFilter({ table: "Cars", measure: "Make" }, "And", [{ value: "subaru", operator: "None" }, { value: "honda", operator: "Contains" }])).toJSON()
]
};
spyHpm.put.and.returnValue(Promise.resolve(null));
// Act
const response = await page1.setFilters(testData.filters);
// Assert
expect(spyHpm.put).toHaveBeenCalledWith(`/report/pages/${page1.name}/filters`, testData.filters, { uid: uniqueId }, jasmine.any(Object));
expect(response).toEqual(null);
});
it('page.removeFilters() sends PUT /report/pages/xyz/filters', async function () {
// Arrange
// Act
await page1.removeFilters();
// Assert
expect(spyHpm.post).toHaveBeenCalledWith(`/report/pages/${page1.name}/filters`, { filtersOperation: models.FiltersOperations.RemoveAll, filters: undefined }, { uid: uniqueId }, jasmine.any(Object));
});
it('page.removeFilters() returns promise that resolves with null if request is accepted', async function () {
// Arrange
spyHpm.post.and.returnValue(Promise.resolve(null));
// Act
const response = await page1.removeFilters();
// Assert
expect(spyHpm.post).toHaveBeenCalledWith(`/report/pages/${page1.name}/filters`, { filtersOperation: models.FiltersOperations.RemoveAll, filters: undefined }, { uid: uniqueId }, jasmine.any(Object));
expect(response).toEqual(null);
});
});
describe('setActive', function () {
it('page.setActive() sends PUT /report/pages/active', async function () {
// Arrange
const testData = {
page: {
name: page1.name,
displayName: null,
isActive: true,
}
};
spyHpm.put.and.returnValue(Promise.resolve(null));
// Act
await page1.setActive();
// Assert
expect(spyHpm.put).toHaveBeenCalledWith(`/report/pages/active`, testData.page, { uid: uniqueId }, jasmine.any(Object));
});
it('page.setActive() returns a promise rejected with errors if the page was invalid', async function () {
// Arrange
const testData = {
page: {
name: page1.name,
displayName: null,
isActive: true,
},
response: {
body: [
{
message: 'page abc123 does not exist on report xyz'
}
]
}
};
spyHpm.put.and.callFake(() => Promise.reject(testData.response));
try {
// Act
await page1.setActive();
fail("setActive should have failed");
} catch (errors) {
// Assert
expect(spyHpm.put).toHaveBeenCalledWith(`/report/pages/active`, testData.page, { uid: uniqueId }, jasmine.any(Object));
expect(errors).toEqual(jasmine.objectContaining(testData.response.body));
}
});
it('page.setActive() returns a promise resolved with null if the page is valid', async function () {
// Arrange
const testData = {
page: {
name: page1.name,
displayName: null,
isActive: true,
}
};
spyHpm.put.and.returnValue(Promise.resolve(null));
// Act
const response = await page1.setActive();
// Assert
expect(spyHpm.put).toHaveBeenCalledWith(`/report/pages/active`, testData.page, { uid: uniqueId }, jasmine.any(Object));
expect(response).toEqual(null);
});
});
describe('custom layout', function () {
it('page.setVisualDisplayState returns promise that rejects with validation error if display state is invalid', async function () {
// Arrange
const visualName = 'visual';
const displayState = 2;
const testData = {
expectedError: {
body: {
message: 'display state is invalid'
}
}
};
spyHpm.get.and.callFake(() => Promise.reject(testData.expectedError));
try {
// Act
await page1.setVisualDisplayState(visualName, displayState);
fail("setVisualDisplayState should have failed");
} catch (error) {
// Assert
expect(spyHpm.get).toHaveBeenCalledWith('/report/pages', { uid: uniqueId }, jasmine.any(Object));
expect(error).toEqual(testData.expectedError.body);
}
});
it('page.setVisualDisplayState returns promise that resolves with null if requst is valid and accepted', async function () {
// Arrange
const visualName = 'visual';
const displayState = models.VisualContainerDisplayMode.Visible;
spyApp.setVisualDisplayState.and.returnValue(Promise.resolve(null));
// Act
const response = await spyApp.setVisualDisplayState(visualName, displayState);
// Assert
expect(spyApp.setVisualDisplayState).toHaveBeenCalled();
expect(response).toEqual(null);
});
it('page.moveVisual returns promise that rejects with validation error if visual name is invalid', async function () {
// Arrange
const visualName = 'invalid visual';
const x = 0;
const y = 0;
const testData = {
expectedError: {
body: {
message: 'visual name is invalid'
}
}
};
spyHpm.get.and.callFake(() => Promise.reject(testData.expectedError));
try {
// Act
await page1.moveVisual(visualName, x, y);
} catch (error) {
// Assert
expect(spyHpm.get).toHaveBeenCalledWith('/report/pages', { uid: uniqueId }, jasmine.any(Object));
expect(error).toEqual(testData.expectedError.body);
}
});
it('page.moveVisual returns promise that resolves with null if requst is valid and accepted', async function () {
// Arrange
const visualName = 'visual';
const x = 0;
const y = 0;
spyApp.moveVisual.and.returnValue(Promise.resolve(null));
// Act
const response = await spyApp.moveVisual(visualName, x, y);
// Assert
expect(spyApp.moveVisual).toHaveBeenCalled();
expect(response).toEqual(null);
});
it('page.resizePage returns promise that rejects with validation error if page is not active page', async function () {
// Arrange=-
const pageSizeType = 1;
const width = 200;
const height = 100;
const testData = {
expectedError: {
message: 'Cannot resize the page. Only the active page can be resized'
},
settings: {
layoutType: models.LayoutType.Custom,
customLayout: {
pageSize: {
type: pageSizeType,
width: width,
height: height
}
}
}
};
spyHpm.patch.and.callFake(() => Promise.reject(testData.expectedError.message));
try {
// Act
await page1.resizePage(pageSizeType, width, height);
} catch (error) {
// Assert
expect(spyHpm.patch).not.toHaveBeenCalledWith('/report/settings', testData.settings, { uid: uniqueId }, jasmine.any(Object));
expect(error).toEqual(testData.expectedError.message);
}
});
it('page.resizePage returns promise that resolves with null if page is active page', async function () {
// Arrange
const pageSizeType = 1;
const width = 200;
const height = 100;
const testData = {
settings: {
layoutType: models.LayoutType.Custom,
customLayout: {
pageSize: {
type: pageSizeType,
width: width,
height: height
}
}
}
};
page1.isActive = true;
spyHpm.patch.and.returnValue(Promise.resolve(null));
// Act
const response = await page1.resizePage(pageSizeType, width, height);
// Assert
expect(spyHpm.patch).toHaveBeenCalledWith('/report/settings', testData.settings, { uid: uniqueId }, jasmine.any(Object));
expect(response).toEqual(null);
});
it('page.resizePage returns promise that resolves with null if request is valid and accepted', async function () {
// Arrange
const pageSizeType = models.PageSizeType.Custom;
const width = 200;
const height = 100;
spyApp.resizeActivePage.and.returnValue(Promise.resolve(null));
// Act
const response = await spyApp.resizeActivePage(pageSizeType, width, height);
// Assert
expect(spyApp.resizeActivePage).toHaveBeenCalled();
expect(response).toEqual(null);
});
});
});
describe('setDisplayName', function () {
it('page.setDisplayName(displayName) sends PUT /report/pages/{pageName}/name', async function () {
// Arrange
const displayName = "newName";
const testData = {
page: {
name: page1.name,
displayName,
}
};
spyHpm.put.and.returnValue(Promise.resolve(null));
// Act
await page1.setDisplayName(displayName);
// Assert
expect(spyHpm.put).toHaveBeenCalledWith(`/report/pages/${page1.name}/name`, testData.page, { uid: uniqueId }, jasmine.any(Object));
});
});
describe('getVisualByName', function () {
it('page.getVisualByName(visualName) returns promise that rejects if visual with given name not found', async function () {
// Arrange
const pageName = page1.name;
const visualName = "visual1";
const testData = {
expectedError: {
body: {
message: 'visual not found'
}
}
};
spyHpm.get.and.callFake(() => Promise.reject(testData.expectedError));
try {
// Act
await page1.getVisualByName(visualName);
} catch (error) {
// Assert
expect(spyHpm.get).toHaveBeenCalledWith(`/report/pages/${pageName}/visuals`, { uid: uniqueId }, jasmine.any(Object));
expect(error).toEqual(testData.expectedError.body);
}
});
it('page.getVisualByName(visualName) returns promise that resolves with visual if request is successful', async function () {
// Arrange
const visualName = "visual1";
const testData = {
expectedResponse:
{
name: "visual1",
title: "Visual 1",
type: "type1",
layout: {},
page: {}
}
};
spyApp.getVisualByName.and.returnValue(Promise.resolve(testData.expectedResponse));
// Act
const visual = await spyApp.getVisualByName(visualName);
// Assert
expect(spyApp.getVisualByName).toHaveBeenCalled();
expect(visual.name).toEqual(testData.expectedResponse.name);
expect(visual.title).toEqual(testData.expectedResponse.title);
});
});
describe('SDK-to-Router (Event subscription)', function () {
/**
* This test should likely be moved to mock app section or removed since it is already covered.
* The validation of supported events should likely happen by powerbi instead of by the SDK
* since this is maitanence problem
*/
it(`report.on(eventName, handler) should throw error if eventName is not supported`, function () {
// Arrange
const testData = {
eventName: 'xyz',
handler: jasmine.createSpy('handler')
};
// Act
const attemptToSubscribeToEvent = (): void => {
report.on(testData.eventName, testData.handler);
};
// Assert
expect(attemptToSubscribeToEvent).toThrowError();
});
});
describe('theme', function () {
it('report.getTheme() sends GET /report/theme', async function () {
// Arrange
const testData = {
response: {
body: [
{
themeJson: {name: "Theme ABC 123"}
}
]
}
};
const expectedHeaders = {
uid: uniqueId,
};
spyHpm.get.and.returnValue(Promise.resolve(testData.response));
try {
await report.getTheme();
expect(spyHpm.put).toHaveBeenCalledWith('/report/theme', expectedHeaders, jasmine.any(Object));
} catch (error) {
console.log("getTheme failed with", error);
fail("getTheme failed");
}
});
it('report.applyTheme(theme) sends PUT /report/theme with theme in body', async function () {
// Arrange
const testData = {
theme: {
themeJson: {
name: "Theme ABC 123"
}
},
response: {
body: null
}
};
const expectedHeaders = {
uid: uniqueId,
};
spyHpm.put.and.returnValue(Promise.resolve(testData.response));
try {
await report.applyTheme(testData.theme);
expect(spyHpm.put).toHaveBeenCalledWith('/report/theme', jasmine.objectContaining(testData.theme), expectedHeaders, jasmine.any(Object));
} catch (error) {
console.log("applyTheme failed with", error);
fail("applyTheme failed");
}
});
it('report.resetTheme() sends PUT /report/theme with empty object as theme in body', async function () {
// Arrange
const response = {
body: null
};
const expectedHeaders = {
uid: uniqueId,
};
spyHpm.put.and.returnValue(Promise.resolve(response));
try {
await report.resetTheme();
expect(spyHpm.put).toHaveBeenCalledWith('/report/theme', {}, expectedHeaders, jasmine.any(Object));
} catch (error) {
console.log("resetTheme failed with", error);
fail("resetTheme failed");
}
});
});
});
describe('createReport', function () {
let createElement: HTMLDivElement;
let create: create.Create;
beforeEach(async () => {
createElement = document.createElement('div');
createElement.className = 'powerbi-create-container';
document.body.appendChild(createElement);
const embedCreateConfiguration = {
datasetId: "fakeReportId",
accessToken: 'fakeToken',
embedUrl: iframeSrc
};
spyHpm.post.and.returnValue(Promise.resolve({}));
create = <create.Create>powerbi.createReport(createElement, embedCreateConfiguration);
createUniqueId = create.config.uniqueId;
const createIframe = createElement.getElementsByTagName('iframe')[0];
await new Promise<void>((resolve, _reject) => createIframe.addEventListener('load', () => resolve(null)));
spyHpm.post.and.callThrough();
});
afterEach(() => {
powerbi.reset(createElement);
createElement.remove();
});
it('create.createReport() sends POST /report/create with configuration in body', async function () {
// Arrange
const testData = {
createConfiguration: {
datasetId: 'fakeId',
accessToken: 'fakeToken'
},
response: {
body: null
}
};
spyHpm.post.and.returnValue(Promise.resolve(testData.response));
// Act
await create.createReport(testData.createConfiguration);
// Assert
expect(spyHpm.post).toHaveBeenCalledWith('/report/create', testData.createConfiguration, { uid: createUniqueId, sdkSessionId: sdkSessionId }, jasmine.any(Object));
});
it('create.createReport() returns promise that rejects with validation error if the create configuration is invalid', async function () {
// Arrange
const testData = {
createConfiguration: {
datasetId: 'fakeId',
accessToken: 'fakeToken'
},
errorResponse: {
body: {
message: "invalid configuration object"
}
}
};
spyHpm.post.and.callFake(() => Promise.reject(testData.errorResponse));
try {
// Act
await create.createReport(testData.createConfiguration);
} catch (error) {
// Assert
expect(spyHpm.post).toHaveBeenCalledWith('/report/create', testData.createConfiguration, { uid: createUniqueId, sdkSessionId: sdkSessionId }, jasmine.any(Object));
expect(error).toEqual(testData.errorResponse.body);
}
});
it('create.createReport() returns promise that resolves with null if create report was successful', async function () {
// Arrange
const testData = {
createConfiguration: {
datasetId: 'fakeId',
accessToken: 'fakeToken'
},
response: {
body: null
}
};
spyHpm.post.and.returnValue(Promise.resolve(testData.response));
// Act
const response = await create.createReport(testData.createConfiguration);
// Assert
expect(spyHpm.post).toHaveBeenCalledWith('/report/create', testData.createConfiguration, { uid: createUniqueId, sdkSessionId: sdkSessionId }, jasmine.any(Object));
expect(response).toEqual(null);
});
});
describe('dashboard', function () {
let dashboardElement: HTMLDivElement;
let dashboard: dashboard.Dashboard;
beforeEach(async () => {
dashboardElement = document.createElement('div');
dashboardElement.className = 'powerbi-dashboard-container';
document.body.appendChild(dashboardElement);
const dashboardEmbedConfiguration = {
type: "dashboard",
id: "fakeDashboardId",
accessToken: 'fakeToken',
embedUrl: iframeSrc
};
spyHpm.post.and.returnValue(Promise.resolve({}));
dashboard = <dashboard.Dashboard>powerbi.embed(dashboardElement, dashboardEmbedConfiguration);
dashboardUniqueId = dashboard.config.uniqueId;
const dashboardIframe = dashboardElement.getElementsByTagName('iframe')[0];
await new Promise<void>((resolve, _reject) => {
dashboardIframe.addEventListener('load', () => resolve(null));
});
spyHpm.post.and.callThrough();
});
afterEach(() => {
powerbi.reset(dashboardElement);
dashboardElement.remove();
});
it('dashboard.load() sends POST /dashboard/load with configuration in body', async function () {
spyHpm.post.and.returnValue(Promise.resolve({}));
try {
// Act
dashboard.iframeLoaded = true;
await dashboard.load();
const expectedHeaders = {
bootstrapped: undefined,
sdkVersion: sdkConfig.default.version,
uid: dashboardUniqueId,
sdkSessionId: sdkSessionId
};
expect(spyHpm.post).toHaveBeenCalled();
// Assert
expect(spyHpm.post).toHaveBeenCalledWith('/dashboard/load', dashboard.config, expectedHeaders, jasmine.any(Object));
} catch (error) {
console.log("dashboard load failed with", error);
fail("dashboard load failed");
}
});
});
describe('visual', function () {
let visualElement: HTMLDivElement;
let embeddedVisual: visual.Visual;
beforeEach(async () => {
visualElement = document.createElement('div');
visualElement.className = 'powerbi-report-container';
document.body.appendChild(visualElement);
visualEmbedConfiguration = {
id: "visual1",
accessToken: 'fakeToken',
embedUrl: iframeSrc,
type: "visual",
pageName: "ReportSection1",
visualName: "VisualContainer1",
width: 1200,
height: 1000
};
spyHpm.post.and.callFake(() => Promise.resolve({}));
embeddedVisual = powerbi.embed(visualElement, visualEmbedConfiguration) as any as visual.Visual;
visualUniqueId = embeddedVisual.config.uniqueId;
const visualFrame = visualElement.getElementsByTagName('iframe')[0];
await new Promise<void>((resolve, _reject) => {
visualFrame.addEventListener('load', () => resolve(null));
});
spyHpm.post.and.callThrough();
});
afterEach(() => {
powerbi.reset(visualElement);
visualElement.remove();
});
it('powerbi.embed with visual name sends POST /report/load with custom layout configuration in body', async function () {
let testData = {
loadConfiguration: visualEmbedConfiguration,
response: {
body: null
}
};
let expectedConfiguration = {
id: visualEmbedConfiguration.id,
accessToken: visualEmbedConfiguration.accessToken,
embedUrl: visualEmbedConfiguration.embedUrl,
type: visualEmbedConfiguration.type,
pageName: visualEmbedConfiguration.pageName,
visualName: visualEmbedConfiguration.visualName,
width: visualEmbedConfiguration.width,
height: visualEmbedConfiguration.height,
groupId: undefined,
uniqueId: embeddedVisual.config.uniqueId,
settings: {
filterPaneEnabled: false,
navContentPaneEnabled: false,
layoutType: models.LayoutType.Custom,
customLayout: {
displayOption: models.DisplayOption.FitToPage,
pageSize: {
type: models.PageSizeType.Custom,
width: testData.loadConfiguration.width,
height: testData.loadConfiguration.height,
},
pagesLayout: {
ReportSection1: {
defaultLayout: {
displayState: {
mode: models.VisualContainerDisplayMode.Hidden
}
},
visualsLayout: {
VisualContainer1: {
displayState: {
mode: models.VisualContainerDisplayMode.Visible
},
x: 1,
y: 1,
z: 1,
width: testData.loadConfiguration.width,
height: testData.loadConfiguration.height
}
}
}
}
}
}
};
spyHpm.post.and.returnValue(Promise.resolve(testData.response));
// Act
let inputConfig = utils.assign({}, embeddedVisual.config, visualEmbedConfiguration);
embeddedVisual.config = inputConfig;
await embeddedVisual.load();
// Assert
expect(spyHpm.post).toHaveBeenCalled();
let spyArgs = spyHpm.post.calls.mostRecent().args;
expect(spyArgs[0]).toEqual('/report/load');
expect(spyArgs[1]).toEqual(expectedConfiguration);
expect(spyArgs[2]).toEqual({
bootstrapped: undefined,
sdkVersion: sdkConfig.default.version,
uid: visualUniqueId,
sdkSessionId: sdkSessionId
});
});
it('embeddedVisual.getFilters(models.FiltersLevel.Report) sends GET /report/filters', async function () {
spyHpm.get.and.callFake(() => Promise.resolve({}));
// Act
await embeddedVisual.getFilters(models.FiltersLevel.Report);
// Assert
expect(spyHpm.get).toHaveBeenCalledWith('/report/filters', { uid: visualUniqueId }, jasmine.any(Object));
});
it('embeddedVisual.setFilters(filters, models.FiltersLevel.Report) sends PUT /report/filters', async function () {
// Arrange
const testData = {
filters: [
(new models.BasicFilter({ table: "Cars", measure: "Make" }, "In", ["subaru", "honda"])).toJSON(),
(new models.AdvancedFilter({ table: "Cars", measure: "Make" }, "And", [{ value: "subaru", operator: "None" }, { value: "honda", operator: "Contains" }])).toJSON()
]
};
// Act
await embeddedVisual.setFilters(testData.filters, models.FiltersLevel.Report);
// Assert
expect(spyHpm.put).toHaveBeenCalledWith('/report/filters', testData.filters, { uid: visualUniqueId }, jasmine.any(Object));
});
it('embeddedVisual.getFilters(models.FiltersLevel.Page) sends GET /report/pages/ReportSection1/filters', async function () {
spyHpm.get.and.callFake(() => Promise.resolve({}));
// Act
await embeddedVisual.getFilters(models.FiltersLevel.Page);
// Assert
expect(spyHpm.get).toHaveBeenCalledWith(`/report/pages/ReportSection1/filters`, { uid: visualUniqueId }, jasmine.any(Object));
});
it('embeddedVisual.setFilters(filters, models.FiltersLevel.Page) sends PUT /report/pages/ReportSection1/filters', async function () {
// Arrange
const testData = {
filters: [
(new models.BasicFilter({ table: "Cars", measure: "Make" }, "In", ["subaru", "honda"])).toJSON(),
(new models.AdvancedFilter({ table: "Cars", measure: "Make" }, "And", [{ value: "subaru", operator: "None" }, { value: "honda", operator: "Contains" }])).toJSON()
],
response: {
body: []
}
};
spyHpm.put.and.returnValue(Promise.resolve(testData.response));
// Act
await embeddedVisual.setFilters(testData.filters, models.FiltersLevel.Page);
// Assert
expect(spyHpm.put).toHaveBeenCalledWith(`/report/pages/ReportSection1/filters`, testData.filters, { uid: visualUniqueId }, jasmine.any(Object));
});
it('embeddedVisual.getFilters() sends GET /report/pages/ReportSection1/visuals/VisualContainer1/filters', async function () {
spyHpm.get.and.callFake(() => Promise.resolve({}));
// Act
await embeddedVisual.getFilters();
// Assert
expect(spyHpm.get).toHaveBeenCalledWith(`/report/pages/ReportSection1/visuals/VisualContainer1/filters`, { uid: visualUniqueId }, jasmine.any(Object));
});
it('embeddedVisual.setFilters(filters) sends PUT /report/pages/ReportSection1/visuals/VisualContainer1/filters', async function () {
// Arrange
const testData = {
filters: [
(new models.BasicFilter({ table: "Cars", measure: "Make" }, "In", ["subaru", "honda"])).toJSON(),
(new models.AdvancedFilter({ table: "Cars", measure: "Make" }, "And", [{ value: "subaru", operator: "None" }, { value: "honda", operator: "Contains" }])).toJSON()
],
response: {
body: []
}
};
spyHpm.put.and.returnValue(Promise.resolve(testData.response));
// Act
await embeddedVisual.setFilters(testData.filters);
// Assert
expect(spyHpm.put).toHaveBeenCalledWith(`/report/pages/ReportSection1/visuals/VisualContainer1/filters`, testData.filters, { uid: visualUniqueId }, jasmine.any(Object));
});
it('Not supported visual method: getPages', function () {
// Act
const attempt = (): void => {
embeddedVisual.getPages();
};
// Assert
expect(attempt).toThrow(visual.Visual.GetPagesNotSupportedError);
});
it('Not supported visual method: setPage', function () {
// Act
const attempt = (): void => {
embeddedVisual.setPage(null);
};
// Assert
expect(attempt).toThrow(visual.Visual.SetPageNotSupportedError);
});
describe('getVisualDescriptor', function () {
it('embeddedVisual.getVisualDescriptor() sends GET /report/pages/xyz/visuals', async function () {
// Act
try {
await embeddedVisual.getVisualDescriptor();
} catch (error) {
// The test only needs to check hpm request
}
// Assert
expect(spyHpm.get).toHaveBeenCalledWith(`/report/pages/ReportSection1/visuals`, { uid: visualUniqueId }, jasmine.any(Object));
});
it('embeddedVisual.getVisualDescriptor() returns promise that rejects with server error if there was error getting visual details', async function () {
// Arrange
const testData = {
expectedError: {
body: {
message: 'internal server error'
}
}
};
spyHpm.get.and.callFake(() => Promise.reject(testData.expectedError));
try {
// Act
await embeddedVisual.getVisualDescriptor();
fail("getVisualDescriptor should succeed");
} catch (error) {
// Assert
expect(spyHpm.get).toHaveBeenCalledWith(`/report/pages/ReportSection1/visuals`, { uid: visualUniqueId }, jasmine.any(Object));
expect(error).toEqual(testData.expectedError.body);
}
});
it('embeddedVisual.getVisualDescriptor() returns promise that resolves with visual details', async function () {
// Arrange
const fakeVisualDescriptor = new visualDescriptor.VisualDescriptor(page1, visualEmbedConfiguration.visualName, 'title', 'type', {});
const testData = {
expectedResponse: {
body: [fakeVisualDescriptor]
}
};
spyHpm.get.and.returnValue(Promise.resolve(testData.expectedResponse));
try {
// Act
const visualDescriptor = await embeddedVisual.getVisualDescriptor();
// Assert
expect(spyHpm.get).toHaveBeenCalledWith(`/report/pages/ReportSection1/visuals`, { uid: visualUniqueId }, jasmine.any(Object));
expect(visualDescriptor.name).toEqual(fakeVisualDescriptor.name);
} catch (error) {
console.log("getVisualDescriptor failed with", error);
fail("getVisualDescriptor failed");
}
});
});
});
}); | the_stack |
/*
* Copyright(c) 2017 Microsoft Corporation. All rights reserved.
*
* This code is licensed under the MIT License (MIT).
*
* 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.
*/
/// <reference path="../Microsoft.Maps.d.ts"/>
declare module Microsoft.Maps.Directions {
/////////////////////////////////////
/// Enumerations
////////////////////////////////////
/** Distance units for calculating the directions in. */
export enum DistanceUnit {
/** A distance in Kilometers. */
km,
/** A distance in Miles. */
miles
}
/** Defines the type of route to calculate. */
export enum RouteMode {
/** Driving directions are calculated. */
driving,
/** Transit directions are calculated. */
transit,
/** Walking directions are calculated. */
walking
}
/** Defines features to avoid when calculating the route. */
export enum RouteAvoidance {
/** Calculate the best route using any travel option available. */
none = 0,
/** Reduce the use of limited access highways when calculating the route. */
minimizeHighways = 1,
/** Reduce the use of roads with tolls when calculating the route. */
minimizeToll = 2,
/** Avoid using limited access highways when calculating the route. */
avoidHighways = 4,
/** Avoid using roads with tolls when calculating the route. */
avoidToll = 8,
/** Avoid using express trains when calculating the route. This option only affects routes with a transitRouteMode that have the culture set to ja-jp. */
avoidExpressTrain = 16,
/** Avoid using airlines when calculating the route. This option only affects routes with a transitRouteMode that have the culture set to ja-jp. */
avoidAirline = 32,
/** Avoid using bullet trains when calculating the route. This option only affects routes with a transitRouteMode that have the culture set to ja-jp. */
avoidBulletTrain = 64
}
/** Response codes for a route calculation request. */
export enum RouteResponseCode {
/** The route was successfully calculated. */
success = 0,
/** An unknown error has occurred. */
unknownError = 1,
/** A nearby road cannot be found for one or more of the route waypoints. */
cannotFindNearbyRoad = 2,
/**
* The distance between two route waypoints, or the total length of the route exceeds the limit of the route mode.
* Modify the waypoint locations so that they are closer together.
*/
tooFar = 3,
/**
* A route cannot be calculated for the specified waypoints. For example, this code is returned when a route between
* “Seattle, WA” and “Honolulu, HI” is requested.
*/
noSolution = 4,
/** There is no route data for the specified waypoints. */
dataSourceNotFound = 5,
/** There are no transit options available for the specified time. */
noAvailableTransitTrip = 7,
/** The transit stops are so close that walking is always a better option. */
transitStopsTooClose = 8,
/** The transit stops are so close that walking is a better option. */
walkingBestAlternative = 9,
/**
* There is no transit data available for the route or for one or more of the specified waypoints,
* or the waypoints are in different transit areas that do not overlap.
*/
outOfTransitBounds = 10,
/** The directions calculation request has timed out. */
timeOut = 11,
/**
* One or more waypoints need to be disambiguated. This error does not occur if the
* autoDisplayDisambiguation directions render option is set to true.
*/
waypointDisambiguation = 12,
/** One or more waypoints do not have an address or location specified. */
hasEmptyWaypoint = 13,
/** The maximum number of waypoints, which is 25, has been exceeded. */
exceedMaxWaypointLimit = 14,
/** At least two waypoints are required to calculate a route. */
atleastTwoWaypointRequired = 15,
/** The first or last waypoint is a via point, which is not allowed. */
firstOrLastStoppointIsVia = 16,
/** The search service failed to return results. */
searchServiceFailed = 17,
/** The credentials passed to the Directions module are invalid. */
invalidCredentials = 18
}
/** Defines optimization options for calculating directions. */
export enum RouteOptimization {
/** Calculate a route the shortest time. */
shortestTime = 0,
/** Calculate a route with the shortest distance. */
shortestDistance = 1,
/** The route is calculated to minimize the time and uses current traffic information. */
timeWithTraffic = 2,
/** The route is calculated to minimize the time and avoid road closures. Traffic information is not used in the calculation. */
timeAvoidClosure = 3,
/** Minimize the cost when calculating directions. This option only affects routes with a transitRouteMode that have the culture set to ja-jp.*/
minimizeMoney = 4,
/** Minimize transit transfers when calculating directions. This option only affects routes with a transitRouteMode that have the culture set to ja-jp.*/
minimizeTransfers = 5,
/** Minimize the amount of walking when calculating directions. This option only affects routes with a transitRouteMode that have the culture set to ja-jp.*/
minimizeWalking = 6
}
/** An enumeration that specifies the releance of a dateTime when calculating a route. */
export enum TimeType {
/** The dateTime parameter contains the desired arrival time for a transit request. */
arrival,
/** The dateTime parameter contains the desired departure time for a transit request. */
departure,
/** The dateTime parameter should be ignored and the first available transit taken. */
firstAvailable,
/** The dateTime parameter contains the latest departure time available for a transit request. */
lastAvailable
}
/////////////////////////////////////
/// Interfaces
////////////////////////////////////
/** Contains the arguments for directions events. */
export interface IDirectionsEventArgs {
/** The calculated route (or routes, if the route mode is transit). */
route: IRoute[];
/** The route summary (or summaries) of the route(s) defined in the route property. */
routeSummary: IRouteSummary[];
}
/** Contains arguments for directions error events. */
export interface IDirectionsErrorEventArgs {
/** The code which identifies the error that occurred. */
responseCode: RouteResponseCode;
/** The error message. */
message: string;
}
/** Represents one direction in a set of route directions. */
export interface IDirectionsStep {
/** The child direction items for this directions step. */
childItineraryItems: IDirectionsStep[];
/** The location of the start of the direction. */
coordinate: Location;
/** The total distance of the step in the unit specified in the distanceUnit property of the DirectionsRequestOptions. */
distance: string;
/** The total time, in seconds, of the direction step. */
durationInSeconds: number;
/** The HTML formatted route instruction associated with the step. */
formattedText: string;
/** A boolean indicating whether the maneuver image is a road shield image. */
isImageRoadShield: boolean;
/** The type of maneuver being performed. */
maneuver: string;
/** An array of strings, where each string is a hint to help determine when to move to the next direction step. Not all direction steps have hints. */
postIntersectionHints: string[];
/** An array of strings, where each string is a hint to help determine when you have arrived at this direction step. Not all direction steps have hints. */
preIntersectionHints: string[];
/** The name of the transit stop where this step originates. */
startStopName: string;
/** The transit line associated with this step. */
transitLine: ITransitLine;
/** The URL of the image to use for transit direction steps. */
transitStepIcon: string;
/** The ID of the transit stop. */
transitStopId: string;
/** The name of the transit line end. */
transitTerminus: string;
/** An array of route warnings associated with this step. */
warnings: IDirectionsStepWarning[];
}
/** Represents a route direction warning, such as a traffic congestion warning. */
export interface IDirectionsStepWarning {
/** Where the warning starts. */
origin: string;
/** The severity of the warning. Values can be: Low Impact, Minor, Moderate, Serious or None. */
severity: string;
/** The warning text. */
text: string;
/** Where the warning ends. */
to: string;
/** The type of warning. A list of Warning type values can be found here: https://msdn.microsoft.com/en-us/library/hh441731.aspx */
warningType: string;
}
/** Represents a route. */
export interface IRoute {
/** The legs of the route. Each route leg represents the route between two waypoints. */
routeLegs: IRouteLeg[];
/** An array of locations that makes up the path of the route. */
routePath: Location[];
}
/** Represents a leg of a route. A route leg is the part of the route between two stop waypoints. */
export interface IRouteLeg {
/** The end time of the route leg. This property only applies when the routeMode of the DirectionsRequestOptions is set to transit. */
endTime: Date;
/** The location of the last waypoint of this leg. */
endWaypointLocation: Location;
/** The directions steps associated with this route leg. */
itineraryItems: IDirectionsStep[];
/** The index of the route to which this route leg belongs. */
originalRouteIndex: number;
/** The start time of the route leg. This property only applies when the routeMode of the DirectionsRequestOptions is set to transit. */
startTime: Date;
/** The location of the first waypoint of this route leg. */
startWaypointLocation: Location;
/** The sub legs of this route leg. A sub leg of a route is the part of the route between a stop point and a via point or between two via points.*/
subLegs: IRouteSubLeg[];
/** The summary which describes this route leg. */
summary: IRouteSummary;
}
/** Represents a route sub leg. A route sub leg is the part of the route between a stop point and a via point or between two via points. */
export interface IRouteSubLeg {
/** The location of the last waypoint of the sub leg. */
actualEnd: Location;
/** The location of the first waypoint of the sub leg. */
actualStart: Location;
/** The description of the last waypoint of the sub leg. */
endDescription: string;
/** The description of the first waypoint of the sub leg. */
startDescription: string;
}
/** Represents a route summary. */
export interface IRouteSummary {
/** The total travel distance of the route */
distance: number;
/** The cost of the route. This property is only returned if the routeMode of the IDirectionsRequestOptions is set to transit and the map culture is set to ja-jp. */
monetaryCost: number;
/** The location of the northeast corner of bounding box that defines the best map view of the route. */
northEast: Location;
/** The location of the southwest corner of bounding box that defines the best map view of the route. */
southWest: Location;
/** The total travel time, in seconds, for the route. */
time: number;
/**
* The total travel time, in seconds, taking into account traffic delays, for the route.
* This property is 0 if the avoidTraffic property of the IDirectionsRequestOptions is set to false.
*/
timeWithTraffic: number;
}
/** Contains information about a transit line. */
export interface ITransitLine {
/** The short name for the transit line. */
abbreviatedName: string;
/** The ID of the agency that owns the transit line. */
agencyId: number;
/** The name of the agency that owns the transit line. */
agencyName: string;
/** The URL of the website of the agency that owns the transit line. */
agencyUrl: string;
/** Phone number for the transit agency. */
phoneNumber: string;
/** Information about the provider of this transit line data. */
providerInfo: string;
/** The uri for the transit agencies website. */
uri: string;
/** The full name of this transit line. */
verboseName: string;
}
/** Options that can be used to define a waypoint. */
export interface IWaypointOptions {
/**
* The address string of the waypoint. For example, the following strings are valid for this parameter: "Seattle", "1 Microsoft Way, Redmond, WA". Either the address or location property must be specified.
*/
address?: string;
/**
* A boolean indicating whether the waypoint is a via point. A via point is a point along the route that is not a stop point. Set this property to
* true if you just want the route to pass through this location. Default: false
*/
isViaPoint?: boolean;
/** The location of the waypoint. Either the address or location property must be specified. */
location?: Location;
}
/** Contains options for the directions to calculate. */
export interface IDirectionsRequestOptions {
/** The unit to use when displaying direction distances. */
distanceUnit?: DistanceUnit;
/** The number of routes to calculate. */
maxRoutes?: number;
/** The features to avoid when calculating the route. */
routeAvoidance?: RouteAvoidance[];
/** A boolean indicating whether the route line on the map can be dragged with the mouse cursor. */
routeDraggable?: boolean;
/** If multiple routes are returned, the index of the route and directions to display. */
routeIndex?: number;
/** The type of directions to calculate. */
routeMode?: RouteMode;
/** The optimization setting for the route calculation. */
routeOptimization?: RouteOptimization;
/** The type of the time specified. The default value is departure. */
timeType?: TimeType;
/** The time to use when calculating the route. If this property is set to null, the current time is used */
time?: Date;
}
/** Represents render options for a route. */
export interface IDirectionsRenderOptions {
/** A boolean indicating whether to automatically set the map view to the best map view of the calculated route. Default: true */
autoUpdateMapView?: boolean;
/** A boolean indicating whether to display the disclaimer about the accuracy of the directions. Default: true */
displayDisclaimer?: boolean;
/** A boolean indicating whether to display the icons for each direction maneuver. Default: true */
displayManeuverIcons?: boolean;
/** A boolean indicating whether to display direction hints that describe when a direction step was missed. Default: true */
displayPostItineraryItemHints?: boolean;
/**
* A boolean indicating whether to display direction hints that describe what to look for before you come to the next
* direction step. The default value is true.
*/
displayPreItineraryItemHints?: boolean;
/** A boolean indicating whether to display the route selector control. Default: true */
displayRouteSelector?: boolean;
/** A boolean indicating whether to display direction warnings. Default: true */
displayStepWarnings?: boolean;
/** A boolean indicating whether to display a warning about walking directions. Default: true */
displayWalkingWarning?: boolean;
/** The polyline options that define how to draw the route line on the map, if the RouteMode is driving. */
drivingPolylineOptions?: IPolylineOptions;
/** The pushpin options that define how the first waypoint should be rendered. */
firstWaypointPushpinOptions?: IPushpinOptions;
/** The DOM element inside which the directions itinerary will be rendered. */
itineraryContainer?: HTMLElement;
/** The pushpin options that define how the last waypoint should be rendered. */
lastWaypointPushpinOptions?: IPushpinOptions;
/** A boolean indicating whether to show the input panel. Default: false */
showInputPanel?: boolean;
/** The options that define how to draw the route line on the map, if the RouteMode is transit. */
transitPolylineOptions?: IPolylineOptions;
/** The options that define how to draw the route line on the map, if the RouteMode is walking. */
walkingPolylineOptions?: IPolylineOptions;
/** The options that define the pushpin to use for all route waypoints by default. The first and last waypoints in the route will be overriden by firstWaypointPushpinOptions and lastWaypointPushpinOptions if set. */
waypointPushpinOptions?: IPushpinOptions;
}
/////////////////////////////////////
/// Classes
////////////////////////////////////
/** An object used to define a start, end or stop location along a route. */
export class Waypoint {
/**
* @constructor
* @param options: Options used to define the Waypoint.
*/
constructor(options: IWaypointOptions);
/** Releases any resources associated with the waypoint. */
public dispose(): void;
/**
* Gets the address associated with the waypoint.
* @returns The address associated with the waypoint.
*/
public getAddress(): string;
/**
* Gets the location of the waypoint.
* @returns The location of the waypoint.
*/
public getLocation(): Location;
/**
* Gets a boolean value indicating whether the waypoint is a via point.
* @returns A boolean value indicating whether the waypoint is a via point.
*/
public isViapoint(): boolean;
/**
* Sets options for the waypoint. For these options to take effect, you must recalculate the route.
* @param options Options used to define the Waypoint.
*/
public setOptions(options: IWaypointOptions): void;
}
/** The main class in the Directions module that process direction calculations and rendering. */
export class DirectionsManager {
/**
* @constructor
* @param map A map to calculate directions for.
* @param waypoints An array of waypoints to be added to the route.
*/
constructor(map: Map, waypoints?: Waypoint[]);
/**
* Adds a waypoint to the route at the given index, if specified. If an index is not specified, the waypoint is added as the last waypoint in the route. The maximum number of walking or driving waypoints is 25. The maximum number of transit waypoints is 2. Up to 10 via points are allowed between two stop waypoints. To recalculate the route, use calculateDirections.
* @param waypoint The waypoint to be added to the directions manager.
* @param index An index at which the waypoint is to be added.
*/
public addWaypoint(waypoint: Waypoint, index?: number): void;
/**
* Calculates directions based on request and render options set
*/
public calculateDirections(): void;
/** Clears the directions request and render options and removes all waypoints */
public clearAll(): void;
/**
* Clears the directions displayed and removes the route line from the map.
* This method does not remove waypoints from the route and retains all calculated direction information and option settings.
*/
public clearDisplay(): void;
/** Deletes the DirectionsManager object and releases any associated resources. */
public dispose(): void;
/**
* Returns all current pushpins for the rendered route.This includes pushpins created by addWaypoint and viaPoints created due to drag and drop.
*/
public getAllPushpins(): Pushpin[];
/**
* Gets all the waypoints in the directions manager.
* @returns All the waypoints in the directions manager.
*/
public getAllWaypoints(): Waypoint[];
/**
* Gets the currently displayed route information.
* @returns The currently displayed route information.
*/
public getCurrentRoute(): IRoute;
/**
* Gets the route render options.
* @returns The route render options
*/
public getRenderOptions(): IDirectionsRenderOptions;
/**
* Gets the directions request options.
* @returns The directions request options.
*/
public getRequestOptions(): IDirectionsRequestOptions;
/**
* Gets the current calculated route(s)
* @returns The current calculated route(s). If the route was not successfully calculated, null is returned.
*/
public getRouteResult(): IRoute[];
/**
* Removes the given waypoint or the waypoint identified by the given index from the route.
* @param waypointOrIndex A Waypoint object to be removed or the index of the waypoint to be removed
*/
public removeWaypoint(waypointOrIndex: Waypoint | number): void;
/**
* Sets the specified render options for the route.
* @param options The options that customize the rendering of the calculated route.
*/
public setRenderOptions(options: IDirectionsRenderOptions): void;
/**
* Sets the specified route calculation options.
* @param options The route calculation options.
*/
public setRequestOptions(options: IDirectionsRequestOptions): void;
/**
* Displays an input panel for calculating directions in the specified container. Provides autosuggest for location inputs.
* @param inputContainerId The id name of the HTML container in which to render the directions input panel.
*/
public showInputPanel(inputContainerId: string): void;
}
}
declare module Microsoft.Maps {
/** A static class that manages events within the map SDK. */
module Events {
/////////////////////////////////////
/// addHandler Definitions
////////////////////////////////////
/**
* Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method.
* @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc.
* @param eventName The type of event to attach. Supported Events:
* • directionsError
* • directionsUpdated
* @param handler The callback function to handle the event when triggered.
* @returns The handler id.
*/
export function addHandler(target: Directions.DirectionsManager, eventName: string, handler: (eventArg?: Directions.IDirectionsEventArgs | Directions.IDirectionsErrorEventArgs) => void): IHandlerId;
/////////////////////////////////////
/// addOne Definitions
////////////////////////////////////
/**
* Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached.
* @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc.
* @param eventName The type of event to attach. Supported Events:
* • directionsError
* • directionsUpdated
* @param handler The callback function to handle the event when triggered.
*/
export function addOne(target: Directions.DirectionsManager, eventName: string, handler: (eventArg?: Directions.IDirectionsEventArgs | Directions.IDirectionsErrorEventArgs) => void): void;
/////////////////////////////////////
/// addThrottledHandler Definitions
////////////////////////////////////
/**
* Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter.
* @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc.
* @param eventName The type of event to attach. Supported Events:
* • directionsError
* • directionsUpdated
* @param handler The callback function to handle the event when triggered.
* @param throttleInterval throttle interval (in ms)
* @returns The handler id.
*/
export function addThrottledHandler(target: Directions.DirectionsManager, eventName: string, handler: (eventArg?: Directions.IDirectionsEventArgs | Directions.IDirectionsErrorEventArgs) => void, throttleInterval: number): IHandlerId;
}
} | the_stack |
'use strict';
import * as _ from 'underscore';
import * as fs from "fs";
import * as nock from "nock";
import * as querystring from "querystring";
import * as url from "url";
require('date-utils');
var adaldir = process.env.ADAL_COV ? '../../lib-cov/' : '../../lib/';
function testRequire(file: any) {
return require(adaldir + file);
}
nock.disableNetConnect();
var adal = testRequire('adal');
//import * as adal from "../../lib/adal";
var log = testRequire('log');
var util: any = {};
var successResponse: any = {
'access_token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1THdqcHdBSk9NOW4tQSJ9.eyJhdWQiOiIwMDAwMDAwMi0wMDAwLTAwMDAtYzAwMC0wMDAwMDAwMDAwMDAiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC82MmYwMzQ3MS02N2MxLTRjNTAtYjlkMS0xMzQ1MDc5ZDk3NzQvIiwiaWF0IjoxMzc4NjAxMTY4LCJuYmYiOjEzNzg2MDExNjgsImV4cCI6MTM3ODYyOTk2OCwidmVyIjoiMS4wIiwidGlkIjoiNjJmMDM0NzEtNjdjMS00YzUwLWI5ZDEtMTM0NTA3OWQ5Nzc0Iiwib2lkIjoiZjEzMDkzNDEtZDcyMy00YTc1LTk2YzktNGIyMTMzMzk0Mjg3Iiwic3ViIjoiZjEzMDkzNDEtZDcyMy00YTc1LTk2YzktNGIyMTMzMzk0Mjg3IiwiYXBwaWQiOiI1YzI1ZDFiZi1iMjMyLTQwMzUtYjZiOS0yYjdlN2U4MzQ2ZDYiLCJhcHBpZGFjciI6IjEifQ.qXM7f9TTiLApxVMwaSrISQQ6UAnfKvKhoIlN9rB0Eff2VXvIWKGRsclPkMQ5x42BQz2N6pSXEsN-LsNCZlQ76Rc3rVRONzeCYh7q_NXcCJG_d6SJTtV5GBfgqFlgT8UF5rblabbMdOiOrddvJm048hWt2Nm3qD3QjQdPBlD7Ksn-lUR1jEJPIqDaBjGom8RawrZTW6X1cy1Kr8mEYFkxcbU91k_RZUumONep9FTR8gfPkboeD8zyvOy64UeysEtcuaNCfhHSBFcwC8MwjUr5r_T7au7ywAcYDOVgoa7oF_dN1JNweiDoNNZ9tyUS-RY3sa3-gXk77gRxpA4CkpittQ',
'token_type': 'Bearer',
'expires_in': 28800,
'resource': '00000002-0000-0000-c000-000000000000',
};
var refreshToken = 'AwABAAAAvPM1KaPlrEqdFSBzjqfTGCDeE7YHWD9jkU2WWYKLjxu928QAbkoFyWpgJLFcp65DcbBqOSYVq5Ty_60YICIdFw61SG4-eT1nWHNOPdzsL2ZzloUsp2DpqlIr1s5Z3953oQBi7dOqiHk37NXQqmNEJ7MfmDp6w3EOa29EPARvjGIHFgtICW1-Y82npw1v1g8Ittb02pksNU2XzH2X0E3l3TuSZWsX5lpl-kfPOc8zppU6bwvT-VOPHZVVLQedDIQZyOiFst9HLUjbiIvBgV7tNwbB4H5yF56QQscz49Nrb3g0ibuNDo7efFawLzNoVHzoTrOTcCGSG1pt8Z-npByrEe7vg1o4nNFjspuxlyMGdnYRAnaZfvgzqROP_m7ZqSd6IAA';
var successResponseWithRefresh: any = _.clone(successResponse);
_.extend(successResponseWithRefresh, {
'scope': '62e90394-69f5-4237-9190-012177145e10',
'refresh_token': refreshToken
});
var encodedIdToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJhdWQiOiJlOTU4YzA5YS1hYzM3LTQ5MDAtYjRkNy1mYjNlZWFmNzMzOGQiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC9jY2ViYTE0Yy02YTAwLTQ5YWMtYjgwNi04NGRlNTJiZjFkNDIvIiwiaWF0IjoxMzkxNjQ1NDU4LCJuYmYiOjEzOTE2NDU0NTgsImV4cCI6MTM5MTY0OTM1OCwidmVyIjoiMS4wIiwidGlkIjoiY2NlYmExNGMtNmEwMC00OWFjLWI4MDYtODRkZTUyYmYxZDQyIiwib2lkIjoiYTQ0MzIwNGEtYWJjOS00Y2I4LWFkYzEtYzBkZmMxMjMwMGFhIiwidXBuIjoicnJhbmRhbGxAcnJhbmRhbGxhYWQxLm9ubWljcm9zb2Z0LmNvbSIsInVuaXF1ZV9uYW1lIjoicnJhbmRhbGxAcnJhbmRhbGxhYWQxLm9ubWljcm9zb2Z0LmNvbSIsInN1YiI6IjRnVHY0RXRvWVctRFRvdzBiRG5KZDFBQTRzZkNoQmJqZXJtcXQ2UV9aYTQiLCJmYW1pbHlfbmFtZSI6IlJhbmRhbGwiLCJnaXZlbl9uYW1lIjoiUmljaCJ9.';
var parsedIdToken = {
'tenantId': 'cceba14c-6a00-49ac-b806-84de52bf1d42',
'userId': 'rrandall@rrandallaad1.onmicrosoft.com',
'givenName': 'Rich',
'familyName': 'Randall',
'isUserIdDisplayable': true,
'oid': 'a443204a-abc9-4cb8-adc1-c0dfc12300aa'
};
var decodedIdToken = {
aud: 'e958c09a-ac37-4900-b4d7-fb3eeaf7338d',
iss: 'https://sts.windows.net/cceba14c-6a00-49ac-b806-84de52bf1d42/',
iat: 1391645458,
nbf: 1391645458,
exp: 1391649358,
ver: '1.0',
tid: 'cceba14c-6a00-49ac-b806-84de52bf1d42',
oid: 'a443204a-abc9-4cb8-adc1-c0dfc12300aa',
upn: 'rrandall@rrandallaad1.onmicrosoft.com',
'unique_name': 'rrandall@rrandallaad1.onmicrosoft.com',
sub: '4gTv4EtoYW-DTow0bDnJd1AA4sfChBbjermqt6Q_Za4',
'family_name': 'Randall',
'given_name': 'Rich'
};
var encodedIdTokenUrlSafe = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJhdWQiOiJlOTU4YzA5YS1hYzM3LTQ5MDAtYjRkNy1mYjNlZWFmNzMzOGQiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC9jY2ViYTE0Yy02YTAwLTQ5YWMtYjgwNi04NGRlNTJiZjFkNDIvIiwiaWF0IjoxMzkxNjQ1NDU4LCJuYmYiOjEzOTE2NDU0NTgsImV4cCI6MTM5MTY0OTM1OCwidmVyIjoiMS4wIiwidGlkIjoiY2NlYmExNGMtNmEwMC00OWFjLWI4MDYtODRkZTUyYmYxZDQyIiwib2lkIjoiYTQ0MzIwNGEtYWJjOS00Y2I4LWFkYzEtYzBkZmMxMjMwMGFhIiwidXBuIjoiZm9vYmFyQHNvbWVwbGFjZWVsc2UuY29tIiwidW5pcXVlX25hbWUiOiJycmFuZGFsbEBycmFuZGFsbGFhZDEub25taWNyb3NvZnQuY29tIiwic3ViIjoiNGdUdjRFdG9ZVy1EVG93MGJEbkpkMUFBNHNmQ2hCYmplcm1xdDZRX1phNCIsImZhbWlseV9uYW1lIjoiUmFuZGFsbCIsImdpdmVuX25hbWUiOiJSaTw_Y2gifQ==.';
var parsedIdTokenUrlSafe = {
'tenantId': 'cceba14c-6a00-49ac-b806-84de52bf1d42',
'userId': 'test@someplaceelse.com',
'givenName': 'Ri<?ch',
'familyName': 'Randall',
'isUserIdDisplayable': true,
'oid': 'a443204a-abc9-4cb8-adc1-c0dfc12300aa'
};
var decodedTokenUrlSafeTest: any = {
aud: 'e958c09a-ac37-4900-b4d7-fb3eeaf7338d',
iss: 'https://sts.windows.net/cceba14c-6a00-49ac-b806-84de52bf1d42/',
iat: 1391645458,
nbf: 1391645458,
exp: 1391649358,
ver: '1.0',
tid: 'cceba14c-6a00-49ac-b806-84de52bf1d42',
oid: 'a443204a-abc9-4cb8-adc1-c0dfc12300aa',
upn: 'test@someplaceelse.com',
'unique_name': 'rrandall@rrandallaad1.onmicrosoft.com',
sub: '4gTv4EtoYW-DTow0bDnJd1AA4sfChBbjermqt6Q_Za4',
'family_name': 'Randall',
'given_name': 'Ri<?ch'
};
var parameters: any = {};
parameters.tenant = 'rrandallaad1.onmicrosoft.com';
parameters.clientId = 'clien&&???tId';
parameters.clientSecret = 'clientSecret*&^(?&';
parameters.resource = '00000002-0000-0000-c000-000000000000';
parameters.evoEndpoint = 'https://login.windows.net';
parameters.username = 'rrandall@' + parameters.tenant;
parameters.password = '<password>';
parameters.authorityHosts = {
global: 'login.windows.net',
china: 'login.chinacloudapi.cn',
gov: 'login-us.microsoftonline.com',
us: 'login.microsoftonline.us'
};
parameters.language = 'en';
parameters.deviceCode = 'ABCDE:device_code';
parameters.refreshToken = refreshToken;
// This is a default authority to be used in tests that don't care that there are multiple.
parameters.authority = parameters.evoEndpoint;
parameters.authorityTenant = parameters.authority + '/' + parameters.tenant;
parameters.adfsUrlNoPath = 'https://adfs.federatedtenant.com';
parameters.adfsMexPath = '/adfs/services/trust/mex';
parameters.adfsWsTrustPath = '/adfs/services/trust/13/usernamemixed';
parameters.adfsWsTrustPath2005 = '/adfs/services/trust/2005/usernamemixed';
parameters.adfsMex = parameters.adfsUrlNoPath + parameters.adfsMexPath;
parameters.adfsWsTrust = parameters.adfsUrlNoPath + parameters.adfsWsTrustPath;
parameters.adfsWsTrust2005 = parameters.adfsUrlNoPath + parameters.adfsWsTrustPath2005;
parameters.successResponse = successResponse;
parameters.successResponseWithRefresh = successResponseWithRefresh;
parameters.authUrl = url.parse(parameters.evoEndpoint + '/' + parameters.tenant);
parameters.tokenPath = '/oauth2/token';
parameters.extraQP = '?api-version=1.0';
parameters.tokenUrlPath = parameters.authUrl.pathname + parameters.tokenPath + parameters.extraQP;
parameters.deviceCodePath = '/oauth2/devicecode'
parameters.deviceCodeUrlPath = parameters.authUrl.pathname + parameters.deviceCodePath + parameters.extraQP;
parameters.authorizePath = '/oauth/authorize';
parameters.authorizeUrlPath = parameters.authUrl.pathname + parameters.authorizePath;
parameters.authorizeUrl = parameters.authUrl.href + parameters.authorizePath;
parameters.instanceDiscoverySuccessResponse = {
'tenant_discovery_endpoint': parameters.authority
};
parameters.userRealmPathTemplate = '/common/UserRealm/<user>';
parameters.userRealmResponseFederated = '{\"account_type\":\"federated\",\"federation_protocol\":\"wstrust\",\"federation_metadata_url\":\"' + parameters.adfsMex + '\",\"federation_active_auth_url\":\"' + parameters.adfsWsTrust + '\",\"ver\":\"0.8\"}';
parameters.userRealmResponseManaged = '{\"account_type\":\"managed\",\"federation_protocol\":\"wstrust\",\"federation_metadata_url\":\"' + parameters.adfsMex + '\",\"federation_active_auth_url\":\"' + parameters.adfsWsTrust + '\",\"ver\":\"0.8\"}';
parameters.MexFile = __dirname + '/../mex/common.mex.xml';
// These two files go together. Editing one without changing the other will break the test.
parameters.RSTRFile = __dirname + '/../wstrust/common.rstr.xml';
parameters.AssertionFile = __dirname + '/../wstrust/common.base64.encoded.assertion.txt';
parameters.logContext = { correlationId: 'test-correlation-id-123456789' };
parameters.callContext = { _logContext: parameters.logContext };
// This is a dummy RSA private cert used for testing purpose.It does not represent valid credential.
// privatePem variable is a fake certificate in the form of a string.
// Hence the following message is added to suppress CredScan warning.
//[SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine")]
util.getSelfSignedCert = function () {
var privatePem = '-----BEGIN RSA PRIVATE KEY-----\n' +
'MIIEpAIBAAKCAQEAoMGZTZi0vU/ICYVgV4vcTwzvZCNXdJ9EgGBBFu1E0/j4FF0Y\n' +
'Fd2sP7IwmWVZLlWJ5VbwAtdMiRdrogX/QnWPfsNfsPzDdRRJD+Erh9tmBzJm08h7\n' +
'1RggS1/VehZ9WNdTDlQM3P+zNg0IG274VIr+ZSBzIbYxV6ecPdRU/EsZ5Wa5SCwG\n' +
'Fu1qPJW8KY8yvse9PHdFiHjrmcZSKTbBCp/2grdBrk/N1jwtH6Yj100l7G69HPE/\n' +
'4kXYRX9f/LjpzF77VMCj7UJtmb1yR3fRHpppbm7GkqvJFM2Kg3UG5fsp8nQBDRc+\n' +
'R3kjm+DU05MoFdsfo3DkzpNJjDcLUPdANe+mWwIDAQABAoIBACdb/1r+XpJTbFjY\n' +
'bSRCPCimtB5CgPEu5ajA6G7inQ2BUcw6luETq07VJA0KwXEUxHSAerdXW4fdUh8T\n' +
'dNIi0oVo9I7y9DBATTs0GGJlF2//qSmFVrxv8chCqJQB2aLc5ZsGfTfG62v6eNeu\n' +
'reKVPYApF8dTQnWBtkF1MXGsOaTuxEecrM6KbES97kElC0QsJ89sDnTUjKuihfc9\n' +
'Q9IfWDbX/5WY6JL7XMbQtKRIzd+y/E9dpU3Hu+UErKWyb5pQiud81/Q/xQThSrVt\n' +
'zpmXwlsEFCrSzDML+aOTDqrsRwypRc5sTNAMadkeRrrlo+5OzoUG1aTxco8tZ1MD\n' +
'ch7RTJECgYEA1fqn93X6S1sA8R4lYOJUDd5JmEskKwLl5Vg2VSinSD1YyMdtPnQa\n' +
'ZWCEbJGXN60tEd7ZjOM4wA0mIrwEkkApFWEiGpMe4aGTD11455rA5IfrZUGPXlcw\n' +
'lkmt4wPytKx/xDLBfa8oAu33dFDe/nhRqQqAMTi7DAnttqjUxPg/N8UCgYEAwFNG\n' +
'qLG+5+J4sq5xoXgDj0Zggi5hx2IEfN68BmyYHvfL8VSDkQMsiYXNAhTWByCkjW9D\n' +
'j/hdouGlDwMCLWq0XPgO/XsSlU7jJExsrRch63kf72PTZP/qapSkOonCe9TViNTQ\n' +
'KiRXu/v9OfJYSRPnpKz0/5goFSq7E12mBWZJJ58CgYEAvmmKNLSAobP+t5H68ycU\n' +
'Yy7u0J31Nm0ixR7lYoyFp8wniKumdA//OT1VOgOoy/vIAoILl8rPQl+xEvG7I6YC\n' +
'qSrBnWJT9bbBVcf5Aih9BCBLgdSATxRJgUNZgI2P2eUy4RXFhyFp+olmTdR1S38o\n' +
'M8PLZYG1OTZQmd3NUOYT430CgYBzU7yEPgnPPTPJWefTvobL7JTEm5GQoQs14c54\n' +
'P7g8obUO4vH+DBwx3yUfAWWSYpWqJjUqaPGlUY/L3673kwvS0AEVKS7sj6CPTLDC\n' +
'XqO9cyWeRIsn/noQLVAJtkAER41AfvTQwHhHxoSDsfoU4DXAvuIvPouSncwOgdKj\n' +
'XEGz2wKBgQDQmB/u4oGaPRf5DdasiAcqofYDEoo/OcpdRPeW2t5z7WDZcjeN4ajR\n' +
'GDoQssBpy1fpsPnghksMhYZL2l9xiSInkFw87ax5EYBS43Mt5HfJPgwpEnA5yV3W\n' +
'WGt3TBp7BgYOKhIID6803lBYfDmtQzdD+xMjlJKSQ9wfZYCuXrYwSg==\n' +
'-----END RSA PRIVATE KEY-----';
return privatePem;
};
parameters.certHash = 'C1:5D:EA:86:56:AD:DF:67:BE:80:31:D8:5E:BD:DC:5A:D6:C4:36:E1';
parameters.nowDate = new Date(1418433646179);
parameters.jwtId = '09841beb-a2c2-4777-a347-34ef055238a8';
parameters.expectedJwt = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IndWM3FobGF0MzJlLWdESFlYcjNjV3RiRU51RSJ9.eyJhdWQiOiJodHRwczovL2xvZ2luLndpbmRvd3MubmV0L3JyYW5kYWxsYWFkMS5vbm1pY3Jvc29mdC5jb20vb2F1dGgyL3Rva2VuIiwiaXNzIjoiY2xpZW4mJj8_P3RJZCIsInN1YiI6ImNsaWVuJiY_Pz90SWQiLCJuYmYiOjE0MTg0MzM2NDYsImV4cCI6MTQxODQzNDI0NiwianRpIjoiMDk4NDFiZWItYTJjMi00Nzc3LWEzNDctMzRlZjA1NTIzOGE4In0.dgF0TRlcASgTMp_1dlm8vd7tudr6n40VeuOQGFnz566s3n76WR_jJDBBBKlYeqc9gwCPFOzrLVAJehVYZ3N7YPzVdulf47rLoQdAp8R_p4Q4hdBZuIzfgDWwXjnP9x_NlfzezEYE4r8KTS2g5BBzPmx538AfIdNM93hWIxQySZGWY5UAhTkT1qE1ce1Yjo1M2HqzEJhTg5TTyfrnDtNxFxmzYhSyA9B41lB5kBuJTXUWXPrr-6eG8cEUOS-iiH7YB1Tf4J7_9JQloevTiOrfv4pSp6xLLXm2ntNBg3gaKsGKdYd-3tsCG0mHn7BzL0b-QCLalkUr8KtgtLqkxuAiLQ';
parameters.cert = (util as any).getSelfSignedCert();
util.commonParameters = parameters;
util.testRequire = testRequire;
var correlationIdRegex = /[^\s]+/;
util.testCorrelationId = correlationIdRegex;
util.setCorrelationId = function (correlationId: any) {
util.testCorrelationId = correlationId || correlationIdRegex;
};
util.turnOnLogging = function (level: any, logFunc: any) {
var consoleLog = function (level: any, message: any, error: any) {
level;
console.log(message);
if (error) {
console.log(error);
}
};
var log = adal.Logging;
var loggingFunction = logFunc || consoleLog;
var loggingLevel = level || log.LOGGING_LEVEL.VERBOSE;
log.setLoggingOptions(
{
level: loggingLevel,
log: loggingFunction
});
};
util.resetLogging = function () {
var log = adal.Logging;
log.setLoggingOptions();
};
var TOKEN_RESPONSE_MAP: any = {};
TOKEN_RESPONSE_MAP['token_type'] = 'tokenType';
TOKEN_RESPONSE_MAP['access_token'] = 'accessToken';
TOKEN_RESPONSE_MAP['refresh_token'] = 'refreshToken';
TOKEN_RESPONSE_MAP['created_on'] = 'createdOn';
TOKEN_RESPONSE_MAP['expires_on'] = 'expiresOn';
TOKEN_RESPONSE_MAP['expires_in'] = 'expiresIn';
TOKEN_RESPONSE_MAP['error'] = 'error';
TOKEN_RESPONSE_MAP['error_description'] = 'errorDescription';
TOKEN_RESPONSE_MAP['resource'] = 'resource';
var DEVICE_CODE_RESPONSE_MAP: any = {};
DEVICE_CODE_RESPONSE_MAP['device_code'] = 'deviceCode';
DEVICE_CODE_RESPONSE_MAP['user_code'] = 'userCode';
DEVICE_CODE_RESPONSE_MAP['verification_url'] = 'verificationUrl';
DEVICE_CODE_RESPONSE_MAP['interval'] = 'interval';
DEVICE_CODE_RESPONSE_MAP['expires_in'] = 'expiresIn';
DEVICE_CODE_RESPONSE_MAP['error'] = 'error';
DEVICE_CODE_RESPONSE_MAP['error_description'] = 'errorDescription';
function mapFields(inObj: any, outObj: any, map: any) {
for (var key in inObj) {
if (map[key]) {
var mappedKey = map[key];
outObj[mappedKey] = inObj[key];
}
}
}
/**
* Create response based on the given options and iteration number.
* @options Options is used to flex the reponse creation, i.e authority, resource and isMRRT.
* @param iteration Iteraton will be used to create a distinct token for each value of iteration and it will always return that same token
* for same value of iteration.
*/
util.createResponse = function (options: any, iteration: any) {
options = options || {};
var authority = options.authority || parameters.authorityTenant;
var baseResponse :any = {
'token_type': 'Bearer',
'expires_in': 28800
};
var resource = options.resource || parameters.resource;
var iterated: any = {
'access_token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1THdqcHdBSk9NOW4tQSJ9.eyJhdWQiOiIwMDAwMDAwMi0wMDAwLTAwMDAtYzAwMC0wMDAwMDAwMDAwMDAiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC82MmYwMzQ3MS02N2MxLTRjNTAtYjlkMS0xMzQ1MDc5ZDk3NzQvIiwiaWF0IjoxMzc4NjAxMTY4LCJuYmYiOjEzNzg2MDExNjgsImV4cCI6MTM3ODYyOTk2OCwidmVyIjoiMS4wIiwidGlkIjoiNjJmMDM0NzEtNjdjMS00YzUwLWI5ZDEtMTM0NTA3OWQ5Nzc0Iiwib2lkIjoiZjEzMDkzNDEtZDcyMy00YTc1LTk2YzktNGIyMTMzMzk0Mjg3Iiwic3ViIjoiZjEzMDkzNDEtZDcyMy00YTc1LTk2YzktNGIyMTMzMzk0Mjg3IiwiYXBwaWQiOiI1YzI1ZDFiZi1iMjMyLTQwMzUtYjZiOS0yYjdlN2U4MzQ2ZDYiLCJhcHBpZGFjciI6IjEifQ.qXM7f9TTiLApxVMwaSrISQQ6UAnfKvKhoIlN9rB0Eff2VXvIWKGRsclPkMQ5x42BQz2N6pSXEsN-LsNCZlQ76Rc3rVRONzeCYh7q_NXcCJG_d6SJTtV5GBfgqFlgT8UF5rblabbMdOiOrddvJm048hWt2Nm3qD3QjQdPBlD7Ksn-lUR1jEJPIqDaBjGom8RawrZTW6X1cy1Kr8mEYFkxcbU91k_RZUumONep9FTR8gfPkboeD8zyvOy64UeysEtcuaNCfhHSBFcwC8MwjUr5r_T7au7ywAcYDOVgoa7oF_dN1JNweiDoNNZ9tyUS-RY3sa3-gXk77gRxpA4CkpittQ',
'resource': resource
};
if (!options.noRefresh) {
if (options.refreshedRefresh) {
iterated['refresh_token'] = 'AwABAAAAvPM1KaPlrEqdFSBzjqfTGCDeE7YHWD9jkU2WWYKLjxu928QAbkoFyWp&yfPNft8DcbBqOSYVq5Ty_60YICIdFw61SG4-eT1nWHNOPdzsL2ZzloUsp2DpqlIr1s5Z3953oQBi7dOqiHk37NXQqmNEJ7MfmDp6w3EOa29EPARvjGIHFgtICW1-Y82npw1v1g8Ittb02pksNU2XzH2X0E3l3TuSZWsX5lpl-kfPOc8zppU6bwvT-VOPHZVVLQedDIQZyOiFst9HLUjbiIvBgV7tNwbB4H5yF56QQscz49Nrb3g0ibuNDo7efFawLzNoVHzoTrOTcCGSG1pt8Z-npByrEe7vg1o4nNFjspuxlyMGdnYRAnaZfvgzqROP_m7ZqSd6IAA';
} else {
iterated['refresh_token'] = parameters.refreshToken;
}
}
if (iteration) {
var iteratedKeys = _.keys(iterated);
for (var i = 0; i < iteratedKeys.length; i++) {
var key = iteratedKeys[i];
iterated[key] = iterated[key] + iteration;
}
}
_.extend(baseResponse, iterated);
if (!options.mrrt) {
delete baseResponse.resource;
}
var dateNow = new Date();
var wireResponse: any = _.clone(baseResponse);
wireResponse['created_on'] = dateNow.getTime();
var decodedResponse: any = {};
mapFields(wireResponse, decodedResponse, TOKEN_RESPONSE_MAP);
decodedResponse['createdOn'] = dateNow;
if (!options.noIdToken) {
wireResponse['id_token'] = options.urlSafeUserId ? encodedIdTokenUrlSafe : encodedIdToken;
var parsedUserInfo = options.urlSafeUserId ? parsedIdTokenUrlSafe : parsedIdToken;
_.extend(decodedResponse, parsedUserInfo);
}
var expiresOnDate;
if (options.expired) {
expiresOnDate = (Date as any).yesterday();
} else {
expiresOnDate = ((new Date()) as any).addSeconds(decodedResponse['expiresIn']);
}
decodedResponse['expiresOn'] = expiresOnDate;
var cachedResponse = _.clone(decodedResponse);
cachedResponse['_clientId'] = parameters.clientId;
cachedResponse['_authority'] = authority;
cachedResponse['resource'] = iterated['resource'];
if (options.mrrt) {
cachedResponse.isMRRT = true;
}
return {
wireResponse: wireResponse,
decodedResponse: decodedResponse,
cachedResponse: cachedResponse,
decodedIdToken: decodedIdToken,
resource: iterated['resource'],
refreshToken: iterated['refresh_token'],
clientId: cachedResponse['_clientId'],
authority: authority
};
};
util.createDeviceCodeResponse = function (options: any, iteration: any) {
iteration;
options = options || {};
var authority: any = options.authority || parameters.authorityTenant;
var resource: any = options.resource || parameters.resource;
authority; resource;
var wireResponse: any = {};
wireResponse['expires_in'] = 28800;
wireResponse['device_code'] = 'device_code:12345';
wireResponse['user_code'] = 'user_code:12345';
wireResponse['verification_url'] = 'go:to:verify';
wireResponse['interval'] = 5;
var decodedResponse = {};
mapFields(wireResponse, decodedResponse, DEVICE_CODE_RESPONSE_MAP);
return {
wireResponse: wireResponse,
decodedResponse: decodedResponse
};
};
util.compareQueryStrings = function (left: any, right: any) {
var leftParameters = querystring.parse(left);
var rightParameters = querystring.parse(right);
return _.isEqual(leftParameters, rightParameters);
};
util.filterQueryString = function (expected: any, received: any) {
return util.compareQueryStrings(expected, received) ? expected : received;
};
util.removeQueryStringIfMatching = function (path: any, query: any) {
var pathUrl = url.parse(path);
return util.compareQueryStrings(pathUrl.query, query) ? pathUrl.pathname : path;
};
function valExists(val: any) {
return val;
}
util.matchStandardRequestHeaders = function (nockRequest: any) {
nockRequest.matchHeader('x-client-SKU', 'Node')
.matchHeader('x-client-Ver', function (ver: any) {
return (ver && ver.indexOf('0.') === 0);
})
.matchHeader('x-client-OS', valExists)
.matchHeader('x-client-CPU', valExists)
.matchHeader('client-request-id', util.testCorrelationId);
};
util.setupExpectedOAuthResponse = function (queryParameters: any, tokenPath: any, httpCode: any, returnDoc: any, authorityEndpoint: any) {
var query = querystring.stringify(queryParameters);
decodedTokenUrlSafeTest;
var authEndpoint = this.getNockAuthorityHost(authorityEndpoint);
var tokenRequest = nock(authEndpoint)
.filteringRequestBody(function (body) {
return util.filterQueryString(query, body);
})
.post(tokenPath, query)
.reply(httpCode, returnDoc, { 'client-request-id': util.testCorrelationId });
util.matchStandardRequestHeaders(tokenRequest);
return tokenRequest;
};
util.setupExpectedClientCredTokenRequestResponse = function (httpCode: any, returnDoc: any, authorityEndpoint: any) {
var authEndpoint = authorityEndpoint || parameters.authority;
var queryParameters: any = {};
queryParameters['grant_type'] = 'client_credentials';
queryParameters['client_id'] = parameters.clientId;
queryParameters['client_secret'] = parameters.clientSecret;
queryParameters['resource'] = parameters.resource;
return util.setupExpectedOAuthResponse(queryParameters, parameters.tokenUrlPath, httpCode, returnDoc, authEndpoint);
};
util.setupExpectedInstanceDiscoveryRequest = function (httpCode: any, discoveryHost: any, returnDoc: any, authority: any) {
var instanceDiscoveryUrl: any = {};
instanceDiscoveryUrl.protocol = 'https:';
instanceDiscoveryUrl.host = discoveryHost;
instanceDiscoveryUrl.pathname = '/common/discovery/instance';
instanceDiscoveryUrl.query = {};
instanceDiscoveryUrl.query['authorization_endpoint'] = url.format(authority);
instanceDiscoveryUrl.query['api-version'] = '1.0';
instanceDiscoveryUrl = url.parse(url.format(instanceDiscoveryUrl));
var instanceDiscoveryEndpoint = this.trimPathFromUrl(instanceDiscoveryUrl);
var discoveryRequest = nock(instanceDiscoveryEndpoint)
.get(instanceDiscoveryUrl.path)
.reply(httpCode, returnDoc);
util.matchStandardRequestHeaders(discoveryRequest);
return discoveryRequest;
};
util.setupExpectedInstanceDiscoveryRequestCommon = function () {
return util.setupExpectedInstanceDiscoveryRequest(
200,
parameters.authority,
parameters.instanceDiscoverySuccessResponse,
parameters.authority);
};
util.setupExpectedUserRealmResponse = function (httpCode: any, returnDoc: any, authority: any) {
httpCode;
var userRealmAuthority = authority || parameters.authority;
userRealmAuthority = this.trimPathFromUrl(userRealmAuthority);
var userRealmPath = parameters.userRealmPathTemplate.replace('<user>', encodeURIComponent(parameters.username));
var query = 'api-version=1.0';
var userRealmRequest = nock(userRealmAuthority)
.filteringPath(function (path) {
return util.removeQueryStringIfMatching(path, query);
})
.get(userRealmPath)
.reply(200, returnDoc);
util.matchStandardRequestHeaders(userRealmRequest);
return userRealmRequest;
};
/**
* Set's up the nock expected response for successful UserRealm request responses.
* @param {bool} federated Indicates whether the response should indicate a federated or managed tenant.
* @return {nock}
*/
util.setupExpectedUserRealmResponseCommon = function (federated: any) {
var responseDoc;
if (federated) {
responseDoc = parameters.userRealmResponseFederated;
} else {
responseDoc = parameters.userRealmResponseManaged;
}
return util.setupExpectedUserRealmResponse(200, responseDoc, parameters.authority);
};
util.setupExpectedInstanceDiscoveryAndUserRealmRequest = function (federated: any) {
var instanceDiscovery = util.setupExpectedInstanceDiscoveryRequestCommon();
var userRealm = util.setupExpectedUserRealmResponseCommon(federated);
return {
done: function () {
instanceDiscovery.done();
userRealm.done();
}
};
};
util.setupExpectedFailedMexCommon = function () {
var mexRequest = nock(parameters.adfsUrlNoPath).get(parameters.adfsMexPath).reply(500);
util.matchStandardRequestHeaders(mexRequest);
return mexRequest;
};
util.setupExpectedMexCommon = function () {
var mexDoc = fs.readFileSync(parameters.MexFile, 'utf8');
var mexRequest = nock(parameters.adfsUrlNoPath).get(parameters.adfsMexPath).reply(200, mexDoc);
util.matchStandardRequestHeaders(mexRequest);
return mexRequest;
};
util.setupExpectedWSTrustRequestCommon = function () {
var RSTRDoc = fs.readFileSync(parameters.RSTRFile, 'utf8');
var wstrustRequest = nock(parameters.adfsUrlNoPath)
.filteringRequestBody(function () { return '*'; })
.post(parameters.adfsWsTrustPath, '*')
.reply(200, RSTRDoc);
util.matchStandardRequestHeaders(wstrustRequest);
return wstrustRequest;
};
util.setupExpectedMexWSTrustRequestCommon = function () {
var expectedMex = util.setupExpectedMexCommon();
var expectedWsTrust = util.setupExpectedWSTrustRequestCommon();
var doneFunc = function () {
expectedMex.done();
expectedWsTrust.done();
};
return { done: doneFunc };
};
util.setupExpectedRefreshTokenRequestResponse = function (httpCode: any, returnDoc: any, authorityEndpoint: any, resource: any, clientSecret: any) {
var authEndpoint = authorityEndpoint || parameters.authority;
var queryParameters: any = {};
queryParameters['grant_type'] = 'refresh_token';
queryParameters['scope'] = 'openid';
queryParameters['client_id'] = parameters.clientId;
if (clientSecret) {
queryParameters['client_secret'] = clientSecret;
}
if (resource) {
queryParameters['resource'] = resource;
}
queryParameters['refresh_token'] = parameters.refreshToken;
return util.setupExpectedOAuthResponse(queryParameters, parameters.tokenUrlPath, httpCode, returnDoc, authEndpoint);
};
util.setupExpectedClientAssertionTokenRequestResponse = function (httpCode: any, returnDoc: any, authorityEndpoint: any) {
var authEndpoint = authorityEndpoint || parameters.authority;
var queryParameters: any = {};
queryParameters['grant_type'] = 'client_credentials';
queryParameters['client_assertion_type'] = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer';
queryParameters['client_assertion'] = parameters.expectedJwt;
queryParameters['client_id'] = parameters.clientId;
queryParameters['resource'] = parameters.resource;
return util.setupExpectedOAuthResponse(queryParameters, parameters.tokenUrlPath, httpCode, returnDoc, authEndpoint);
};
function isDateWithinTolerance(date: any, expectedDate?: any) {
var expected = expectedDate || new Date();
var fiveBefore = expected.clone();
fiveBefore.addSeconds(-5);
expected.addSeconds(5);
if (date.between(fiveBefore, expected)) {
return true;
}
return false;
}
function isExpiresWithinTolerance(expiresOn: any, expired?: any) {
if (!expiresOn) {
console.log('no expires_on');
return false;
}
// Add the expected expires_in latency.
var expectedExpires = expired ? new Date() : (Date as any).yesterday();
expectedExpires = expiresOn.addSeconds(28800);
return isDateWithinTolerance(expiresOn, expectedExpires);
}
util.isMatchTokenResponse = function (expected: any, received: any, print: any) {
var expiresOn = received['expiresOn'];
var createdOn = received['createdOn'];
if (print) {
console.log('DIFFS');
util.findDiffs(expected, received);
console.log('EXPECTED');
console.log(expected);
console.log('RECEIVED');
console.log(received);
}
if (!(isExpiresWithinTolerance(expiresOn) || isExpiresWithinTolerance(expiresOn, true))) {
return false;
}
if (!isDateWithinTolerance(createdOn)) {
return false;
}
// Compare the expected and responses without the expires_on field as that was validated above.
var receivedClone = _.clone(received);
delete receivedClone['expiresOn'];
delete receivedClone['createdOn'];
var expectedClone = _.clone(expected);
delete expectedClone['expiresOn'];
delete expectedClone['createdOn'];
if (receivedClone.clientId && !expectedClone.clientId) {
delete receivedClone.clientId;
}
var isEqual = _.isEqual(expectedClone, receivedClone);
return isEqual;
};
util.isMathDeviceCodeResponse = function (expected: any, received: any, print: any) {
if (print) {
console.log('DIFFS');
util.findDiffs(expected, received);
console.log('EXPECTED');
console.log(expected);
console.log('RECEIVED');
console.log(received);
}
var receivedClone = _.clone(received);
var expectedClone = _.clone(expected);
var isEqual = _.isEqual(expectedClone, receivedClone);
return isEqual;
};
util.createTokenResponseWithIdToken = function (response: any) {
response = response || _.clone(parameters.successResponseWithRefresh);
_.extend(response, parsedIdToken);
return response;
};
util.isMatchIdTokenResponse = function (expected: any, received: any) {
expected = _.clone(expected);
_.extend(expected, parsedIdToken);
return util.isMatchTokenResponse(expected, received);
};
util.createIdTokenServerResponse = function (baseResponse: any) {
var sourceResponse = baseResponse || _.clone(parameters.successResponseWithRefresh);
sourceResponse = _.clone(sourceResponse);
sourceResponse['id_token'] = encodedIdToken;
return sourceResponse;
};
util.createEmptyADALObject = function () {
var context = log.createLogContext();
var component = 'TEST';
var logger = new log.Logger(component, context);
var callContext = { _logContext: context };
var adalObject = {
_log: logger,
_callContext: callContext
};
return adalObject;
};
util.findDiffs = function (leftObj: any, rightObj: any) {
var keys = _.keys(leftObj);
var rightKeys = _.keys(rightObj);
if (keys.length !== rightKeys.length) {
console.log('unmatched number of keys.');
}
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (leftObj[key] !== rightObj[key]) {
console.log(key + ': ' + leftObj[key] + ' | ' + rightObj[key]);
}
}
};
util.clearStaticCache = function () {
var context = new adal.AuthenticationContext(parameters.authorityTenant);
var cacheArray = context.cache._entries;
var entry;
do {
entry = cacheArray.pop();
} while (entry);
};
util.trimPathFromUrl = function (stringUrl: string) {
var u: any = url.parse(stringUrl);
return url.resolve(u, '/');
};
util.getNockAuthorityHost = function (authority: any) {
var authEndpoint = authority || this.commonParameters.evoEndpoint;
return this.trimPathFromUrl(authEndpoint);
};
module.exports = util; | the_stack |
import * as assert from 'assert';
import { Constants } from 'vs/base/common/uint';
import { Range } from 'vs/editor/common/core/range';
import { DiffComputer, ICharChange, ILineChange } from 'vs/editor/common/diff/diffComputer';
import { IIdentifiedSingleEditOperation, ITextModel } from 'vs/editor/common/model';
import { createTextModel } from 'vs/editor/test/common/testTextModel';
function assertDiff(originalLines: string[], modifiedLines: string[], expectedChanges: ILineChange[], shouldComputeCharChanges: boolean = true, shouldPostProcessCharChanges: boolean = false, shouldIgnoreTrimWhitespace: boolean = false) {
const diffComputer = new DiffComputer(originalLines, modifiedLines, {
shouldComputeCharChanges,
shouldPostProcessCharChanges,
shouldIgnoreTrimWhitespace,
shouldMakePrettyDiff: true,
maxComputationTime: 0
});
const changes = diffComputer.computeDiff().changes;
const mapCharChange = (charChange: ICharChange) => {
return {
originalStartLineNumber: charChange.originalStartLineNumber,
originalStartColumn: charChange.originalStartColumn,
originalEndLineNumber: charChange.originalEndLineNumber,
originalEndColumn: charChange.originalEndColumn,
modifiedStartLineNumber: charChange.modifiedStartLineNumber,
modifiedStartColumn: charChange.modifiedStartColumn,
modifiedEndLineNumber: charChange.modifiedEndLineNumber,
modifiedEndColumn: charChange.modifiedEndColumn,
};
};
const actual = changes.map((lineChange) => {
return {
originalStartLineNumber: lineChange.originalStartLineNumber,
originalEndLineNumber: lineChange.originalEndLineNumber,
modifiedStartLineNumber: lineChange.modifiedStartLineNumber,
modifiedEndLineNumber: lineChange.modifiedEndLineNumber,
charChanges: (lineChange.charChanges ? lineChange.charChanges.map(mapCharChange) : undefined)
};
});
assert.deepStrictEqual(actual, expectedChanges);
if (!shouldIgnoreTrimWhitespace) {
// The diffs should describe how to apply edits to the original text model to get to the modified text model.
const modifiedTextModel = createTextModel(modifiedLines.join('\n'));
const expectedValue = modifiedTextModel.getValue();
{
// Line changes:
const originalTextModel = createTextModel(originalLines.join('\n'));
originalTextModel.applyEdits(changes.map(c => getLineEdit(c, modifiedTextModel)));
assert.deepStrictEqual(originalTextModel.getValue(), expectedValue);
originalTextModel.dispose();
}
if (shouldComputeCharChanges) {
// Char changes:
const originalTextModel = createTextModel(originalLines.join('\n'));
originalTextModel.applyEdits(changes.flatMap(c => getCharEdits(c, modifiedTextModel)));
assert.deepStrictEqual(originalTextModel.getValue(), expectedValue);
originalTextModel.dispose();
}
modifiedTextModel.dispose();
}
}
function getCharEdits(lineChange: ILineChange, modifiedTextModel: ITextModel): IIdentifiedSingleEditOperation[] {
if (!lineChange.charChanges) {
return [getLineEdit(lineChange, modifiedTextModel)];
}
return lineChange.charChanges.map(c => {
const originalRange = new Range(c.originalStartLineNumber, c.originalStartColumn, c.originalEndLineNumber, c.originalEndColumn);
const modifiedRange = new Range(c.modifiedStartLineNumber, c.modifiedStartColumn, c.modifiedEndLineNumber, c.modifiedEndColumn);
return {
range: originalRange,
text: modifiedTextModel.getValueInRange(modifiedRange)
};
});
}
function getLineEdit(lineChange: ILineChange, modifiedTextModel: ITextModel): IIdentifiedSingleEditOperation {
let originalRange: LineRange;
if (lineChange.originalEndLineNumber === 0) {
// Insertion
originalRange = new LineRange(lineChange.originalStartLineNumber + 1, 0);
} else {
originalRange = new LineRange(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber - lineChange.originalStartLineNumber + 1);
}
let modifiedRange: LineRange;
if (lineChange.modifiedEndLineNumber === 0) {
// Deletion
modifiedRange = new LineRange(lineChange.modifiedStartLineNumber + 1, 0);
} else {
modifiedRange = new LineRange(lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber - lineChange.modifiedStartLineNumber + 1);
}
const [r1, r2] = diffFromLineRanges(originalRange, modifiedRange);
return {
range: r1,
text: modifiedTextModel.getValueInRange(r2),
};
}
function diffFromLineRanges(originalRange: LineRange, modifiedRange: LineRange): [Range, Range] {
if (originalRange.startLineNumber === 1 || modifiedRange.startLineNumber === 1) {
if (!originalRange.isEmpty && !modifiedRange.isEmpty) {
return [
new Range(
originalRange.startLineNumber,
1,
originalRange.endLineNumberExclusive - 1,
Constants.MAX_SAFE_SMALL_INTEGER,
),
new Range(
modifiedRange.startLineNumber,
1,
modifiedRange.endLineNumberExclusive - 1,
Constants.MAX_SAFE_SMALL_INTEGER,
)
];
}
// When one of them is one and one of them is empty, the other cannot be the last line of the document
return [
new Range(
originalRange.startLineNumber,
1,
originalRange.endLineNumberExclusive,
1,
),
new Range(
modifiedRange.startLineNumber,
1,
modifiedRange.endLineNumberExclusive,
1,
)
];
}
return [
new Range(
originalRange.startLineNumber - 1,
Constants.MAX_SAFE_SMALL_INTEGER,
originalRange.endLineNumberExclusive - 1,
Constants.MAX_SAFE_SMALL_INTEGER,
),
new Range(
modifiedRange.startLineNumber - 1,
Constants.MAX_SAFE_SMALL_INTEGER,
modifiedRange.endLineNumberExclusive - 1,
Constants.MAX_SAFE_SMALL_INTEGER,
)
];
}
class LineRange {
public constructor(
public readonly startLineNumber: number,
public readonly lineCount: number
) { }
public get isEmpty(): boolean {
return this.lineCount === 0;
}
public get endLineNumberExclusive(): number {
return this.startLineNumber + this.lineCount;
}
}
function createLineDeletion(startLineNumber: number, endLineNumber: number, modifiedLineNumber: number): ILineChange {
return {
originalStartLineNumber: startLineNumber,
originalEndLineNumber: endLineNumber,
modifiedStartLineNumber: modifiedLineNumber,
modifiedEndLineNumber: 0,
charChanges: undefined
};
}
function createLineInsertion(startLineNumber: number, endLineNumber: number, originalLineNumber: number): ILineChange {
return {
originalStartLineNumber: originalLineNumber,
originalEndLineNumber: 0,
modifiedStartLineNumber: startLineNumber,
modifiedEndLineNumber: endLineNumber,
charChanges: undefined
};
}
function createLineChange(originalStartLineNumber: number, originalEndLineNumber: number, modifiedStartLineNumber: number, modifiedEndLineNumber: number, charChanges?: ICharChange[]): ILineChange {
return {
originalStartLineNumber: originalStartLineNumber,
originalEndLineNumber: originalEndLineNumber,
modifiedStartLineNumber: modifiedStartLineNumber,
modifiedEndLineNumber: modifiedEndLineNumber,
charChanges: charChanges
};
}
function createCharChange(
originalStartLineNumber: number, originalStartColumn: number, originalEndLineNumber: number, originalEndColumn: number,
modifiedStartLineNumber: number, modifiedStartColumn: number, modifiedEndLineNumber: number, modifiedEndColumn: number
) {
return {
originalStartLineNumber: originalStartLineNumber,
originalStartColumn: originalStartColumn,
originalEndLineNumber: originalEndLineNumber,
originalEndColumn: originalEndColumn,
modifiedStartLineNumber: modifiedStartLineNumber,
modifiedStartColumn: modifiedStartColumn,
modifiedEndLineNumber: modifiedEndLineNumber,
modifiedEndColumn: modifiedEndColumn
};
}
suite('Editor Diff - DiffComputer', () => {
// ---- insertions
test('one inserted line below', () => {
const original = ['line'];
const modified = ['line', 'new line'];
const expected = [createLineInsertion(2, 2, 1)];
assertDiff(original, modified, expected);
});
test('two inserted lines below', () => {
const original = ['line'];
const modified = ['line', 'new line', 'another new line'];
const expected = [createLineInsertion(2, 3, 1)];
assertDiff(original, modified, expected);
});
test('one inserted line above', () => {
const original = ['line'];
const modified = ['new line', 'line'];
const expected = [createLineInsertion(1, 1, 0)];
assertDiff(original, modified, expected);
});
test('two inserted lines above', () => {
const original = ['line'];
const modified = ['new line', 'another new line', 'line'];
const expected = [createLineInsertion(1, 2, 0)];
assertDiff(original, modified, expected);
});
test('one inserted line in middle', () => {
const original = ['line1', 'line2', 'line3', 'line4'];
const modified = ['line1', 'line2', 'new line', 'line3', 'line4'];
const expected = [createLineInsertion(3, 3, 2)];
assertDiff(original, modified, expected);
});
test('two inserted lines in middle', () => {
const original = ['line1', 'line2', 'line3', 'line4'];
const modified = ['line1', 'line2', 'new line', 'another new line', 'line3', 'line4'];
const expected = [createLineInsertion(3, 4, 2)];
assertDiff(original, modified, expected);
});
test('two inserted lines in middle interrupted', () => {
const original = ['line1', 'line2', 'line3', 'line4'];
const modified = ['line1', 'line2', 'new line', 'line3', 'another new line', 'line4'];
const expected = [createLineInsertion(3, 3, 2), createLineInsertion(5, 5, 3)];
assertDiff(original, modified, expected);
});
// ---- deletions
test('one deleted line below', () => {
const original = ['line', 'new line'];
const modified = ['line'];
const expected = [createLineDeletion(2, 2, 1)];
assertDiff(original, modified, expected);
});
test('two deleted lines below', () => {
const original = ['line', 'new line', 'another new line'];
const modified = ['line'];
const expected = [createLineDeletion(2, 3, 1)];
assertDiff(original, modified, expected);
});
test('one deleted lines above', () => {
const original = ['new line', 'line'];
const modified = ['line'];
const expected = [createLineDeletion(1, 1, 0)];
assertDiff(original, modified, expected);
});
test('two deleted lines above', () => {
const original = ['new line', 'another new line', 'line'];
const modified = ['line'];
const expected = [createLineDeletion(1, 2, 0)];
assertDiff(original, modified, expected);
});
test('one deleted line in middle', () => {
const original = ['line1', 'line2', 'new line', 'line3', 'line4'];
const modified = ['line1', 'line2', 'line3', 'line4'];
const expected = [createLineDeletion(3, 3, 2)];
assertDiff(original, modified, expected);
});
test('two deleted lines in middle', () => {
const original = ['line1', 'line2', 'new line', 'another new line', 'line3', 'line4'];
const modified = ['line1', 'line2', 'line3', 'line4'];
const expected = [createLineDeletion(3, 4, 2)];
assertDiff(original, modified, expected);
});
test('two deleted lines in middle interrupted', () => {
const original = ['line1', 'line2', 'new line', 'line3', 'another new line', 'line4'];
const modified = ['line1', 'line2', 'line3', 'line4'];
const expected = [createLineDeletion(3, 3, 2), createLineDeletion(5, 5, 3)];
assertDiff(original, modified, expected);
});
// ---- changes
test('one line changed: chars inserted at the end', () => {
const original = ['line'];
const modified = ['line changed'];
const expected = [
createLineChange(1, 1, 1, 1, [
createCharChange(1, 5, 1, 5, 1, 5, 1, 13)
])
];
assertDiff(original, modified, expected);
});
test('one line changed: chars inserted at the beginning', () => {
const original = ['line'];
const modified = ['my line'];
const expected = [
createLineChange(1, 1, 1, 1, [
createCharChange(1, 1, 1, 1, 1, 1, 1, 4)
])
];
assertDiff(original, modified, expected);
});
test('one line changed: chars inserted in the middle', () => {
const original = ['abba'];
const modified = ['abzzba'];
const expected = [
createLineChange(1, 1, 1, 1, [
createCharChange(1, 3, 1, 3, 1, 3, 1, 5)
])
];
assertDiff(original, modified, expected);
});
test('one line changed: chars inserted in the middle (two spots)', () => {
const original = ['abba'];
const modified = ['abzzbzza'];
const expected = [
createLineChange(1, 1, 1, 1, [
createCharChange(1, 3, 1, 3, 1, 3, 1, 5),
createCharChange(1, 4, 1, 4, 1, 6, 1, 8)
])
];
assertDiff(original, modified, expected);
});
test('one line changed: chars deleted 1', () => {
const original = ['abcdefg'];
const modified = ['abcfg'];
const expected = [
createLineChange(1, 1, 1, 1, [
createCharChange(1, 4, 1, 6, 1, 4, 1, 4)
])
];
assertDiff(original, modified, expected);
});
test('one line changed: chars deleted 2', () => {
const original = ['abcdefg'];
const modified = ['acfg'];
const expected = [
createLineChange(1, 1, 1, 1, [
createCharChange(1, 2, 1, 3, 1, 2, 1, 2),
createCharChange(1, 4, 1, 6, 1, 3, 1, 3)
])
];
assertDiff(original, modified, expected);
});
test('two lines changed 1', () => {
const original = ['abcd', 'efgh'];
const modified = ['abcz'];
const expected = [
createLineChange(1, 2, 1, 1, [
createCharChange(1, 4, 2, 5, 1, 4, 1, 5)
])
];
assertDiff(original, modified, expected);
});
test('two lines changed 2', () => {
const original = ['foo', 'abcd', 'efgh', 'BAR'];
const modified = ['foo', 'abcz', 'BAR'];
const expected = [
createLineChange(2, 3, 2, 2, [
createCharChange(2, 4, 3, 5, 2, 4, 2, 5)
])
];
assertDiff(original, modified, expected);
});
test('two lines changed 3', () => {
const original = ['foo', 'abcd', 'efgh', 'BAR'];
const modified = ['foo', 'abcz', 'zzzzefgh', 'BAR'];
const expected = [
createLineChange(2, 3, 2, 3, [
createCharChange(2, 4, 2, 5, 2, 4, 2, 5),
createCharChange(3, 1, 3, 1, 3, 1, 3, 5)
])
];
assertDiff(original, modified, expected);
});
test('two lines changed 4', () => {
const original = ['abc'];
const modified = ['', '', 'axc', ''];
const expected = [
createLineChange(1, 1, 1, 4, [
createCharChange(1, 1, 1, 1, 1, 1, 3, 1),
createCharChange(1, 2, 1, 3, 3, 2, 3, 3),
createCharChange(1, 4, 1, 4, 3, 4, 4, 1)
])
];
assertDiff(original, modified, expected);
});
test('empty original sequence in char diff', () => {
const original = ['abc', '', 'xyz'];
const modified = ['abc', 'qwe', 'rty', 'xyz'];
const expected = [
createLineChange(2, 2, 2, 3)
];
assertDiff(original, modified, expected);
});
test('three lines changed', () => {
const original = ['foo', 'abcd', 'efgh', 'BAR'];
const modified = ['foo', 'zzzefgh', 'xxx', 'BAR'];
const expected = [
createLineChange(2, 3, 2, 3, [
createCharChange(2, 1, 3, 1, 2, 1, 2, 4),
createCharChange(3, 5, 3, 5, 2, 8, 3, 4),
])
];
assertDiff(original, modified, expected);
});
test('big change part 1', () => {
const original = ['foo', 'abcd', 'efgh', 'BAR'];
const modified = ['hello', 'foo', 'zzzefgh', 'xxx', 'BAR'];
const expected = [
createLineInsertion(1, 1, 0),
createLineChange(2, 3, 3, 4, [
createCharChange(2, 1, 3, 1, 3, 1, 3, 4),
createCharChange(3, 5, 3, 5, 3, 8, 4, 4)
])
];
assertDiff(original, modified, expected);
});
test('big change part 2', () => {
const original = ['foo', 'abcd', 'efgh', 'BAR', 'RAB'];
const modified = ['hello', 'foo', 'zzzefgh', 'xxx', 'BAR'];
const expected = [
createLineInsertion(1, 1, 0),
createLineChange(2, 3, 3, 4, [
createCharChange(2, 1, 3, 1, 3, 1, 3, 4),
createCharChange(3, 5, 3, 5, 3, 8, 4, 4)
]),
createLineDeletion(5, 5, 5)
];
assertDiff(original, modified, expected);
});
test('char change postprocessing merges', () => {
const original = ['abba'];
const modified = ['azzzbzzzbzzza'];
const expected = [
createLineChange(1, 1, 1, 1, [
createCharChange(1, 2, 1, 4, 1, 2, 1, 13)
])
];
assertDiff(original, modified, expected, true, true);
});
test('ignore trim whitespace', () => {
const original = ['\t\t foo ', 'abcd', 'efgh', '\t\t BAR\t\t'];
const modified = [' hello\t', '\t foo \t', 'zzzefgh', 'xxx', ' BAR \t'];
const expected = [
createLineInsertion(1, 1, 0),
createLineChange(2, 3, 3, 4, [
createCharChange(2, 1, 2, 5, 3, 1, 3, 4),
createCharChange(3, 5, 3, 5, 4, 1, 4, 4)
])
];
assertDiff(original, modified, expected, true, false, true);
});
test('issue #12122 r.hasOwnProperty is not a function', () => {
const original = ['hasOwnProperty'];
const modified = ['hasOwnProperty', 'and another line'];
const expected = [
createLineInsertion(2, 2, 1)
];
assertDiff(original, modified, expected);
});
test('empty diff 1', () => {
const original = [''];
const modified = ['something'];
const expected = [
createLineChange(1, 1, 1, 1, [
createCharChange(0, 0, 0, 0, 0, 0, 0, 0)
])
];
assertDiff(original, modified, expected, true, false, true);
});
test('empty diff 2', () => {
const original = [''];
const modified = ['something', 'something else'];
const expected = [
createLineChange(1, 1, 1, 2, [
createCharChange(0, 0, 0, 0, 0, 0, 0, 0)
])
];
assertDiff(original, modified, expected, true, false, true);
});
test('empty diff 3', () => {
const original = ['something', 'something else'];
const modified = [''];
const expected = [
createLineChange(1, 2, 1, 1, [
createCharChange(0, 0, 0, 0, 0, 0, 0, 0)
])
];
assertDiff(original, modified, expected, true, false, true);
});
test('empty diff 4', () => {
const original = ['something'];
const modified = [''];
const expected = [
createLineChange(1, 1, 1, 1, [
createCharChange(0, 0, 0, 0, 0, 0, 0, 0)
])
];
assertDiff(original, modified, expected, true, false, true);
});
test('empty diff 5', () => {
const original = [''];
const modified = [''];
const expected: ILineChange[] = [];
assertDiff(original, modified, expected, true, false, true);
});
test('pretty diff 1', () => {
const original = [
'suite(function () {',
' test1() {',
' assert.ok(true);',
' }',
'',
' test2() {',
' assert.ok(true);',
' }',
'});',
'',
];
const modified = [
'// An insertion',
'suite(function () {',
' test1() {',
' assert.ok(true);',
' }',
'',
' test2() {',
' assert.ok(true);',
' }',
'',
' test3() {',
' assert.ok(true);',
' }',
'});',
'',
];
const expected = [
createLineInsertion(1, 1, 0),
createLineInsertion(10, 13, 8)
];
assertDiff(original, modified, expected, true, false, true);
});
test('pretty diff 2', () => {
const original = [
'// Just a comment',
'',
'function compute(a, b, c, d) {',
' if (a) {',
' if (b) {',
' if (c) {',
' return 5;',
' }',
' }',
' // These next lines will be deleted',
' if (d) {',
' return -1;',
' }',
' return 0;',
' }',
'}',
];
const modified = [
'// Here is an inserted line',
'// and another inserted line',
'// and another one',
'// Just a comment',
'',
'function compute(a, b, c, d) {',
' if (a) {',
' if (b) {',
' if (c) {',
' return 5;',
' }',
' }',
' return 0;',
' }',
'}',
];
const expected = [
createLineInsertion(1, 3, 0),
createLineDeletion(10, 13, 12),
];
assertDiff(original, modified, expected, true, false, true);
});
test('pretty diff 3', () => {
const original = [
'class A {',
' /**',
' * m1',
' */',
' method1() {}',
'',
' /**',
' * m3',
' */',
' method3() {}',
'}',
];
const modified = [
'class A {',
' /**',
' * m1',
' */',
' method1() {}',
'',
' /**',
' * m2',
' */',
' method2() {}',
'',
' /**',
' * m3',
' */',
' method3() {}',
'}',
];
const expected = [
createLineInsertion(7, 11, 6)
];
assertDiff(original, modified, expected, true, false, true);
});
test('issue #23636', () => {
const original = [
'if(!TextDrawLoad[playerid])',
'{',
'',
' TextDrawHideForPlayer(playerid,TD_AppleJob[3]);',
' TextDrawHideForPlayer(playerid,TD_AppleJob[4]);',
' if(!AppleJobTreesType[AppleJobTreesPlayerNum[playerid]])',
' {',
' for(new i=0;i<10;i++) if(StatusTD_AppleJobApples[playerid][i]) TextDrawHideForPlayer(playerid,TD_AppleJob[5+i]);',
' }',
' else',
' {',
' for(new i=0;i<10;i++) if(StatusTD_AppleJobApples[playerid][i]) TextDrawHideForPlayer(playerid,TD_AppleJob[15+i]);',
' }',
'}',
'else',
'{',
' TextDrawHideForPlayer(playerid,TD_AppleJob[3]);',
' TextDrawHideForPlayer(playerid,TD_AppleJob[27]);',
' if(!AppleJobTreesType[AppleJobTreesPlayerNum[playerid]])',
' {',
' for(new i=0;i<10;i++) if(StatusTD_AppleJobApples[playerid][i]) TextDrawHideForPlayer(playerid,TD_AppleJob[28+i]);',
' }',
' else',
' {',
' for(new i=0;i<10;i++) if(StatusTD_AppleJobApples[playerid][i]) TextDrawHideForPlayer(playerid,TD_AppleJob[38+i]);',
' }',
'}',
];
const modified = [
' if(!TextDrawLoad[playerid])',
' {',
' ',
' TextDrawHideForPlayer(playerid,TD_AppleJob[3]);',
' TextDrawHideForPlayer(playerid,TD_AppleJob[4]);',
' if(!AppleJobTreesType[AppleJobTreesPlayerNum[playerid]])',
' {',
' for(new i=0;i<10;i++) if(StatusTD_AppleJobApples[playerid][i]) TextDrawHideForPlayer(playerid,TD_AppleJob[5+i]);',
' }',
' else',
' {',
' for(new i=0;i<10;i++) if(StatusTD_AppleJobApples[playerid][i]) TextDrawHideForPlayer(playerid,TD_AppleJob[15+i]);',
' }',
' }',
' else',
' {',
' TextDrawHideForPlayer(playerid,TD_AppleJob[3]);',
' TextDrawHideForPlayer(playerid,TD_AppleJob[27]);',
' if(!AppleJobTreesType[AppleJobTreesPlayerNum[playerid]])',
' {',
' for(new i=0;i<10;i++) if(StatusTD_AppleJobApples[playerid][i]) TextDrawHideForPlayer(playerid,TD_AppleJob[28+i]);',
' }',
' else',
' {',
' for(new i=0;i<10;i++) if(StatusTD_AppleJobApples[playerid][i]) TextDrawHideForPlayer(playerid,TD_AppleJob[38+i]);',
' }',
' }',
];
const expected = [
createLineChange(
1, 27, 1, 27,
[
createCharChange(1, 1, 1, 1, 1, 1, 1, 2),
createCharChange(2, 1, 2, 1, 2, 1, 2, 2),
createCharChange(3, 1, 3, 1, 3, 1, 3, 2),
createCharChange(4, 1, 4, 1, 4, 1, 4, 2),
createCharChange(5, 1, 5, 1, 5, 1, 5, 2),
createCharChange(6, 1, 6, 1, 6, 1, 6, 2),
createCharChange(7, 1, 7, 1, 7, 1, 7, 2),
createCharChange(8, 1, 8, 1, 8, 1, 8, 2),
createCharChange(9, 1, 9, 1, 9, 1, 9, 2),
createCharChange(10, 1, 10, 1, 10, 1, 10, 2),
createCharChange(11, 1, 11, 1, 11, 1, 11, 2),
createCharChange(12, 1, 12, 1, 12, 1, 12, 2),
createCharChange(13, 1, 13, 1, 13, 1, 13, 2),
createCharChange(14, 1, 14, 1, 14, 1, 14, 2),
createCharChange(15, 1, 15, 1, 15, 1, 15, 2),
createCharChange(16, 1, 16, 1, 16, 1, 16, 2),
createCharChange(17, 1, 17, 1, 17, 1, 17, 2),
createCharChange(18, 1, 18, 1, 18, 1, 18, 2),
createCharChange(19, 1, 19, 1, 19, 1, 19, 2),
createCharChange(20, 1, 20, 1, 20, 1, 20, 2),
createCharChange(21, 1, 21, 1, 21, 1, 21, 2),
createCharChange(22, 1, 22, 1, 22, 1, 22, 2),
createCharChange(23, 1, 23, 1, 23, 1, 23, 2),
createCharChange(24, 1, 24, 1, 24, 1, 24, 2),
createCharChange(25, 1, 25, 1, 25, 1, 25, 2),
createCharChange(26, 1, 26, 1, 26, 1, 26, 2),
createCharChange(27, 1, 27, 1, 27, 1, 27, 2),
]
)
// createLineInsertion(7, 11, 6)
];
assertDiff(original, modified, expected, true, true, false);
});
test('issue #43922', () => {
const original = [
' * `yarn [install]` -- Install project NPM dependencies. This is automatically done when you first create the project. You should only need to run this if you add dependencies in `package.json`.',
];
const modified = [
' * `yarn` -- Install project NPM dependencies. You should only need to run this if you add dependencies in `package.json`.',
];
const expected = [
createLineChange(
1, 1, 1, 1,
[
createCharChange(1, 9, 1, 19, 1, 9, 1, 9),
createCharChange(1, 58, 1, 120, 1, 48, 1, 48),
]
)
];
assertDiff(original, modified, expected, true, true, false);
});
test('issue #42751', () => {
const original = [
' 1',
' 2',
];
const modified = [
' 1',
' 3',
];
const expected = [
createLineChange(
2, 2, 2, 2,
[
createCharChange(2, 3, 2, 4, 2, 3, 2, 5)
]
)
];
assertDiff(original, modified, expected, true, true, false);
});
test('does not give character changes', () => {
const original = [
' 1',
' 2',
'A',
];
const modified = [
' 1',
' 3',
' A',
];
const expected = [
createLineChange(
2, 3, 2, 3
)
];
assertDiff(original, modified, expected, false, false, false);
});
test('issue #44422: Less than ideal diff results', () => {
const original = [
'export class C {',
'',
' public m1(): void {',
' {',
' //2',
' //3',
' //4',
' //5',
' //6',
' //7',
' //8',
' //9',
' //10',
' //11',
' //12',
' //13',
' //14',
' //15',
' //16',
' //17',
' //18',
' }',
' }',
'',
' public m2(): void {',
' if (a) {',
' if (b) {',
' //A1',
' //A2',
' //A3',
' //A4',
' //A5',
' //A6',
' //A7',
' //A8',
' }',
' }',
'',
' //A9',
' //A10',
' //A11',
' //A12',
' //A13',
' //A14',
' //A15',
' }',
'',
' public m3(): void {',
' if (a) {',
' //B1',
' }',
' //B2',
' //B3',
' }',
'',
' public m4(): boolean {',
' //1',
' //2',
' //3',
' //4',
' }',
'',
'}',
];
const modified = [
'export class C {',
'',
' constructor() {',
'',
'',
'',
'',
' }',
'',
' public m1(): void {',
' {',
' //2',
' //3',
' //4',
' //5',
' //6',
' //7',
' //8',
' //9',
' //10',
' //11',
' //12',
' //13',
' //14',
' //15',
' //16',
' //17',
' //18',
' }',
' }',
'',
' public m4(): boolean {',
' //1',
' //2',
' //3',
' //4',
' }',
'',
'}',
];
const expected = [
createLineChange(
2, 0, 3, 9
),
createLineChange(
25, 55, 31, 0
)
];
assertDiff(original, modified, expected, false, false, false);
});
test('gives preference to matching longer lines', () => {
const original = [
'A',
'A',
'BB',
'C',
];
const modified = [
'A',
'BB',
'A',
'D',
'E',
'A',
'C',
];
const expected = [
createLineChange(
2, 2, 1, 0
),
createLineChange(
3, 0, 3, 6
)
];
assertDiff(original, modified, expected, false, false, false);
});
test('issue #119051: gives preference to fewer diff hunks', () => {
const original = [
'1',
'',
'',
'2',
'',
];
const modified = [
'1',
'',
'1.5',
'',
'',
'2',
'',
'3',
'',
];
const expected = [
createLineChange(
2, 0, 3, 4
),
createLineChange(
5, 0, 8, 9
)
];
assertDiff(original, modified, expected, false, false, false);
});
test('issue #121436: Diff chunk contains an unchanged line part 1', () => {
const original = [
'if (cond) {',
' cmd',
'}',
];
const modified = [
'if (cond) {',
' if (other_cond) {',
' cmd',
' }',
'}',
];
const expected = [
createLineChange(
1, 0, 2, 2
),
createLineChange(
2, 0, 4, 4
)
];
assertDiff(original, modified, expected, false, false, true);
});
test('issue #121436: Diff chunk contains an unchanged line part 2', () => {
const original = [
'if (cond) {',
' cmd',
'}',
];
const modified = [
'if (cond) {',
' if (other_cond) {',
' cmd',
' }',
'}',
];
const expected = [
createLineChange(
1, 0, 2, 2
),
createLineChange(
2, 2, 3, 3
),
createLineChange(
2, 0, 4, 4
)
];
assertDiff(original, modified, expected, false, false, false);
});
}); | the_stack |
export interface ApplicationDataListResponse {
/** List of requested objects. */
value?: ApplicationData[];
/** Token used in retrieving the next page. If null, there are no additional pages. */
skipToken?: string;
/** Continuation link (absolute URI) to the next page of results in the list. */
nextLink?: string;
}
export interface ApplicationData {
/** Application product details. */
applicationProductDetails?: ApplicationProductDetail[];
/** Schema for storing measurement reading and unit. */
avgMaterial?: Measure;
/** Schema for storing measurement reading and unit. */
totalMaterial?: Measure;
/** Schema for storing measurement reading and unit. */
area?: Measure;
/** Source of the operation data. */
source?: string;
/**
* Modified date-time of the operation data, sample format: yyyy-MM-ddTHH:mm:ssZ.
* Note: this will be specified by the source provider itself.
*/
operationModifiedDateTime?: Date;
/** Start date-time of the operation data, sample format: yyyy-MM-ddTHH:mm:ssZ. */
operationStartDateTime?: Date;
/** End date-time of the operation data, sample format: yyyy-MM-ddTHH:mm:ssZ. */
operationEndDateTime?: Date;
/** Link for attachments. */
attachmentsLink?: string;
/** Optional boundary ID of the field for which operation was applied. */
associatedBoundaryId?: string;
/** Optional boundary ID of the actual area for which operation was applied inside the specified field. */
operationBoundaryId?: string;
/** Farmer ID which belongs to the operation data. */
farmerId?: string;
/** Unique resource ID. */
id?: string;
/** The ETag value to implement optimistic concurrency. */
eTag?: string;
/** Status of the resource. */
status?: string;
/** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */
createdDateTime?: Date;
/** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */
modifiedDateTime?: Date;
/** Name to identify resource. */
name?: string;
/** Textual description of the resource. */
description?: string;
/**
* A collection of key value pairs that belongs to the resource.
* Each pair must not have a key greater than 50 characters
* and must not have a value greater than 150 characters.
* Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported.
*/
properties?: ApplicationDataPropertiesDictionary;
}
export interface ApplicationProductDetail {
/** Name of the product applied. */
productName?: string;
/** A flag indicating whether product is a carrier for a tank mix. */
isCarrier?: boolean;
/** Schema for storing measurement reading and unit. */
avgMaterial?: Measure;
/** Schema for storing measurement reading and unit. */
totalMaterial?: Measure;
}
export interface Measure {
/** Data unit. */
unit?: string;
/** Data value. */
value?: number;
}
export interface ErrorResponse {
/** An error from the Azure AgPlatform service. */
error?: Error;
/** Unique trace ID. */
traceId?: string;
}
export interface Error {
/** Server-defined set of error codes. */
code?: string;
/** Human-readable representation of the error. */
message?: string;
/** Target of the error. */
target?: string;
/** Array of details about specific errors that led to this reported error. */
details?: Error[];
/**
* Inner error containing list of errors.
* <see href="https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#innererror--object">InnerError reference document</see>.
*/
innererror?: InnerError;
}
export type InnerError = InnerErrorBase & InnerErrorDictionary;
export interface InnerErrorBase {
/**
* Specific error code than was provided by the
* containing error.
*/
code?: string;
/**
* Inner error containing list of errors.
* <see href="https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#innererror--object">InnerError reference document</see>.
*/
innererror?: InnerError;
}
export interface AttachmentListResponse {
/** List of requested objects. */
value?: Attachment[];
/** Token used in retrieving the next page. If null, there are no additional pages. */
skipToken?: string;
/** Continuation link (absolute URI) to the next page of results in the list. */
nextLink?: string;
}
export interface Attachment {
/** Farmer id for this attachment. */
farmerId?: string;
/** Associated Resource id for this attachment. */
resourceId?: string;
/**
* Associated Resource type for this attachment
* i.e. Farmer, Farm, Field, SeasonalField, Boundary, FarmOperationApplicationData, HarvestData, TillageData, PlantingData.
*/
resourceType?: string;
/** Original File Name for this attachment. */
originalFileName?: string;
/** Unique id. */
id?: string;
/** Status of the resource. */
status?: string;
/** Date when resource was created. */
createdDateTime?: Date;
/** Date when resource was last modified. */
modifiedDateTime?: Date;
/** Name to identify resource. */
name?: string;
/** Textual description of resource. */
description?: string;
/** The ETag value to implement optimistic concurrency. */
eTag?: string;
}
export interface BoundaryListResponse {
/** List of requested objects. */
value?: Boundary[];
/** Token used in retrieving the next page. If null, there are no additional pages. */
skipToken?: string;
/** Continuation link (absolute URI) to the next page of results in the list. */
nextLink?: string;
}
export interface Boundary {
/** Farmer ID. */
farmerId?: string;
/** ID of the parent(field or seasonalField) it belongs to. */
parentId?: string;
/** GeoJSON abstract class. */
geometry?: GeoJsonObject;
/** Is the boundary primary. */
isPrimary?: boolean;
/** Boundary area in acres. */
acreage?: number;
/** Type of the parent it belongs to. */
parentType?: string;
/** Unique resource ID. */
id?: string;
/** The ETag value to implement optimistic concurrency. */
eTag?: string;
/** Status of the resource. */
status?: string;
/** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */
createdDateTime?: Date;
/** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */
modifiedDateTime?: Date;
/** Name to identify resource. */
name?: string;
/** Textual description of the resource. */
description?: string;
/**
* A collection of key value pairs that belongs to the resource.
* Each pair must not have a key greater than 50 characters
* and must not have a value greater than 150 characters.
* Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported.
*/
properties?: BoundaryPropertiesDictionary;
}
export type GeoJsonObject = Polygon | MultiPolygon | Point;
export interface SearchBoundaryQuery {
/** Ids of the resource. */
ids?: string[];
/** Names of the resource. */
names?: string[];
/**
* Filters on key-value pairs within the Properties object.
* eg. "{testKey} eq {testValue}".
*/
propertyFilters?: string[];
/** Statuses of the resource. */
statuses?: string[];
/** Minimum creation date of resource (inclusive). */
minCreatedDateTime?: Date;
/** Maximum creation date of resource (inclusive). */
maxCreatedDateTime?: Date;
/** Minimum last modified date of resource (inclusive). */
minLastModifiedDateTime?: Date;
/** Maximum last modified date of resource (inclusive). */
maxLastModifiedDateTime?: Date;
/**
* Maximum number of items needed (inclusive).
* Minimum = 10, Maximum = 1000, Default value = 50.
*/
maxPageSize?: number;
/** Skip token for getting next set of results. */
skipToken?: string;
/** Is the boundary primary. */
isPrimary?: boolean;
/** Type of the parent it belongs to. */
parentType?: string;
/** Parent Ids of the resource. */
parentIds?: string[];
/** Minimum acreage of the boundary (inclusive). */
minAcreage?: number;
/** Maximum acreage of the boundary (inclusive). */
maxAcreage?: number;
/** GeoJSON abstract class. */
intersectsWithGeometry?: GeoJsonObject;
}
export interface CascadeDeleteJob {
/** Farmer ID. */
farmerId: string;
/** The id of the resource. */
resourceId: string;
/** The type of the resource. */
resourceType: string;
/** Unique job id. */
id?: string;
/**
* Status of the job.
* Possible values: 'Waiting', 'Running', 'Succeeded', 'Failed', 'Cancelled'.
*/
status?: string;
/** Duration of the job in seconds. */
durationInSeconds?: number;
/** Status message to capture more details of the job. */
message?: string;
/** Job created at dateTime. Sample format: yyyy-MM-ddTHH:mm:ssZ. */
createdDateTime?: Date;
/** Job was last acted upon at dateTime. Sample format: yyyy-MM-ddTHH:mm:ssZ. */
lastActionDateTime?: Date;
/** Job start time when available. Sample format: yyyy-MM-ddTHH:mm:ssZ. */
startTime?: Date;
/** Job end time when available. Sample format: yyyy-MM-ddTHH:mm:ssZ. */
endTime?: Date;
/** Name to identify resource. */
name?: string;
/** Textual description of the resource. */
description?: string;
/**
* A collection of key value pairs that belongs to the resource.
* Each pair must not have a key greater than 50 characters
* and must not have a value greater than 150 characters.
* Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported.
*/
properties?: CascadeDeleteJobPropertiesDictionary;
}
export interface BoundaryOverlapResponse {
/** Acreage of Main boundary. */
boundaryAcreage?: number;
/** Acreage of other boundary. */
otherBoundaryAcreage?: number;
/** Acreage of intersecting boundary. */
intersectingAcreage?: number;
}
export interface CropListResponse {
/** List of requested objects. */
value?: Crop[];
/** Token used in retrieving the next page. If null, there are no additional pages. */
skipToken?: string;
/** Continuation link (absolute URI) to the next page of results in the list. */
nextLink?: string;
}
export interface Crop {
/** Crop phenotype. */
phenotype?: string;
/** Unique resource ID. */
id?: string;
/** The ETag value to implement optimistic concurrency. */
eTag?: string;
/** Status of the resource. */
status?: string;
/** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */
createdDateTime?: Date;
/** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */
modifiedDateTime?: Date;
/** Name to identify resource. */
name?: string;
/** Textual description of the resource. */
description?: string;
/**
* A collection of key value pairs that belongs to the resource.
* Each pair must not have a key greater than 50 characters
* and must not have a value greater than 150 characters.
* Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported.
*/
properties?: CropPropertiesDictionary;
}
export interface CropVarietyListResponse {
/** List of requested objects. */
value?: CropVariety[];
/** Token used in retrieving the next page. If null, there are no additional pages. */
skipToken?: string;
/** Continuation link (absolute URI) to the next page of results in the list. */
nextLink?: string;
}
export interface CropVariety {
/** ID of the crop it belongs to. */
cropId?: string;
/** CropVariety Brand. */
brand?: string;
/** CropVariety product. */
product?: string;
/** Unique resource ID. */
id?: string;
/** The ETag value to implement optimistic concurrency. */
eTag?: string;
/** Status of the resource. */
status?: string;
/** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */
createdDateTime?: Date;
/** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */
modifiedDateTime?: Date;
/** Name to identify resource. */
name?: string;
/** Textual description of the resource. */
description?: string;
/**
* A collection of key value pairs that belongs to the resource.
* Each pair must not have a key greater than 50 characters
* and must not have a value greater than 150 characters.
* Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported.
*/
properties?: CropVarietyPropertiesDictionary;
}
export interface FarmerListResponse {
/** List of requested objects. */
value?: Farmer[];
/** Token used in retrieving the next page. If null, there are no additional pages. */
skipToken?: string;
/** Continuation link (absolute URI) to the next page of results in the list. */
nextLink?: string;
}
export interface Farmer {
/** Unique resource ID. */
id?: string;
/** The ETag value to implement optimistic concurrency. */
eTag?: string;
/** Status of the resource. */
status?: string;
/** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */
createdDateTime?: Date;
/** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */
modifiedDateTime?: Date;
/** Name to identify resource. */
name?: string;
/** Textual description of the resource. */
description?: string;
/**
* A collection of key value pairs that belongs to the resource.
* Each pair must not have a key greater than 50 characters
* and must not have a value greater than 150 characters.
* Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported.
*/
properties?: FarmerPropertiesDictionary;
}
export interface FarmOperationDataIngestionJob {
/** Farmer ID. */
farmerId: string;
/** Authentication provider ID. */
authProviderId: string;
/** List of operation types for which data needs to be downloaded. Available values: AllOperations, Application, Planting, Harvest, Tillage. */
operations?: string[];
/** Start Year (Minimum = 2000, Maximum = CurrentYear). */
startYear: number;
/** Unique job id. */
id?: string;
/**
* Status of the job.
* Possible values: 'Waiting', 'Running', 'Succeeded', 'Failed', 'Cancelled'.
*/
status?: string;
/** Duration of the job in seconds. */
durationInSeconds?: number;
/** Status message to capture more details of the job. */
message?: string;
/** Job created at dateTime. Sample format: yyyy-MM-ddTHH:mm:ssZ. */
createdDateTime?: Date;
/** Job was last acted upon at dateTime. Sample format: yyyy-MM-ddTHH:mm:ssZ. */
lastActionDateTime?: Date;
/** Job start time when available. Sample format: yyyy-MM-ddTHH:mm:ssZ. */
startTime?: Date;
/** Job end time when available. Sample format: yyyy-MM-ddTHH:mm:ssZ. */
endTime?: Date;
/** Name to identify resource. */
name?: string;
/** Textual description of the resource. */
description?: string;
/**
* A collection of key value pairs that belongs to the resource.
* Each pair must not have a key greater than 50 characters
* and must not have a value greater than 150 characters.
* Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported.
*/
properties?: FarmOperationDataIngestionJobPropertiesDictionary;
}
export interface FarmListResponse {
/** List of requested objects. */
value?: Farm[];
/** Token used in retrieving the next page. If null, there are no additional pages. */
skipToken?: string;
/** Continuation link (absolute URI) to the next page of results in the list. */
nextLink?: string;
}
export interface Farm {
/** Farmer ID. */
farmerId?: string;
/** Unique resource ID. */
id?: string;
/** The ETag value to implement optimistic concurrency. */
eTag?: string;
/** Status of the resource. */
status?: string;
/** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */
createdDateTime?: Date;
/** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */
modifiedDateTime?: Date;
/** Name to identify resource. */
name?: string;
/** Textual description of the resource. */
description?: string;
/**
* A collection of key value pairs that belongs to the resource.
* Each pair must not have a key greater than 50 characters
* and must not have a value greater than 150 characters.
* Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported.
*/
properties?: FarmPropertiesDictionary;
}
export interface FieldListResponse {
/** List of requested objects. */
value?: Field[];
/** Token used in retrieving the next page. If null, there are no additional pages. */
skipToken?: string;
/** Continuation link (absolute URI) to the next page of results in the list. */
nextLink?: string;
}
export interface Field {
/** ID of the associated Farm. */
farmId?: string;
/** Farmer ID. */
farmerId?: string;
/** Primary boundary id. */
primaryBoundaryId?: string;
/** Boundary Ids. */
boundaryIds?: string[];
/** Unique resource ID. */
id?: string;
/** The ETag value to implement optimistic concurrency. */
eTag?: string;
/** Status of the resource. */
status?: string;
/** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */
createdDateTime?: Date;
/** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */
modifiedDateTime?: Date;
/** Name to identify resource. */
name?: string;
/** Textual description of the resource. */
description?: string;
/**
* A collection of key value pairs that belongs to the resource.
* Each pair must not have a key greater than 50 characters
* and must not have a value greater than 150 characters.
* Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported.
*/
properties?: FieldPropertiesDictionary;
}
export interface HarvestDataListResponse {
/** List of requested objects. */
value?: HarvestData[];
/** Token used in retrieving the next page. If null, there are no additional pages. */
skipToken?: string;
/** Continuation link (absolute URI) to the next page of results in the list. */
nextLink?: string;
}
export interface HarvestData {
/** Schema for storing measurement reading and unit. */
totalYield?: Measure;
/** Schema for storing measurement reading and unit. */
avgYield?: Measure;
/** Schema for storing measurement reading and unit. */
totalWetMass?: Measure;
/** Schema for storing measurement reading and unit. */
avgWetMass?: Measure;
/** Schema for storing measurement reading and unit. */
avgMoisture?: Measure;
/** Schema for storing measurement reading and unit. */
avgSpeed?: Measure;
/** Harvest product details. */
harvestProductDetails?: HarvestProductDetail[];
/** Schema for storing measurement reading and unit. */
area?: Measure;
/** Source of the operation data. */
source?: string;
/**
* Modified date-time of the operation data, sample format: yyyy-MM-ddTHH:mm:ssZ.
* Note: this will be specified by the source provider itself.
*/
operationModifiedDateTime?: Date;
/** Start date-time of the operation data, sample format: yyyy-MM-ddTHH:mm:ssZ. */
operationStartDateTime?: Date;
/** End date-time of the operation data, sample format: yyyy-MM-ddTHH:mm:ssZ. */
operationEndDateTime?: Date;
/** Link for attachments. */
attachmentsLink?: string;
/** Optional boundary ID of the field for which operation was applied. */
associatedBoundaryId?: string;
/** Optional boundary ID of the actual area for which operation was applied inside the specified field. */
operationBoundaryId?: string;
/** Farmer ID which belongs to the operation data. */
farmerId?: string;
/** Unique resource ID. */
id?: string;
/** The ETag value to implement optimistic concurrency. */
eTag?: string;
/** Status of the resource. */
status?: string;
/** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */
createdDateTime?: Date;
/** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */
modifiedDateTime?: Date;
/** Name to identify resource. */
name?: string;
/** Textual description of the resource. */
description?: string;
/**
* A collection of key value pairs that belongs to the resource.
* Each pair must not have a key greater than 50 characters
* and must not have a value greater than 150 characters.
* Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported.
*/
properties?: HarvestDataPropertiesDictionary;
}
export interface HarvestProductDetail {
/** Name of the product. */
productName?: string;
/** Schema for storing measurement reading and unit. */
area?: Measure;
/** Schema for storing measurement reading and unit. */
totalYield?: Measure;
/** Schema for storing measurement reading and unit. */
avgYield?: Measure;
/** Schema for storing measurement reading and unit. */
avgMoisture?: Measure;
/** Schema for storing measurement reading and unit. */
totalWetMass?: Measure;
/** Schema for storing measurement reading and unit. */
avgWetMass?: Measure;
}
export interface ImageProcessingRasterizeJob {
/** Farmer ID. */
farmerId: string;
/** Shapefile attachment ID. */
shapefileAttachmentId: string;
/** List of shapefile column names to create raster attachments. */
shapefileColumnNames: string[];
/** Unique job id. */
id?: string;
/**
* Status of the job.
* Possible values: 'Waiting', 'Running', 'Succeeded', 'Failed', 'Cancelled'.
*/
status?: string;
/** Duration of the job in seconds. */
durationInSeconds?: number;
/** Status message to capture more details of the job. */
message?: string;
/** Job created at dateTime. Sample format: yyyy-MM-ddTHH:mm:ssZ. */
createdDateTime?: Date;
/** Job was last acted upon at dateTime. Sample format: yyyy-MM-ddTHH:mm:ssZ. */
lastActionDateTime?: Date;
/** Job start time when available. Sample format: yyyy-MM-ddTHH:mm:ssZ. */
startTime?: Date;
/** Job end time when available. Sample format: yyyy-MM-ddTHH:mm:ssZ. */
endTime?: Date;
/** Name to identify resource. */
name?: string;
/** Textual description of the resource. */
description?: string;
/**
* A collection of key value pairs that belongs to the resource.
* Each pair must not have a key greater than 50 characters
* and must not have a value greater than 150 characters.
* Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported.
*/
properties?: ImageProcessingRasterizeJobPropertiesDictionary;
}
export interface OAuthProviderListResponse {
/** List of requested objects. */
value?: OAuthProvider[];
/** Token used in retrieving the next page. If null, there are no additional pages. */
skipToken?: string;
/** Continuation link (absolute URI) to the next page of results in the list. */
nextLink?: string;
}
export interface OAuthProvider {
/** OAuth App ID for given OAuth Provider. */
appId?: string;
/**
* OAuth App secret for given Provider.
* Note: Won't be sent in response.
*/
appSecret?: string;
/**
* OAuth Api key for given Provider.
* Note: currently Applicable to Climate provider. Won't be sent in response.
*/
apiKey?: string;
/**
* An optional flag to determine if the App is ready to be used for Production scenarios in the provider side or not. (Default value: false)
* Note: Currently applicable for JohnDeere.
*/
isProductionApp?: boolean;
/** Unique OAuth provider ID. */
id?: string;
/** The ETag value to implement optimistic concurrency. */
eTag?: string;
/** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */
createdDateTime?: Date;
/** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */
modifiedDateTime?: Date;
/** Name to identify resource. */
name?: string;
/** Textual description of the resource. */
description?: string;
/**
* A collection of key value pairs that belongs to the resource.
* Each pair must not have a key greater than 50 characters
* and must not have a value greater than 150 characters.
* Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported.
*/
properties?: OAuthProviderPropertiesDictionary;
}
export interface OAuthTokenListResponse {
/** List of requested objects. */
value?: OAuthToken[];
/** Token used in retrieving the next page. If null, there are no additional pages. */
skipToken?: string;
/** Continuation link (absolute URI) to the next page of results in the list. */
nextLink?: string;
}
export interface OAuthToken {
/** Farmer ID for this OAuth config. */
farmerId: string;
/** ID of the OAuth provider resource containing app information. */
authProviderId: string;
/** An optional flag indicating whether the token is a valid or expired (Default value: true). */
isValid?: boolean;
/** The ETag value to implement optimistic concurrency. */
eTag?: string;
/** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */
createdDateTime?: Date;
/** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */
modifiedDateTime?: Date;
}
export interface OAuthConnectRequest {
/** ID of the farmer. */
farmerId: string;
/** ID of the OAuthProvider. */
oAuthProviderId: string;
/** Link to redirect the user to, at the end of the oauth flow. */
userRedirectLink: string;
/** State to provide back when redirecting the user, at the end of the oauth flow. */
userRedirectState?: string;
}
export interface PlantingDataListResponse {
/** List of requested objects. */
value?: PlantingData[];
/** Token used in retrieving the next page. If null, there are no additional pages. */
skipToken?: string;
/** Continuation link (absolute URI) to the next page of results in the list. */
nextLink?: string;
}
export interface PlantingData {
/** Schema for storing measurement reading and unit. */
avgPlantingRate?: Measure;
/** Schema for storing measurement reading and unit. */
totalMaterial?: Measure;
/** Schema for storing measurement reading and unit. */
avgMaterial?: Measure;
/** Planting product details. */
plantingProductDetails?: PlantingProductDetail[];
/** Schema for storing measurement reading and unit. */
area?: Measure;
/** Source of the operation data. */
source?: string;
/**
* Modified date-time of the operation data, sample format: yyyy-MM-ddTHH:mm:ssZ.
* Note: this will be specified by the source provider itself.
*/
operationModifiedDateTime?: Date;
/** Start date-time of the operation data, sample format: yyyy-MM-ddTHH:mm:ssZ. */
operationStartDateTime?: Date;
/** End date-time of the operation data, sample format: yyyy-MM-ddTHH:mm:ssZ. */
operationEndDateTime?: Date;
/** Link for attachments. */
attachmentsLink?: string;
/** Optional boundary ID of the field for which operation was applied. */
associatedBoundaryId?: string;
/** Optional boundary ID of the actual area for which operation was applied inside the specified field. */
operationBoundaryId?: string;
/** Farmer ID which belongs to the operation data. */
farmerId?: string;
/** Unique resource ID. */
id?: string;
/** The ETag value to implement optimistic concurrency. */
eTag?: string;
/** Status of the resource. */
status?: string;
/** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */
createdDateTime?: Date;
/** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */
modifiedDateTime?: Date;
/** Name to identify resource. */
name?: string;
/** Textual description of the resource. */
description?: string;
/**
* A collection of key value pairs that belongs to the resource.
* Each pair must not have a key greater than 50 characters
* and must not have a value greater than 150 characters.
* Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported.
*/
properties?: PlantingDataPropertiesDictionary;
}
export interface PlantingProductDetail {
/** Name of the product. */
productName?: string;
/** Schema for storing measurement reading and unit. */
area?: Measure;
/** Schema for storing measurement reading and unit. */
totalMaterial?: Measure;
/** Schema for storing measurement reading and unit. */
avgMaterial?: Measure;
}
export interface SceneListResponse {
/** List of requested objects. */
value?: Scene[];
/** Token used in retrieving the next page. If null, there are no additional pages. */
skipToken?: string;
/** Continuation link (absolute URI) to the next page of results in the list. */
nextLink?: string;
}
export interface Scene {
/** Date-time of the scene, sample format: yyyy-MM-ddTHH:mm:ssZ. */
sceneDateTime?: Date;
/** Data provider of the scene. */
provider?: string;
/** Data source of the scene. */
source?: string;
/** Collection of image files. */
imageFiles?: ImageFile[];
/** Supported image formats for scene resource. */
imageFormat?: ImageFormat;
/** Cloud cover percentage of the scene. */
cloudCoverPercentage?: number;
/** Dark pixel percentage of the scene. */
darkPixelPercentage?: number;
/** Median of NDVI of the scene. */
ndviMedianValue?: number;
/** Boundary ID which belongs to the scene. */
boundaryId?: string;
/** Farmer ID which belongs to the scene. */
farmerId?: string;
/** Unique scene resource ID. */
id?: string;
/** The ETag value to implement optimistic concurrency. */
eTag?: string;
}
export interface ImageFile {
/** Link of the image file. */
fileLink?: string;
/** Name of the image file. */
name: string;
/** Supported image formats for scene resource. */
imageFormat?: ImageFormat;
/** Resolution of image file in meters. */
resolution?: number;
}
export interface SatelliteDataIngestionJob {
/** Farmer ID. */
farmerId: string;
/** The id of the boundary object for which satellite data is being fetched. */
boundaryId: string;
/** Start Date. */
startDateTime: Date;
/** End Date. */
endDateTime: Date;
/** Provider of satellite data. */
provider?: DataProvider;
/** Source of satellite data. */
source?: Source;
/** Data Model for SatelliteIngestionJobRequest. */
data?: SatelliteData;
/** Unique job id. */
id?: string;
/**
* Status of the job.
* Possible values: 'Waiting', 'Running', 'Succeeded', 'Failed', 'Cancelled'.
*/
status?: string;
/** Duration of the job in seconds. */
durationInSeconds?: number;
/** Status message to capture more details of the job. */
message?: string;
/** Job created at dateTime. Sample format: yyyy-MM-ddTHH:mm:ssZ. */
createdDateTime?: Date;
/** Job was last acted upon at dateTime. Sample format: yyyy-MM-ddTHH:mm:ssZ. */
lastActionDateTime?: Date;
/** Job start time when available. Sample format: yyyy-MM-ddTHH:mm:ssZ. */
startTime?: Date;
/** Job end time when available. Sample format: yyyy-MM-ddTHH:mm:ssZ. */
endTime?: Date;
/** Name to identify resource. */
name?: string;
/** Textual description of the resource. */
description?: string;
/**
* A collection of key value pairs that belongs to the resource.
* Each pair must not have a key greater than 50 characters
* and must not have a value greater than 150 characters.
* Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported.
*/
properties?: SatelliteDataIngestionJobPropertiesDictionary;
}
export interface SatelliteData {
/** List of ImageNames. */
imageNames?: string[];
/** List of ImageFormats. Available value: TIF. */
imageFormats?: string[];
/** List of ImageResolutions in meters. Available values: 10, 20, 60. */
imageResolutions?: number[];
}
export interface SeasonalFieldListResponse {
/** List of requested objects. */
value?: SeasonalField[];
/** Token used in retrieving the next page. If null, there are no additional pages. */
skipToken?: string;
/** Continuation link (absolute URI) to the next page of results in the list. */
nextLink?: string;
}
export interface SeasonalField {
/** Farmer ID. */
farmerId?: string;
/** Primary boundary id. */
primaryBoundaryId?: string;
/** Boundary Ids. */
boundaryIds?: string[];
/** ID of the associated Farm. */
farmId?: string;
/** ID of the associated Field. */
fieldId?: string;
/** ID of the season it belongs to. */
seasonId?: string;
/** CropVariety ids. */
cropVarietyIds?: string[];
/** ID of the crop it belongs to. */
cropId?: string;
/** Average yield value of the seasonal field. */
avgYieldValue?: number;
/** Unit of the average yield value attribute. */
avgYieldUnit?: string;
/** Average seed population value of the seasonal field. */
avgSeedPopulationValue?: number;
/** Unit of average seed population value attribute. */
avgSeedPopulationUnit?: string;
/** Planting datetime, sample format: yyyy-MM-ddTHH:mm:ssZ. */
plantingDateTime?: Date;
/** Unique resource ID. */
id?: string;
/** The ETag value to implement optimistic concurrency. */
eTag?: string;
/** Status of the resource. */
status?: string;
/** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */
createdDateTime?: Date;
/** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */
modifiedDateTime?: Date;
/** Name to identify resource. */
name?: string;
/** Textual description of the resource. */
description?: string;
/**
* A collection of key value pairs that belongs to the resource.
* Each pair must not have a key greater than 50 characters
* and must not have a value greater than 150 characters.
* Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported.
*/
properties?: SeasonalFieldPropertiesDictionary;
}
export interface SeasonListResponse {
/** List of requested objects. */
value?: Season[];
/** Token used in retrieving the next page. If null, there are no additional pages. */
skipToken?: string;
/** Continuation link (absolute URI) to the next page of results in the list. */
nextLink?: string;
}
export interface Season {
/** Season start datetime, sample format: yyyy-MM-ddTHH:mm:ssZ. */
startDateTime?: Date;
/** Season end datetime, sample format: yyyy-MM-ddTHH:mm:ssZ. */
endDateTime?: Date;
/** Season year. */
year?: number;
/** Unique resource ID. */
id?: string;
/** The ETag value to implement optimistic concurrency. */
eTag?: string;
/** Status of the resource. */
status?: string;
/** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */
createdDateTime?: Date;
/** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */
modifiedDateTime?: Date;
/** Name to identify resource. */
name?: string;
/** Textual description of the resource. */
description?: string;
/**
* A collection of key value pairs that belongs to the resource.
* Each pair must not have a key greater than 50 characters
* and must not have a value greater than 150 characters.
* Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported.
*/
properties?: SeasonPropertiesDictionary;
}
export interface TillageDataListResponse {
/** List of requested objects. */
value?: TillageData[];
/** Token used in retrieving the next page. If null, there are no additional pages. */
skipToken?: string;
/** Continuation link (absolute URI) to the next page of results in the list. */
nextLink?: string;
}
export interface TillageData {
/** Schema for storing measurement reading and unit. */
tillageDepth?: Measure;
/** Schema for storing measurement reading and unit. */
tillagePressure?: Measure;
/** Schema for storing measurement reading and unit. */
area?: Measure;
/** Source of the operation data. */
source?: string;
/**
* Modified date-time of the operation data, sample format: yyyy-MM-ddTHH:mm:ssZ.
* Note: this will be specified by the source provider itself.
*/
operationModifiedDateTime?: Date;
/** Start date-time of the operation data, sample format: yyyy-MM-ddTHH:mm:ssZ. */
operationStartDateTime?: Date;
/** End date-time of the operation data, sample format: yyyy-MM-ddTHH:mm:ssZ. */
operationEndDateTime?: Date;
/** Link for attachments. */
attachmentsLink?: string;
/** Optional boundary ID of the field for which operation was applied. */
associatedBoundaryId?: string;
/** Optional boundary ID of the actual area for which operation was applied inside the specified field. */
operationBoundaryId?: string;
/** Farmer ID which belongs to the operation data. */
farmerId?: string;
/** Unique resource ID. */
id?: string;
/** The ETag value to implement optimistic concurrency. */
eTag?: string;
/** Status of the resource. */
status?: string;
/** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */
createdDateTime?: Date;
/** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */
modifiedDateTime?: Date;
/** Name to identify resource. */
name?: string;
/** Textual description of the resource. */
description?: string;
/**
* A collection of key value pairs that belongs to the resource.
* Each pair must not have a key greater than 50 characters
* and must not have a value greater than 150 characters.
* Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported.
*/
properties?: TillageDataPropertiesDictionary;
}
export interface WeatherDataListResponse {
/** List of requested objects. */
value?: WeatherData[];
/** Token used in retrieving the next page. If null, there are no additional pages. */
skipToken?: string;
/** Continuation link (absolute URI) to the next page of results in the list. */
nextLink?: string;
}
export interface WeatherData {
/** Farmer ID. */
farmerId: string;
/** Boundary ID. */
boundaryId: string;
/** ID of the weather extension. */
extensionId: string;
/** Location model class. */
location: Location;
/** Date-time of the weather data, sample format: yyyy-MM-ddTHH:mm:ssZ. */
dateTime: Date;
/** Unit System like US/SI etc. */
unitSystemCode?: string;
/** Version of the weather data extension. */
extensionVersion: string;
/** Type of weather data (forecast/historical). */
weatherDataType: string;
/** Granularity of weather data (daily/hourly). */
granularity: string;
/** Schema for storing measurement reading and unit. */
cloudCover?: Measure;
/** Schema for storing measurement reading and unit. */
dewPoint?: Measure;
/** Schema for storing measurement reading and unit. */
growingDegreeDay?: Measure;
/** Schema for storing measurement reading and unit. */
precipitation?: Measure;
/** Schema for storing measurement reading and unit. */
pressure?: Measure;
/** Schema for storing measurement reading and unit. */
relativeHumidity?: Measure;
/** Schema for storing measurement reading and unit. */
soilMoisture?: Measure;
/** Schema for storing measurement reading and unit. */
soilTemperature?: Measure;
/** Schema for storing measurement reading and unit. */
temperature?: Measure;
/** Schema for storing measurement reading and unit. */
visibility?: Measure;
/** Schema for storing measurement reading and unit. */
wetBulbTemperature?: Measure;
/** Schema for storing measurement reading and unit. */
windChill?: Measure;
/** Schema for storing measurement reading and unit. */
windDirection?: Measure;
/** Schema for storing measurement reading and unit. */
windGust?: Measure;
/** Schema for storing measurement reading and unit. */
windSpeed?: Measure;
/** Weather data ID. */
id?: string;
/** The ETag value to implement optimistic concurrency. */
eTag?: string;
/** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */
createdDateTime?: Date;
/** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */
modifiedDateTime?: Date;
/**
* A collection of key value pairs that belongs to the resource.
* Each pair must not have a key greater than 50 characters
* and must not have a value greater than 150 characters.
* Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported.
*/
properties?: WeatherDataPropertiesDictionary;
}
export interface Location {
/** Latitude of the location. */
latitude: number;
/** Longitude of the location. */
longitude: number;
}
export interface WeatherDataIngestionJob {
/** The id of the boundary object for which weather data is being fetched. */
boundaryId: string;
/** The id of the farmer object for which weather data is being fetched. */
farmerId: string;
/** ID of the extension to be used for the providerInput. eg. DTN.ClearAg. */
extensionId: string;
/** Extension api name to which request is to be made. */
extensionApiName: string;
/** Extension api input dictionary which would be used to feed request query/body/parameter information. */
extensionApiInput: WeatherDataIngestionJobExtensionApiInputDictionary;
/** App id of the weather data provider. */
extensionDataProviderAppId?: string;
/** Api key of the weather data provider. */
extensionDataProviderApiKey?: string;
/** Unique job id. */
id?: string;
/**
* Status of the job.
* Possible values: 'Waiting', 'Running', 'Succeeded', 'Failed', 'Cancelled'.
*/
status?: string;
/** Duration of the job in seconds. */
durationInSeconds?: number;
/** Status message to capture more details of the job. */
message?: string;
/** Job created at dateTime. Sample format: yyyy-MM-ddTHH:mm:ssZ. */
createdDateTime?: Date;
/** Job was last acted upon at dateTime. Sample format: yyyy-MM-ddTHH:mm:ssZ. */
lastActionDateTime?: Date;
/** Job start time when available. Sample format: yyyy-MM-ddTHH:mm:ssZ. */
startTime?: Date;
/** Job end time when available. Sample format: yyyy-MM-ddTHH:mm:ssZ. */
endTime?: Date;
/** Name to identify resource. */
name?: string;
/** Textual description of the resource. */
description?: string;
/**
* A collection of key value pairs that belongs to the resource.
* Each pair must not have a key greater than 50 characters
* and must not have a value greater than 150 characters.
* Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported.
*/
properties?: WeatherDataIngestionJobPropertiesDictionary;
}
export interface WeatherDataDeleteJob {
/** ID of the extension to be used for the providerInput. eg. DTN.ClearAg. */
extensionId: string;
/** The id of the farmer object for which weather data is being fetched. */
farmerId: string;
/** The id of the boundary object for which weather data is being fetched. */
boundaryId: string;
/** Type of weather data. Possible values include: 'forecast' , 'historical'. */
weatherDataType?: string;
/** Granularity of weather data. Possible values include: 'daily' , 'hourly'. */
granularity?: string;
/** Weather data start UTC date-time (inclusive), sample format: yyyy-MM-ddTHH:mm:ssZ. */
startDateTime?: Date;
/** Weather data end UTC date-time (inclusive), sample format: yyyy-MM-ddTHH:mm:ssZ. */
endDateTime?: Date;
/** Unique job id. */
id?: string;
/**
* Status of the job.
* Possible values: 'Waiting', 'Running', 'Succeeded', 'Failed', 'Cancelled'.
*/
status?: string;
/** Duration of the job in seconds. */
durationInSeconds?: number;
/** Status message to capture more details of the job. */
message?: string;
/** Job created at dateTime. Sample format: yyyy-MM-ddTHH:mm:ssZ. */
createdDateTime?: Date;
/** Job was last acted upon at dateTime. Sample format: yyyy-MM-ddTHH:mm:ssZ. */
lastActionDateTime?: Date;
/** Job start time when available. Sample format: yyyy-MM-ddTHH:mm:ssZ. */
startTime?: Date;
/** Job end time when available. Sample format: yyyy-MM-ddTHH:mm:ssZ. */
endTime?: Date;
/** Name to identify resource. */
name?: string;
/** Textual description of the resource. */
description?: string;
/**
* A collection of key value pairs that belongs to the resource.
* Each pair must not have a key greater than 50 characters
* and must not have a value greater than 150 characters.
* Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported.
*/
properties?: WeatherDataDeleteJobPropertiesDictionary;
}
export interface MultiPolygonCoordinates {
/**
* Gets or sets Coordinates of GeoJSON Object.
* It must be an array of polygons, each polygon contains list of linear rings.
* For Polygons with more than one of these rings, the first MUST be the exterior ring,
* and any others MUST be interior rings.
*/
coordinates: number[][][][];
}
export type MultiPolygon = MultiPolygonBase &
MultiPolygonCoordinates & {
type: "MultiPolygon";
};
export interface MultiPolygonBase {}
export interface PointCoordinates {
/**
* Gets or sets the coordinate of this point.
* It must be an array of 2 or 3 elements for a 2D or 3D system.
*/
coordinates: number[];
}
export type Point = PointBase &
PointCoordinates & {
type: "Point";
};
export interface PointBase {}
export interface PolygonCoordinates {
/**
* Gets or sets type of the GeoJSON Object.
* It must be an array of linear ring coordinate arrays.
* For Polygons with more than one of these rings, the first MUST be the exterior ring,
* and any others MUST be interior rings.
*/
coordinates: number[][][];
}
export type Polygon = PolygonBase &
PolygonCoordinates & {
type: "Polygon";
};
export interface PolygonBase {}
export interface Paths1LxjoxzFarmersFarmeridAttachmentsAttachmentidPatchRequestbodyContentMultipartFormDataSchema {
/** File to be uploaded. */
file?: string;
/** Farmer id for this attachment. */
farmerId?: string;
/** Associated Resource id for this attachment. */
resourceId?: string;
/**
* Associated Resource type for this attachment
* i.e. Farmer, Farm, Field, SeasonalField, Boundary, FarmOperationApplicationData, HarvestData, TillageData, PlantingData.
*/
resourceType?: string;
/** Original File Name for this attachment. */
originalFileName?: string;
/** Unique id. */
id?: string;
/** Status of the resource. */
status?: string;
/** Date when resource was created. */
createdDateTime?: string;
/** Date when resource was last modified. */
modifiedDateTime?: string;
/** Name to identify resource. */
name?: string;
/** Textual description of resource. */
description?: string;
/** The ETag value to implement optimistic concurrency. */
eTag?: string;
}
export type GeoJsonObjectType = "Point" | "Polygon" | "MultiPolygon";
export type ImageFormat = "TIF";
export type DataProvider = "Microsoft";
export type Source = "Sentinel_2_L2A";
export type ApplicationDataPropertiesDictionary = Record<string, unknown>;
export type InnerErrorDictionary = Record<string, unknown>;
export type BoundaryPropertiesDictionary = Record<string, unknown>;
export type CascadeDeleteJobPropertiesDictionary = Record<string, unknown>;
export type CropPropertiesDictionary = Record<string, unknown>;
export type CropVarietyPropertiesDictionary = Record<string, unknown>;
export type FarmerPropertiesDictionary = Record<string, unknown>;
export type FarmOperationDataIngestionJobPropertiesDictionary = Record<string, unknown>;
export type FarmPropertiesDictionary = Record<string, unknown>;
export type FieldPropertiesDictionary = Record<string, unknown>;
export type HarvestDataPropertiesDictionary = Record<string, unknown>;
export type ImageProcessingRasterizeJobPropertiesDictionary = Record<string, unknown>;
export type OAuthProviderPropertiesDictionary = Record<string, unknown>;
export type PlantingDataPropertiesDictionary = Record<string, unknown>;
export type SatelliteDataIngestionJobPropertiesDictionary = Record<string, unknown>;
export type SeasonalFieldPropertiesDictionary = Record<string, unknown>;
export type SeasonPropertiesDictionary = Record<string, unknown>;
export type TillageDataPropertiesDictionary = Record<string, unknown>;
export type WeatherDataPropertiesDictionary = Record<string, unknown>;
export type WeatherDataIngestionJobExtensionApiInputDictionary = Record<string, unknown>;
export type WeatherDataIngestionJobPropertiesDictionary = Record<string, unknown>;
export type WeatherDataDeleteJobPropertiesDictionary = Record<string, unknown>; | the_stack |
import test from 'ava';
import * as fse from 'fs-extra';
import { join, dirname, basename } from '../src/path';
import {
exec, generateUniqueTmpDirName, EXEC_OPTIONS, getSnowexec,
} from './helper';
import { COMMIT_ORDER, REFERENCE_TYPE, Repository } from '../src/repository';
import { Reference } from '../src/reference';
import { DirItem, OSWALK, osWalk } from '../src/io';
// test doesn't work on the GitHub runners
// https://github.com/seb-mtl/SnowFS/runs/1923599289?check_suite_focus=true#step:7:245
test('snow add/commit/log', async (t) => {
t.timeout(180000);
const snow: string = getSnowexec();
const snowWorkdir = generateUniqueTmpDirName();
await exec(t, snow, ['init', basename(snowWorkdir)], { cwd: dirname(snowWorkdir) });
for (let i = 0; i < 2; ++i) {
t.log(`Write abc${i}.txt`);
fse.writeFileSync(join(snowWorkdir, `abc${i}.txt`), 'Hello World');
// eslint-disable-next-line no-await-in-loop
await exec(t, snow, ['add', '.'], { cwd: snowWorkdir });
// eslint-disable-next-line no-await-in-loop
await exec(t, snow, ['commit', '-m', `add hello-world ${i}`], { cwd: snowWorkdir });
// eslint-disable-next-line no-await-in-loop
await exec(t, snow, ['log'], { cwd: snowWorkdir });
}
t.is(true, true);
});
test('snow switch', async (t) => {
t.timeout(180000);
let out: string | void;
const snow: string = getSnowexec();
const snowWorkdir = generateUniqueTmpDirName();
// Create branch succesfully
await exec(t, snow, ['init', basename(snowWorkdir)], { cwd: dirname(snowWorkdir) });
for (let i = 0; i < 3; ++i) {
t.log(`Write abc${i}.txt`);
fse.writeFileSync(join(snowWorkdir, `abc${i}.txt`), `Hello World ${i}`);
// eslint-disable-next-line no-await-in-loop
await exec(t, snow, ['add', '.'], { cwd: snowWorkdir });
// eslint-disable-next-line no-await-in-loop
await exec(t, snow, ['commit', '-m', `add hello-world ${i}`], { cwd: snowWorkdir });
// eslint-disable-next-line no-await-in-loop
out = await exec(t, snow, ['branch', `branch-${i}`], { cwd: snowWorkdir }, EXEC_OPTIONS.RETURN_STDOUT);
t.true((out as string).includes(`A branch 'branch-${i}' got created.`));
}
await exec(t, snow, ['log', '--verbose'], { cwd: snowWorkdir });
let dirItems: DirItem[];
let dirPaths: string[];
// switch to all branches while no modifications are present in the working dir
t.log('Switch to branch-0');
await exec(t, snow, ['switch', 'branch-0'], { cwd: snowWorkdir });
dirItems = await osWalk(snowWorkdir, OSWALK.FILES);
dirPaths = dirItems.map((d) => basename(d.relPath));
t.is(dirItems.length, 1);
t.true(dirPaths.includes('abc0.txt'));
t.log('Switch to branch-1');
await exec(t, snow, ['switch', 'branch-1'], { cwd: snowWorkdir });
dirItems = await osWalk(snowWorkdir, OSWALK.FILES);
dirPaths = dirItems.map((d) => basename(d.relPath));
t.is(dirItems.length, 2);
t.true(dirPaths.includes('abc0.txt'));
t.true(dirPaths.includes('abc1.txt'));
t.log('Switch to branch-2');
await exec(t, snow, ['switch', 'branch-2'], { cwd: snowWorkdir });
dirItems = await osWalk(snowWorkdir, OSWALK.FILES);
dirPaths = dirItems.map((d) => basename(d.relPath));
t.is(dirItems.length, 3);
t.true(dirPaths.includes('abc0.txt'));
t.true(dirPaths.includes('abc1.txt'));
t.true(dirPaths.includes('abc2.txt'));
t.log('Make some changes to the working directory');
t.log(' Update abc0.txt');
fse.writeFileSync(join(snowWorkdir, 'abc0.txt'), 'Hello World Fooooo');
t.log(' Write abc3.txt');
fse.writeFileSync(join(snowWorkdir, 'abc3.txt'), 'Hello World 3');
fse.removeSync(join(snowWorkdir, 'abc1.txt'));
// switch to branches while...
// ... one is modified (abc0.txt)
// ... one deleted (abc1.txt)
// ... one file is untouched (abc2.txt)
// ... and one added (abc.txt)
const error = await t.throwsAsync(async () => exec(t, snow, ['switch', 'branch-0'], { cwd: snowWorkdir }, EXEC_OPTIONS.RETURN_STDOUT));
const lines = error.message.split('\n');
t.true(lines.includes('A abc3.txt')); // abc3.txt got added in the working dir
t.true(lines.includes('M abc0.txt')); // abc0.txt got added in the working dir
// abc1.txt did not get reported as deleted because switch/checkout don't mind if a file got deleted by the user since it can be restored
t.true(lines.includes("fatal: You have local changes to 'branch-0'; not switching branches."));
t.log('Switch and discard the local changes');
await exec(t, snow, ['switch', 'branch-0', '--discard-changes'], { cwd: snowWorkdir });
dirItems = await osWalk(snowWorkdir, OSWALK.FILES);
dirPaths = dirItems.map((d) => basename(d.relPath));
t.is(dirItems.length, 1);
t.true(dirPaths.includes('abc0.txt'));
t.log('Switch back to branch-2 and go from there');
await exec(t, snow, ['switch', 'branch-2'], { cwd: snowWorkdir });
t.log('Make some changes again to the working directory');
t.log(' Update abc0.txt');
fse.writeFileSync(join(snowWorkdir, 'abc0.txt'), 'Hello World Fooooo');
t.log(' Write abc3.txt');
fse.writeFileSync(join(snowWorkdir, 'abc3.txt'), 'Hello World 3');
fse.removeSync(join(snowWorkdir, 'abc1.txt'));
// switch back to branch-0 and keep all changes
await exec(t, snow, ['switch', 'branch-0', '--keep-changes'], { cwd: snowWorkdir });
// carried over the changes
t.is(fse.readFileSync(join(snowWorkdir, 'abc0.txt')).toString(), 'Hello World Fooooo');
t.is(fse.readFileSync(join(snowWorkdir, 'abc2.txt')).toString(), 'Hello World 2');
t.is(fse.readFileSync(join(snowWorkdir, 'abc3.txt')).toString(), 'Hello World 3');
t.false(fse.pathExistsSync(join(snowWorkdir, 'abc1.txt')));
});
test('snow checkout', async (t) => {
let out: string | void;
const snow: string = getSnowexec();
const snowWorkdir = generateUniqueTmpDirName();
// Create branch succesfully
await exec(t, snow, ['init', basename(snowWorkdir)], { cwd: dirname(snowWorkdir) });
for (let i = 0; i < 3; ++i) {
t.log(`Write abc${i}.txt`);
fse.writeFileSync(join(snowWorkdir, `abc${i}.txt`), `Hello World ${i}`);
// eslint-disable-next-line no-await-in-loop
await exec(t, snow, ['add', '.'], { cwd: snowWorkdir });
// eslint-disable-next-line no-await-in-loop
await exec(t, snow, ['commit', '-m', `add hello-world ${i}`], { cwd: snowWorkdir });
// eslint-disable-next-line no-await-in-loop
out = await exec(t, snow, ['branch', `branch-${i}`], { cwd: snowWorkdir }, EXEC_OPTIONS.RETURN_STDOUT);
t.true((out as string).includes(`A branch 'branch-${i}' got created.`));
}
await exec(t, snow, ['log', '--verbose'], { cwd: snowWorkdir });
let dirItems: DirItem[];
let dirPaths: string[];
const repo = await Repository.open(snowWorkdir);
const allCommits = repo.getAllCommits(COMMIT_ORDER.OLDEST_FIRST);
// switch to all branches while no modifications are present in the working dir
t.log(`Switch to ${allCommits[1]}`);
await exec(t, snow, ['checkout', allCommits[1].hash], { cwd: snowWorkdir });
dirItems = await osWalk(snowWorkdir, OSWALK.FILES);
dirPaths = dirItems.map((d) => basename(d.relPath));
t.is(dirItems.length, 1);
t.true(dirPaths.includes('abc0.txt'));
// We can now delete the Main branch
// For this unit-test, delete Main so we don't have two references for the same commit
// otherwise checking out the latest commit is ambigious
await exec(t, snow, ['branch', '--delete', 'Main'], { cwd: snowWorkdir });
t.log(`Switch to ${allCommits[2]}`);
await exec(t, snow, ['checkout', allCommits[2].hash], { cwd: snowWorkdir });
dirItems = await osWalk(snowWorkdir, OSWALK.FILES);
dirPaths = dirItems.map((d) => basename(d.relPath));
t.is(dirItems.length, 2);
t.true(dirPaths.includes('abc0.txt'));
t.true(dirPaths.includes('abc1.txt'));
t.log(`Switch to ${allCommits[3]}`);
await exec(t, snow, ['checkout', allCommits[3].hash], { cwd: snowWorkdir });
dirItems = await osWalk(snowWorkdir, OSWALK.FILES);
dirPaths = dirItems.map((d) => basename(d.relPath));
t.is(dirItems.length, 3);
t.true(dirPaths.includes('abc0.txt'));
t.true(dirPaths.includes('abc1.txt'));
t.true(dirPaths.includes('abc2.txt'));
t.log('Make some changes to the working directory');
t.log(' Update abc0.txt');
fse.writeFileSync(join(snowWorkdir, 'abc0.txt'), 'Hello World Fooooo');
t.log(' Write abc3.txt');
fse.writeFileSync(join(snowWorkdir, 'abc3.txt'), 'Hello World 3');
fse.removeSync(join(snowWorkdir, 'abc1.txt'));
// switch to branches while...
// ... one is modified (abc0.txt)
// ... one deleted (abc1.txt)
// ... one file is untouched (abc2.txt)
// ... and one added (abc.txt)
const error = await t.throwsAsync(async () => exec(t, snow, ['checkout', allCommits[1].hash], { cwd: snowWorkdir }, EXEC_OPTIONS.RETURN_STDOUT));
const lines = error.message.split('\n');
t.true(lines.includes('A abc3.txt')); // abc3.txt got added in the working dir
t.true(lines.includes('M abc0.txt')); // abc0.txt got added in the working dir
// abc1.txt did not get reported as deleted because switch/checkout don't mind if a file got deleted by the user since it can be restored
t.true(lines.includes(`fatal: You have local changes to '${allCommits[1].hash}'; not switching branches.`));
t.log('Switch and discard the local changes');
await exec(t, snow, ['checkout', allCommits[1].hash, '--discard-changes'], { cwd: snowWorkdir });
dirItems = await osWalk(snowWorkdir, OSWALK.FILES);
dirPaths = dirItems.map((d) => basename(d.relPath));
t.is(dirItems.length, 1);
t.true(dirPaths.includes('abc0.txt'));
t.log(`Switch back to ${allCommits[3].hash} and go from there`);
await exec(t, snow, ['checkout', allCommits[3].hash], { cwd: snowWorkdir });
t.log('Make some changes again to the working directory');
t.log(' Update abc0.txt');
fse.writeFileSync(join(snowWorkdir, 'abc0.txt'), 'Hello World Fooooo');
t.log(' Write abc3.txt');
fse.writeFileSync(join(snowWorkdir, 'abc3.txt'), 'Hello World 3');
fse.removeSync(join(snowWorkdir, 'abc1.txt'));
// switch back to branch-0 and keep all changes
await exec(t, snow, ['checkout', allCommits[1].hash, '--keep-changes'], { cwd: snowWorkdir });
// carried over the changes
t.is(fse.readFileSync(join(snowWorkdir, 'abc0.txt')).toString(), 'Hello World Fooooo');
t.is(fse.readFileSync(join(snowWorkdir, 'abc2.txt')).toString(), 'Hello World 2');
t.is(fse.readFileSync(join(snowWorkdir, 'abc3.txt')).toString(), 'Hello World 3');
t.false(fse.pathExistsSync(join(snowWorkdir, 'abc1.txt')));
});
test('snow branch foo-branch', async (t) => {
t.timeout(180000);
let out: string | void;
let error: any;
const snow: string = getSnowexec();
const snowWorkdir = generateUniqueTmpDirName();
// Create branch succesfully
await exec(t, snow, ['init', basename(snowWorkdir)], { cwd: dirname(snowWorkdir) });
t.log('Write foo.txt');
fse.writeFileSync(join(snowWorkdir, 'foo.txt'), 'foo');
await exec(t, snow, ['add', '.'], { cwd: snowWorkdir });
await exec(t, snow, ['commit', '-m', 'First user-commit'], { cwd: snowWorkdir });
const repoBefore = await Repository.open(snowWorkdir);
const headHash = repoBefore.getHead().hash;
const allCommits = repoBefore.getAllCommits(COMMIT_ORDER.OLDEST_FIRST);
const firstCommit = allCommits[0];
const secondCommit = allCommits[1];
t.log(`HEAD now at ${headHash}`);
// snow branch foo-branch
out = await exec(t, snow, ['branch', 'foo-branch'], { cwd: snowWorkdir }, EXEC_OPTIONS.RETURN_STDOUT);
t.true((out as string).includes("A branch 'foo-branch' got created."));
// the hash of 'foo-branch' must match the hash
const repoAfter = await Repository.open(snowWorkdir);
t.is(headHash, repoAfter.findReferenceByName(REFERENCE_TYPE.BRANCH, 'foo-branch').target());
// Don't create a branch twice
// snow branch foo-branch
error = await t.throwsAsync(async () => exec(t, snow, ['branch', 'foo-branch'], { cwd: snowWorkdir }, EXEC_OPTIONS.RETURN_STDOUT));
t.true(error.message.includes("A branch named 'foo-branch' already exists."));
// Create a branch with a different starting point
// snow branch bar-branch 768FF3AA8273DFEB81E7A111572C823EA0850499
out = await exec(t, snow, ['branch', 'bar-branch', firstCommit.hash], { cwd: snowWorkdir }, EXEC_OPTIONS.RETURN_STDOUT);
t.true((out as string).includes("A branch 'bar-branch' got created."));
// verify the target() and start() point are equal (in this case the
// start-point and target are still the same since the branch didn't move forward)
const repoAfter2 = await Repository.open(snowWorkdir);
const checkedOutBranch: string = repoAfter2.getHead().getName();
const fooBranch: Reference = repoAfter2.findReferenceByName(REFERENCE_TYPE.BRANCH, 'foo-branch');
t.is(secondCommit.hash, fooBranch.target());
t.is(secondCommit.hash, fooBranch.start());
const barBranch: Reference = repoAfter2.findReferenceByName(REFERENCE_TYPE.BRANCH, 'bar-branch');
t.is(firstCommit.hash, barBranch.target());
t.is(firstCommit.hash, barBranch.start());
// Delete foo-branch and bar branch
out = await exec(t, snow, ['branch', '--delete', 'foo-branch'], { cwd: snowWorkdir }, EXEC_OPTIONS.RETURN_STDOUT);
t.true((out as string).includes(`Deleted branch 'foo-branch' (was ${fooBranch.target()})`));
out = await exec(t, snow, ['branch', '--delete', 'bar-branch'], { cwd: snowWorkdir }, EXEC_OPTIONS.RETURN_STDOUT);
t.true((out as string).includes(`Deleted branch 'bar-branch' (was ${barBranch.target()})`));
// Try to delete the HEAD branch which must fail
error = await t.throwsAsync(async () =>
exec(t, snow, ['branch', '--delete', checkedOutBranch], { cwd: snowWorkdir }, EXEC_OPTIONS.RETURN_STDOUT));
if (process.platform === 'darwin') {
// on macOS 'process.cwd()' in the branch command returns /private/var/...
t.true(error.message.includes(`Cannot delete branch '${checkedOutBranch}' checked out at '/private${repoAfter2.workdir()}'`));
} else {
t.true(error.message.includes(`Cannot delete branch '${checkedOutBranch}' checked out at '${repoAfter2.workdir()}'`));
}
});
test('snow add .', async (t) => {
t.timeout(180000);
const snow: string = getSnowexec();
const snowWorkdir = generateUniqueTmpDirName();
const subdir = join(snowWorkdir, 'subdir');
await exec(t, snow, ['init', basename(snowWorkdir)], { cwd: dirname(snowWorkdir) });
t.log('Write foo.txt');
fse.writeFileSync(join(snowWorkdir, 'foo.txt'), 'foo');
t.log('Create subdir');
fse.mkdirpSync(subdir);
t.log('Write subdir/foo.txt');
fse.writeFileSync(join(subdir, 'bar.txt'), 'bar');
await exec(t, snow, ['add', '.'], { cwd: subdir });
// TODO: (Fix getStatus to differ between worktree and staging area)
// const stdout = await exec(t, snow, ['status', '--output=json-pretty'], { cwd: subdir }, EXEC_OPTIONS.RETURN_STDOUT);
t.is(true, true);
});
test('snow add *', async (t) => {
const snow: string = getSnowexec();
const snowWorkdir = generateUniqueTmpDirName();
const subdir = join(snowWorkdir, 'subdir');
await exec(t, snow, ['init', basename(snowWorkdir)], { cwd: dirname(snowWorkdir) });
t.log('Write foo.txt');
fse.writeFileSync(join(snowWorkdir, 'foo.txt'), 'foo');
t.log('Create subdir');
fse.mkdirpSync(subdir);
t.log('Write subdir/foo.txt');
fse.writeFileSync(join(subdir, 'bar.txt'), 'bar');
await exec(t, snow, ['add', '*'], { cwd: subdir });
// TODO: (Fix getStatus to differ between worktree and staging area)
// const stdout = await exec(t, snow, ['status', '--output=json-pretty'], { cwd: subdir }, EXEC_OPTIONS.RETURN_STDOUT);
t.is(true, true);
});
/**
* This test ensures that foo.txt is not added to the staging area because cwd is the subdirectory
*/
test('snow add foo.txt', async (t) => {
const snow: string = getSnowexec();
const snowWorkdir = generateUniqueTmpDirName();
const subdir = join(snowWorkdir, 'subdir');
await exec(t, snow, ['init', basename(snowWorkdir)], { cwd: dirname(snowWorkdir) });
t.log('Write foo.txt');
fse.writeFileSync(join(snowWorkdir, 'foo.txt'), 'foo');
t.log('Create subdir');
fse.mkdirpSync(subdir);
t.log('Write subdir/foo.txt');
fse.writeFileSync(join(subdir, 'bar.txt'), 'bar');
await exec(t, snow, ['add', 'foo.txt'], { cwd: subdir });
// TODO: (Fix getStatus to differ between worktree and staging area)
// const stdout = await exec(t, snow, ['status', '--output=json-pretty'], { cwd: subdir }, EXEC_OPTIONS.RETURN_STDOUT);
t.is(true, true);
});
test('snow add bar.txt', async (t) => {
const snow: string = getSnowexec();
const snowWorkdir = generateUniqueTmpDirName();
const subdir = join(snowWorkdir, 'subdir');
await exec(t, snow, ['init', basename(snowWorkdir)], { cwd: dirname(snowWorkdir) });
t.log('Write foo.txt');
fse.writeFileSync(join(snowWorkdir, 'foo.txt'), 'foo');
t.log('Create subdir');
fse.mkdirpSync(subdir);
t.log('Write subdir/foo.txt');
fse.writeFileSync(join(subdir, 'bar.txt'), 'bar');
await exec(t, snow, ['add', 'bar.txt'], { cwd: subdir });
// TODO: (Fix getStatus to differ between worktree and staging area)
// const stdout = await exec(t, snow, ['status', '--output=json-pretty'], { cwd: subdir }, EXEC_OPTIONS.RETURN_STDOUT);
t.is(true, true);
});
test('snow rm foo.txt', async (t) => {
const snow: string = getSnowexec();
const snowWorkdir = generateUniqueTmpDirName();
const subdir = join(snowWorkdir, 'subdir');
await exec(t, snow, ['init', basename(snowWorkdir)], { cwd: dirname(snowWorkdir) });
t.log('Write foo.txt');
fse.writeFileSync(join(snowWorkdir, 'foo.txt'), 'foo');
t.log('Create subdir');
fse.mkdirpSync(subdir);
t.log('Write subdir/foo.txt');
fse.writeFileSync(join(subdir, 'bar.txt'), 'bar');
await exec(t, snow, ['add', '*'], { cwd: snowWorkdir });
await exec(t, snow, ['commit', '-m', 'First commit'], { cwd: snowWorkdir });
// delete the file and commit
await exec(t, snow, ['rm', 'foo.txt'], { cwd: snowWorkdir });
await exec(t, snow, ['commit', '-m', 'Delete foo.txt'], { cwd: snowWorkdir });
// TODO: (Fix getStatus to differ between worktree and staging area)
// const stdout = await exec(t, snow, ['status', '--output=json-pretty'], { cwd: subdir }, EXEC_OPTIONS.RETURN_STDOUT);
t.is(true, true);
});
test('snow rm subdir', async (t) => {
const snow: string = getSnowexec();
const snowWorkdir = generateUniqueTmpDirName();
const subdir = join(snowWorkdir, 'subdir');
await exec(t, snow, ['init', basename(snowWorkdir)], { cwd: dirname(snowWorkdir) });
t.log('Write foo.txt');
fse.writeFileSync(join(snowWorkdir, 'foo.txt'), 'foo');
t.log('Create subdir');
fse.mkdirpSync(subdir);
t.log('Write subdir/foo.txt');
fse.writeFileSync(join(subdir, 'bar.txt'), 'bar');
await exec(t, snow, ['add', '*'], { cwd: snowWorkdir });
await exec(t, snow, ['commit', '-m', 'First commit'], { cwd: snowWorkdir });
// delete the file and commit
await exec(t, snow, ['rm', 'subdir'], { cwd: snowWorkdir });
await exec(t, snow, ['commit', '-m', 'Delete subdir'], { cwd: snowWorkdir });
// TODO: (Fix getStatus to differ between worktree and staging area)
// const stdout = await exec(t, snow, ['status', '--output=json-pretty'], { cwd: subdir }, EXEC_OPTIONS.RETURN_STDOUT);
t.is(true, true);
});
test('snow rm subdir/bar.txt', async (t) => {
const snow: string = getSnowexec();
const snowWorkdir = generateUniqueTmpDirName();
const subdir = join(snowWorkdir, 'subdir');
await exec(t, snow, ['init', basename(snowWorkdir)], { cwd: dirname(snowWorkdir) });
t.log('Write foo.txt');
fse.writeFileSync(join(snowWorkdir, 'foo.txt'), 'foo');
t.log('Create subdir');
fse.mkdirpSync(subdir);
t.log('Write subdir/foo.txt');
fse.writeFileSync(join(subdir, 'bar.txt'), 'bar');
await exec(t, snow, ['add', '*'], { cwd: snowWorkdir });
await exec(t, snow, ['commit', '-m', 'First commit'], { cwd: snowWorkdir });
// delete the file and commit
await exec(t, snow, ['rm', 'subdir/bar.txt'], { cwd: snowWorkdir });
await exec(t, snow, ['commit', '-m', 'Delete subdir/bar.txt'], { cwd: snowWorkdir });
// TODO: (Fix getStatus to differ between worktree and staging area)
// const stdout = await exec(t, snow, ['status', '--output=json-pretty'], { cwd: subdir }, EXEC_OPTIONS.RETURN_STDOUT);
t.is(true, true);
});
test('snow rm file-does-not-exist', async (t) => {
const snow: string = getSnowexec();
const snowWorkdir = generateUniqueTmpDirName();
const subdir = join(snowWorkdir, 'subdir');
await exec(t, snow, ['init', basename(snowWorkdir)], { cwd: dirname(snowWorkdir) });
t.log('Write foo.txt');
fse.writeFileSync(join(snowWorkdir, 'foo.txt'), 'foo');
t.log('Create subdir');
fse.mkdirpSync(subdir);
t.log('Write subdir/foo.txt');
fse.writeFileSync(join(subdir, 'bar.txt'), 'bar');
await exec(t, snow, ['add', '*'], { cwd: snowWorkdir });
await exec(t, snow, ['commit', '-m', 'First commit'], { cwd: snowWorkdir });
const error = await t.throwsAsync(async () => exec(t, snow, ['rm', 'file-does-not-exist'], { cwd: snowWorkdir }));
t.true(error.message.includes('fatal: ENOENT: no such file or directory, stat'));
// TODO: (Fix getStatus to differ between worktree and staging area)
// const stdout = await exec(t, snow, ['status', '--output=json-pretty'], { cwd: subdir }, EXEC_OPTIONS.RETURN_STDOUT);
t.is(true, true);
});
test('Commit User Data --- STORE AND LOAD IDENTICAL', async (t) => {
const snow: string = getSnowexec();
const snowWorkdir = generateUniqueTmpDirName();
const uData: any = { str_key: 'str_value', int_key: 3 };
await exec(t, snow, ['init', basename(snowWorkdir)], { cwd: dirname(snowWorkdir) });
await exec(t, snow,
['commit', '-m', 'unit test user data', '--allow-empty', '--input=stdin'], { cwd: snowWorkdir },
EXEC_OPTIONS.RETURN_STDOUT | EXEC_OPTIONS.WRITE_STDIN,
`--user-data: ${JSON.stringify(uData)}`);
const out = await exec(t, snow, ['log', '--output=json'], { cwd: snowWorkdir }, EXEC_OPTIONS.RETURN_STDOUT);
const c: any = JSON.parse(String(out));
let identical = false;
if (c.commits.length > 0) {
const d = c.commits[0].userData;
// eslint-disable-next-line guard-for-in
for (const key in d) {
if (!(key in uData)) {
identical = false;
break;
}
if (d[key] !== uData[key]) {
identical = false;
break;
}
identical = true;
}
}
t.is(true, identical);
});
test('Commit User Data --- FAIL INVALID INPUT', async (t) => {
const snow: string = getSnowexec();
const snowWorkdir = generateUniqueTmpDirName();
await exec(t, snow, ['init', basename(snowWorkdir)], { cwd: dirname(snowWorkdir) });
const error = await t.throwsAsync(async () => exec(t, snow,
['commit', '-m', 'unit test user data', '--allow-empty', '--input=stdin'], { cwd: snowWorkdir },
EXEC_OPTIONS.RETURN_STDOUT | EXEC_OPTIONS.WRITE_STDIN, '--user-data: garbage-because-json-object-expected'));
const errorMsgSub = 'fatal: invalid user-data: SyntaxError: Unexpected token g in JSON at position 0';
t.true(error.message.includes(errorMsgSub));
});
test('Commit Tags --- STORE AND LOAD IDENTICAL', async (t) => {
const snow: string = getSnowexec();
const snowWorkdir = generateUniqueTmpDirName();
const tag1 = 'FirstTag';
const tag2 = 'SecondTag';
await exec(t, snow, ['init', basename(snowWorkdir)], { cwd: dirname(snowWorkdir) });
await exec(t, snow, ['commit', '-m', 'unit test tags', '--allow-empty', `--tags=${tag1},${tag2}`], { cwd: snowWorkdir });
const out = await exec(t, snow, ['log', '--output=json'], { cwd: snowWorkdir }, EXEC_OPTIONS.RETURN_STDOUT);
const c: any = JSON.parse(String(out));
let identical = false;
if (c.commits.length > 0) {
const d = c.commits[0].tags;
identical = d.includes(tag1) && d.includes(tag2);
}
t.is(true, identical);
});
test('Commit Tags --- SPECIAL SYMBOLS INPUT', async (t) => {
const snow: string = getSnowexec();
const snowWorkdir = generateUniqueTmpDirName();
const tag1 = '[]}';
const tag2 = '\'%$[,.}}';
await exec(t, snow, ['init', basename(snowWorkdir)], { cwd: dirname(snowWorkdir) });
await exec(t, snow, ['commit', '-m', 'unit test tags', '--allow-empty', `--tags=${tag1},${tag2}`], { cwd: snowWorkdir });
const out = await exec(t, snow, ['log', '--output=json'], { cwd: snowWorkdir }, EXEC_OPTIONS.RETURN_STDOUT);
const c: any = JSON.parse(String(out));
let tags: string[] = [];
if (c.commits.length > 0) {
tags = c.commits[0].tags;
}
t.is(true, tags.length === 3); // === 3 due to comma in tag2
});
test('Commit Tags --- EMPTY INPUT', async (t) => {
const snow: string = getSnowexec();
const snowWorkdir = generateUniqueTmpDirName();
await exec(t, snow, ['init', basename(snowWorkdir)], { cwd: dirname(snowWorkdir) });
await exec(t, snow, ['commit', '-m', 'unit test tags', '--allow-empty', '--tags='], { cwd: snowWorkdir });
const out = await exec(t, snow, ['log'], { cwd: snowWorkdir }, EXEC_OPTIONS.RETURN_STDOUT);
// should not print tags as we never passed any
const tagsLog = 'Tags:';
t.is(true, !String(out).includes(tagsLog));
});
test('Branch User Data --- STORE AND LOAD IDENTICAL', async (t) => {
const snow: string = getSnowexec();
const snowWorkdir = generateUniqueTmpDirName();
const uData: any = { str_key: 'str_value', int_key: 3 };
const branchName = 'u-data-test';
await exec(t, snow, ['init', basename(snowWorkdir)], { cwd: dirname(snowWorkdir) });
await exec(t, snow,
['branch', branchName, '--input=stdin'], { cwd: snowWorkdir },
EXEC_OPTIONS.RETURN_STDOUT | EXEC_OPTIONS.WRITE_STDIN,
`--user-data:${JSON.stringify(uData)}`);
const out = await exec(t, snow, ['log', '--output=json'], { cwd: snowWorkdir }, EXEC_OPTIONS.RETURN_STDOUT);
const c: any = JSON.parse(String(out));
let identical = false;
if (c.refs.length > 1) {
const d = c.refs[1].userData;
// eslint-disable-next-line guard-for-in
for (const key in d) {
if (!(key in uData)) {
identical = false;
break;
}
if (d[key] !== uData[key]) {
identical = false;
break;
}
identical = true;
}
}
t.is(true, identical);
});
test('Branch User Data --- FAIL INVALID INPUT', async (t) => {
const snow: string = getSnowexec();
const snowWorkdir = generateUniqueTmpDirName();
const branchName = 'u-data-test';
await exec(t, snow, ['init', basename(snowWorkdir)], { cwd: dirname(snowWorkdir) });
const error = await t.throwsAsync(async () => exec(t, snow,
['branch', branchName, '--input=stdin'], { cwd: snowWorkdir },
EXEC_OPTIONS.RETURN_STDOUT | EXEC_OPTIONS.WRITE_STDIN, '--user-data: garbage-because-json-object-expected'));
const errorMsgSub = 'fatal: invalid user-data: SyntaxError: Unexpected token g in JSON at position 0';
t.true(error.message.includes(errorMsgSub));
t.log('Test failed as expected');
});
test('Multi-Index -- CREATE 2 INDEXES, COMMIT SEQUENTIALLY', async (t) => {
const snow: string = getSnowexec();
const snowWorkdir = generateUniqueTmpDirName();
await exec(t, snow, ['init', basename(snowWorkdir)], { cwd: dirname(snowWorkdir) });
t.log('Write a.txt');
fse.writeFileSync(join(snowWorkdir, 'a.txt'), 'a');
t.log('Write b.txt');
fse.writeFileSync(join(snowWorkdir, 'b.txt'), 'b');
const outAddA = await exec(t, snow, ['add', 'a.txt', '--index', 'create'], { cwd: snowWorkdir }, EXEC_OPTIONS.RETURN_STDOUT);
const outAddB = await exec(t, snow, ['add', 'b.txt', '--index', 'create'], { cwd: snowWorkdir }, EXEC_OPTIONS.RETURN_STDOUT);
const indexAMatch = /Created new index:\s\[(\w*)\]/.exec(outAddA as string);
t.true(Boolean(indexAMatch));
const indexBMatch = /Created new index:\s\[(\w*)\]/.exec(outAddB as string);
t.true(Boolean(indexBMatch));
t.log('Write dontcommit-c.txt'); // dummy file just to ensure file is not commited
fse.writeFileSync(join(snowWorkdir, 'dontcommit-c.txt'), 'dontcommit-c');
if (indexAMatch) {
const indexA: string = indexAMatch[1];
await exec(t, snow, ['commit', '-m', 'commit a.txt', '--index', indexA], { cwd: snowWorkdir });
}
t.log('Write dontcommit-d.txt'); // dummy file just to ensure file is not commited
fse.writeFileSync(join(snowWorkdir, 'dontcommit-d.txt'), 'dontcommit-d');
if (indexBMatch) {
const indexB: string = indexBMatch[1];
await exec(t, snow, ['commit', '-m', 'commit b.txt', '--index', indexB], { cwd: snowWorkdir });
}
t.log('Write dontcommit-e.txt'); // dummy file just to ensure file is not commited
fse.writeFileSync(join(snowWorkdir, 'dontcommit-e.txt'), 'dontcommit-e');
const repo = await Repository.open(snowWorkdir);
const allCommits = repo.getAllCommits(COMMIT_ORDER.OLDEST_FIRST);
t.is(allCommits.length, 3, 'all 3 commits'); // Dummy commit 'Created Project' + 'commit a.txt' + 'commit b.txt'
t.is(allCommits[1].message, 'commit a.txt');
t.is(allCommits[2].message, 'commit b.txt');
// ensure a.txt and b.txt are in their commits
t.true(allCommits[1].root.children.map((t) => t.path).includes('a.txt'));
t.true(allCommits[1].root.children.map((t) => t.path).includes('a.txt'));
t.true(allCommits[2].root.children.map((t) => t.path).includes('b.txt'));
// ensure the commits ONLY contain these files
t.is(allCommits[1].root.children.length, 1, '"First" commit shall contain 1 file (a.txt)');
t.is(allCommits[2].root.children.length, 2, 'Last commit shall contain 2 files (a.txt, b.txt)');
});
test('Multi-Index -- FAIL INVALID INPUT TEST 1', async (t) => {
t.timeout(180000);
const snow: string = getSnowexec();
const snowWorkdir = generateUniqueTmpDirName();
await exec(t, snow, ['init', basename(snowWorkdir)], { cwd: dirname(snowWorkdir) });
t.log('Write abc.txt');
fse.writeFileSync(join(snowWorkdir, 'abc.txt'), 'Hello World');
const error = await t.throwsAsync(async () => exec(t, snow, ['add', '.', '--index', 'non-existing-index'], { cwd: snowWorkdir }));
const errorMsgSub = 'fatal: unknown index: non-existing-index';
t.true(error.message.includes(errorMsgSub));
t.log('Test failed as expected');
});
test('driveinfo test', async (t) => {
const snow: string = getSnowexec();
const out1 = await exec(t, snow, ['driveinfo'], {}, EXEC_OPTIONS.RETURN_STDOUT) as string;
const parsedObj = JSON.parse(out1);
if (!Array.isArray(parsedObj) || parsedObj.length === 0) {
t.fail('expected array with minimum size of 1 element');
return;
}
t.log(out1);
t.true(parsedObj[0].description?.length > 0, 'stdout must be a JSON parsable string');
t.true(out1.includes(' '), 'driveinfo uses --output json-pretty as default and requires a 4-width space JSON output');
const out2 = await exec(t, snow, ['driveinfo', '--output', 'json'], {}, EXEC_OPTIONS.RETURN_STDOUT) as string;
t.true(JSON.parse(out2)[0].description?.length > 0, 'stdout must be a JSON parsable string');
t.true(out1.includes(' '), 'driveinfo --output json must return a minified JSON output');
const out3 = await exec(t, snow, ['driveinfo', '--output', 'json-pretty'], {}, EXEC_OPTIONS.RETURN_STDOUT) as string;
t.true(JSON.parse(out3)[0].description?.length > 0, 'stdout must be a JSON parsable string');
t.true(out1.includes(' '), 'driveinfo --output json-pretty requires a 4-width space JSON output');
}); | the_stack |
import {
INodeProperties
} from 'n8n-workflow';
import { capitalizeInitial } from '../GenericFunctions';
import { CamelCaseResource } from '../types';
export const billingAddress: INodeProperties = {
displayName: 'Billing Address',
name: 'Billing_Address',
type: 'fixedCollection',
default: {},
placeholder: 'Add Billing Address Field',
options: [
{
displayName: 'Billing Address Fields',
name: 'address_fields',
values: [
{
displayName: 'Street',
name: 'Billing_Street',
type: 'string',
default: '',
},
{
displayName: 'City',
name: 'Billing_City',
type: 'string',
default: '',
},
{
displayName: 'State',
name: 'Billing_State',
type: 'string',
default: '',
},
{
displayName: 'Country',
name: 'Billing_Country',
type: 'string',
default: '',
},
{
displayName: 'Zip Code',
name: 'Billing_Code',
type: 'string',
default: '',
},
],
},
],
};
export const shippingAddress: INodeProperties = {
displayName: 'Shipping Address',
name: 'Shipping_Address',
type: 'fixedCollection',
default: {},
placeholder: 'Add Shipping Address Field',
options: [
{
displayName: 'Shipping Address Fields',
name: 'address_fields',
values: [
{
displayName: 'Street',
name: 'Shipping_Street',
type: 'string',
default: '',
},
{
displayName: 'City',
name: 'Shipping_City',
type: 'string',
default: '',
},
{
displayName: 'State',
name: 'Shipping_State',
type: 'string',
default: '',
},
{
displayName: 'Country',
name: 'Shipping_Country',
type: 'string',
default: '',
},
{
displayName: 'Zip Code',
name: 'Shipping_Code',
type: 'string',
default: '',
},
],
},
],
};
export const mailingAddress: INodeProperties = {
displayName: 'Mailing Address',
name: 'Mailing_Address',
type: 'fixedCollection',
default: {},
placeholder: 'Add Mailing Address Field',
options: [
{
displayName: 'Mailing Address Fields',
name: 'address_fields',
values: [
{
displayName: 'Street',
name: 'Mailing_Street',
type: 'string',
default: '',
},
{
displayName: 'City',
name: 'Mailing_City',
type: 'string',
default: '',
},
{
displayName: 'State',
name: 'Mailing_State',
type: 'string',
default: '',
},
{
displayName: 'Country',
name: 'Mailing_Country',
type: 'string',
default: '',
},
{
displayName: 'Zip Code',
name: 'Mailing_Zip',
type: 'string',
default: '',
},
],
},
],
};
export const otherAddress: INodeProperties = {
displayName: 'Other Address',
name: 'Other_Address',
type: 'fixedCollection',
default: {},
placeholder: 'Add Other Address Field',
options: [
{
displayName: 'Other Address Fields',
name: 'address_fields',
values: [
{
displayName: 'Street',
name: 'Other_Street',
type: 'string',
default: '',
},
{
displayName: 'City',
name: 'Other_City',
type: 'string',
default: '',
},
{
displayName: 'State',
name: 'Other_State',
type: 'string',
default: '',
},
{
displayName: 'Zip Code',
name: 'Other_Zip',
type: 'string',
default: '',
},
],
},
],
};
export const address: INodeProperties = {
displayName: 'Address',
name: 'Address',
type: 'fixedCollection',
default: {},
placeholder: 'Add Address Field',
options: [
{
displayName: 'Address Fields',
name: 'address_fields',
values: [
{
displayName: 'Street',
name: 'Street',
type: 'string',
default: '',
},
{
displayName: 'City',
name: 'City',
type: 'string',
default: '',
},
{
displayName: 'State',
name: 'State',
type: 'string',
default: '',
},
{
displayName: 'Country',
name: 'Country',
type: 'string',
default: '',
},
{
displayName: 'Zip Code',
name: 'Zip_Code',
type: 'string',
default: '',
},
],
},
],
};
// displayName: 'Products',
// name: 'Product_Details',
// type: 'collection',
// typeOptions: {
// multipleValues: true,
// multipleValueButtonText: 'Add Product',
// },
// default: {},
// placeholder: 'Add Field',
// displayOptions: {
// show: {
// resource: [
// resource,
// ],
// operation: [
// operation,
// ],
// },
// },
export const productDetailsOptions: INodeProperties[] = [
{
displayName: 'List Price',
name: 'list_price',
type: 'number',
default: '',
},
{
displayName: 'Product ID',
name: 'id',
type: 'options',
default: [],
typeOptions: {
loadOptionsMethod: 'getProducts',
},
},
{
displayName: 'Product Description',
name: 'product_description',
type: 'string',
default: '',
},
{
displayName: 'Quantity',
name: 'quantity',
type: 'number',
default: 1,
},
{
displayName: 'Quantity in Stock',
name: 'quantity_in_stock',
type: 'number',
default: 0,
},
{
displayName: 'Tax',
name: 'Tax',
type: 'number',
default: 0,
},
{
displayName: 'Total',
name: 'total',
type: 'number',
default: 0,
},
{
displayName: 'Total After Discount',
name: 'total_after_discount',
type: 'number',
default: 0,
},
{
displayName: 'Total (Net)',
name: 'net_total',
type: 'number',
default: 0,
},
{
displayName: 'Unit Price',
name: 'unit_price',
type: 'number',
default: 0,
},
];
export const makeGetAllFields = (resource: CamelCaseResource): INodeProperties[] => {
const loadOptionsMethod = `get${capitalizeInitial(resource)}Fields`;
return [
{
displayName: 'Return All',
name: 'returnAll',
type: 'boolean',
default: false,
description: 'Return all results.',
displayOptions: {
show: {
resource: [
resource,
],
operation: [
'getAll',
],
},
},
},
{
displayName: 'Limit',
name: 'limit',
type: 'number',
default: 5,
description: 'The number of results to return.',
typeOptions: {
minValue: 1,
maxValue: 1000,
},
displayOptions: {
show: {
resource: [
resource,
],
operation: [
'getAll',
],
returnAll: [
false,
],
},
},
},
{
displayName: 'Options',
name: 'options',
type: 'collection',
placeholder: 'Add Option',
default: {},
displayOptions: {
show: {
resource: [
resource,
],
operation: [
'getAll',
],
},
},
options: [
{
displayName: 'Approved',
name: 'approved',
type: 'boolean',
default: true,
description: 'Retrieve only approved records. Defaults to true.',
},
{
displayName: 'Converted',
name: 'converted',
type: 'boolean',
default: false,
description: 'Retrieve only converted records. Defaults to false.',
},
{
displayName: 'Fields',
name: 'fields',
type: 'multiOptions',
typeOptions: {
loadOptionsMethod,
},
default: [],
description: 'Return only these fields.',
},
{
displayName: 'Include Child',
name: 'include_child',
type: 'boolean',
default: false,
description: 'Retrieve only records from child territories.',
},
{
displayName: 'Sort By',
name: 'sort_by',
type: 'options',
typeOptions: {
loadOptionsMethod,
},
default: [],
description: 'Field to sort records by.',
},
{
displayName: 'Sort Order',
name: 'sort_order',
type: 'options',
options: [
{
name: 'Ascending',
value: 'asc',
},
{
name: 'Descending',
value: 'desc',
},
],
default: 'desc',
description: 'Ascending or descending order sort order.',
},
{
displayName: 'Territory ID',
name: 'territory_id',
type: 'string',
default: '',
description: 'Retrieve only records from this territory.',
},
],
},
];
};
export const makeCustomFieldsFixedCollection = (resource: CamelCaseResource): INodeProperties => {
const loadOptionsMethod = `getCustom${capitalizeInitial(resource)}Fields`;
return {
displayName: 'Custom Fields',
name: 'customFields',
placeholder: 'Add Custom Field',
type: 'fixedCollection',
typeOptions: {
multipleValues: true,
},
description: 'Filter by custom fields.',
default: {},
options: [
{
name: 'customFields',
displayName: 'Custom Field',
values: [
{
displayName: 'Field ID',
name: 'fieldId',
type: 'options',
typeOptions: {
loadOptionsMethod,
},
default: '',
description: 'Custom field to set a value to.',
},
{
displayName: 'Value',
name: 'value',
type: 'string',
default: '',
description: 'Value to set on custom field.',
},
],
},
],
};
};
// https://www.zoho.com/subscriptions/help/supported-currencies.html
export const currencies = [
{ name: 'US Dollar', value: 'USD' },
{ name: 'Euro', value: 'EUR' },
{ name: 'UAE Dirham', value: 'AED' },
{ name: 'Afghani', value: 'AFN' },
{ name: 'Lek', value: 'ALL' },
{ name: 'Argentine Peso', value: 'ARS' },
{ name: 'Australian Dollar', value: 'AUD' },
{ name: 'Azerbaijan Manat', value: 'AZN' },
{ name: 'Barbados Dollar', value: 'BBD' },
{ name: 'Taka', value: 'BDT' },
{ name: 'Bulgarian Lev', value: 'BGN' },
{ name: 'Bermudian Dollar', value: 'BMD' },
{ name: 'Brunei Dollar', value: 'BND' },
{ name: 'Boliviano', value: 'BOB' },
{ name: 'Brazilian Real', value: 'BRL' },
{ name: 'Bahamian Dollar', value: 'BSD' },
{ name: 'Pula', value: 'BWP' },
{ name: 'Belize Dollar', value: 'BZD' },
{ name: 'Canadian Dollar', value: 'CAD' },
{ name: 'Swiss Franc', value: 'CHF' },
{ name: 'Chilean Peso', value: 'CLP' },
{ name: 'Yuan Renminbi', value: 'CNY' },
{ name: 'Colombian Peso', value: 'COP' },
{ name: 'Costa Rican Colon', value: 'CRC' },
{ name: 'Czech Koruna', value: 'CZK' },
{ name: 'Danish Krone', value: 'DKK' },
{ name: 'Dominican Peso', value: 'DOP' },
{ name: 'Algerian Dinar', value: 'DZD' },
{ name: 'Egyptian Pound', value: 'EGP' },
{ name: 'Fiji Dollar', value: 'FJD' },
{ name: 'Pound Sterling', value: 'GBP' },
{ name: 'Quetzal', value: 'GTQ' },
{ name: 'Hong Kong Dollar', value: 'HKD' },
{ name: 'Lempira', value: 'HNL' },
{ name: 'Kuna', value: 'HRK' },
{ name: 'Forint', value: 'HUF' },
{ name: 'Rupiah', value: 'IDR' },
{ name: 'New Israeli Sheqel', value: 'ILS' },
{ name: 'Indian Rupee', value: 'INR' },
{ name: 'Jamaican Dollar', value: 'JMD' },
{ name: 'Yen', value: 'JPY' },
{ name: 'Kenyan Shilling', value: 'KES' },
{ name: 'Won', value: 'KRW' },
{ name: 'Tenge', value: 'KZT' },
{ name: 'Lao Kip', value: 'LAK' },
{ name: 'Lebanese Pound', value: 'LBP' },
{ name: 'Sri Lanka Rupee', value: 'LKR' },
{ name: 'Liberian Dollar', value: 'LRD' },
{ name: 'Moroccan Dirham', value: 'MAD' },
{ name: 'Kyat', value: 'MMK' },
{ name: 'Pataca', value: 'MOP' },
{ name: 'Ouguiya', value: 'MRO' },
{ name: 'Mauritius Rupee', value: 'MUR' },
{ name: 'Rufiyaa', value: 'MVR' },
{ name: 'Mexican Peso', value: 'MXN' },
{ name: 'Malaysian Ringgit', value: 'MYR' },
{ name: 'Cordoba Oro', value: 'NIO' },
{ name: 'Norwegian Krone', value: 'NOK' },
{ name: 'Nepalese Rupee', value: 'NPR' },
{ name: 'New Zealand Dollar', value: 'NZD' },
{ name: 'Sol', value: 'PEN' },
{ name: 'Kina', value: 'PGK' },
{ name: 'Philippine Peso', value: 'PHP' },
{ name: 'Pakistan Rupee', value: 'PKR' },
{ name: 'Zloty', value: 'PLN' },
{ name: 'Qatari Rial', value: 'QAR' },
{ name: 'Romanian Leu', value: 'RON' },
{ name: 'Russian Ruble', value: 'RUB' },
{ name: 'Saudi Riyal', value: 'SAR' },
{ name: 'Solomon Islands Dollar ', value: 'SBD' },
{ name: 'Seychelles Rupee', value: 'SCR' },
{ name: 'Swedish Krona', value: 'SEK' },
{ name: 'Singapore Dollar', value: 'SGD' },
{ name: 'Syrian Pound', value: 'SYP' },
{ name: 'Baht', value: 'THB' },
{ name: 'Pa’anga', value: 'TOP' },
{ name: 'Turkish Lira', value: 'TRY' },
{ name: 'Trinidad and Tobago Dollar', value: 'TTD' },
{ name: 'New Taiwan Dollar', value: 'TWD' },
{ name: 'Hryvnia', value: 'UAH' },
{ name: 'Dong', value: 'VND' },
{ name: 'Vatu', value: 'VUV' },
{ name: 'Tala', value: 'WST' },
{ name: 'East Caribbean Dollar', value: 'XCD' },
{ name: 'West African CFA Franc', value: 'XOF' },
{ name: 'Yemeni Rial', value: 'YER' },
{ name: 'Rand', value: 'ZAR' },
]; | the_stack |
import { SRNC } from './SRNC-Definitions';
import { register as registerLandmarksJaws } from './SRNC-LandmarksAndGroups-Win_JAWS';
import { register as registerLandmarksJawsVpc } from './SRNC-LandmarksAndGroups-Win_JAWS_VPC';
import { register as registerElementTypesJaws } from './SRNC-ElementTypes-Win_JAWS';
import { register as registerElementTypesJawsVpc } from './SRNC-ElementTypes-Win_JAWS_VPC';
import { register as registerElementStatesJaws } from './SRNC-ElementStates-Win_JAWS';
import { register as registerUsagesJaws } from './SRNC-Usages-Win_JAWS';
import { register as registerStateRulesJaws } from './SRNC-StateRules-Win_JAWS';
import { register as registerStateRulesJawsVpc } from './SRNC-StateRules-Win_JAWS_VPC';
import { register as registerReadingOrderJaws } from './SRNC-ReadingOrder-Win_JAWS';
import { register as registerReadingOrderJawsVpc } from './SRNC-ReadingOrder-Win_JAWS_VPC';
registerLandmarksJaws(SRNC);
registerLandmarksJawsVpc(SRNC);
registerElementTypesJaws(SRNC);
registerElementTypesJawsVpc(SRNC);
registerElementStatesJaws(SRNC);
registerUsagesJaws(SRNC);
registerStateRulesJaws(SRNC);
registerStateRulesJawsVpc(SRNC);
registerReadingOrderJaws(SRNC);
registerReadingOrderJawsVpc(SRNC);
export interface IAriaElement extends HTMLElement {
ariaLabel: string | null;
ariaLabelledByElements: HTMLElement[] | null;
ariaDescribedByElements: HTMLElement[] | null;
ariaActiveDescendantElement: HTMLElement | null;
role: string | null;
type: string | null;
}
export type FocusableElement = {
path: string[];
element: IAriaElement;
};
export type SRNCPlatform = 'Win/JAWS' | 'Win/JAWS/VPC';
export class NarrationComputer {
computedParts: Record<string, string> = {
landmarksAndGroups: undefined,
name: undefined,
content: undefined,
description: undefined,
type: undefined,
state: undefined,
position: undefined,
level: undefined,
usage: undefined,
};
// Traverses the DOM rooted at the given element to find all the focusable elements and returns them.
async getFocusableElements(element: IAriaElement): Promise<FocusableElement[]> {
// Prepare all the arrays
const activeDescendantsParents: IAriaElement[] = [];
const path: string[] = [];
const focusableElements: FocusableElement[] = [];
// Traverse down the DOM tree rooted at the element to first find the activeDescendants parent elements, and then all the focusable elements and their paths
this.findActiveDescendantsParents(element, activeDescendantsParents);
await this.findFocusableElements(element, path, focusableElements, activeDescendantsParents);
return focusableElements;
} // End getFocusableElements
// Recursively traverses the DOM tree rooted at the given element to find all the parents which have the ariaActiveDescendantElement property set, and saves the found elements to the given parents array.
findActiveDescendantsParents(element: IAriaElement, parents: IAriaElement[]) {
if (element.ariaActiveDescendantElement != null) {
// Begin if 1
parents.push(element);
} // End if 1
Array.from(element.children).forEach((child: IAriaElement) => {
// Begin forEach 1
this.findActiveDescendantsParents(child, parents);
}); // End forEach 1
} // End findActiveDescendantsParents
// Recursively traverses the given element to find all the focusable elements and saves their paths along the way.
async findFocusableElements(
element: IAriaElement,
path: string[],
focusableElements: FocusableElement[],
activeDescendantsParents: IAriaElement[],
) {
// Determine the path
const newPath = path.slice();
const node = await (window as any).getComputedAccessibleNode(element);
// Only add the item to the path if the role is not a generic container
if (node.role !== 'genericContainer') {
const item = node.name ? `${node.role} (${node.name})` : node.role;
newPath.push(item);
}
// If the element is focusable, save it together with its path
const isDirectlyFocusable =
(element.getAttribute('tabindex') || element.tabIndex >= 0) && element.ariaActiveDescendantElement == null;
const isActiveDescendant = activeDescendantsParents.some(parent => {
// Begin some 1
return parent.tabIndex >= 0 && parent.ariaActiveDescendantElement === element;
}); // End some 1
if (isDirectlyFocusable || isActiveDescendant) {
// Begin if 1
const focusableElement: FocusableElement = {
path: newPath,
element,
};
focusableElements.push(focusableElement);
// return;
} // End if 1
// Traverse down to all the children
for (let i = 0; i < element.children.length; i++) {
// Begin for 1
const child = element.children[i] as IAriaElement;
await this.findFocusableElements(child, newPath, focusableElements, activeDescendantsParents);
} // End for 1
} // End findFocusableElements
// Computes and returns the screen reader narration for the given element using the previous element and platform.
async getNarration(element: IAriaElement, prevElement: IAriaElement, platform: SRNCPlatform): Promise<string> {
// Retrieve the computed accessible node
const node = await (window as any).getComputedAccessibleNode(element);
const inheritance = this.getPlatformInheritance(platform);
// Compute and store all the narration parts
this.computeLandmarksAndGroups(element, prevElement, inheritance);
this.computeDescription(element, inheritance);
this.computeNameContentAndTitle(node, element);
this.computePositionAndLevel(inheritance);
this.computeTypeAndState(node, element, inheritance);
this.computeUsage(element, inheritance);
const computedNarration = this.composeNarrationFromParts(element, inheritance);
return computedNarration;
} // End getNarration
// Returns ARIA landmarks and groups that would be entered and narrated when focus moves from the given previous element to the given element, for the given platform inheritance list.
getEnteredLandmarksAndGroups(element: HTMLElement, prevElement: HTMLElement, inheritance: string[]): string[] {
const landmarksAndGroups = [];
const commonAncestor = this.getCommonAncestor(element, prevElement);
if (!commonAncestor) {
// Begin if 1
return landmarksAndGroups;
} // End if 1
// Find all the landmarks and groups between the element and the common ancestor, and compute and save their narration
let parent = element.parentElement as IAriaElement;
while (parent !== commonAncestor) {
// Begin while 1
let skipParent = false;
// The "<header>" and "<footer>" elements don't create a landmark if they are a descendant of a sectioning element.
// Note: According to MDN, they should not create a landmark if they are descendants also of of sectioning roles (e.g. article or main), but using all JAWS, NVDA and VoiceOver they actually do. However, they do only when tabbed into, not when entered with virtual cursor. Therefore, in this code, we don't follow MDN, but follow how screen readers actually behave.
// See: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/header
if (!parent.role && ['header', 'footer'].includes(parent.tagName.toLowerCase())) {
// Begin if 1
const sectionElements = ['article', 'aside', 'main', 'nav', 'section'];
const sectionRoles = SRNC.hfLandmarkInSectionRole.includes(inheritance[0])
? []
: ['article', 'complementary', 'main', 'navigation', 'region'];
let ancestor = parent.parentElement as IAriaElement;
while (ancestor !== element.ownerDocument.body) {
// Begin while 2
const isSectionElementAncestor = sectionElements.includes(ancestor.tagName.toLowerCase());
const isSectionRoleAncestor = sectionRoles.includes(ancestor.role);
if (isSectionElementAncestor || isSectionRoleAncestor) {
// Begin if 2
skipParent = true;
break;
} // End if 2
ancestor = ancestor.parentElement as IAriaElement;
} // End while 2
} // End if 1
if (!skipParent) {
// Begin if 1
const landmarkOrGroup = [];
// Test if the parent's role or tag name exists in the landmarks and groups definitions
let testedName = `role=${parent.role}`;
let definition = parent.role
? this.getDefinitionByKey(testedName, inheritance, 'landmarksAndGroups')
: undefined;
if (!parent.role && !definition) {
// Begin if 2
testedName = parent.tagName.toLowerCase();
definition = this.getDefinitionByKey(testedName, inheritance, 'landmarksAndGroups');
} // End if 2
// Skip the definition if landmark or group should be ignored
const ignoredLandmarksAndGroups = this.getDefinition(inheritance, 'ignoredLandmarksAndGroups');
if (ignoredLandmarksAndGroups && ignoredLandmarksAndGroups.includes(testedName)) {
// Begin if 2
definition = undefined;
} // End if 2
// If the "aria-label" or "aria-labelledby" attribute exists together with a landmark or group element or role, or if it is the "narrateLabelIfNoRole" exception, add its value to the narration
// However, don't add its value to the narration if it is an exception that "aria-label" and "aria-labelledby" should be ignored""""
const ignoreLabel = this.getDefinition(inheritance, 'ignoreLabel');
if (
(definition || SRNC.narrateLabelIfNoRole.includes(inheritance[0])) &&
(!ignoreLabel || !ignoreLabel.includes(testedName))
) {
// Begin if 2
const label =
parent.ariaLabelledByElements
?.map((labElement: HTMLElement) => {
return labElement.textContent;
})
.join(SRNC.DESCBY_AND_LABBY_SEPARATOR) ||
parent.ariaLabel ||
undefined;
if (label) {
// Begin if 3
landmarkOrGroup.push(label);
} // End if 3
} // End if 2
// If the definition exists and it is not an exception that the landmark or group element or role also must have the "aria-label" or "aria-labelledby" attribute to be narrated, add the definition to the narration
const narrateOnlyWhenLabelled = this.getDefinition(inheritance, 'narrateOnlyWhenLabelled');
if (
definition &&
(landmarkOrGroup.length >= 1 || !narrateOnlyWhenLabelled || !narrateOnlyWhenLabelled.includes(testedName))
) {
// Begin if 2
landmarkOrGroup.push(definition);
} // End if 2
landmarksAndGroups.unshift(landmarkOrGroup.join(' '));
} // End if 1
parent = parent.parentElement as IAriaElement;
} // End while 1
return landmarksAndGroups;
} // End getEnteredLandmarksAndGroups
getCommonAncestor(element1: HTMLElement, element2: HTMLElement): HTMLElement {
let parent1 = element1.parentElement;
let parent2 = element2.parentElement;
while (parent1 !== parent2 && parent1 !== element1.ownerDocument.body) {
// Begin while 1
while (parent2 !== element2.ownerDocument.body) {
// Begin while 2
if (parent1 === parent2) {
// Begin if 1
return parent1;
} // End if 1
// If the element1 is an ancestor of the element2, return
if (parent2 === element1) {
// Begin if 1
return null;
} // End if 1
parent2 = parent2.parentElement;
} // End while 2
// If the element2 is an ancestor of the element1, return
if (parent1 === element2) {
// Begin if 1
return null;
} // End if 1
parent2 = element2.parentElement;
parent1 = parent1.parentElement;
} // End while 1
return parent1;
} // End getCommonAncestor
// Returns the platform inheritance list for the given platform
getPlatformInheritance(platform: SRNCPlatform): string[] {
const inheritance = [platform];
let inheritedPlatform = platform;
while (SRNC.inheritance[inheritedPlatform]) {
// Begin while 1
inheritedPlatform = SRNC.inheritance[inheritedPlatform];
inheritance.push(inheritedPlatform);
} // End while 1
return inheritance;
} // End getPlatformInheritance
// Returns the definition based on the given definition key, platform inheritance list and definition type. If the definition doesn't exist, returns undefined.
getDefinitionByKey(key: string, inheritance: string[], type: string): string {
const definitions = SRNC[type];
// Loop through the platform inheratance list to find the platform which has the searched key
const platform = inheritance.find(testedPlatform => {
// Begin find 1
return definitions[testedPlatform] && definitions[testedPlatform][key] !== undefined;
}); // End find 1
const definition = definitions[platform] && definitions[platform][key] ? definitions[platform][key] : undefined;
return definition;
} // End getDefinitionByKey
// Returns the definition based on the given platform inheritance list and definition type. If the definition doesn't exist, returns undefined.
getDefinition(inheritance: string[], type: string): string {
const definitions = SRNC[type];
// Loop through the platform inheratance list to find the platform which has the definition
const platform = inheritance.find(testedPlatform => {
// Begin find 1
return definitions[testedPlatform] !== undefined;
}); // End find 1
const definition = definitions[platform];
return definition;
} // End getDefinition
// Returns the definition name and (possibly inherited) platform based on the given element, platform inheritance list and definition type. If the definition doesn't exist, returns undefined for both the definition name and platform.
getDefinitionNameAndPlatform(element: IAriaElement, inheritance: string[], type: string): string[] {
const definitions = SRNC[type];
let definitionName = '[default]';
let platform = inheritance[inheritance.length - 1];
if (!definitions[platform] || !definitions[platform][definitionName]) {
// Begin if 1
definitionName = undefined;
platform = undefined;
} // End if 1
// Loop through the platform inheratance list to find the definition name and (possibly inherited) platform
inheritance.some(testedPlatform => {
// Begin some 1
let testedName = `role=${element.role}`;
let definition = definitions[testedPlatform] ? definitions[testedPlatform][testedName] : undefined;
if (definition) {
// Begin if 1
// A definition exists for the element role
// Handle the situation when the definition is a reference to another definition
definitionName = typeof definition === 'string' ? definition : testedName;
platform = testedPlatform;
return true;
} // End if 1
testedName = element.tagName.toLowerCase();
// In the case of the <input> element, the definition name is further determined by the element's "type" attribute
if (testedName === 'input') {
// Begin if 2
testedName += `:${element.type}`;
} // End if 2
definition = definitions[testedPlatform] ? definitions[testedPlatform][testedName] : undefined;
if (definition && !element.role) {
// Begin if 2
// A definition exists for the element tag name and element has no role
// Handle the situation when the definition is a reference to another definition
definitionName = typeof definition === 'string' ? definition : testedName;
platform = testedPlatform;
return true;
} // End if 2
return false;
}); // End some 1
return [definitionName, platform];
} // End getDefinitionNameAndPlatform
// Returns the definition name and (possibly inherited) platform based on the given definition key, platform inheritance list and definition type. If the definition doesn't exist, returns undefined for both the definition name and platform.
getDefinitionNameAndPlatformByKey(key: string, inheritance: string[], type: string): string[] {
const definitions = SRNC[type];
// Loop through the platform inheratance list to find the platform which has the searched key
const platform = inheritance.find(testedPlatform => {
// Begin find 1
return definitions[testedPlatform] && definitions[testedPlatform][key] !== undefined;
}); // End find 1
const definition = definitions[platform] && definitions[platform][key] ? definitions[platform][key] : undefined;
// Handle the situation when the definition is a reference to another definition
const definitionName = typeof definition === 'string' ? definition : key;
return [definitionName, platform];
} // End getDefinitionNameAndPlatformByKey
// Computes and stores the landmarksAndGroups part of the narration for the given element, previous element and platform inheritance list.
computeLandmarksAndGroups(element: HTMLElement, prevElement: HTMLElement, inheritance: string[]) {
if (prevElement == null) {
this.computedParts.landmarksAndGroups = undefined;
return;
}
const landmarksAndGroups = this.getEnteredLandmarksAndGroups(element, prevElement, inheritance);
this.computedParts.landmarksAndGroups = landmarksAndGroups.join(SRNC.LANDMARKS_AND_GROUPS_SEPARATOR);
} // End computeLandmarksAndGroups
// Computes and stores the usage part of the narration for the given definitionName, element and platform.
computeUsage(element: HTMLElement, inheritance: string[]) {
const [definitionName, platform] = this.getDefinitionNameAndPlatform(
element as IAriaElement,
inheritance,
'usages',
);
this.computedParts.usage = undefined;
// On some platforms the usage part is not narrated
if (SRNC.ignoreUsage.includes(inheritance[0])) {
// Begin if 1
return;
} // End if 1
const usages = SRNC.usages[platform] ? SRNC.usages[platform][definitionName] : undefined;
if (usages) {
// Begin if 1
this.computedParts.usage = usages['[default]'] || undefined;
// Find the usage which matches the element's state
// If there are more matching states, the last usage definition will be used
for (const usageName in usages) {
// Begin for 1
const [stateName, stateValue] = usageName.split('=');
const stateNameAndValueMatch = element.getAttribute(stateName) === stateValue;
// Handle the special case of the "checked" state name where we are looking for the DOM property instead of the state attribute
const checkedDOMPropAndValueMatch =
stateName === 'checked' && (element as HTMLInputElement).checked.toString() === stateValue;
this.computedParts.usage =
stateNameAndValueMatch || checkedDOMPropAndValueMatch ? usages[usageName] : this.computedParts.usage;
} // End for 1
} // End if 1
} // End computeUsage
// Computes and stores the accessible description part of the narration for the given definitionName, element and platform inheritance list.
computeDescription(element: HTMLElement, inheritance: string[]) {
this.computedParts.description = undefined;
// On some platforms the description part is not narrated
if (SRNC.ignoreDescription.includes(inheritance[0])) {
// Begin if 1
return;
} // End if 1
// Handle some special cases
const elementName = element.tagName.toLowerCase();
if (
elementName === 'textarea' &&
SRNC.stringOverridesDescription.includes(inheritance[0]) &&
(element as HTMLTextAreaElement).value.trim()
) {
// Begin if 1
this.computedParts.description = this.getDefinition(inheritance, 'containsText');
return;
} // End if 1
this.computedParts.description =
(element as IAriaElement).ariaDescribedByElements
?.map((descElement: HTMLElement) => {
return descElement.textContent;
})
.join(SRNC.DESCBY_AND_LABBY_SEPARATOR) || undefined;
} // End computeDescription
// Computes and stores the accessible name, content and title parts of the narration for the given element using the given computed node.
computeNameContentAndTitle(node: any, element: HTMLElement) {
this.computedParts.name = node.name;
this.computedParts.content = node.valueText || element.textContent;
// If the title attribute is present, set its value as the description part of the narration if it was not computed as accessible name and if no accessible description was computed before
this.computedParts.description =
element.title && this.computedParts.name !== element.title && !this.computedParts.description
? element.title
: this.computedParts.description;
} // End computeNameContentAndTitle
// Sets the position and level narration parts as constant strings because the real computation of the position in set and level would be too difficult.
computePositionAndLevel(inheritance: string[]) {
this.computedParts.position = undefined;
this.computedParts.level = undefined;
// On some platforms the position and level parts are not narrated
if (SRNC.ignorePositionAndLevel.includes(inheritance[0])) {
// Begin if 1
return;
} // End if 1
// We can set the position and level parts for all elements regardless of the definition name because whether it will eventually be included in the final narration will be determined by the reading order definition
this.computedParts.position = this.getDefinition(inheritance, 'positions');
this.computedParts.level = this.getDefinition(inheritance, 'levels');
} // End computePositionAndLevel
// Computes the type and state parts of the narration for the given definitionName, element and platform using the given computed node.
computeTypeAndState(node: any, element: HTMLElement, inheritance: string[]) {
let [definitionName, platform] = this.getDefinitionNameAndPlatform(
element as IAriaElement,
inheritance,
'stateRules',
);
// Set the default ttype and state for unknown roles and element types
this.computedParts.type = `[${node.role}]`;
this.computedParts.state = undefined;
const rules = SRNC.stateRules[platform] ? SRNC.stateRules[platform][definitionName] : undefined;
if (rules) {
// Begin if 1
// If the definition name has no states (i.e. is not a widget, like <h1>), the definition doesn't actually consist of state rules, but is just an object with a reference to the element type
if (typeof rules === 'object' && rules.constructor === Object) {
// Begin if 2ė
this.computedParts.type = this.getDefinitionByKey(rules.elementType, inheritance, 'elementTypes');
return;
} // End if 2
// Find the rule with the state combination that matches the states present on the element
for (let i = 0; i < rules.length; i++) {
// Begin for 1
const rule = rules[i];
const combination = rule.combination || [];
const possibleStates = SRNC.possibleStates[definitionName] || [];
const skipRule = possibleStates.some((possibleState: string) => {
// Begin some 1
const stateValue = element.getAttribute(possibleState);
// A state is considred not to be present on the element if it is null, or is false but is included in the "falseMeansNotPresent" list. But let's define it the other way around so that there is not too much negations
const elementHasState =
stateValue !== null && (stateValue !== 'false' || !SRNC.falseMeansNotPresent.includes(possibleState));
// Handle the special case of the "checked" state where we are not looking for an attribute but a DOM property
const elementHasCheckedProp =
possibleState === 'checked' && (element as HTMLInputElement).checked !== undefined;
const elementHasStateOrCheckedProp = elementHasState || elementHasCheckedProp;
const combinationHasState = combination.includes(possibleState);
// Check if the presence of the state on the element matches its presence in the combination list. If not, continue with the next rule
if (elementHasStateOrCheckedProp !== combinationHasState) {
// Begin if 2
return true;
} // End if 2
return false;
}); // End some 1
if (skipRule) {
continue;
}
// We have found the matching rule, retrieve and store the element's type
this.computedParts.type = this.getDefinitionByKey(rule.elementType, inheritance, 'elementTypes');
// Compute and store the element's state
const computedStateArr: string[] = [];
[definitionName, platform] = this.getDefinitionNameAndPlatformByKey(
definitionName,
inheritance,
'elementStates',
);
if (!definitionName || !platform) {
// Begin if 1
// The element states definition doesn't exist, so break and let the state default to undefined.
// Note: This should never hapen since every state rule should have element states definition
break;
} // End if 1
const elementStates = SRNC.elementStates[platform][definitionName];
// If there is just one or no state in the combination list, the order does not have to be specified, an therefore the combination can be used as the order. But if the order is specified explicitly, use that order
const order = combination.length <= 1 && !rule.order ? combination : rule.order;
// Determine the state narration for each state in the order list by looking if corresponding state and its value exist in the state strings definitions
order.forEach((stateName: string) => {
// Begin forEach 1
let stateValue;
if (stateName === 'checked') {
// Begin if 2
// Handle the special case of the "checked" state name where we are looking for the DOM property value instead of the state attribute value
stateValue = (element as HTMLInputElement).checked;
} else {
// Else if 2
// Get the state attribute value. If the attribute is not present, consider it as if it had "false" value
stateValue = element.getAttribute(stateName) || 'false';
} // End if 2
// Determine the state string by using "<stateName>=<stateValue>" as the definition key. If such key does not exist, try using "<stateName>=" as the key. Therefore, "<stateName>=" key will match the given stateName and any not defined stateValue
const partialState = elementStates[`${stateName}=${stateValue}`] || elementStates[`${stateName}=`];
if (partialState) {
// Begin if 2
computedStateArr.push(partialState);
} // End if 2
}); // End forEach 1
this.computedParts.state = computedStateArr.join(SRNC.STATES_SEPARATOR);
break;
} // End for 1
} // End if 1
} // End computeTypeAndState
// Composes and returns the complete screen reader narration according to the values of all the internally stored computed parts in the correct order and based on the given definition name and platform.
composeNarrationFromParts(element: HTMLElement, inheritance: string[]): string {
const [definitionName, platform] = this.getDefinitionNameAndPlatform(
element as IAriaElement,
inheritance,
'readingOrder',
);
const readingOrder = SRNC.readingOrder[platform][definitionName];
const computedNarrationArr = [];
readingOrder.forEach(partName => {
// Begin forEach 1
const partValue = this.computedParts[partName];
if (partValue) {
// Begin if 1
computedNarrationArr.push(partValue);
} // End if 1
}); // End forEach 1
const computedNarration = computedNarrationArr.join(SRNC.PARTS_SEPARATOR);
return computedNarration;
} // End composeNarrationFromParts
} // End NarrationComputer | the_stack |
import {ArrayUtils} from '../../../core/ArrayUtils';
import {TypedGlNode} from './_Base';
import {
GlConnectionPoint,
GlConnectionPointComponentsCountMap,
GlConnectionPointType,
} from '../utils/io/connections/Gl';
// https://github.com/stegu/webgl-noise/
import NoiseCommon from './gl/noise/common.glsl';
// import cellular2D from './Gl/noise/cellular2D.glsl'
// import cellular2x2 from './Gl/noise/cellular2x2.glsl'
// import cellular2x2x2 from './Gl/noise/cellular2x2x2.glsl'
// import cellular3D from './Gl/noise/cellular3D.glsl'
import classicnoise2D from './gl/noise/classicnoise2D.glsl';
import classicnoise3D from './gl/noise/classicnoise3D.glsl';
import classicnoise4D from './gl/noise/classicnoise4D.glsl';
import noise2D from './gl/noise/noise2D.glsl';
import noise3D from './gl/noise/noise3D.glsl';
// import noise3Dgrad from './Gl/noise/noise3Dgrad.glsl'
import noise4D from './gl/noise/noise4D.glsl';
// import psrdnoise2D from './Gl/noise/psrdnoise2D.glsl'
export enum NoiseName {
// 'cellular2D',
// 'cellular2x2',
// 'cellular2x2x2',
// 'cellular3D',
CLASSIC_PERLIN_2D = 'Classic Perlin 2D',
// 'Classic Perlin 2D with periodic variant',
CLASSIC_PERLIN_3D = 'Classic Perlin 3D',
// 'Classic Perlin 3D with periodic variant',
CLASSIC_PERLIN_4D = 'Classic Perlin 4D',
// 'Classic Perlin 4D with periodic variant',
NOISE_2D = 'noise2D',
NOISE_3D = 'noise3D',
// 'noise3Dgrad',
NOISE_4D = 'noise4D',
// 'Periodic Simplex Rotating Derivative', // psrdnoise
// 'Periodic Simplex Derivative', // psdnoise
// 'Periodic Simplex Rotating', // psrnoise
// 'Periodic Simplex', // psnoise
// 'Simplex Rotating Derivating', // srdnoise
// 'Simplex Derivating', // sdnoise
// 'Simplex Rotating', // srnoise
// 'Simplex', // snoise
}
export const NOISE_NAMES: Array<NoiseName> = [
NoiseName.CLASSIC_PERLIN_2D,
NoiseName.CLASSIC_PERLIN_3D,
NoiseName.CLASSIC_PERLIN_4D,
NoiseName.NOISE_2D,
NoiseName.NOISE_3D,
NoiseName.NOISE_4D,
];
type StringByNoise = {[key in NoiseName]: string};
const IMPORT_BY_NOISE_NAME: StringByNoise = {
[NoiseName.CLASSIC_PERLIN_2D]: classicnoise2D,
[NoiseName.CLASSIC_PERLIN_3D]: classicnoise3D,
[NoiseName.CLASSIC_PERLIN_4D]: classicnoise4D,
[NoiseName.NOISE_2D]: noise2D,
[NoiseName.NOISE_3D]: noise3D,
[NoiseName.NOISE_4D]: noise4D,
};
type ConnectionTypeByNoise = {[key in NoiseName]: GlConnectionPointType};
const INPUT_TYPES_BY_NOISE_NAME: ConnectionTypeByNoise = {
[NoiseName.CLASSIC_PERLIN_2D]: GlConnectionPointType.VEC2,
[NoiseName.CLASSIC_PERLIN_3D]: GlConnectionPointType.VEC3,
[NoiseName.CLASSIC_PERLIN_4D]: GlConnectionPointType.VEC4,
[NoiseName.NOISE_2D]: GlConnectionPointType.VEC2,
[NoiseName.NOISE_3D]: GlConnectionPointType.VEC3,
[NoiseName.NOISE_4D]: GlConnectionPointType.VEC4,
};
const OUTPUT_TYPE_BY_NOISE_NAME: ConnectionTypeByNoise = {
[NoiseName.CLASSIC_PERLIN_2D]: GlConnectionPointType.FLOAT,
[NoiseName.CLASSIC_PERLIN_3D]: GlConnectionPointType.FLOAT,
[NoiseName.CLASSIC_PERLIN_4D]: GlConnectionPointType.FLOAT,
[NoiseName.NOISE_2D]: GlConnectionPointType.FLOAT,
[NoiseName.NOISE_3D]: GlConnectionPointType.FLOAT,
[NoiseName.NOISE_4D]: GlConnectionPointType.FLOAT,
};
const METHOD_NAMES_BY_NOISE_NAME: StringByNoise = {
[NoiseName.CLASSIC_PERLIN_2D]: 'cnoise',
[NoiseName.CLASSIC_PERLIN_3D]: 'cnoise',
[NoiseName.CLASSIC_PERLIN_4D]: 'cnoise',
[NoiseName.NOISE_2D]: 'snoise',
[NoiseName.NOISE_3D]: 'snoise',
[NoiseName.NOISE_4D]: 'snoise',
};
enum OUTPUT_TYPE {
NoChange = 0,
Float = 1,
Vec2 = 2,
Vec3 = 3,
Vec4 = 4,
}
const OUTPUT_TYPES: Array<OUTPUT_TYPE> = [
OUTPUT_TYPE.NoChange,
OUTPUT_TYPE.Float,
OUTPUT_TYPE.Vec2,
OUTPUT_TYPE.Vec3,
OUTPUT_TYPE.Vec4,
];
type StringByOutputType = {[key in OUTPUT_TYPE]: string};
const OUTPUT_TYPE_LABEL: StringByOutputType = {
[OUTPUT_TYPE.NoChange]: 'Same as noise',
[OUTPUT_TYPE.Float]: 'Float',
[OUTPUT_TYPE.Vec2]: 'Vec2',
[OUTPUT_TYPE.Vec3]: 'Vec3',
[OUTPUT_TYPE.Vec4]: 'Vec4',
};
type ConnectionTypeByOutputType = {[key in OUTPUT_TYPE]: GlConnectionPointType};
const CONNECTION_TYPE_BY_OUTPUT_TYPE: ConnectionTypeByOutputType = {
[OUTPUT_TYPE.NoChange]: GlConnectionPointType.FLOAT,
[OUTPUT_TYPE.Float]: GlConnectionPointType.FLOAT,
[OUTPUT_TYPE.Vec2]: GlConnectionPointType.VEC2,
[OUTPUT_TYPE.Vec3]: GlConnectionPointType.VEC3,
[OUTPUT_TYPE.Vec4]: GlConnectionPointType.VEC4,
};
const ALL_COMPONENTS = ['x', 'y', 'z', 'w'];
const OUTPUT_NAME = 'noise';
const default_noise_type = NOISE_NAMES.indexOf(NoiseName.NOISE_3D);
const default_output_type = OUTPUT_TYPE.NoChange;
const DefaultValues: PolyDictionary<number> = {
amp: 1,
freq: 1,
};
enum InputName {
AMP = 'amp',
POSITION = 'position',
FREQ = 'freq',
OFFSET = 'offset',
}
import {NodeParamsConfig, ParamConfig} from '../utils/params/ParamsConfig';
import {ShadersCollectionController} from './code/utils/ShadersCollectionController';
import {ThreeToGl} from '../../../core/ThreeToGl';
import {FunctionGLDefinition} from './utils/GLDefinition';
import {PolyDictionary} from '../../../types/GlobalTypes';
class NoiseGlParamsConfig extends NodeParamsConfig {
type = ParamConfig.INTEGER(default_noise_type, {
menu: {
entries: NOISE_NAMES.map((noise_name, i) => {
const noise_output_type = OUTPUT_TYPE_BY_NOISE_NAME[noise_name];
const name = `${noise_name} (output: ${noise_output_type})`;
return {name: name, value: i};
}),
},
});
outputType = ParamConfig.INTEGER(default_output_type, {
menu: {
entries: OUTPUT_TYPES.map((output_type) => {
const val = OUTPUT_TYPES[output_type];
const name = OUTPUT_TYPE_LABEL[val];
return {name: name, value: val};
}),
},
});
octaves = ParamConfig.INTEGER(3, {range: [1, 10], rangeLocked: [true, false]});
ampAttenuation = ParamConfig.FLOAT(0.5, {range: [0, 1]});
freqIncrease = ParamConfig.FLOAT(2, {
range: [0, 10],
separatorAfter: true,
});
}
const ParamsConfig = new NoiseGlParamsConfig();
export class NoiseGlNode extends TypedGlNode<NoiseGlParamsConfig> {
paramsConfig = ParamsConfig;
static type() {
return 'noise';
}
// public readonly gl_connections_controller: GlConnectionsController = new GlConnectionsController(this);
initializeNode() {
super.initializeNode();
this.io.connection_points.initializeNode();
this.io.connection_points.spare_params.set_inputless_param_names(['octaves', 'ampAttenuation', 'freqIncrease']);
this.io.outputs.setNamedOutputConnectionPoints([
new GlConnectionPoint(OUTPUT_NAME, GlConnectionPointType.FLOAT),
]);
this.io.connection_points.set_expected_input_types_function(this._expected_input_types.bind(this));
this.io.connection_points.set_expected_output_types_function(this._expected_output_types.bind(this));
this.io.connection_points.set_input_name_function(this._gl_input_name.bind(this));
this.io.connection_points.set_output_name_function(() => OUTPUT_NAME);
}
protected _gl_input_name(index: number) {
return [InputName.AMP, InputName.POSITION, InputName.FREQ, InputName.OFFSET][index];
}
paramDefaultValue(name: string) {
return DefaultValues[name];
}
private _expected_input_types(): GlConnectionPointType[] {
const noise_name = NOISE_NAMES[this.pv.type];
const amplitude_type = this._expected_output_types()[0];
const type = INPUT_TYPES_BY_NOISE_NAME[noise_name];
return [amplitude_type, type, type, type];
}
private _expected_output_types(): GlConnectionPointType[] {
const noise_name = NOISE_NAMES[this.pv.type];
const output_type = OUTPUT_TYPES[this.pv.outputType];
if (output_type == OUTPUT_TYPE.NoChange) {
return [INPUT_TYPES_BY_NOISE_NAME[noise_name]];
} else {
return [CONNECTION_TYPE_BY_OUTPUT_TYPE[output_type]];
}
}
setLines(shaders_collection_controller: ShadersCollectionController) {
const function_declaration_lines = [];
const body_lines = [];
const noise_name = NOISE_NAMES[this.pv.type];
const noise_function = IMPORT_BY_NOISE_NAME[noise_name];
const noise_output_gl_type = OUTPUT_TYPE_BY_NOISE_NAME[noise_name];
function_declaration_lines.push(new FunctionGLDefinition(this, NoiseCommon));
function_declaration_lines.push(new FunctionGLDefinition(this, noise_function));
function_declaration_lines.push(new FunctionGLDefinition(this, this.fbm_function()));
const output_gl_type = this._expected_output_types()[0];
// if the requested output type matches the noise signature
if (output_gl_type == noise_output_gl_type) {
const line = this.single_noise_line();
// body_lines.push( `${output_gl_type} ${noise} = ${amp}*${method_name}(${joined_args})` )
body_lines.push(line);
} else {
// if the requested output type does not match the noise signature
const requested_components_count = GlConnectionPointComponentsCountMap[output_gl_type];
// const noise_output_components_count = OUTPUT_TYPE_BY_NOISE_NAME[output_gl_type]
// if(requested_components_count < noise_output_components_count){
// // not sure we ever go through here with the current noise set
// let component = ArrayUtils.range(requested_components_count).map(i=>ALL_COMPONENTS[i]).join('')
// const line = this.single_noise_line('', component)
// body_lines.push(line)
// } else {
const lines_count_required = requested_components_count;
const assembly_args: string[] = [];
const noise = this.glVarName('noise');
for (let i = 0; i < lines_count_required; i++) {
const component = ALL_COMPONENTS[i];
assembly_args.push(`${noise}${component}`);
const input_type = INPUT_TYPES_BY_NOISE_NAME[noise_name];
// if (CoreType.isArray(input_constructor)) {
// TODO: for noise3Dgrad and other noises with 2 inputs
// } else {
const offset_gl_type = input_type;
const offset_components_count = GlConnectionPointComponentsCountMap[offset_gl_type];
const offset_values = ArrayUtils.range(offset_components_count)
.map((j) => ThreeToGl.float(1000 * i))
.join(', ');
const offset2 = `${offset_gl_type}(${offset_values})`;
const line = this.single_noise_line(component, component, offset2);
body_lines.push(line);
// }
}
const joined_args = assembly_args.join(', ');
const assembly_line = `vec${lines_count_required} ${noise} = vec${lines_count_required}(${joined_args})`;
body_lines.push(assembly_line);
// }
}
shaders_collection_controller.addDefinitions(this, function_declaration_lines);
shaders_collection_controller.addBodyLines(this, body_lines);
}
private fbm_method_name() {
const noise_name = NOISE_NAMES[this.pv.type];
const method_name = METHOD_NAMES_BY_NOISE_NAME[noise_name];
return `fbm_${method_name}_${this.name()}`;
}
private fbm_function() {
const noise_name = NOISE_NAMES[this.pv.type];
const method_name = METHOD_NAMES_BY_NOISE_NAME[noise_name];
const input_type = INPUT_TYPES_BY_NOISE_NAME[noise_name];
return `
float ${this.fbm_method_name()} (in ${input_type} st) {
float value = 0.0;
float amplitude = 1.0;
for (int i = 0; i < ${ThreeToGl.integer(this.pv.octaves)}; i++) {
value += amplitude * ${method_name}(st);
st *= ${ThreeToGl.float(this.pv.freqIncrease)};
amplitude *= ${ThreeToGl.float(this.pv.ampAttenuation)};
}
return value;
}
`;
}
private single_noise_line(output_name_suffix?: string, component?: string, offset2?: string) {
// const noise_name = NOISE_NAMES[this.pv.type];
// const method_name = METHOD_NAMES_BY_NOISE_NAME[noise_name]
const method_name = this.fbm_method_name();
const amp = ThreeToGl.any(this.variableForInput(InputName.AMP));
const position = ThreeToGl.any(this.variableForInput(InputName.POSITION));
const freq = ThreeToGl.any(this.variableForInput(InputName.FREQ));
let offset = ThreeToGl.any(this.variableForInput(InputName.OFFSET));
if (offset2) {
offset = `(${offset}+${offset2})`;
}
const args = [`(${position}*${freq})+${offset}`];
// we cannot use amp as is in all cases
// if the noise outputs a vec2 and the amp is vec3, we cannot simply do vec3*vec2
// therefore, in such a case, we must only take the required component of vec3
// examples:
// - noise is cellular 2D (outputs vec2) and requested output is float:
// nothing to do
// - noise is cellular 2D (outputs vec2) and requested output is vec2:
// nothing to do
// - noise is cellular 2D (outputs vec3) and requested output is vec2:
// we have:
// x = amp.x * vec2.x
// y = amp.y * vec2.y
// z = amp.z * 0
// output = vec3(x,y,z)
// add other args if required
// const input_type = INPUT_TYPES_BY_NOISE_NAME[noise_name];
// if (CoreType.isArray(input_constructor)) {
// const properties = lodash_clone(input_constructor);
// properties.shift(); // remove position
// properties.forEach((property) => {
// const arg_name = Object.keys(property)[0];
// const arg = ThreeToGl.any(this.variableForInput(arg_name));
// args.push(arg);
// });
// }
const joined_args = args.join(', ');
// let output_type = OUTPUT_TYPE_BY_NOISE_NAME[noise_name]
const noise = this.glVarName(OUTPUT_NAME);
const right_hand = `${amp}*${method_name}(${joined_args})`;
if (component) {
return `float ${noise}${output_name_suffix} = (${right_hand}).${component}`;
} else {
// it looks like we never go here with the current set of noises
const output_type = this.io.outputs.namedOutputConnectionPoints()[0].type();
return `${output_type} ${noise} = ${right_hand}`;
}
}
} | the_stack |
import Footer from "./Footer";
import IPoint from "./data/interface/IPoint";
import ViewCode from "./ViewCode";
import Help from "./Help";
import Share from "./share";
import LiveCode from "./code/LiveCode";
import BufferList from "./buffer/BufferList";
import FooterEvent from "./event/FooterEvent";
import ConnectionsCanvas from "./patch/ConnectionsCanvas";
import ConnectionsCanvasEvent from "./event/ConnectionsCanvasEvent";
import Header from "./Header";
import HeaderEvent from "./event/HeaderEvent";
import VisualModuleEvent from "./event/VisualModuleEvent";
import Module from "../patchwork/core/Module";
import Tracking from "./net/Tracking";
import PatchEvent from "../patchwork/event/PatchEvent";
import VisualModule from "./patch/VisualModule";
import ModuleDefinitions from "../patchwork/config/ModuleDefinitions";
import Patch from "../patchwork/core/Patch";
import EditorUtils from "./util/EditorUtils";
declare var $:any;
class Editor
{
public footer:Footer;
public viewOffset:IPoint;
public viewCode:ViewCode;
public help:Help;
public share:Share;
public liveCode:LiveCode;
public bufferList:BufferList;
public $drawArea:any;
public connectionsCanvas:ConnectionsCanvas;
public header:Header;
public audioContext:AudioContext;
public visualModuleEventHandler;
public connectionCreationMouseUpHandler;
public connectionCreationMouseMoveHandler;
public screenDragMouseDownHandler;
public screenDragMouseUpHandler;
public screenDragMouseMoveHandler;
public visualModules:Array<any>;
public $fileInput:any;
public patch:Patch;
public startScreenDragPoint:IPoint;
public patchEventHandler:any;
public connectionCreationData:any;
constructor(audioContext)
{
var startPatch = new Patch(audioContext); // TODO rename startPatch to patch
this.viewOffset = {x: 0, y: 0};
// some stuff in footer
this.viewCode = new ViewCode(startPatch);
this.help = new Help(startPatch);
this.share = new Share(startPatch);
this.liveCode = new LiveCode(startPatch);
// buffer
this.bufferList = new BufferList(startPatch.bufferManager);
// get some display objs
this.$drawArea = $('.draw-area');
this.footer = new Footer();
this.footer.addEventListener(FooterEvent.BREADCRUMB_CLICK, this.handleBreadcrumbClick.bind(this));
this.footer.addEventListener(FooterEvent.GENERATE_CODE, this.handleBreadcrumbClick.bind(this));
this.footer.addEventListener(FooterEvent.HELP, this.handleBreadcrumbClick.bind(this));
this.footer.addEventListener(FooterEvent.SHARE, this.handleBreadcrumbClick.bind(this));
// init the canvas
this.connectionsCanvas = new ConnectionsCanvas(this.viewOffset);
this.connectionsCanvas.addEventListener(ConnectionsCanvasEvent.CONNECTION_CLICKED, function(type, data)
{
// click on connection, remove it
this.patch.removeConnection(this.patch.connections[data.connectionIndex]);
}.bind(this));
// create header
this.header = new Header();
this.header.addEventListener(HeaderEvent.MENU_ITEM_SELECTED, this.handleMenuItemSelected.bind(this));
// now the connectionscanvas & header are here, we can set the patch
this.setPatch(startPatch);
this.visualModules = [];
this.audioContext = audioContext;
this.clearConnectionCreationData();
// create some handlers
this.visualModuleEventHandler = this.handleVisualModuleEvent.bind(this);
// bind some handlers
this.connectionCreationMouseUpHandler = this.handleConnectionCreationMouseUp.bind(this);
this.connectionCreationMouseMoveHandler = this.handleConnectionCreationMouseMove.bind(this);
this.screenDragMouseDownHandler = this.handleScreenDragMouseEvent.bind(this);
this.screenDragMouseUpHandler = this.handleScreenDragMouseEvent.bind(this);
this.screenDragMouseMoveHandler = this.handleScreenDragMouseEvent.bind(this);
// get hidden file input (used for loading) and listen to changes // TODO MOVE TO HEADER
this.$fileInput = $('input[type="file"]');
this.$fileInput.on('change', function(event)
{
var files = this.$fileInput[0].files;
if(files.length === 1)
{
var reader = new FileReader();
reader.onload = function(event)
{
this.patch.loadPatch(reader.result);
}.bind(this);
reader.readAsText(files[0]);
}
else
{
console.error('Multiple files selected');
}
}.bind(this));
// listen for dragging on the patch
this.$drawArea.on('mousedown', this.screenDragMouseDownHandler);
}
public handleBreadcrumbClick(type, data):void
{
switch(type)
{
case FooterEvent.BREADCRUMB_CLICK:
{
var rootPatch = this.patch.getRootPatch();
if(typeof data.id !== 'undefined')
{
var idList = data.id.split('$');
var patch = rootPatch;
for(var i = 0; i < idList.length; i++)
{
patch = patch.getModuleById(idList[i]).subPatch;
}
this.setPatch(patch);
}
else
{
// goto root
this.setPatch(rootPatch);
}
break;
}
case FooterEvent.GENERATE_CODE:
{
this.viewCode.showFullCode(this.patch.getRootPatch());
break;
}
case FooterEvent.HELP:
{
this.help.show();
break;
}
case FooterEvent.SHARE:
{
this.share.patch = this.patch.getRootPatch();
this.share.show();
break;
}
default:
{
console.warn('Unhandled FooterEvent: ' + type);
}
}
}
public setPatch(patch:Patch):void
{
if(this.patch)
{
this.removeAllVisualModules();
this.removePatchEventListeners(this.patch);
this.patch = null;
}
this.patch = patch;
this.addPatchEventListeners(this.patch);
this.addAllVisualModules();
this.connectionsCanvas.draw(this.patch);
this.header.patch = patch;
this.footer.setBreadcrumb(patch);
}
public addAllVisualModules():void
{
for(var i = 0; i < this.patch.modules.length; i++)
{
this.addVisualModule(this.patch.modules[i]);
}
}
public handleMenuItemSelected(event, eventData):void
{
var type = eventData.type;
var data = eventData.data;
if(type === 'patch')
{
switch(data)
{
case 'clear':
{
this.patch.clear();
break;
}
case 'load':
{
this.$fileInput.click();
break;
}
case 'save':
{
this.download('patch.pw', JSON.stringify(this.patch.toObject()));
break;
}
case 'close_subpatch':
{
if(this.patch.parentModule) this.setPatch(this.patch.parentModule.parentPatch);
break;
}
case 'to_object':
{
console.log(this.patch);
var json = JSON.stringify(this.patch.toObject());
console.log(JSON.parse(json));
console.log(json);
break;
}
default:
{
console.warn('Unhandled patch menu action: ' + data);
}
}
}
else
{
console.log('Unhandled menu action', eventData);
}
}
public handleScreenDragMouseEvent(event):void
{
switch(event.type)
{
case 'mousedown':
{
if(event.altKey)
{
// store startpoint
this.startScreenDragPoint = {x: event.clientX, y: event.clientY};
// listen for move and mouseup events
this.$drawArea.on('mousemove', this.screenDragMouseMoveHandler);
this.$drawArea.on('mouseup', this.screenDragMouseUpHandler);
}
break;
}
case 'mousemove':
{
//console.log(this.startScreenDragPoint);
var move = {
x: event.clientX - this.startScreenDragPoint.x,
y: event.clientY - this.startScreenDragPoint.y
};
var moveX = event.originalEvent.movementX || event.originalEvent.mozMovementX || 0;
var moveY = event.originalEvent.movementY || event.originalEvent.mozMovementY || 0;
this.viewOffset.x -= moveX;
this.viewOffset.y -= moveY;
this.moveViewToOffset();
break;
}
case 'mouseup':
{
// stop listening for move & up events
this.$drawArea.off('mousemove', this.screenDragMouseMoveHandler);
this.$drawArea.off('mouseup', this.screenDragMouseUpHandler);
break;
}
}
}
public moveViewToOffset():void
{
// reposition all modules
this.visualModules.forEach(function(visualModule)
{
visualModule.moveToPosition();
});
// redraw the canvas
this.connectionsCanvas.draw(this.patch);
}
public handleVisualModuleEvent(type, data):void
{
switch(type)
{
case VisualModuleEvent.MOVE:
{
this.connectionsCanvas.draw(this.patch);
break;
}
case VisualModuleEvent.REMOVE:
{
Tracking.trackEvent('visual_module', 'remove');
this.patch.removeModuleById(data.moduleId);
break;
}
case VisualModuleEvent.OPEN_SUBPATCH:
{
this.setPatch(data.module.subPatch);
Tracking.trackEvent('visual_module', 'open_subpatch');
break;
}
case VisualModuleEvent.ATTRIBUTE_CHANGED:
{
break;
}
default:
{
console.warn('Unhandled visual module event: ' + type);
break;
}
}
}
public addVisualModuleEventHandlers(visualModule:any):void
{
visualModule.addEventListener(VisualModuleEvent.MOVE, this.visualModuleEventHandler);
visualModule.addEventListener(VisualModuleEvent.REMOVE, this.visualModuleEventHandler);
visualModule.addEventListener(VisualModuleEvent.OPEN_SUBPATCH, this.visualModuleEventHandler);
visualModule.addEventListener(VisualModuleEvent.ATTRIBUTE_CHANGED, this.visualModuleEventHandler);
}
public removeVisualModuleEventHandlers(visualModule:any):void
{
visualModule.removeEventListener(VisualModuleEvent.MOVE, this.visualModuleEventHandler);
visualModule.removeEventListener(VisualModuleEvent.REMOVE, this.visualModuleEventHandler);
visualModule.removeEventListener(VisualModuleEvent.OPEN_SUBPATCH, this.visualModuleEventHandler);
visualModule.removeEventListener(VisualModuleEvent.ATTRIBUTE_CHANGED, this.visualModuleEventHandler);
}
public addPatchEventListeners(patch:Patch):void
{
if(!this.patchEventHandler) this.patchEventHandler = this.handlePatchEvent.bind(this);
patch.addEventListener(PatchEvent.MODULE_ADDED, this.patchEventHandler);
patch.addEventListener(PatchEvent.MODULE_REMOVED, this.patchEventHandler);
patch.addEventListener(PatchEvent.CONNECTION_ADDED, this.patchEventHandler);
patch.addEventListener(PatchEvent.CONNECTION_PRE_REMOVE, this.patchEventHandler);
patch.addEventListener(PatchEvent.CONNECTION_POST_REMOVE, this.patchEventHandler);
patch.addEventListener(PatchEvent.PATCH_CLEARED, this.patchEventHandler);
//patch.addEventListener(PatchEvent.MODULE_ATTRIBUTE_CHANGED, this.patchEventHandler);
}
public removePatchEventListeners(patch:Patch):void
{
// remove patch events
patch.removeEventListener(PatchEvent.MODULE_ADDED, this.patchEventHandler);
patch.removeEventListener(PatchEvent.MODULE_REMOVED, this.patchEventHandler);
patch.removeEventListener(PatchEvent.CONNECTION_ADDED, this.patchEventHandler);
patch.removeEventListener(PatchEvent.CONNECTION_PRE_REMOVE, this.patchEventHandler);
patch.removeEventListener(PatchEvent.CONNECTION_POST_REMOVE, this.patchEventHandler);
patch.removeEventListener(PatchEvent.PATCH_CLEARED, this.patchEventHandler);
//patch.removeEventListener(PatchEvent.MODULE_ATTRIBUTE_CHANGED, this.patchEventHandler);
}
public download(filename, text):void
{
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.click();
}
public handlePatchEvent(type:string, data):void
{
switch(type)
{
case PatchEvent.MODULE_ADDED:
{
// only add if the added module is in the currently visible patch
if(data.module.parentPatch === this.patch)
{
this.addVisualModule(data.module);
}
break;
}
case PatchEvent.MODULE_REMOVED:
{
this.removeVisualModuleById(data.module.id);
this.connectionsCanvas.draw(this.patch);
break;
}
case PatchEvent.CONNECTION_ADDED:
{
this.connectionsCanvas.draw(this.patch);
Tracking.trackEvent('connection', 'added');
break;
}
case PatchEvent.CONNECTION_PRE_REMOVE:
{
// does nothing
break;
}
case PatchEvent.CONNECTION_POST_REMOVE:
{
this.connectionsCanvas.draw(this.patch);
Tracking.trackEvent('connection', 'removed');
break;
}
case PatchEvent.PATCH_CLEARED:
{
// TODO reset viewport
break;
}
// case PatchEvent.MODULE_ATTRIBUTE_CHANGED:
// {
// var visualModule = this.getVisualModuleById(data.module.id);
// console.log(visualModule);
// break;
// }
default:
{
console.error('Unknown event type: ' + type);
}
}
}
public getVisualModuleById(moduleId:string):any
{
for(var i = 0; i < this.visualModules.length; i++)
{
var visualModule = this.visualModules[i];
if(visualModule.module.id === moduleId) return visualModule;
}
}
public removeVisualModuleById(moduleId:string):void
{
var visualModule = this.getVisualModuleById(moduleId);
if(visualModule)
{
// remove from dom
visualModule.$element.detach();
// remove from list
var index = this.visualModules.indexOf(visualModule);
if(index > -1)
{
this.visualModules.splice(index, 1);
visualModule.destruct();
}
else
{
console.error('VisualModule not in list?!');
}
}
else
{
console.error('VisualModule not found for id: ' + moduleId);
}
}
public removeAllVisualModules():void // TODO why is this needed? modules are removed one by one
{
for(var i = this.patch.modules.length - 1; i >= 0; i--)
{
this.removeVisualModuleById(this.patch.modules[i].id);
}
}
public addVisualModule(module:Module):void
{
var visualModule = new VisualModule(module, this.viewOffset);
this.visualModules.push(visualModule);
// set to a default position, unless the module already has one (in loaded patches the modules have positions)
var defaultPosition = module.position ? module.position : {x: 300, y: 200};
visualModule.setPosition(defaultPosition.x, defaultPosition.y);
// add element to container
this.$drawArea.append(visualModule.$element);
visualModule.$element.on('mousedown', function(event)
{
if(EditorUtils.elementIsTransput(event.target))
{
// mousedown on input or output, store the connectioncreation data
this.setConnectionCreationDataByTransputElement(event.target);
// prevent cursor from changing into textthingie
event.preventDefault();
// listen to move and mouse up events on document
document.addEventListener('mousemove', this.connectionCreationMouseMoveHandler);
document.addEventListener('mouseup', this.connectionCreationMouseUpHandler);
}
}.bind(this));
// listen for events
this.addVisualModuleEventHandlers(visualModule);
}
public handleAddModuleClick(event):void
{
var moduleType = event.target.dataset.type;
var definition = ModuleDefinitions.findByType(moduleType);
var args = [];
if(definition.args)
{
// node needs constructor arguments
for(var i = 0; i < definition.args.length; i++)
{
args.push(prompt(definition.args[i].label));
}
}
this.patch.addModuleByType(moduleType, args);
}
public clearConnectionCreationData():void
{
this.connectionCreationData = {source: null, destination: null};
// set also in the connection canvas, so it can draw a connection while it's being created
this.connectionsCanvas.connectionCreationData = null;
}
public setConnectionCreationDataByTransputElement(transput):void
{
var moduleId = EditorUtils.getModuleIdByTransputElement(transput);
var transputIndex = transput.dataset.index || null;
var audioParamId = transput.dataset.audioparam || null;
// convert from string to number
if(transputIndex) transputIndex = parseInt(transputIndex);
var data = {moduleId: moduleId, transputIndex: transputIndex, audioParamId: audioParamId};
if(EditorUtils.elementIsInput(transput))
{
this.connectionCreationData.destination = data;
}
else if(EditorUtils.elementIsOutput(transput))
{
this.connectionCreationData.source = data;
}
else
{
console.error('Element is no input or output'); // TODO remove?
}
// give creation data to canvas (so it can draw during dragging a new connection)
this.connectionsCanvas.connectionCreationData = this.connectionCreationData;
// console.log('source: ', this.connectionCreationData.source);
// console.log('destination: ', this.connectionCreationData.destination);
}
public handleConnectionCreationMouseMove(event):void
{
this.connectionsCanvas.drawWithCreation(this.patch, event.pageX, event.pageY);
}
public handleConnectionCreationMouseUp(event):void
{
document.removeEventListener('mouseup', this.connectionCreationMouseUpHandler);
document.removeEventListener('mousemove', this.connectionCreationMouseMoveHandler);
if((EditorUtils.elementIsInput(event.target) && this.connectionCreationData.source) ||
(EditorUtils.elementIsOutput(event.target) && this.connectionCreationData.destination))
{
this.setConnectionCreationDataByTransputElement(event.target);
// both source and destination should be filled now, create the connection
if(this.connectionCreationData.source && this.connectionCreationData.destination)
{
var success = this.patch.addConnection(
this.connectionCreationData.source.moduleId,
this.connectionCreationData.source.transputIndex,
this.connectionCreationData.destination.moduleId,
this.connectionCreationData.destination.transputIndex
);
// redraw on fail, so the connectioncreation line should be removed (by redrawing)
if(!success) this.connectionsCanvas.draw(null); // todo i dont think this does anything without any param
}
else
{
console.error('Source and/or destination not filled', this.connectionCreationData);
}
}
else
{
console.log('invalid connection');
// do a redraw, so the creation-line disappears
this.connectionsCanvas.draw(this.patch);
}
this.clearConnectionCreationData();
}
}
export default Editor; | the_stack |
import "jest";
import React from "react";
import "react-native";
import renderer from "react-test-renderer";
import { inMemory } from "@hickory/in-memory";
import { createRouter, prepareRoutes } from "@curi/router";
import { TouchableHighlight, Text } from "react-native";
import { sleep } from "../../../utils/tests";
import { createRouterComponent, AsyncLink } from "@curi/react-native";
let { act } = renderer;
// play nice
function fakeEvent(props = {}) {
return {
defaultPrevented: false,
preventDefault() {
this.defaultPrevented = true;
},
...props
};
}
describe("<AsyncLink>", () => {
describe("anchor", () => {
it("renders a <TouchableHighlight> by default", () => {
let routes = prepareRoutes([
{ name: "Test", path: "" },
{ name: "Catch All", path: "(.*)" }
]);
let router = createRouter(inMemory, routes);
let Router = createRouterComponent(router);
let tree = renderer.create(
<Router>
<AsyncLink name="Test">
{navigating => <Text>{navigating}</Text>}
</AsyncLink>
</Router>
);
let anchor = tree.root.findByType(TouchableHighlight);
expect(anchor).toBeDefined();
});
it("when provided, it renders the component instead of an anchor", () => {
let routes = prepareRoutes([
{ name: "Test", path: "" },
{ name: "Catch All", path: "(.*)" }
]);
let router = createRouter(inMemory, routes);
let Router = createRouterComponent(router);
let StyledAnchor = props => (
<TouchableHighlight style={{ borderColor: "orange" }} {...props} />
);
let tree = renderer.create(
<Router>
<AsyncLink name="Test" anchor={StyledAnchor}>
{navigating => <Text>{navigating}</Text>}
</AsyncLink>
</Router>
);
let anchor = tree.root.find(StyledAnchor);
expect(anchor).toBeDefined();
});
});
describe("navigation location", () => {
describe("name", () => {
it("has no pathname component if name is not provided", async () => {
let mockNavigate = jest.fn();
let routes = prepareRoutes([{ name: "Catch All", path: "(.*)" }]);
let router = createRouter(inMemory, routes, {
history: {
locations: [{ url: "/the-initial-location" }]
}
});
router.history.navigate = mockNavigate;
let Router = createRouterComponent(router);
let tree = renderer.create(
<Router>
<AsyncLink name={null} hash="test">
{navigating => <Text>{navigating}</Text>}
</AsyncLink>
</Router>
);
let anchor = tree.root.findByType(TouchableHighlight);
await act(async () => {
anchor.props.onPress(fakeEvent());
});
expect(mockNavigate.mock.calls[0][0]).toMatchObject({
url: "#test"
});
});
});
describe("params", () => {
let routes = prepareRoutes([
{ name: "Park", path: "park/:name" },
{ name: "Catch All", path: "(.*)" }
]);
it("uses params to generate the location to navigate to", async () => {
let mockNavigate = jest.fn();
let router = createRouter(inMemory, routes);
router.history.navigate = mockNavigate;
let Router = createRouterComponent(router);
let params = { name: "Glacier" };
let tree = renderer.create(
<Router>
<AsyncLink name="Park" params={params}>
{navigating => <Text>{navigating}</Text>}
</AsyncLink>
</Router>
);
let anchor = tree.root.findByType(TouchableHighlight);
await act(async () => {
anchor.props.onPress(fakeEvent());
});
expect(mockNavigate.mock.calls[0][0]).toMatchObject({
url: "/park/Glacier"
});
});
it("updates location to navigate to when props change", async () => {
let mockNavigate = jest.fn();
let router = createRouter(inMemory, routes);
router.history.navigate = mockNavigate;
let Router = createRouterComponent(router);
let params = { name: "Glacier" };
let tree = renderer.create(
<Router>
<AsyncLink name="Park" params={params}>
{navigating => <Text>{navigating}</Text>}
</AsyncLink>
</Router>
);
let anchor = tree.root.findByType(TouchableHighlight);
await act(async () => {
anchor.props.onPress(fakeEvent());
});
expect(mockNavigate.mock.calls[0][0]).toMatchObject({
url: "/park/Glacier"
});
let newParams = { name: "Yellowstone" };
await act(async () => {
tree.update(
<Router>
<AsyncLink name="Park" params={newParams}>
{navigating => <Text>{navigating}</Text>}
</AsyncLink>
</Router>
);
});
await act(async () => {
anchor.props.onPress(fakeEvent());
});
expect(mockNavigate.mock.calls[1][0]).toMatchObject({
url: "/park/Yellowstone"
});
});
});
describe("hash & query", () => {
it("merges hash & query props with the pathname when creating href", async () => {
let mockNavigate = jest.fn();
let routes = prepareRoutes([
{ name: "Test", path: "test" },
{ name: "Catch All", path: "(.*)" }
]);
let router = createRouter(inMemory, routes);
router.history.navigate = mockNavigate;
let Router = createRouterComponent(router);
let tree = renderer.create(
<Router>
<AsyncLink name="Test" query="one=two" hash="hashtag">
{navigating => <Text>{navigating}</Text>}
</AsyncLink>
</Router>
);
let anchor = tree.root.findByType(TouchableHighlight);
await act(async () => {
anchor.props.onPress(fakeEvent());
});
expect(mockNavigate.mock.calls[0][0]).toMatchObject({
url: "/test?one=two#hashtag"
});
});
});
});
describe("additional props", () => {
it("passes additional props to the rendered anchor", () => {
let mockNavigate = jest.fn();
let routes = prepareRoutes([
{ name: "Test", path: "" },
{ name: "Catch All", path: "(.*)" }
]);
let router = createRouter(inMemory, routes, {
history: {
locations: [{ url: "/the-initial-location" }]
}
});
router.history.navigate = mockNavigate;
let Router = createRouterComponent(router);
let style = { backgroundColor: "red" };
let tree = renderer.create(
<Router>
<AsyncLink name="Test" style={style}>
{navigating => <Text>{navigating}</Text>}
</AsyncLink>
</Router>
);
let anchor = tree.root.findByType(TouchableHighlight);
expect(anchor.props.style).toMatchObject(style);
});
it('does not overwrite "native" props set on the rendered element', () => {
let onPress = jest.fn();
let routes = prepareRoutes([
{ name: "Test", path: "" },
{ name: "Catch All", path: "(.*)" }
]);
let router = createRouter(inMemory, routes, {
history: {
locations: [{ url: "/the-initial-location" }]
}
});
let Router = createRouterComponent(router);
let tree = renderer.create(
<Router>
<AsyncLink name="Test" onPress={onPress}>
{navigating => <Text>{navigating}</Text>}
</AsyncLink>
</Router>
);
let anchor = tree.root.findByType(TouchableHighlight);
expect(anchor.props.onPress).not.toBe(onPress);
});
});
describe("ref", () => {
it("returns the anchor's ref, not the link's", () => {
let mockNavigate = jest.fn();
let routes = prepareRoutes([
{ name: "Parks", path: "parks" },
{ name: "Catch All", path: "(.*)" }
]);
let router = createRouter(inMemory, routes, {
history: {
locations: [{ url: "/the-initial-location" }]
}
});
router.history.navigate = mockNavigate;
let Router = createRouterComponent(router);
let ref = React.createRef();
let tree = renderer.create(
<Router>
<AsyncLink name="Parks" ref={ref}>
{navigating => <Text>{navigating}</Text>}
</AsyncLink>
</Router>
);
let anchor = tree.root.findByType(TouchableHighlight);
expect(anchor.instance).toBe(ref.current);
});
});
describe("children", () => {
it("is called with the <AsyncLink>'s current navigating state (false on mount)", () => {
let routes = prepareRoutes([
{ name: "Test", path: "" },
{ name: "Catch All", path: "(.*)" }
]);
let router = createRouter(inMemory, routes);
let Router = createRouterComponent(router);
let tree = renderer.create(
<Router>
<AsyncLink name="Test">
{navigating => {
expect(navigating).toBe(false);
return <Text>Test</Text>;
}}
</AsyncLink>
</Router>
);
});
});
describe("pressing a link", () => {
describe("navigation method", () => {
it('method="anchor"', async () => {
let mockNavigate = jest.fn();
let routes = prepareRoutes([
{ name: "Test", path: "" },
{ name: "Catch All", path: "(.*)" }
]);
let router = createRouter(inMemory, routes);
router.history.navigate = mockNavigate;
let Router = createRouterComponent(router);
let tree = renderer.create(
<Router>
<AsyncLink name="Test" method={"anchor"}>
{navigating => <Text>{navigating}</Text>}
</AsyncLink>
</Router>
);
let anchor = tree.root.findByType(TouchableHighlight);
await act(async () => {
anchor.props.onPress(fakeEvent());
});
expect(mockNavigate.mock.calls[0][1]).toBe("anchor");
});
it('method="push"', async () => {
let mockNavigate = jest.fn();
let routes = prepareRoutes([
{ name: "Test", path: "" },
{ name: "Catch All", path: "(.*)" }
]);
let router = createRouter(inMemory, routes);
router.history.navigate = mockNavigate;
let Router = createRouterComponent(router);
let tree = renderer.create(
<Router>
<AsyncLink name="Test" method={"push"}>
{navigating => <Text>{navigating}</Text>}
</AsyncLink>
</Router>
);
let anchor = tree.root.findByType(TouchableHighlight);
await act(async () => {
anchor.props.onPress(fakeEvent());
});
expect(mockNavigate.mock.calls[0][1]).toBe("push");
});
it('method="replace"', async () => {
let mockNavigate = jest.fn();
let routes = prepareRoutes([
{ name: "Test", path: "" },
{ name: "Catch All", path: "(.*)" }
]);
let router = createRouter(inMemory, routes);
router.history.navigate = mockNavigate;
let Router = createRouterComponent(router);
let tree = renderer.create(
<Router>
<AsyncLink name="Test" method={"replace"}>
{navigating => <Text>{navigating}</Text>}
</AsyncLink>
</Router>
);
let anchor = tree.root.findByType(TouchableHighlight);
await act(async () => {
anchor.props.onPress(fakeEvent());
});
expect(mockNavigate.mock.calls[0][1]).toBe("replace");
});
});
describe("children(navigating)", () => {
it("children(true) after clicking", async () => {
// if a link has no on methods, finished will be called almost
// immediately (although this style should only be used for routes
// with resolve methods)
let routes = prepareRoutes([
{
name: "Test",
path: "test",
resolve() {
return new Promise(resolve => {
setTimeout(() => {
resolve("done");
}, 25);
});
}
},
{ name: "Catch All", path: "(.*)" }
]);
let router = createRouter(inMemory, routes);
let Router = createRouterComponent(router);
let tree = renderer.create(
<Router>
<AsyncLink name="Test">
{navigating => {
return <Text>{navigating.toString()}</Text>;
}}
</AsyncLink>
</Router>
);
let anchor = tree.root.findByType(TouchableHighlight);
let text = anchor.findByType(Text);
expect(text.instance.props.children).toBe("false");
await act(async () => {
anchor.props.onPress(fakeEvent());
});
expect(text.instance.props.children).toBe("true");
});
it("children(false) when navigation is cancelled", async () => {
let routes = prepareRoutes([
{ name: "Test", path: "test" },
{
name: "Slow",
path: "slow",
resolve() {
// takes 500ms to resolve
return new Promise(resolve => {
setTimeout(() => {
resolve("slow");
}, 500);
});
}
},
{
name: "Fast",
path: "fast"
},
{ name: "Catch All", path: "(.*)" }
]);
let router = createRouter(inMemory, routes);
let Router = createRouterComponent(router);
let tree = renderer.create(
<Router>
<React.Fragment>
<AsyncLink name="Slow">
{navigating => {
return <Text>{`Slow ${navigating.toString()}`}</Text>;
}}
</AsyncLink>
<AsyncLink name="Fast">
{navigating => {
return <Text>{`Fast ${navigating.toString()}`}</Text>;
}}
</AsyncLink>
</React.Fragment>
</Router>
);
let [slowLink, fastLink] = tree.root.findAllByType(TouchableHighlight);
let text = slowLink.findByType(Text);
expect(text.instance.props.children).toBe("Slow false");
await act(async () => {
slowLink.props.onPress(fakeEvent());
});
expect(text.instance.props.children).toBe("Slow true");
await act(async () => {
fastLink.props.onPress(fakeEvent());
});
expect(text.instance.props.children).toBe("Slow false");
});
it("children(false) when navigation is finished", async () => {
let routes = prepareRoutes([
{ name: "Test", path: "test" },
{
name: "Loader",
path: "load",
resolve() {
return new Promise(resolve => {
setTimeout(() => {
resolve("done");
}, 25);
});
}
},
{ name: "Catch All", path: "(.*)" }
]);
let router = createRouter(inMemory, routes);
let Router = createRouterComponent(router);
let tree = renderer.create(
<Router>
<AsyncLink name="Loader">
{navigating => {
return <Text>{navigating.toString()}</Text>;
}}
</AsyncLink>
</Router>
);
let anchor = tree.root.findByType(TouchableHighlight);
let text = anchor.findByType(Text);
expect(text.instance.props.children).toBe("false");
await act(async () => {
anchor.props.onPress(fakeEvent());
});
expect(text.instance.props.children).toBe("true");
await act(async () => {
await sleep(50);
});
let { response } = router.current();
expect(response.name).toBe("Loader");
expect(text.instance.props.children).toBe("false");
});
// TODO: run this once act() fix is out (act causes error calls);
it("does not call setState if component has unmounted", async done => {
let realError = console.error;
let mockError = jest.fn();
console.error = mockError;
let routes = prepareRoutes([
{ name: "Test", path: "test" },
{
name: "Blork",
path: "blork",
resolve() {
return new Promise(resolve => {
setTimeout(() => {
resolve("Finally finished");
// need to verify error in another timeout
setTimeout(() => {
expect(mockError.mock.calls.length).toBe(0);
console.error = realError;
done();
});
}, 500);
});
}
},
{ name: "Catch All", path: "(.*)" }
]);
let router = createRouter(inMemory, routes);
let Router = createRouterComponent(router);
let tree = renderer.create(
<Router>
<AsyncLink name="Blork">
{navigating => {
return <Text>{navigating.toString()}</Text>;
}}
</AsyncLink>
</Router>
);
let anchor = tree.root.findByType(TouchableHighlight);
await act(async () => {
anchor.props.onPress(fakeEvent());
});
tree.unmount();
});
});
describe("onNav", () => {
it("calls onNav prop func if provided", async () => {
let mockNavigate = jest.fn();
let onNav = jest.fn();
let routes = prepareRoutes([
{ name: "Test", path: "" },
{ name: "Catch All", path: "(.*)" }
]);
let router = createRouter(inMemory, routes);
router.history.navigate = mockNavigate;
let Router = createRouterComponent(router);
let tree = renderer.create(
<Router>
<AsyncLink name="Test" onNav={onNav}>
{navigating => <Text>{navigating}</Text>}
</AsyncLink>
</Router>
);
let anchor = tree.root.findByType(TouchableHighlight);
await act(async () => {
anchor.props.onPress(fakeEvent());
});
expect(mockNavigate.mock.calls.length).toBe(1);
expect(onNav.mock.calls.length).toBe(1);
expect(mockNavigate.mock.calls.length).toBe(1);
});
it("does not call history.navigate if onNav prevents default", () => {
let mockNavigate = jest.fn();
let onNav = jest.fn(event => {
event.preventDefault();
});
let routes = prepareRoutes([
{ name: "Test", path: "" },
{ name: "Catch All", path: "(.*)" }
]);
let router = createRouter(inMemory, routes);
router.history.navigate = mockNavigate;
let Router = createRouterComponent(router);
let tree = renderer.create(
<Router>
<AsyncLink name="Test" onNav={onNav}>
{navigating => <Text>{navigating}</Text>}
</AsyncLink>
</Router>
);
let anchor = tree.root.findByType(TouchableHighlight);
anchor.props.onPress(fakeEvent());
expect(onNav.mock.calls.length).toBe(1);
expect(mockNavigate.mock.calls.length).toBe(0);
});
});
it("doesn't call history.navigate if event.preventDefault has been called", () => {
let mockNavigate = jest.fn();
let routes = prepareRoutes([
{ name: "Test", path: "" },
{ name: "Catch All", path: "(.*)" }
]);
let router = createRouter(inMemory, routes);
router.history.navigate = mockNavigate;
let Router = createRouterComponent(router);
let tree = renderer.create(
<Router>
<AsyncLink name="Test">
{navigating => <Text>{navigating}</Text>}
</AsyncLink>
</Router>
);
let anchor = tree.root.findByType(TouchableHighlight);
anchor.props.onPress(fakeEvent({ defaultPrevented: true }));
expect(mockNavigate.mock.calls.length).toBe(0);
});
});
}); | the_stack |
import config from '../util/config'
import logger from '../util/logger'
import { users } from './user'
import { branches as globalBranches, BranchController, Branch } from './branch'
import { messages, TextMessage, Message, ServerMessage } from './message'
import { NLU } from './nlu'
import { Envelope } from './envelope'
import { State } from './state'
import dialogues from './dialogue'
import { store } from './store'
import { IContext } from './server'
import { adapters } from './adapter'
import middlewares, { Middleware } from './middleware'
/** Options for defining thought process. */
export interface IThought {
name: string
b: State
validate?: () => Promise<boolean> | boolean
action?: (success: boolean) => Promise<any> | any
branches?: { [id: string]: Branch }
middleware?: Middleware
}
/**
* Defines a process to wrap execution of middleware of the same name.
* Validators can prevent a process from running.
* Actions can effect the state before the next process validates.
*/
export class Thought implements IThought {
name: string
b: State
validate: () => Promise<boolean> | boolean = () => Promise.resolve(true)
action: (success: boolean) => Promise<any> | any = (_) => Promise.resolve()
middleware: Middleware
branches?: { [id: string]: Branch }
/**
* Create new thought process with optional validate and action functions.
* Presence of branches in options determines how middleware will execute.
* Without middleware option, will the middleware of same name as the thought.
*/
constructor (atts: IThought) {
this.name = atts.name
this.b = atts.b
if (atts.validate) this.validate = atts.validate
if (atts.action) this.action = atts.action
if (atts.branches) this.branches = atts.branches
this.middleware = (atts.middleware)
? atts.middleware
: middlewares.get(this.name)
}
/**
* Call validate, execute middleware, possibly branches, then action.
* Will not enter process with empty branches or if state `done` is true.
* Without branches, execute middleware, resolve on completion.
* With branches, process each branch or until state `done` is true.
* Action will be called with the boolean success of the process.
* Process succeeds if middleware completed or branches were matched.
* If process succeeds, timestamp is added to state.
*/
async process () {
if (this.b.exit) return Promise.resolve()
return new Promise((resolve, reject) => {
const { b, name, validate, middleware, branches } = this
if (typeof branches !== 'undefined') {
if (Object.keys(branches).length === 0) {
logger.debug(`[thought] skip ${name}, no branches to process`)
return reject()
}
if (b.done) {
logger.debug(`[thought] skip ${name}, branch processing is done`)
return reject()
}
}
Promise.resolve(validate())
.then(async (valid) => {
if (!valid) return reject()
const branchCount = Object.keys(this.branches || {}).length
const branchDetail = (branchCount)
? ` against ${branchCount} branch${branchCount > 1 ? 'es' : ''}`
: ``
if (b.message) {
logger.debug(`[thought] ${name} processing incoming message ID ${b.message.id}${branchDetail}`)
} else if (b.envelopes) {
logger.debug(`[thought] ${name} processing outgoing envelopes${branchDetail}`)
}
if (typeof branches === 'undefined') return middleware.execute(b, resolve).then(reject)
for (let id in branches) {
if (b.done) break
await branches[id].execute(b, middleware)
}
return (b.matched) ? resolve() : reject()
})
.catch((err) => {
logger.debug(`[thought] ${name} validation error ${err.message}`)
reject(err)
})
})
.then(() => {
if (!this.b.processed[this.name]) this.b.processed[this.name] = Date.now()
return this.action(true)
})
.catch((err) => {
if (err instanceof Error) {
logger.error(`[thought] ${this.name} error, ${err.message}`)
throw err
}
return this.action(false)
})
}
}
/** Collection of Thought instances, extends object. */
export type ThoughtProcesses = object & { [key: string]: Thought }
/**
* Collection of processes and branches to execute with middleware and state.
* Will use global branches by default, but can be replaced with custom set.
* Sequence arrays define orders of named processes, to run consecutively.
* Default sequences are `receive` and `dispatch` to process incoming/outgoing.
* Each process may have a `validate` method to run before processing and an
* `action` method to run after. Validate returning false will skip the process.
*/
export class Thoughts {
b: State
branches: BranchController
sequence: { [key: string]: string[] } = {
serve: ['hear', 'serve', 'act', 'remember'],
receive: ['hear', 'listen', 'understand', 'act', 'remember'],
respond: ['respond'],
dispatch: ['respond', 'remember']
}
processes: ThoughtProcesses
/**
* Start new instance of thought processes with optional branches to process.
* By default will process global branches, but can accept an isolated
* branches for specific conversational context.
*/
constructor (
state: State,
initBranches?: BranchController
) {
this.b = state
this.branches = (initBranches)
? new BranchController(initBranches)
: new BranchController(globalBranches)
const { b } = this
// Define processes with validation and post processing actions
this.processes = {
hear: new Thought({
name: 'hear', b
}),
listen: new Thought({
name: 'listen', b, branches: this.branches.listen
}),
understand: new Thought({
name: 'understand', b, branches: this.branches.understand
}),
serve: new Thought({
name: 'serve', b, branches: this.branches.serve
}),
act: new Thought({
name: 'act', b, branches: this.branches.act
}),
respond: new Thought({
name: 'respond', b
}),
remember: new Thought({
name: 'remember', b
})
}
// Ignore all further branches if hear process interrupted
this.processes.hear.action = async (success: boolean) => {
if (!success) this.b.finish()
}
// Only processed forced understand branches if listen branches matched
this.processes.listen.action = async (success: boolean) => {
if (success) this.branches.forced('understand')
}
// Get NLU result before processing NLU branches and only if required
this.processes.understand.validate = async () => {
if (!adapters.loaded.nlu) {
logger.debug(`[thought] skip understand, no nlu adapter`)
} else if (!(this.b.message instanceof TextMessage)) {
logger.debug(`[thought] skip understand, not a text message`)
} else if (this.b.message.toString().trim() === '') {
logger.debug(`[thought] skip understand, message text is empty`)
} else if (
config.get('nlu-min-length') &&
this.b.message.toString().trim().length < config.get('nlu-min-length')
) {
logger.debug(`[thought] skip understand, message text too short`)
} else {
const nluResultsRaw = await adapters.loaded.nlu.process(this.b.message)
if (!nluResultsRaw || Object.keys(nluResultsRaw).length === 0) {
logger.error(`[thought] nlu processing returned empty`)
} else {
this.b.message.nlu = new NLU().addResults(nluResultsRaw)
logger.info(`[thought] nlu processed ${this.b.message.nlu.printResults()}`)
return true
}
}
return false
}
// Wrap message in catch all before processing act branches
this.processes.act.validate = async () => {
if (this.b.matched) {
logger.debug(`[thought] found match, clearing unforced catch branches`)
this.branches.forced('act')
}
if (!this.branches.exist('act')) {
logger.debug(`[thought] no catch branches remain, ending processing`)
return false
}
if (this.b.message) {
if (this.b.matched) logger.debug(`[thought] message matched, processing forced catch`)
else logger.debug(`[thought] message unmatched, replacing with catch message type`)
this.b.message = messages.catchAll(this.b.message)
}
return true
}
// Connect response envelope to last branch before processing respond
this.processes.respond.validate = async () => {
if (!adapters.loaded.message) {
logger.error(`[thought] message adapter not found`)
return false
}
const envelope = this.b.pendingEnvelope()
if (!envelope) return false
if (this.b.matchingBranch) envelope.branchId = this.b.matchingBranch.id
return true
}
// Don't respond unless middleware completed (timestamped) with envelope
this.processes.respond.action = async (success: boolean) => {
if (success) {
const envelope = this.b.respondEnvelope()
await adapters.loaded.message!.dispatch(envelope)
envelope.responded = Date.now()
}
}
// Don't remember states with unmatched messages
this.processes.remember.validate = async () => {
if (this.b.sequence === 'respond') {
logger.debug(`[thought] skip remember on respond`)
} else if (!adapters.loaded.storage) {
logger.debug(`[thought] skip remember, no storage adapter`)
} else {
logger.debug(`[thought] remembering ${this.b.matched ? 'matched state and user' : 'unmatched state'}`)
if (this.b.matched) users.byId(this.b.message.user.id, this.b.message.user)
return true
}
return false
}
// Don't remember unless middleware completed (timestamped)
this.processes.remember.action = async (success) => {
if (success) await store.keep('states', this.b)
}
}
/** Begin processing each thought in defined sequence. */
async start (sequence: string) {
if (!this.sequence[sequence]) throw new Error('[thought] invalid sequence')
if (!this.b.sequence) this.b.sequence = sequence
for (let process of this.sequence[sequence]) {
await this.processes[process].process()
}
return this.b
}
}
/** Control creation of thought processes for incoming/outgoing sequences. */
export class ThoughtController {
/**
* Initiate sequence of thought processes for an incoming message.
* Branch callbacks may also respond. Final state is remembered.
*
* If audience is engaged in dialogue, use the isolated dialogue path instead of
* default "global" path. The dialogue path is then progressed to a clean path,
* to allow adding a new set of branches upon matching the current ones.
* If no branches matched, no new branches would be added to the new path, so
* we revert to the previous path (the one that was just processed). If branches
* matched, but no additional branches added, close the dialogue.
*/
async receive (
message: Message,
branches?: BranchController
) {
logger.info(`[thought] receive message ID ${message.id}`)
const startingState = new State({ message })
const dlg = dialogues.engaged(startingState)
if (dlg && !branches) branches = dlg.progressBranches()
const thought = new Thoughts(startingState, branches)
const finalState = await thought.start('receive')
if (dlg) {
if (!finalState.resolved) dlg.revertBranches()
else if (!dlg.branches.exist()) await dlg.close()
logger.debug(JSON.stringify(dlg.branches))
}
return finalState
}
/** Initiate chain of thought processes for responding to a server request. */
async serve (
message: ServerMessage,
context: IContext,
branches?: BranchController
) {
logger.info(`[thought] serving ${message.id} for ${message.user.id}`)
const startingState = new State({ message, context })
const dlg = dialogues.engaged(startingState)
if (dlg && !branches) branches = dlg.progressBranches()
const thought = new Thoughts(startingState, branches)
const finalState = await thought.start('serve')
if (dlg) {
if (!finalState.matched) dlg.revertBranches()
else if (dlg.branches.exist()) await dlg.close()
}
return finalState
}
/**
* Initiate a response from an existing state. Sequence does not remember
* because it will usually by triggered from within the `receive` sequence.
*/
async respond (b: State) {
if (!b.matchingBranch) logger.info(`[thought] respond without matched branch`)
else logger.info(`[thought] respond to matched branch ${b.matchingBranch.id}`)
return new Thoughts(b).start('respond')
}
/**
* Initiate chain of thought processes for an outgoing envelope.
* This is for sending unprompted by a branch. Final state is remembered.
*/
async dispatch (envelope: Envelope) {
logger.info(`[thought] dispatch envelope ${envelope.id}`)
return new Thoughts(new State({ envelopes: [envelope] })).start('dispatch')
}
}
export const thoughts = new ThoughtController()
export default thoughts | the_stack |
import {Mutable, FromAny, AnyTiming, Timing, Easing, Interpolator} from "@swim/util";
import {Affinity} from "../fastener/Affinity";
import type {FastenerOwner, FastenerFlags} from "../fastener/Fastener";
import {PropertyInit, PropertyClass, Property} from "../property/Property";
import {StringAnimator} from "./"; // forward import
import {NumberAnimator} from "./"; // forward import
import {BooleanAnimator} from "./"; // forward import
/** @internal */
export type MemberAnimatorValue<O, K extends keyof O> =
O[K] extends Animator<any, infer T> ? T : never;
/** @internal */
export type MemberAnimatorValueInit<O, K extends keyof O> =
O[K] extends Animator<any, any, infer U> ? U : never;
/** @internal */
export type MemberAnimatorInit<O, K extends keyof O> =
O[K] extends Animator<any, infer T, infer U> ? T | U : never;
/** @internal */
export type MemberAnimatorInitMap<O> =
{-readonly [K in keyof O as O[K] extends Property<any, any> ? K : never]?: MemberAnimatorInit<O, K>};
/** @internal */
export type AnimatorValue<A extends Animator<any, any>> =
A extends Animator<any, infer T, any> ? T : never;
/** @internal */
export type AnimatorValueInit<A extends Animator<any, any>> =
A extends Animator<any, infer T, infer U> ? T | U : never;
/** @public */
export interface AnimatorInit<T = unknown, U = never> extends PropertyInit<T, U> {
extends?: {prototype: Animator<any, any>} | string | boolean | null;
transformState?(state: T): T;
willSetState?(newState: T, oldState: T): void;
didSetState?(newState: T, oldState: T): void;
willStartTweening?(): void;
didStartTweening?(): void;
willStopTweening?(): void;
didStopTweening?(): void;
willTransition?(oldValue: T): void;
didTransition?(newValue: T): void;
didInterrupt?(value: T): void;
}
/** @public */
export type AnimatorDescriptor<O = unknown, T = unknown, U = T, I = {}> = ThisType<Animator<O, T, U> & I> & AnimatorInit<T, U> & Partial<I>;
/** @public */
export interface AnimatorClass<A extends Animator<any, any> = Animator<any, any>> extends PropertyClass<A> {
/** @internal */
readonly TweeningFlag: FastenerFlags;
/** @internal */
readonly DivergedFlag: FastenerFlags;
/** @internal */
readonly InterruptFlag: FastenerFlags;
/** @internal @override */
readonly FlagShift: number;
/** @internal @override */
readonly FlagMask: FastenerFlags;
}
/** @public */
export interface AnimatorFactory<A extends Animator<any, any> = Animator<any, any>> extends AnimatorClass<A> {
extend<I = {}>(className: string, classMembers?: Partial<I> | null): AnimatorFactory<A> & I;
specialize(type: unknown): AnimatorFactory | null;
define<O, T, U = T>(className: string, descriptor: AnimatorDescriptor<O, T, U>): AnimatorFactory<Animator<any, T, U>>;
define<O, T, U = T, I = {}>(className: string, descriptor: {implements: unknown} & AnimatorDescriptor<O, T, U, I>): AnimatorFactory<Animator<any, T, U> & I>;
<O, T extends string | undefined = string | undefined, U extends string | undefined = string | undefined>(descriptor: {type: typeof String} & AnimatorDescriptor<O, T, U>): PropertyDecorator;
<O, T extends number | undefined = number | undefined, U extends number | string | undefined = number | string | undefined>(descriptor: {type: typeof Number} & AnimatorDescriptor<O, T, U>): PropertyDecorator;
<O, T extends boolean | undefined = boolean | undefined, U extends boolean | string | undefined = boolean | string | undefined>(descriptor: {type: typeof Boolean} & AnimatorDescriptor<O, T, U>): PropertyDecorator;
<O, T, U = T>(descriptor: ({type: FromAny<T, U>} | {fromAny(value: T | U): T}) & AnimatorDescriptor<O, T, U>): PropertyDecorator;
<O, T, U = T>(descriptor: AnimatorDescriptor<O, T, U>): PropertyDecorator;
<O, T, U = T, I = {}>(descriptor: {implements: unknown} & AnimatorDescriptor<O, T, U, I>): PropertyDecorator;
}
/** @public */
export interface Animator<O = unknown, T = unknown, U = T> extends Property<O, T, U> {
(): T;
(newState: T | U, timingOrAffinity: Affinity | AnyTiming | boolean | null | undefined): O;
(newState: T | U, timing?: AnyTiming | boolean | null, affinity?: Affinity): O;
/** @protected @override */
onInherit(superFastener: Property<unknown, T>): void;
/** @override */
setValue(newValue: T | U, affinity?: Affinity): void;
get superState(): T | undefined;
getSuperState(): NonNullable<T>;
getSuperStateOr<E>(elseState: E): NonNullable<T> | E;
readonly state: T;
getState(): NonNullable<T>;
getStateOr<E>(elseState: E): NonNullable<T> | E;
transformState(state: T): T;
setState(newState: T | U, timingOrAffinity: Affinity | AnyTiming | boolean | null | undefined): void;
setState(newState: T | U, timing?: AnyTiming | boolean | null, affinity?: Affinity): void;
/** @protected */
willSetState(newstate: T, oldState: T): void;
/** @protected */
onSetState(newstate: T, oldState: T): void;
/** @protected */
didSetState(newstate: T, oldState: T): void;
readonly timing: Timing | null;
readonly interpolator: Interpolator<T> | null;
setInterpolatedValue(newValue: T, newState?: T): void;
/** @internal @protected @override */
decohereSubFastener(subFastener: Property<unknown, T>): void;
/** @override */
recohere(t: number): void;
/** @internal @protected */
tween(t: number): void;
/** @internal @protected */
tweenInherited(t: number): void;
/**
* Returns `true` if this animator is actively transitioning to a new `state`.
*/
get tweening(): boolean;
/** @internal */
startTweening(): void;
/** @protected */
willStartTweening(): void;
/** @protected */
onStartTweening(): void;
/** @protected */
didStartTweening(): void;
/** @internal */
stopTweening(): void;
/** @protected */
willStopTweening(): void;
/** @protected */
onStopTweening(): void;
/** @protected */
didStopTweening(): void;
/** @internal @protected */
willTransition(oldValue: T): void;
/** @internal @protected */
didTransition(newValue: T): void;
/** @internal @protected */
didInterrupt(value: T): void;
/** @protected @override */
onUnmount(): void;
}
/** @public */
export const Animator = (function (_super: typeof Property) {
const Animator: AnimatorFactory = _super.extend("Animator");
Animator.prototype.onInherit = function <T>(this: Animator<unknown, T>, superFastener: Property<unknown, T>): void {
let newValue: T;
let newState: T;
if (superFastener instanceof Animator) {
newValue = this.transformSuperValue(superFastener.value);
newState = this.transformSuperValue(superFastener.state);
} else {
newValue = this.transformSuperValue(superFastener.value);
newState = newValue;
}
const oldState = this.state;
const stateChanged = !this.equalValues(newState, oldState);
if (stateChanged) {
this.willSetState(newState, oldState);
(this as Mutable<typeof this>).state = newState;
(this as Mutable<typeof this>).timing = null;
(this as Mutable<typeof this>).interpolator = null;
this.onSetState(newState, oldState);
}
this.setValue(newValue, Affinity.Reflexive);
if (stateChanged) {
this.didSetState(newState, oldState);
if ((this.flags & Animator.TweeningFlag) !== 0) {
this.didInterrupt(this.value);
}
}
if (superFastener instanceof Animator && (superFastener.flags & Animator.TweeningFlag) !== 0) {
this.startTweening();
} else {
this.stopTweening();
}
};
Animator.prototype.setValue = function <T, U>(this: Animator<unknown, T, U>, newValue: T | U, affinity?: Affinity): void {
if (affinity === void 0) {
affinity = Affinity.Extrinsic;
}
if (this.minAffinity(affinity)) {
newValue = this.fromAny(newValue);
newValue = this.transformValue(newValue);
const oldValue = this.value;
if (!this.equalValues(newValue, oldValue)) {
this.willSetValue(newValue, oldValue!);
(this as Mutable<typeof this>).value = newValue;
this.onSetValue(newValue, oldValue!);
this.didSetValue(newValue, oldValue!);
this.decohereSubFasteners();
}
}
};
Object.defineProperty(Animator.prototype, "superState", {
get: function <T>(this: Animator<unknown, T>): T | undefined {
const superFastener = this.superFastener;
return superFastener instanceof Animator ? superFastener.state : void 0;
},
configurable: true,
});
Animator.prototype.getSuperState = function <T>(this: Animator<unknown, T>): NonNullable<T> {
const superState = this.superState;
if (superState === void 0 || superState === null) {
let message = superState + " ";
if (this.name.length !== 0) {
message += this.name + " ";
}
message += "super state";
throw new TypeError(message);
}
return superState as NonNullable<T>;
};
Animator.prototype.getSuperStateOr = function <T, E>(this: Animator<unknown, T>, elseState: E): NonNullable<T> | E {
let superState: T | E | undefined = this.superState;
if (superState === void 0 || superState === null) {
superState = elseState;
}
return superState as NonNullable<T> | E;
};
Animator.prototype.getState = function <T>(this: Animator<unknown, T>): NonNullable<T> {
const state = this.state;
if (state === void 0 || state === null) {
let message = state + " ";
if (this.name.length !== 0) {
message += this.name + " ";
}
message += "state";
throw new TypeError(message);
}
return state as NonNullable<T>;
};
Animator.prototype.getStateOr = function <T, E>(this: Animator<unknown, T>, elseState: E): NonNullable<T> | E {
let state: T | E = this.state;
if (state === void 0 || state === null) {
state = elseState;
}
return state as NonNullable<T> | E;
};
Animator.prototype.transformState = function <T>(this: Animator<unknown, T>, state: T): T {
return state;
};
Animator.prototype.setState = function <T, U>(this: Animator<unknown, T, U>, newState: T | U, timing?: Affinity | AnyTiming | boolean | null, affinity?: Affinity): void {
if (typeof timing === "number") {
affinity = timing;
timing = void 0;
}
if (affinity === void 0) {
affinity = Affinity.Extrinsic;
}
if (this.minAffinity(affinity)) {
newState = this.fromAny(newState);
newState = this.transformState(newState);
const oldState = this.state;
if (!this.equalValues(newState, oldState)) {
if (timing === void 0 || timing === null || timing === false) {
timing = false;
} else if (timing === true) {
timing = this.timing !== null ? this.timing : false;
} else {
timing = Timing.fromAny(timing);
}
const animated = timing !== false && this.definedValue(oldState);
this.willSetState(newState, oldState);
(this as Mutable<typeof this>).state = newState;
if (animated) {
(this as Mutable<typeof this>).timing = timing as Timing;
(this as Mutable<typeof this>).interpolator = Interpolator(this.value, newState);
if ((this.flags & Animator.TweeningFlag) !== 0) {
this.setFlags(this.flags | (Animator.DivergedFlag | Animator.InterruptFlag));
} else {
this.setFlags(this.flags | Animator.DivergedFlag);
}
} else {
(this as Mutable<typeof this>).timing = null;
(this as Mutable<typeof this>).interpolator = null;
}
this.onSetState(newState, oldState);
if (!animated) {
this.setValue(newState, Affinity.Reflexive);
}
this.didSetState(newState, oldState);
if (animated) {
this.startTweening();
} else if ((this.flags & Animator.TweeningFlag) !== 0) {
this.didInterrupt(this.value);
this.stopTweening();
}
}
}
};
Animator.prototype.willSetState = function <T>(this: Animator<unknown, T>, newState: T, oldState: T): void {
// hook
};
Animator.prototype.onSetState = function <T>(this: Animator<unknown, T>, newState: T, oldState: T): void {
// hook
};
Animator.prototype.didSetState = function <T>(this: Animator<unknown, T>, newState: T, oldState: T): void {
// hook
};
Animator.prototype.setInterpolatedValue = function <T>(this: Animator<unknown, T>, newValue: T, newState?: T): void {
const oldState = arguments.length > 1 ? this.state : void 0;
const stateChanged = arguments.length > 1 && !this.equalValues(newState!, oldState);
if (stateChanged) {
this.willSetState(newState!, oldState!);
(this as Mutable<typeof this>).state = newState!;
(this as Mutable<typeof this>).timing = null;
(this as Mutable<typeof this>).interpolator = null;
this.onSetState(newState!, oldState!);
}
this.setValue(newValue, Affinity.Reflexive);
if (stateChanged) {
this.didSetState(newState!, oldState!);
if ((this.flags & Animator.TweeningFlag) !== 0) {
this.didInterrupt(this.value);
this.stopTweening();
}
}
};
Animator.prototype.decohereSubFastener = function (this: Animator, subFastener: Property): void {
if ((subFastener.flags & Animator.InheritedFlag) === 0 && Math.min(this.flags & Affinity.Mask, Affinity.Intrinsic) >= (subFastener.flags & Affinity.Mask)) {
subFastener.setInherited(true, this);
} else if ((subFastener.flags & Animator.InheritedFlag) !== 0) {
if ((this.flags & Animator.TweeningFlag) !== 0 && subFastener instanceof Animator) {
subFastener.startTweening();
}
if ((subFastener.flags & Animator.DecoherentFlag) === 0) {
subFastener.setCoherent(false);
subFastener.decohere();
}
}
};
Animator.prototype.recohere = function <T>(this: Animator<unknown, T>, t: number): void {
const flags = this.flags;
if ((flags & Animator.InheritedFlag) !== 0) {
this.tweenInherited(t);
} else if ((flags & Animator.TweeningFlag) !== 0) {
this.tween(t);
}
};
Animator.prototype.tween = function <T>(this: Animator<unknown, T>, t: number): void {
const oldValue = this.value;
let timing = this.timing;
if (timing === null) {
timing = Easing.linear.withDomain(t, t);
(this as Mutable<typeof this>).timing = timing;
}
let interpolator = this.interpolator;
if (interpolator === null) {
interpolator = Interpolator(oldValue, this.state);
(this as Mutable<typeof this>).interpolator = interpolator;
}
if ((this.flags & Animator.InterruptFlag) !== 0) {
this.setFlags(this.flags & ~Animator.InterruptFlag);
this.didInterrupt(oldValue);
}
if ((this.flags & Animator.DivergedFlag) !== 0) {
this.setFlags(this.flags & ~Animator.DivergedFlag);
if (!this.equalValues(this.state, oldValue)) {
timing = timing.withDomain(t, t + timing.duration);
} else {
timing = timing.withDomain(t - timing.duration, t);
}
(this as Mutable<typeof this>).timing = timing;
this.willTransition(oldValue);
}
const u = timing(t);
const newValue = interpolator(u);
this.setValue(newValue, Affinity.Reflexive);
if (u < 1) {
this.decohere();
} else if ((this.flags & Animator.TweeningFlag) !== 0) {
this.stopTweening();
(this as Mutable<typeof this>).interpolator = null;
this.didTransition(this.value);
} else {
this.setCoherent(true);
}
};
Animator.prototype.tweenInherited = function <T>(this: Animator<unknown, T>, t: number): void {
const superFastener = this.superFastener;
if (superFastener !== null) {
let newValue: T;
let newState: T;
if (superFastener instanceof Animator) {
newValue = this.transformSuperValue(superFastener.value);
newState = this.transformSuperValue(superFastener.state);
} else {
newValue = this.transformSuperValue(superFastener.value);
newState = newValue;
}
const oldState = this.state;
const stateChanged = !this.equalValues(newState, oldState);
if (stateChanged) {
this.willSetState(newState, oldState);
(this as Mutable<typeof this>).state = newState!;
(this as Mutable<typeof this>).timing = null;
(this as Mutable<typeof this>).interpolator = null;
this.onSetState(newState, oldState);
}
this.setValue(newValue, Affinity.Reflexive);
if (stateChanged) {
this.didSetState(newState, oldState!);
if ((this.flags & Animator.TweeningFlag) !== 0) {
this.didInterrupt(this.value);
}
}
if (superFastener instanceof Animator && (superFastener.flags & Animator.TweeningFlag) !== 0) {
this.decohere();
} else if ((this.flags & Animator.TweeningFlag) !== 0) {
this.stopTweening();
} else {
this.setCoherent(true);
}
} else {
this.stopTweening();
}
};
Object.defineProperty(Animator.prototype, "tweening", {
get: function (this: Animator): boolean {
return (this.flags & Animator.TweeningFlag) !== 0;
},
configurable: true,
});
Animator.prototype.startTweening = function (this: Animator): void {
if ((this.flags & Animator.TweeningFlag) === 0) {
this.willStartTweening();
this.setFlags(this.flags | Animator.TweeningFlag);
this.onStartTweening();
this.didStartTweening();
}
};
Animator.prototype.willStartTweening = function (this: Animator): void {
// hook
};
Animator.prototype.onStartTweening = function (this: Animator): void {
if ((this.flags & Animator.DecoherentFlag) === 0) {
this.setCoherent(false);
this.decohere();
}
this.decohereSubFasteners();
};
Animator.prototype.didStartTweening = function (this: Animator): void {
// hook
};
Animator.prototype.stopTweening = function (this: Animator): void {
if ((this.flags & Animator.TweeningFlag) !== 0) {
this.willStopTweening();
this.setFlags(this.flags & ~Animator.TweeningFlag);
this.onStopTweening();
this.didStopTweening();
}
};
Animator.prototype.willStopTweening = function (this: Animator): void {
// hook
};
Animator.prototype.onStopTweening = function (this: Animator): void {
this.setCoherent(true);
};
Animator.prototype.didStopTweening = function (this: Animator): void {
// hook
};
Animator.prototype.willTransition = function <T>(this: Animator<unknown, T>, oldValue: T): void {
// hook
};
Animator.prototype.didTransition = function <T>(this: Animator<unknown, T>, newValue: T): void {
// hook
};
Animator.prototype.didInterrupt = function <T>(this: Animator<unknown, T>, value: T): void {
// hook
};
Animator.prototype.onUnmount = function (this: Animator): void {
this.stopTweening();
_super.prototype.onUnmount.call(this);
};
Animator.construct = function <A extends Animator<any, any>>(animatorClass: {prototype: A}, animator: A | null, owner: FastenerOwner<A>): A {
if (animator === null) {
animator = function (state?: AnimatorValueInit<A>, timing?: Affinity | AnyTiming | boolean | null, affinity?: Affinity): AnimatorValue<A> | FastenerOwner<A> {
if (arguments.length === 0) {
return animator!.value;
} else {
if (arguments.length === 2) {
animator!.setState(state!, timing);
} else {
animator!.setState(state!, timing as AnyTiming | boolean | null | undefined, affinity);
}
return animator!.owner;
}
} as A;
delete (animator as Partial<Mutable<A>>).name; // don't clobber prototype name
Object.setPrototypeOf(animator, animatorClass.prototype);
}
animator = _super.construct(animatorClass, animator, owner) as A;
(animator as Mutable<typeof animator>).state = animator.value;
(animator as Mutable<typeof animator>).timing = null;
(animator as Mutable<typeof animator>).interpolator = null;
return animator;
};
Animator.specialize = function (type: unknown): AnimatorFactory | null {
if (type === String) {
return StringAnimator;
} else if (type === Number) {
return NumberAnimator;
} else if (type === Boolean) {
return BooleanAnimator;
}
return null;
};
Animator.define = function <O, T, U>(className: string, descriptor: AnimatorDescriptor<O, T, U>): AnimatorFactory<Animator<any, T, U>> {
let superClass = descriptor.extends as AnimatorFactory | null | undefined;
const affinity = descriptor.affinity;
const inherits = descriptor.inherits;
const value = descriptor.value;
const initValue = descriptor.initValue;
delete descriptor.extends;
delete descriptor.implements;
delete descriptor.affinity;
delete descriptor.inherits;
delete descriptor.value;
delete descriptor.initValue;
if (superClass === void 0 || superClass === null) {
superClass = this.specialize(descriptor.type);
}
if (superClass === null) {
superClass = this;
if (descriptor.fromAny === void 0 && FromAny.is<T, U>(descriptor.type)) {
descriptor.fromAny = descriptor.type.fromAny;
}
}
const animatorClass = superClass.extend(className, descriptor);
animatorClass.construct = function (animatorClass: {prototype: Animator<any, any>}, animator: Animator<O, T, U> | null, owner: O): Animator<O, T, U> {
animator = superClass!.construct(animatorClass, animator, owner);
if (affinity !== void 0) {
animator.initAffinity(affinity);
}
if (inherits !== void 0) {
animator.initInherits(inherits);
}
if (initValue !== void 0) {
(animator as Mutable<typeof animator>).value = animator.fromAny(initValue());
(animator as Mutable<typeof animator>).state = animator.value;
} else if (value !== void 0) {
(animator as Mutable<typeof animator>).value = animator.fromAny(value);
(animator as Mutable<typeof animator>).state = animator.value;
}
return animator;
};
return animatorClass;
};
(Animator as Mutable<typeof Animator>).TweeningFlag = 1 << (_super.FlagShift + 0);
(Animator as Mutable<typeof Animator>).DivergedFlag = 1 << (_super.FlagShift + 1);
(Animator as Mutable<typeof Animator>).InterruptFlag = 1 << (_super.FlagShift + 2);
(Animator as Mutable<typeof Animator>).FlagShift = _super.FlagShift + 3;
(Animator as Mutable<typeof Animator>).FlagMask = (1 << Animator.FlagShift) - 1;
return Animator;
})(Property); | the_stack |
import { Component, Input, OnInit, ViewChild, ElementRef, Type, OnDestroy } from '@angular/core';
import { FormControl } from '@angular/forms';
import { CoreError } from '@classes/errors/error';
import { CoreFileUploader, CoreFileUploaderStoreFilesResult } from '@features/fileuploader/services/fileuploader';
import { CoreFile } from '@services/file';
import { CoreFileEntry, CoreFileHelper } from '@services/file-helper';
import { CoreFileSession } from '@services/file-session';
import { CoreSites } from '@services/sites';
import { CoreSync } from '@services/sync';
import { CoreDomUtils } from '@services/utils/dom';
import { CoreTextUtils } from '@services/utils/text';
import { CoreUtils } from '@services/utils/utils';
import { Translate } from '@singletons';
import { CoreEventObserver, CoreEvents } from '@singletons/events';
import { CoreFormFields, CoreForms } from '@singletons/form';
import { AddonWorkshopAssessmentStrategyDelegate } from '../../services/assessment-strategy-delegate';
import {
AddonModWorkshopProvider,
AddonModWorkshopOverallFeedbackMode,
AddonModWorkshop,
AddonModWorkshopData,
AddonModWorkshopGetWorkshopAccessInformationWSResponse,
AddonModWorkshopGetAssessmentFormFieldsParsedData,
} from '../../services/workshop';
import { AddonModWorkshopHelper, AddonModWorkshopSubmissionAssessmentWithFormData } from '../../services/workshop-helper';
import { AddonModWorkshopOffline } from '../../services/workshop-offline';
/**
* Component that displays workshop assessment strategy form.
*/
@Component({
selector: 'addon-mod-workshop-assessment-strategy',
templateUrl: 'addon-mod-workshop-assessment-strategy.html',
})
export class AddonModWorkshopAssessmentStrategyComponent implements OnInit, OnDestroy {
@Input() workshop!: AddonModWorkshopData;
@Input() access!: AddonModWorkshopGetWorkshopAccessInformationWSResponse;
@Input() assessmentId!: number;
@Input() userId!: number;
@Input() strategy!: string;
@Input() edit = false;
@ViewChild('assessmentForm') formElement!: ElementRef;
componentClass?: Type<unknown>;
data: AddonModWorkshopAssessmentStrategyData = {
workshopId: 0,
assessment: undefined,
edit: false,
selectedValues: [],
fieldErrors: {},
strategy: '',
moduleId: 0,
courseId: undefined,
};
assessmentStrategyLoaded = false;
notSupported = false;
feedbackText = '';
feedbackControl = new FormControl();
overallFeedkback = false;
overallFeedkbackRequired = false;
component = AddonModWorkshopProvider.COMPONENT;
componentId?: number;
weights: number[] = [];
weight?: number;
protected obsInvalidated?: CoreEventObserver;
protected hasOffline = false;
protected originalData: {
text: string;
files: CoreFileEntry[];
weight: number;
selectedValues: AddonModWorkshopGetAssessmentFormFieldsParsedData[];
} = {
text: '',
files: [],
weight: 1,
selectedValues: [],
};
/**
* Component being initialized.
*/
async ngOnInit(): Promise<void> {
if (!this.assessmentId || !this.strategy) {
this.assessmentStrategyLoaded = true;
return;
}
this.data.workshopId = this.workshop.id;
this.data.edit = this.edit;
this.data.strategy = this.strategy;
this.data.moduleId = this.workshop.coursemodule;
this.data.courseId = this.workshop.course;
this.componentClass = AddonWorkshopAssessmentStrategyDelegate.getComponentForPlugin(this.strategy);
if (this.componentClass) {
this.overallFeedkback = this.workshop.overallfeedbackmode != AddonModWorkshopOverallFeedbackMode.DISABLED;
this.overallFeedkbackRequired =
this.workshop.overallfeedbackmode == AddonModWorkshopOverallFeedbackMode.ENABLED_REQUIRED;
this.componentId = this.workshop.coursemodule;
// Load Weights selector.
if (this.edit && this.access.canallocate) {
this.weights;
for (let i = 16; i >= 0; i--) {
this.weights[i] = i;
}
}
// Check if rich text editor is enabled.
if (this.edit) {
// Block the workshop.
CoreSync.blockOperation(AddonModWorkshopProvider.COMPONENT, this.workshop.id);
}
try {
await this.load();
this.obsInvalidated = CoreEvents.on(
AddonModWorkshopProvider.ASSESSMENT_INVALIDATED,
this.load.bind(this),
CoreSites.getCurrentSiteId(),
);
} catch (error) {
this.componentClass = undefined;
CoreDomUtils.showErrorModalDefault(error, 'Error loading assessment.');
} finally {
this.assessmentStrategyLoaded = true;
}
} else {
// Helper data and fallback.
this.notSupported = !AddonWorkshopAssessmentStrategyDelegate.isPluginSupported(this.strategy);
this.assessmentStrategyLoaded = true;
}
}
/**
* Convenience function to load the assessment data.
*
* @return Promised resvoled when data is loaded.
*/
protected async load(): Promise<void> {
this.data.assessment = await AddonModWorkshopHelper.getReviewerAssessmentById(this.workshop.id, this.assessmentId, {
userId: this.userId,
cmId: this.workshop.coursemodule,
});
if (this.edit) {
try {
const offlineAssessment = await AddonModWorkshopOffline.getAssessment(this.workshop.id, this.assessmentId);
const offlineData = offlineAssessment.inputdata;
this.hasOffline = true;
this.data.assessment.feedbackauthor = <string>offlineData.feedbackauthor;
if (this.access.canallocate) {
this.data.assessment.weight = <number>offlineData.weight;
}
// Override assessment plugins values.
this.data.assessment.form!.current = AddonModWorkshop.parseFields(
CoreUtils.objectToArrayOfObjects(offlineData, 'name', 'value'),
);
// Override offline files.
if (offlineData) {
this.data.assessment.feedbackattachmentfiles =
await AddonModWorkshopHelper.getAssessmentFilesFromOfflineFilesObject(
<CoreFileUploaderStoreFilesResult>offlineData.feedbackauthorattachmentsid,
this.workshop.id,
this.assessmentId,
);
}
} catch {
this.hasOffline = false;
// Ignore errors.
} finally {
this.feedbackText = this.data.assessment.feedbackauthor;
this.feedbackControl.setValue(this.feedbackText);
this.originalData.text = this.data.assessment.feedbackauthor;
if (this.access.canallocate) {
this.originalData.weight = this.data.assessment.weight;
}
this.originalData.files = [];
this.data.assessment.feedbackattachmentfiles.forEach((file) => {
let filename = CoreFile.getFileName(file);
if (!filename) {
// We don't have filename, extract it from the path.
filename = CoreFileHelper.getFilenameFromPath(file) || '';
}
this.originalData.files.push({
filename,
fileurl: '', // No needed to compare.
});
});
}
}
try {
this.data.selectedValues = await AddonWorkshopAssessmentStrategyDelegate.getOriginalValues(
this.strategy,
this.data.assessment.form!,
this.workshop.id,
);
} finally {
this.originalData.selectedValues = CoreUtils.clone(this.data.selectedValues);
if (this.edit) {
CoreFileSession.setFiles(
AddonModWorkshopProvider.COMPONENT,
this.workshop.id + '_' + this.assessmentId,
this.data.assessment.feedbackattachmentfiles,
);
if (this.access.canallocate) {
this.weight = this.data.assessment.weight;
}
}
}
}
/**
* Check if data has changed.
*
* @return True if data has changed.
*/
hasDataChanged(): boolean {
if (!this.assessmentStrategyLoaded) {
return false;
}
// Compare feedback text.
const text = CoreTextUtils.restorePluginfileUrls(this.feedbackText, this.data.assessment?.feedbackcontentfiles || []);
if (this.originalData.text != text) {
return true;
}
if (this.access.canallocate && this.originalData.weight != this.weight) {
return true;
}
// Compare feedback files.
const files = CoreFileSession.getFiles(
AddonModWorkshopProvider.COMPONENT,
this.workshop.id + '_' + this.assessmentId,
) || [];
if (CoreFileUploader.areFileListDifferent(files, this.originalData.files)) {
return true;
}
return AddonWorkshopAssessmentStrategyDelegate.hasDataChanged(
this.workshop.strategy!,
this.originalData.selectedValues,
this.data.selectedValues,
);
}
/**
* Save the assessment.
*
* @return Promise resolved when done, rejected if assessment could not be saved.
*/
async saveAssessment(): Promise<void> {
const files = CoreFileSession.getFiles(
AddonModWorkshopProvider.COMPONENT,
this.workshop.id + '_' + this.assessmentId,
) || [];
let saveOffline = false;
let allowOffline = !files.length;
const modal = await CoreDomUtils.showModalLoading('core.sending', true);
this.data.fieldErrors = {};
try {
let attachmentsId: CoreFileUploaderStoreFilesResult | number;
try {
// Upload attachments first if any.
attachmentsId = await AddonModWorkshopHelper.uploadOrStoreAssessmentFiles(
this.workshop.id,
this.assessmentId,
files,
saveOffline,
);
} catch (error) {
if (CoreUtils.isWebServiceError(error)) {
throw error;
}
// Cannot upload them in online, save them in offline.
saveOffline = true;
allowOffline = true;
attachmentsId = await AddonModWorkshopHelper.uploadOrStoreAssessmentFiles(
this.workshop.id,
this.assessmentId,
files,
saveOffline,
);
}
const text = CoreTextUtils.restorePluginfileUrls(this.feedbackText, this.data.assessment?.feedbackcontentfiles || []);
let assessmentData: CoreFormFields<unknown>;
try {
assessmentData = await AddonModWorkshopHelper.prepareAssessmentData(
this.workshop,
this.data.selectedValues,
text,
this.data.assessment!.form!,
attachmentsId,
);
} catch (errors) {
this.data.fieldErrors = errors;
throw new CoreError(Translate.instant('core.errorinvalidform'));
}
let gradeUpdated = false;
if (saveOffline) {
// Save assessment in offline.
await AddonModWorkshopOffline.saveAssessment(
this.workshop.id,
this.assessmentId,
this.workshop.course,
assessmentData,
);
gradeUpdated = false;
} else {
// Try to send it to server.
// Don't allow offline if there are attachments since they were uploaded fine.
gradeUpdated = await AddonModWorkshop.updateAssessment(
this.workshop.id,
this.assessmentId,
this.workshop.course,
assessmentData,
undefined,
allowOffline,
);
}
CoreForms.triggerFormSubmittedEvent(this.formElement, !!gradeUpdated, CoreSites.getCurrentSiteId());
const promises: Promise<void>[] = [];
// If sent to the server, invalidate and clean.
if (gradeUpdated) {
promises.push(AddonModWorkshopHelper.deleteAssessmentStoredFiles(this.workshop.id, this.assessmentId));
promises.push(AddonModWorkshop.invalidateAssessmentFormData(this.workshop.id, this.assessmentId));
promises.push(AddonModWorkshop.invalidateAssessmentData(this.workshop.id, this.assessmentId));
}
await CoreUtils.ignoreErrors(Promise.all(promises));
CoreEvents.trigger(AddonModWorkshopProvider.ASSESSMENT_SAVED, {
workshopId: this.workshop.id,
assessmentId: this.assessmentId,
userId: CoreSites.getCurrentSiteUserId(),
}, CoreSites.getCurrentSiteId());
if (files) {
// Delete the local files from the tmp folder.
CoreFileUploader.clearTmpFiles(files);
}
} catch (error) {
CoreDomUtils.showErrorModalDefault(error, 'Error saving assessment.');
} finally {
modal.dismiss();
}
}
/**
* Feedback text changed.
*
* @param text The new text.
*/
onFeedbackChange(text: string): void {
this.feedbackText = text;
}
/**
* Component destroyed.
*/
ngOnDestroy(): void {
this.obsInvalidated?.off();
if (this.data.assessment?.feedbackattachmentfiles) {
// Delete the local files from the tmp folder.
CoreFileUploader.clearTmpFiles(this.data.assessment.feedbackattachmentfiles);
}
}
}
type AddonModWorkshopAssessmentStrategyData = {
workshopId: number;
assessment?: AddonModWorkshopSubmissionAssessmentWithFormData;
edit: boolean;
selectedValues: AddonModWorkshopGetAssessmentFormFieldsParsedData[];
fieldErrors: AddonModWorkshopAssessmentStrategyFieldErrors;
strategy: string;
moduleId: number;
courseId?: number;
};
export type AddonModWorkshopAssessmentStrategyFieldErrors = Record<string, string>; | the_stack |
import type { CSSProperties, ReactNode, Component, PureComponent, HTMLAttributes, TextareaHTMLAttributes } from 'react';
// 忽略 T 对象中 键在 K 中的所有的属性
type Override<T1, T2> = Omit<T1, keyof T2> & T2;
// base type
export type SizeType = 'sm' | 'md' | 'lg';
// ThemeProvider
interface ThemeProviderProps {
theme: any;
}
export declare class ThemeProvider extends Component<ThemeProviderProps> {}
export { default as Tree } from './lib/components/Tree';
export { default as Cascader } from './lib/components/Cascader';
export { default as Link } from './lib/components/Link';
export { default as AutoComplete } from './lib/components/AutoComplete';
export { default as Switch, SwitchProps } from './lib/components/Switch';
export { default as Tabs, TabsProps, TabPaneProps } from './lib/components/Tabs';
export { default as Input } from './lib/components/Input';
import Input from './lib/components/Input';
export { default as Checkbox, CheckboxProps } from './lib/components/Checkbox';
export { default as Menu } from './lib/components/Menu';
export { default as Collapse } from './lib/components/Collapse';
export { default as ActionList } from './lib/components/ActionList';
import ActionList from './lib/components/ActionList';
export { default as Tooltip } from './lib/components/Tooltip';
export { default as PopConfirm } from './lib/components/PopConfirm';
export { default as ConfigProvider } from './lib/components/ConfigProvider';
export { default as Icon } from './lib/components/Icon';
export { default as Select } from './lib/components/Select';
export { default as Breadcrumb } from './lib/components/Breadcrumb';
// Button
import { ButtonProps } from './lib/components/Button/Button';
export { default as Button } from './lib/components/Button';
// Box
type BoxSpacing = 'sm' | 'md' | 'lg' | number | string;
export interface BoxProps extends HTMLAttributes<HTMLDivElement> {
container?: boolean;
spacing?: BoxSpacing | [BoxSpacing, BoxSpacing?];
direction?: 'row' | 'row-reverse' | 'column' | 'column-reverse';
wrap?: 'nowrap' | 'wrap' | 'wrap-reverse';
alignItems?: 'center' | 'flex-start' | 'flex-end' | 'stretch';
alignContent?: 'center' | 'flex-start' | 'flex-end' | 'space-between' | 'space-around';
justifyContent?: 'center' | 'flex-start' | 'flex-end' | 'space-between' | 'space-around' | 'stretch';
padding?: BoxSpacing;
width?: string;
height?: string;
span?: number;
order?: number;
flex?: string;
cleanMargin?: boolean;
}
export declare class Box extends PureComponent<BoxProps> {}
// Row
export type RowType = 'flex';
export type RowAlign = 'top' | 'middle' | 'bottom';
export type RowJustify = 'start' | 'end' | 'center' | 'space-around' | 'space-between';
export interface RowProps extends HTMLAttributes<HTMLDivElement> {
type?: RowType;
align?: RowAlign;
justify?: RowJustify;
gutter?: number;
}
export declare class Row extends Component<RowProps> {}
// Col
export interface ColProps extends HTMLAttributes<HTMLDivElement> {
span?: number;
offset?: number;
pull?: number;
push?: number;
order?: number;
}
export declare class Col extends Component<ColProps> {}
// Grid
export interface GridType {
Row: Row;
Col: Col;
}
export declare const Grid: GridType;
// Combine
export interface CombineProps extends HTMLAttributes<HTMLDivElement> {
sharedProps?: CompactSharedProps;
spacing?: 'compact' | 'smart' | 'sm' | 'md' | 'lg' | string;
}
export declare class Combine extends PureComponent<CombineProps> {}
// Compact
export interface CompactSharedProps {
[key: string]: any;
}
export interface CompactProps extends HTMLAttributes<HTMLDivElement> {
sharedProps?: CompactSharedProps;
}
export declare class Compact extends Component<CompactProps> {}
// NumberInput
export type NumberInputStyleType = 'default' | 'split' | 'pagination';
export type NumberInputProps = Override<
HTMLAttributes<HTMLInputElement>,
{
value?: number | string;
defaultValue?: number | string;
onChange?: (value: number | string) => void;
onNumberChange?: (value: number) => void;
disabled?: boolean;
readOnly?: boolean;
max?: number;
min?: number;
step?: number | string;
upHandler?: ReactNode;
downHandler?: ReactNode;
formatter?: (value: number) => number | string;
parser?: (value: string) => string;
precision?: number;
styleType?: NumberInputStyleType;
size?: SizeType;
suffix?: ReactNode;
inputStyle?: CSSProperties;
computeValidNumber?: (value: number) => number;
hideHandler?: boolean;
}
>;
export declare class NumberInput extends Component<NumberInputProps> {}
// Textarea
export type TextareaProps = TextareaHTMLAttributes<HTMLTextAreaElement>;
export declare class Textarea extends Component<TextareaProps> {}
// Radio
export type RadioStyleType = 'default' | 'button' | 'tag' | 'card' | 'text' | 'list';
export interface RadioProps {
checked?: boolean;
defaultChecked?: boolean;
disabled?: boolean;
onChange?: (checked: boolean) => void;
value?: any;
styleType?: RadioStyleType;
size?: SizeType;
title?: ReactNode;
extra?: ReactNode;
disabledLabel?: ReactNode;
}
interface RadioOption extends RadioProps {
label?: ReactNode;
}
export type RadioOptions = RadioOption[];
export interface RadioGroupProps {
value?: any;
defaultValue?: any;
onChange?: (value: any) => void;
options?: RadioOptions;
disabled?: boolean;
size?: SizeType;
styleType?: RadioStyleType;
}
declare class RadioGroup extends Component<RadioGroupProps> {}
export declare class Radio extends Component<RadioProps> {
static Group: typeof RadioGroup;
}
// Slider
export interface SliderMark {
label?: string;
step?: number;
ratio?: number;
}
export interface SliderMarks {
[key: string]: SliderMark | ReactNode;
}
interface NumberInputTipFormatterOption {
currentValue: number;
inputValue: number;
isSensitive: boolean;
locale: any;
}
export type SliderProps = Override<
HTMLAttributes<HTMLDivElement>,
{
value?: number;
defaultValue?: number;
onChange?: (value: number) => void;
onLastChange?: (value: number) => void;
disabled?: boolean;
min?: number;
max?: number;
step?: number | string;
marks?: SliderMarks;
className?: string;
style?: CSSProperties;
sliderClassName?: string;
numberInput?: NumberInputProps;
isSensitive?: boolean;
numberInputTipFormatter?: (option: NumberInputTipFormatterOption) => ReactNode;
tipFormatter?: (value: number) => ReactNode;
size?: SizeType;
}
>;
export declare class Slider extends Component<SliderProps> {}
// Upload
export interface UploadFile {
name: string;
uid: string;
size?: number;
status?: 'uploading' | 'success' | 'error';
thumbnailUrl?: string;
url?: string;
type?: string;
lastModified?: number;
lastModifiedDate?: Date;
progress?: number;
error?: Error;
}
interface UpdateProgress {
(progress: number): void;
}
type UploadListTypeOption<T> = [T, 'none' | 'dropzone' | 'thumbnail'];
export type UploadListType =
| 'none'
| 'text'
| 'list'
| 'dropzone'
| UploadListTypeOption<'list'>
| UploadListTypeOption<'dropzone'>;
export interface UploadCustomStyle {
listMaxHeight?: string;
[key: string]: any;
}
export interface UploadProps {
onChange?: (fileList: UploadFile[]) => void;
onAdd?: (fileList: UploadFile[]) => boolean;
onRemove?: (file: UploadFile, index: number) => boolean;
getRemovableOfItem?: (file: UploadFile) => boolean;
onError?: (error: Error) => void;
onPreview?: (file: UploadFile, index: number) => void;
getPreviewableOfItem?: (file: UploadFile) => boolean;
handleUpload?: <T = any>(file: UploadFile, updateProgress: UpdateProgress) => Promise<any>;
disabled?: boolean;
multiple?: boolean;
accept?: string;
maxSize?: number;
maxCount?: number;
selector?: ReactNode;
listType?: UploadListType;
defaultFileList?: (File | UploadFile)[];
fileList?: (File | UploadFile)[];
style?: CSSProperties;
customStyle?: UploadCustomStyle;
}
export declare class Upload extends Component<UploadProps> {}
// Calendar
export { default as Calendar } from './lib/components/Calendar';
// DatePicker
export { default as DatePicker } from './lib/components/DatePicker';
// ZForm
export interface FormShape {
getFieldsValue: Function;
getFieldValue: Function;
getFieldInstance: Function;
setFieldsValue: Function;
setFields: Function;
setFieldsInitialValue: Function;
getFieldDecorator: Function;
getFieldProps: Function;
getFieldsError: Function;
getFieldError: Function;
isFieldValidating: Function;
isFieldsValidating: Function;
isFieldsTouched: Function;
isFieldTouched: Function;
isSubmitting: Function;
submit: Function;
validateFields: Function;
resetFields: Function;
}
export interface ZFormProps extends FormProps {
form?: FormShape;
}
interface ControllerDecoratorOptions {
[key: string]: any;
}
export declare class ZForm extends Component<ZFormProps> {
static formDecorator?: (options: FormShape) => Function;
static controllerDecorator?: (options: ControllerDecoratorOptions) => Function;
static formShape?: FormShape;
}
// Transfer
type TransferSearch = (searchValue: string, item: any) => boolean;
interface TransferSource {
title?: ReactNode;
footer?: ReactNode;
search?: boolean | TransferSearch;
disabled?: boolean;
}
export type TransferProps = Override<
HTMLAttributes<HTMLDivElement>,
{
dataSource?: any[];
renderList?: (options: TransferProps) => ReactNode;
selectedKeys?: string[];
defaultSelectedKeys?: string[];
onChange?: (keys: string[]) => void;
disabled?: boolean;
search?: boolean | TransferSearch;
source?: TransferSource;
target?: TransferSource;
}
>;
export declare class Transfer extends PureComponent<TransferProps> {}
// TransferMenu
export interface TransferMenuProps extends TransferProps {
renderItem?: (item: any) => ReactNode;
}
export declare class TransferMenu extends PureComponent<TransferMenuProps> {}
// TransferTable
export interface TransferTableProps extends TransferProps {
columns?: Column[];
tableProps?: TableProps;
}
export declare class TransferTable extends PureComponent<TransferTableProps> {}
// EditableTable
interface EditableTableAddition extends EditableListAddition {
tip?: ReactNode;
}
interface EditableTableRowDeletion {
onDelete?: (record: any) => void;
getDisabledOfRow?: (record: any) => boolean;
fixed?: boolean;
}
export interface EditableTableProps extends TableProps {
addition?: boolean | EditableTableAddition;
rowDeletion?: boolean | EditableTableRowDeletion;
}
export declare class EditableTable extends PureComponent<EditableTableProps> {}
// EditableList
interface EditableListAddition {
onAdd?: Function;
disabled?: boolean;
}
interface EditableListRowDeletion {
onDelete?: (item: any) => void;
getDisabledOfItem?: (item: any) => boolean;
}
interface EditableListGrid {
itemCol?: ColProps;
actionCol?: ColProps;
}
export interface EditableListProps {
dataSource?: any[];
renderItem?: (item: any) => ReactNode;
grid?: EditableListGrid;
size?: SizeType;
addition?: boolean | EditableListAddition;
itemDeletion?: boolean | EditableListRowDeletion;
}
export declare class EditableList extends PureComponent<EditableListProps> {}
// Notice
export { default as Notice, NoticeProps } from './lib/components/Notice';
// Badge
export { default as Badge, BadgeProps } from './lib/components/Badge';
// Tag
export type TagStyleType =
| 'default'
| 'green'
| 'yellow'
| 'red'
| 'primary'
| 'purple'
| 'lightblue'
| 'blue'
| 'orange'
| 'cyan'
| 'success'
| 'warning'
| 'error'
| 'purple-fill'
| 'lightblue-fill'
| 'blue-fill'
| 'orange-fill'
| 'yellow-fill'
| 'cyan-fill'
| string;
export interface TagProps extends HTMLAttributes<HTMLSpanElement> {
styleType?: TagStyleType;
closable?: boolean;
onClose?: () => void;
icon?: 'circle-fill' | 'circle' | 'loading' | 'custom' | ReactNode;
disabled?: boolean;
}
export declare class TagIcon extends PureComponent<TagProps> {}
export declare class Tag extends PureComponent<TagProps> {
declare static Icon: typeof TagIcon;
}
// Popover
interface PopupAlign {
points?: string[];
offset?: number[];
}
export type PopoverPlacement =
| 'topLeft'
| 'top'
| 'topRight'
| 'bottomLeft'
| 'bottom'
| 'bottomRight'
| 'leftTop'
| 'left'
| 'leftBottom'
| 'rightTop'
| 'right'
| 'rightBottom';
export interface GetPopupContainer {
(): HTMLElement;
}
export interface PopoverProps extends HTMLAttributes<HTMLDivElement> {
visible?: boolean;
defaultVisible?: boolean;
onVisibleChange?: (visible: boolean) => void;
trigger?: 'hover' | 'focus' | 'click' | 'contextMenu';
alignPoint?: boolean;
placement?: PopoverPlacement;
align?: PopupAlign;
stretch?: 'with' | 'minWidth' | 'height' | 'minHeight';
popup?: ReactNode;
popupClassName?: string;
popupStyle?: CSSProperties;
zIndex?: number;
getPopupContainer?: GetPopupContainer;
forwardPopupContainer?: boolean | GetPopupContainer;
prefixCls?: string;
animation?: 'fade' | 'zoom' | 'bounce' | 'slide-up';
}
export declare class Popover extends Component<PopoverProps> {}
// Modal
interface ModalGetFooter {
(): ReactNode;
}
interface ModalCustomStyle {
[key: string]: any;
}
export interface ModalProps {
title?: ReactNode;
footer?: ReactNode | ModalGetFooter;
visible?: boolean;
size?: SizeType;
zIndex?: number;
closable?: boolean;
mask?: boolean;
maskClosable?: boolean;
keyboard?: boolean;
onClose?: Function;
onOk?: Function;
afterClose?: Function;
destroyOnClose?: boolean;
maskAnimation?: string;
animation?: string;
className?: string;
wrapClassName?: string;
customStyle?: ModalCustomStyle;
style?: CSSProperties;
bodyStyle?: CSSProperties;
maskStyle?: CSSProperties;
}
interface ModalConfirmHandle {
destroy(): void;
}
interface ModalConfirm {
(options: ModalProps): ModalConfirmHandle;
}
export declare class ModalContent extends Component<HTMLAttributes<HTMLDivElement>> {}
export declare class Modal extends Component<ModalProps> {
static confirm: ModalConfirm;
static alert: ModalConfirm;
static open: ModalConfirm;
static Content: typeof ModalContent;
}
// Drawer
export interface DrawerProps {
visible?: boolean;
mask?: boolean;
maskClosable?: boolean;
keyboard?: boolean;
onClose?: () => void;
destroyOnClose?: boolean;
placement?: 'left' | 'right' | 'top' | 'bottom';
width?: string | number;
height?: string | number;
getContainer?: () => ReactNode;
zIndex?: number;
closeHandler?: null | false;
}
export declare class Drawer extends Component<DrawerProps> {}
// Table
export interface TableScroll {
x?: number;
y?: number;
onScroll?: (e: WheelEvent) => void;
}
type RowKey = () => string;
export interface RowSelection {
fixed?: boolean;
onChange?: Function;
defaultSelectedRowKeys?: string[];
selectedRowKeys?: string[];
getDisabledOfRow?: (row: any) => boolean;
multiple?: boolean;
selectedTip?: boolean | 'button';
disabled?: boolean;
}
interface GetRowClassName {
(): string;
}
interface ColumnRender {
(col: any, row?: any): ReactNode;
}
export interface Column {
key?: string;
className?: string;
colSpan?: number;
title?: ReactNode;
dataIndex?: string;
width?: string | number;
fixed?: 'left' | 'right';
render?: ColumnRender;
onCellClick?: Function;
onCell?: Function;
onHeaderCell?: Function;
[key: string]: any;
}
interface DefaultColumnConfig {
[key: string]: string;
}
interface TableRowBack extends HTMLTableDataCellElement {}
interface TableCustomStyle {
outerPadding?: string;
[key: string]: any;
}
interface TableDefaultOrder {
key: string;
state: 'desc' | 'asc';
}
export interface TableConditionChangeEventOrder {
order: string;
filter: string[];
searchValue: string;
}
interface ConditionChangeEvent {
(condition: TableConditionChangeEventOrder): void;
}
interface TableContextMenu {
(row: object, hide: boolean): ReactNode;
}
export interface TableProps {
pagination?: PaginationProps;
dataSource?: any[];
columns?: Column[];
columnPlaceholder?: boolean;
defaultColumnConfig?: DefaultColumnConfig;
onColumnConfigChange?: (config: DefaultColumnConfig) => void;
expandedRowRender?: (row: any) => ReactNode;
expandIconAsCell?: boolean;
expandIconColumnIndex?: number;
hideExpandIcon?: boolean;
defaultExpandedRowKeys?: string[];
expandedRowKeys?: string[];
defaultExpandAllRows?: boolean;
onExpandedRowsChange?: (row: any) => void;
onExpand?: Function;
onRow?: (row: any, index: number) => TableRowBack;
onHeaderRow?: (row: any, index: number) => TableRowBack;
rowSelection?: RowSelection | true;
onRowSelect?: (keys: string[]) => void;
showHeader?: boolean;
title?: () => ReactNode;
footer?: () => ReactNode;
emptyContent?: ReactNode;
errorContent?: ReactNode;
handleSearch?: (row: any, searchValue: string) => boolean;
customStyle?: TableCustomStyle;
scroll?: TableScroll;
tableLayout?: 'auto' | 'fixed';
rowKey?: string | RowKey;
zebraCrossing?: boolean;
components?: any;
defaultOrder?: TableDefaultOrder;
onConditionChange?: ConditionChangeEvent;
doNotHandleCondition?: boolean;
contextMenu?: TableContextMenu;
className?: string;
rowClassName?: string | GetRowClassName;
}
interface ColumnConfigButtonProps extends ButtonProps {
modalProps?: ModalProps;
}
declare class TableColumnConfigButton extends Component<ColumnConfigButtonProps> {}
interface TableExpandedRowContentProps extends HTMLAttributes<HTMLDivElement> {}
declare class TableExpandedRowContent extends Component<TableExpandedRowContentProps> {}
declare class HoverDisplayArea extends Component<HTMLAttributes<HTMLDivElement>> {}
export declare class Table extends Component<TableProps> {
static ColumnConfigButton: typeof TableColumnConfigButton;
static SearchInput: typeof Input['Search'];
static ActionList: typeof ActionList;
static ExpandedRowContent: typeof TableExpandedRowContent;
static HoverDisplayArea: typeof HoverDisplayArea;
static getColumnConfigFromLocalStorage: typeof Function;
static setColumnConfigToLocalStorage: typeof Function;
}
// Form
export interface FormLabelCol {
span?: number;
offset?: number;
pull?: number;
push?: number;
}
interface FormItemTip {
icon?: ReactNode;
content?: ReactNode;
}
export interface FormItemProps extends RowProps {
label?: ReactNode;
labelCol?: FormLabelCol;
controllerCol?: FormLabelCol;
help?: ReactNode;
required?: boolean;
status?: 'default' | 'success' | 'warning' | 'error' | 'loading';
shareStatus?: boolean;
tip?: ReactNode | FormItemTip;
}
export type FormGroupProps = Override<
HTMLAttributes<HTMLDivElement>,
{
title?: ReactNode;
itemProps?: FormItemProps;
}
>;
export interface FormSubAreaProps extends HTMLAttributes<HTMLFormElement> {
itemProps?: FormItemProps;
}
export interface FormProps extends HTMLAttributes<HTMLFormElement> {
size?: 'md' | 'lg';
itemProps?: FormItemProps;
}
declare class FormItem extends PureComponent<FormItemProps> {}
declare class FormGroup extends Component<FormGroupProps> {}
declare class FormSubArea extends PureComponent<FormSubAreaProps> {}
export declare class Form extends PureComponent<FormProps> {
static Item: typeof FormItem;
static Group: typeof FormGroup;
static SubArea: typeof FormSubArea;
}
// Card
export interface CardHeaderProps extends HTMLAttributes<HTMLDivElement> {
comment?: ReactNode;
}
declare class CardHeader extends Component<CardHeaderProps> {}
declare class CardContent extends Component<HTMLAttributes<HTMLDivElement>> {}
declare class CardFooter extends Component<HTMLAttributes<HTMLDivElement>> {}
declare class CardAction extends Component<HTMLAttributes<HTMLDivElement>> {}
export type CardProps = HTMLAttributes<HTMLDivElement>;
export declare class Card extends PureComponent<CardProps> {
static Header: typeof CardHeader;
static Content: typeof CardContent;
static Footer: typeof CardFooter;
static Action: typeof CardAction;
}
// Steps
interface Step {
key?: string | number;
step?: ReactNode;
title?: ReactNode;
remark?: ReactNode;
}
export interface StepsProps extends HTMLAttributes<HTMLDivElement> {
steps: Step[];
current?: string | number;
status?: 'current' | 'loading' | 'error';
}
export declare class Steps extends Component<StepsProps> {}
// Message
export type MessageProps = Override<
HTMLAttributes<HTMLDivElement>,
{
closable?: boolean;
title?: ReactNode;
footer?: ReactNode;
styleType?: 'default' | 'success' | 'loading' | 'warning' | 'error';
}
>;
interface MessageOption {
zIndex?: number;
style?: CSSProperties;
className?: string;
}
interface MessageHandle {
destroy(): void;
}
interface MessageMethod {
(content: ReactNode, duration?: number, onClose?: () => void, option?: MessageOption): MessageHandle;
}
interface MessageConfig {
duration?: number;
getContainer?: () => ReactNode;
top?: number;
}
export declare class Message extends Component<MessageProps> {
static message: MessageMethod;
static info: MessageMethod;
static warning: MessageMethod;
static success: MessageMethod;
static error: MessageMethod;
static loading: MessageMethod;
static config: (config: MessageConfig) => void;
}
// Pagination
interface GetPaginationShowTotal {
(total: number): string;
}
interface ShowQuickJumperObject {
goButton?: ReactNode;
}
export type PaginationProps = Override<
HTMLAttributes<HTMLUListElement>,
{
current?: number;
defaultCurrent?: number;
total?: number;
showTotal?: boolean | GetPaginationShowTotal;
pageSize?: number;
defaultPageSize?: number;
onChange?: (page: number, pageSize: number) => void;
onAdvise?: (newCurrent: number, pageSize: number) => void;
showSizeChanger?: boolean;
showLessItems?: boolean;
onPageSizeChange?: (current: number, pageSize: number) => void;
showPrevNextJumpers?: boolean;
showQuickJumper?: boolean | ShowQuickJumperObject;
showTitle?: boolean;
pageSizeOptions?: Array<number | string>;
simple?: boolean;
size?: SizeType;
}
>;
export declare class Pagination extends Component<PaginationProps> {}
// Progress
interface ProgressFormat {
(percent: number): string;
}
export interface ProgressProps extends HTMLAttributes<HTMLDivElement> {
percent?: number;
color?: 'success' | 'warn' | 'error' | string;
format?: null | ProgressFormat;
}
export declare class Progress extends Component<ProgressProps> {}
// Loading
export interface LoadingProps extends HTMLAttributes<HTMLDivElement> {
loading?: boolean;
indicator?: ReactNode;
tip?: ReactNode;
maskStyle?: CSSProperties;
maskClassName?: string;
}
export declare class Loading extends Component<LoadingProps> {}
// LocaleProvider
interface LocaleProviderProps {
children?: ReactNode;
locale?: any;
}
export declare class LocaleProvider extends Component<LocaleProviderProps> {} | the_stack |
import * as assert from 'assert';
import { VSBuffer } from 'vs/base/common/buffer';
import { DisposableStore, toDisposable } from 'vs/base/common/lifecycle';
import { IFileService } from 'vs/platform/files/common/files';
import { ILogService } from 'vs/platform/log/common/log';
import { IUserDataProfilesService } from 'vs/platform/userDataProfile/common/userDataProfile';
import { getTasksContentFromSyncContent, TasksSynchroniser } from 'vs/platform/userDataSync/common/tasksSync';
import { Change, IUserDataSyncStoreService, MergeState, SyncResource, SyncStatus } from 'vs/platform/userDataSync/common/userDataSync';
import { UserDataSyncClient, UserDataSyncTestServer } from 'vs/platform/userDataSync/test/common/userDataSyncClient';
suite('TasksSync', () => {
const disposableStore = new DisposableStore();
const server = new UserDataSyncTestServer();
let client: UserDataSyncClient;
let testObject: TasksSynchroniser;
setup(async () => {
client = disposableStore.add(new UserDataSyncClient(server));
await client.setUp(true);
testObject = client.getSynchronizer(SyncResource.Tasks) as TasksSynchroniser;
disposableStore.add(toDisposable(() => client.instantiationService.get(IUserDataSyncStoreService).clear()));
});
teardown(() => disposableStore.clear());
test('when tasks file does not exist', async () => {
const fileService = client.instantiationService.get(IFileService);
const tasksResource = client.instantiationService.get(IUserDataProfilesService).defaultProfile.tasksResource;
assert.deepStrictEqual(await testObject.getLastSyncUserData(), null);
let manifest = await client.manifest();
server.reset();
await testObject.sync(manifest);
assert.deepStrictEqual(server.requests, [
{ type: 'GET', url: `${server.url}/v1/resource/${testObject.resource}/latest`, headers: {} },
]);
assert.ok(!await fileService.exists(tasksResource));
const lastSyncUserData = await testObject.getLastSyncUserData();
const remoteUserData = await testObject.getRemoteUserData(null);
assert.deepStrictEqual(lastSyncUserData!.ref, remoteUserData.ref);
assert.deepStrictEqual(lastSyncUserData!.syncData, remoteUserData.syncData);
assert.strictEqual(lastSyncUserData!.syncData, null);
manifest = await client.manifest();
server.reset();
await testObject.sync(manifest);
assert.deepStrictEqual(server.requests, []);
manifest = await client.manifest();
server.reset();
await testObject.sync(manifest);
assert.deepStrictEqual(server.requests, []);
});
test('when tasks file does not exist and remote has changes', async () => {
const client2 = disposableStore.add(new UserDataSyncClient(server));
await client2.setUp(true);
const content = JSON.stringify({
'version': '2.0.0',
'tasks': [{
'type': 'npm',
'script': 'watch',
'label': 'Watch'
}]
});
const tasksResource2 = client2.instantiationService.get(IUserDataProfilesService).defaultProfile.tasksResource;
await client2.instantiationService.get(IFileService).writeFile(tasksResource2, VSBuffer.fromString(content));
await client2.sync();
const fileService = client.instantiationService.get(IFileService);
const tasksResource = client.instantiationService.get(IUserDataProfilesService).defaultProfile.tasksResource;
await testObject.sync(await client.manifest());
assert.deepStrictEqual(testObject.status, SyncStatus.Idle);
const lastSyncUserData = await testObject.getLastSyncUserData();
const remoteUserData = await testObject.getRemoteUserData(null);
assert.strictEqual(getTasksContentFromSyncContent(lastSyncUserData!.syncData!.content!, client.instantiationService.get(ILogService)), content);
assert.strictEqual(getTasksContentFromSyncContent(remoteUserData!.syncData!.content!, client.instantiationService.get(ILogService)), content);
assert.strictEqual((await fileService.readFile(tasksResource)).value.toString(), content);
});
test('when tasks file exists locally and remote has no tasks', async () => {
const fileService = client.instantiationService.get(IFileService);
const tasksResource = client.instantiationService.get(IUserDataProfilesService).defaultProfile.tasksResource;
const content = JSON.stringify({
'version': '2.0.0',
'tasks': [{
'type': 'npm',
'script': 'watch',
'label': 'Watch'
}]
});
fileService.writeFile(tasksResource, VSBuffer.fromString(content));
await testObject.sync(await client.manifest());
assert.deepStrictEqual(testObject.status, SyncStatus.Idle);
const lastSyncUserData = await testObject.getLastSyncUserData();
const remoteUserData = await testObject.getRemoteUserData(null);
assert.strictEqual(getTasksContentFromSyncContent(lastSyncUserData!.syncData!.content!, client.instantiationService.get(ILogService)), content);
assert.strictEqual(getTasksContentFromSyncContent(remoteUserData!.syncData!.content!, client.instantiationService.get(ILogService)), content);
});
test('first time sync: when tasks file exists locally with same content as remote', async () => {
const client2 = disposableStore.add(new UserDataSyncClient(server));
await client2.setUp(true);
const content = JSON.stringify({
'version': '2.0.0',
'tasks': [{
'type': 'npm',
'script': 'watch',
'label': 'Watch'
}]
});
const tasksResource2 = client2.instantiationService.get(IUserDataProfilesService).defaultProfile.tasksResource;
await client2.instantiationService.get(IFileService).writeFile(tasksResource2, VSBuffer.fromString(content));
await client2.sync();
const fileService = client.instantiationService.get(IFileService);
const tasksResource = client.instantiationService.get(IUserDataProfilesService).defaultProfile.tasksResource;
await fileService.writeFile(tasksResource, VSBuffer.fromString(content));
await testObject.sync(await client.manifest());
assert.deepStrictEqual(testObject.status, SyncStatus.Idle);
const lastSyncUserData = await testObject.getLastSyncUserData();
const remoteUserData = await testObject.getRemoteUserData(null);
assert.strictEqual(getTasksContentFromSyncContent(lastSyncUserData!.syncData!.content!, client.instantiationService.get(ILogService)), content);
assert.strictEqual(getTasksContentFromSyncContent(remoteUserData!.syncData!.content!, client.instantiationService.get(ILogService)), content);
assert.strictEqual((await fileService.readFile(tasksResource)).value.toString(), content);
});
test('when tasks file locally has moved forward', async () => {
const fileService = client.instantiationService.get(IFileService);
const tasksResource = client.instantiationService.get(IUserDataProfilesService).defaultProfile.tasksResource;
fileService.writeFile(tasksResource, VSBuffer.fromString(JSON.stringify({
'version': '2.0.0',
'tasks': []
})));
await testObject.sync(await client.manifest());
const content = JSON.stringify({
'version': '2.0.0',
'tasks': [{
'type': 'npm',
'script': 'watch',
'label': 'Watch'
}]
});
fileService.writeFile(tasksResource, VSBuffer.fromString(content));
await testObject.sync(await client.manifest());
assert.deepStrictEqual(testObject.status, SyncStatus.Idle);
const lastSyncUserData = await testObject.getLastSyncUserData();
const remoteUserData = await testObject.getRemoteUserData(null);
assert.strictEqual(getTasksContentFromSyncContent(lastSyncUserData!.syncData!.content!, client.instantiationService.get(ILogService)), content);
assert.strictEqual(getTasksContentFromSyncContent(remoteUserData!.syncData!.content!, client.instantiationService.get(ILogService)), content);
});
test('when tasks file remotely has moved forward', async () => {
const client2 = disposableStore.add(new UserDataSyncClient(server));
await client2.setUp(true);
const tasksResource2 = client2.instantiationService.get(IUserDataProfilesService).defaultProfile.tasksResource;
const fileService2 = client2.instantiationService.get(IFileService);
await fileService2.writeFile(tasksResource2, VSBuffer.fromString(JSON.stringify({
'version': '2.0.0',
'tasks': []
})));
const fileService = client.instantiationService.get(IFileService);
const tasksResource = client.instantiationService.get(IUserDataProfilesService).defaultProfile.tasksResource;
await client2.sync();
await testObject.sync(await client.manifest());
const content = JSON.stringify({
'version': '2.0.0',
'tasks': [{
'type': 'npm',
'script': 'watch',
'label': 'Watch'
}]
});
fileService2.writeFile(tasksResource2, VSBuffer.fromString(content));
await client2.sync();
await testObject.sync(await client.manifest());
assert.deepStrictEqual(testObject.status, SyncStatus.Idle);
const lastSyncUserData = await testObject.getLastSyncUserData();
const remoteUserData = await testObject.getRemoteUserData(null);
assert.strictEqual(getTasksContentFromSyncContent(lastSyncUserData!.syncData!.content!, client.instantiationService.get(ILogService)), content);
assert.strictEqual(getTasksContentFromSyncContent(remoteUserData!.syncData!.content!, client.instantiationService.get(ILogService)), content);
assert.strictEqual((await fileService.readFile(tasksResource)).value.toString(), content);
});
test('when tasks file has moved forward locally and remotely with same changes', async () => {
const client2 = disposableStore.add(new UserDataSyncClient(server));
await client2.setUp(true);
const tasksResource2 = client2.instantiationService.get(IUserDataProfilesService).defaultProfile.tasksResource;
const fileService2 = client2.instantiationService.get(IFileService);
await fileService2.writeFile(tasksResource2, VSBuffer.fromString(JSON.stringify({
'version': '2.0.0',
'tasks': []
})));
const fileService = client.instantiationService.get(IFileService);
const tasksResource = client.instantiationService.get(IUserDataProfilesService).defaultProfile.tasksResource;
await client2.sync();
await testObject.sync(await client.manifest());
const content = JSON.stringify({
'version': '2.0.0',
'tasks': [{
'type': 'npm',
'script': 'watch',
'label': 'Watch'
}]
});
fileService2.writeFile(tasksResource2, VSBuffer.fromString(content));
await client2.sync();
fileService.writeFile(tasksResource, VSBuffer.fromString(content));
await testObject.sync(await client.manifest());
assert.deepStrictEqual(testObject.status, SyncStatus.Idle);
const lastSyncUserData = await testObject.getLastSyncUserData();
const remoteUserData = await testObject.getRemoteUserData(null);
assert.strictEqual(getTasksContentFromSyncContent(lastSyncUserData!.syncData!.content!, client.instantiationService.get(ILogService)), content);
assert.strictEqual(getTasksContentFromSyncContent(remoteUserData!.syncData!.content!, client.instantiationService.get(ILogService)), content);
assert.strictEqual((await fileService.readFile(tasksResource)).value.toString(), content);
});
test('when tasks file has moved forward locally and remotely - accept preview', async () => {
const client2 = disposableStore.add(new UserDataSyncClient(server));
await client2.setUp(true);
const tasksResource2 = client2.instantiationService.get(IUserDataProfilesService).defaultProfile.tasksResource;
const fileService2 = client2.instantiationService.get(IFileService);
await fileService2.writeFile(tasksResource2, VSBuffer.fromString(JSON.stringify({
'version': '2.0.0',
'tasks': []
})));
const fileService = client.instantiationService.get(IFileService);
const tasksResource = client.instantiationService.get(IUserDataProfilesService).defaultProfile.tasksResource;
await client2.sync();
await testObject.sync(await client.manifest());
fileService2.writeFile(tasksResource2, VSBuffer.fromString(JSON.stringify({
'version': '2.0.0',
'tasks': [{
'type': 'npm',
'script': 'watch',
}]
})));
await client2.sync();
const content = JSON.stringify({
'version': '2.0.0',
'tasks': [{
'type': 'npm',
'script': 'watch',
'label': 'Watch'
}]
});
fileService.writeFile(tasksResource, VSBuffer.fromString(content));
await testObject.sync(await client.manifest());
assert.deepStrictEqual(testObject.status, SyncStatus.HasConflicts);
assert.deepStrictEqual(testObject.conflicts.length, 1);
assert.deepStrictEqual(testObject.conflicts[0].mergeState, MergeState.Conflict);
assert.deepStrictEqual(testObject.conflicts[0].localChange, Change.Modified);
assert.deepStrictEqual(testObject.conflicts[0].remoteChange, Change.Modified);
assert.deepStrictEqual((await fileService.readFile(testObject.conflicts[0].previewResource)).value.toString(), content);
await testObject.accept(testObject.conflicts[0].previewResource);
await testObject.apply(false);
assert.deepStrictEqual(testObject.status, SyncStatus.Idle);
const lastSyncUserData = await testObject.getLastSyncUserData();
const remoteUserData = await testObject.getRemoteUserData(null);
assert.strictEqual(getTasksContentFromSyncContent(lastSyncUserData!.syncData!.content!, client.instantiationService.get(ILogService)), content);
assert.strictEqual(getTasksContentFromSyncContent(remoteUserData!.syncData!.content!, client.instantiationService.get(ILogService)), content);
assert.strictEqual((await fileService.readFile(tasksResource)).value.toString(), content);
});
test('when tasks file has moved forward locally and remotely - accept modified preview', async () => {
const client2 = disposableStore.add(new UserDataSyncClient(server));
await client2.setUp(true);
const tasksResource2 = client2.instantiationService.get(IUserDataProfilesService).defaultProfile.tasksResource;
const fileService2 = client2.instantiationService.get(IFileService);
await fileService2.writeFile(tasksResource2, VSBuffer.fromString(JSON.stringify({
'version': '2.0.0',
'tasks': []
})));
const fileService = client.instantiationService.get(IFileService);
const tasksResource = client.instantiationService.get(IUserDataProfilesService).defaultProfile.tasksResource;
await client2.sync();
await testObject.sync(await client.manifest());
fileService2.writeFile(tasksResource2, VSBuffer.fromString(JSON.stringify({
'version': '2.0.0',
'tasks': [{
'type': 'npm',
'script': 'watch',
}]
})));
await client2.sync();
fileService.writeFile(tasksResource, VSBuffer.fromString(JSON.stringify({
'version': '2.0.0',
'tasks': [{
'type': 'npm',
'script': 'watch',
'label': 'Watch'
}]
})));
await testObject.sync(await client.manifest());
const content = JSON.stringify({
'version': '2.0.0',
'tasks': [{
'type': 'npm',
'script': 'watch',
'label': 'Watch 2'
}]
});
await testObject.accept(testObject.conflicts[0].previewResource, content);
await testObject.apply(false);
assert.deepStrictEqual(testObject.status, SyncStatus.Idle);
const lastSyncUserData = await testObject.getLastSyncUserData();
const remoteUserData = await testObject.getRemoteUserData(null);
assert.strictEqual(getTasksContentFromSyncContent(lastSyncUserData!.syncData!.content!, client.instantiationService.get(ILogService)), content);
assert.strictEqual(getTasksContentFromSyncContent(remoteUserData!.syncData!.content!, client.instantiationService.get(ILogService)), content);
assert.strictEqual((await fileService.readFile(tasksResource)).value.toString(), content);
});
test('when tasks file has moved forward locally and remotely - accept remote', async () => {
const client2 = disposableStore.add(new UserDataSyncClient(server));
await client2.setUp(true);
const tasksResource2 = client2.instantiationService.get(IUserDataProfilesService).defaultProfile.tasksResource;
const fileService2 = client2.instantiationService.get(IFileService);
await fileService2.writeFile(tasksResource2, VSBuffer.fromString(JSON.stringify({
'version': '2.0.0',
'tasks': []
})));
const fileService = client.instantiationService.get(IFileService);
const tasksResource = client.instantiationService.get(IUserDataProfilesService).defaultProfile.tasksResource;
await client2.sync();
await testObject.sync(await client.manifest());
const content = JSON.stringify({
'version': '2.0.0',
'tasks': [{
'type': 'npm',
'script': 'watch',
}]
});
fileService2.writeFile(tasksResource2, VSBuffer.fromString(content));
await client2.sync();
fileService.writeFile(tasksResource, VSBuffer.fromString(JSON.stringify({
'version': '2.0.0',
'tasks': [{
'type': 'npm',
'script': 'watch',
'label': 'Watch'
}]
})));
await testObject.sync(await client.manifest());
assert.deepStrictEqual(testObject.status, SyncStatus.HasConflicts);
await testObject.accept(testObject.conflicts[0].remoteResource);
await testObject.apply(false);
assert.deepStrictEqual(testObject.status, SyncStatus.Idle);
const lastSyncUserData = await testObject.getLastSyncUserData();
const remoteUserData = await testObject.getRemoteUserData(null);
assert.strictEqual(getTasksContentFromSyncContent(lastSyncUserData!.syncData!.content!, client.instantiationService.get(ILogService)), content);
assert.strictEqual(getTasksContentFromSyncContent(remoteUserData!.syncData!.content!, client.instantiationService.get(ILogService)), content);
assert.strictEqual((await fileService.readFile(tasksResource)).value.toString(), content);
});
test('when tasks file has moved forward locally and remotely - accept local', async () => {
const client2 = disposableStore.add(new UserDataSyncClient(server));
await client2.setUp(true);
const tasksResource2 = client2.instantiationService.get(IUserDataProfilesService).defaultProfile.tasksResource;
const fileService2 = client2.instantiationService.get(IFileService);
await fileService2.writeFile(tasksResource2, VSBuffer.fromString(JSON.stringify({
'version': '2.0.0',
'tasks': []
})));
const fileService = client.instantiationService.get(IFileService);
const tasksResource = client.instantiationService.get(IUserDataProfilesService).defaultProfile.tasksResource;
await client2.sync();
await testObject.sync(await client.manifest());
fileService2.writeFile(tasksResource2, VSBuffer.fromString(JSON.stringify({
'version': '2.0.0',
'tasks': [{
'type': 'npm',
'script': 'watch',
}]
})));
await client2.sync();
const content = JSON.stringify({
'version': '2.0.0',
'tasks': [{
'type': 'npm',
'script': 'watch',
'label': 'Watch'
}]
});
fileService.writeFile(tasksResource, VSBuffer.fromString(content));
await testObject.sync(await client.manifest());
assert.deepStrictEqual(testObject.status, SyncStatus.HasConflicts);
await testObject.accept(testObject.conflicts[0].localResource);
await testObject.apply(false);
assert.deepStrictEqual(testObject.status, SyncStatus.Idle);
const lastSyncUserData = await testObject.getLastSyncUserData();
const remoteUserData = await testObject.getRemoteUserData(null);
assert.strictEqual(getTasksContentFromSyncContent(lastSyncUserData!.syncData!.content!, client.instantiationService.get(ILogService)), content);
assert.strictEqual(getTasksContentFromSyncContent(remoteUserData!.syncData!.content!, client.instantiationService.get(ILogService)), content);
assert.strictEqual((await fileService.readFile(tasksResource)).value.toString(), content);
});
test('when tasks file is created after first sync', async () => {
const fileService = client.instantiationService.get(IFileService);
const tasksResource = client.instantiationService.get(IUserDataProfilesService).defaultProfile.tasksResource;
await testObject.sync(await client.manifest());
const content = JSON.stringify({
'version': '2.0.0',
'tasks': [{
'type': 'npm',
'script': 'watch',
'label': 'Watch'
}]
});
await fileService.createFile(tasksResource, VSBuffer.fromString(content));
let lastSyncUserData = await testObject.getLastSyncUserData();
const manifest = await client.manifest();
server.reset();
await testObject.sync(manifest);
assert.deepStrictEqual(server.requests, [
{ type: 'POST', url: `${server.url}/v1/resource/${testObject.resource}`, headers: { 'If-Match': lastSyncUserData?.ref } },
]);
lastSyncUserData = await testObject.getLastSyncUserData();
const remoteUserData = await testObject.getRemoteUserData(null);
assert.deepStrictEqual(lastSyncUserData!.ref, remoteUserData.ref);
assert.deepStrictEqual(lastSyncUserData!.syncData, remoteUserData.syncData);
assert.strictEqual(getTasksContentFromSyncContent(lastSyncUserData!.syncData!.content!, client.instantiationService.get(ILogService)), content);
});
test('apply remote when tasks file does not exist', async () => {
const fileService = client.instantiationService.get(IFileService);
const tasksResource = client.instantiationService.get(IUserDataProfilesService).defaultProfile.tasksResource;
if (await fileService.exists(tasksResource)) {
await fileService.del(tasksResource);
}
const preview = (await testObject.preview(await client.manifest(), {}))!;
server.reset();
const content = await testObject.resolveContent(preview.resourcePreviews[0].remoteResource);
await testObject.accept(preview.resourcePreviews[0].remoteResource, content);
await testObject.apply(false);
assert.deepStrictEqual(server.requests, []);
});
}); | the_stack |
* @module OrbitGT
*/
//package orbitgt.spatial.geom;
type int8 = number;
type int16 = number;
type int32 = number;
type float32 = number;
type float64 = number;
import { ASystem } from "../../system/runtime/ASystem";
import { Coordinate } from "./Coordinate";
/**
* Class Line defines a line between two 3D XYZ points.
*
* @version 1.0 March 2010
*/
/** @internal */
export class Line {
/** The start point */
public p0: Coordinate;
/** The end point */
public p1: Coordinate;
/**
* Create a new line.
* @param p0 the start point.
* @param p1 the end point.
*/
public constructor(p0: Coordinate, p1: Coordinate) {
/* Store the points */
this.p0 = p0;
this.p1 = p1;
}
/**
* Create a new line.
* @return a new line.
*/
public static create(): Line {
return new Line(Coordinate.create(), Coordinate.create());
}
/**
* Create a new line.
* @param p0 the start point.
* @param p1 the end point.
*/
public static fromPoints(p0: Coordinate, p1: Coordinate): Line {
return new Line(p0, p1);
}
/**
* Create a new line.
* @param x0 the x of the start point.
* @param y0 the y of the start point.
* @param z0 the z of the start point.
* @param x1 the x of the end point.
* @param y1 the y of the end point.
* @param z1 the z of the end point.
*/
public static fromXYZ(x0: float64, y0: float64, z0: float64, x1: float64, y1: float64, z1: float64): Line {
return new Line(new Coordinate(x0, y0, z0), new Coordinate(x1, y1, z1));
}
/**
* Get the start point.
* @return the start point.
*/
public getPoint0(): Coordinate {
return this.p0;
}
/**
* Get the end point.
* @return the end point.
*/
public getPoint1(): Coordinate {
return this.p1;
}
/**
* Get a point along the line.
* @param t the position of the point (0.0 at start and 1.0 at end).
* @return a point.
*/
public getPoint(t: float64): Coordinate {
/* Avoid rounding errors */
if (t == 0.0) return this.p0;
if (t == 1.0) return this.p1;
/* Calculate a new point */
let x: float64 = this.p0.getX() + t * (this.p1.getX() - this.p0.getX());
let y: float64 = this.p0.getY() + t * (this.p1.getY() - this.p0.getY());
let z: float64 = this.p0.getZ() + t * (this.p1.getZ() - this.p0.getZ());
return new Coordinate(x, y, z);
}
/**
* Get a point along the line.
* @param t the position of the point (0.0 at start and 1.0 at end).
* @param point the result point (must be mutable).
*/
public getPointTo(t: float64, point: Coordinate): void {
/* Start point? */
if (t == 0.0) {
/* Copy */
point.setXYZ(this.p0.getX(), this.p0.getY(), this.p0.getZ());
}
/* End point? */
else if (t == 1.0) {
/* Copy */
point.setXYZ(this.p1.getX(), this.p1.getY(), this.p1.getZ());
}
/* Intermediate point */
else {
/* Calculate a new point */
let x: float64 = this.p0.getX() + t * (this.p1.getX() - this.p0.getX());
let y: float64 = this.p0.getY() + t * (this.p1.getY() - this.p0.getY());
let z: float64 = this.p0.getZ() + t * (this.p1.getZ() - this.p0.getZ());
point.setXYZ(x, y, z);
}
}
/**
* Get the X coordinate of a point along the line.
* @param t the position of the point (0.0 at start and 1.0 at end).
* @return the coordinate.
*/
public getPointX(t: float64): float64 {
/* Start point? */
if (t == 0.0) {
/* Copy */
return this.p0.getX();
}
/* End point? */
else if (t == 1.0) {
/* Copy */
return this.p1.getX();
}
/* Intermediate point */
else {
/* Calculate a new point */
return this.p0.getX() + t * (this.p1.getX() - this.p0.getX());
}
}
/**
* Get the Y coordinate of a point along the line.
* @param t the position of the point (0.0 at start and 1.0 at end).
* @return the coordinate.
*/
public getPointY(t: float64): float64 {
/* Start point? */
if (t == 0.0) {
/* Copy */
return this.p0.getY();
}
/* End point? */
else if (t == 1.0) {
/* Copy */
return this.p1.getY();
}
/* Intermediate point */
else {
/* Calculate a new point */
return this.p0.getY() + t * (this.p1.getY() - this.p0.getY());
}
}
/**
* Get the Z coordinate of a point along the line.
* @param t the position of the point (0.0 at start and 1.0 at end).
* @return the coordinate.
*/
public getPointZ(t: float64): float64 {
/* Start point? */
if (t == 0.0) {
/* Copy */
return this.p0.getZ();
}
/* End point? */
else if (t == 1.0) {
/* Copy */
return this.p1.getZ();
}
/* Intermediate point */
else {
/* Calculate a new point */
return this.p0.getZ() + t * (this.p1.getZ() - this.p0.getZ());
}
}
/**
* Get a point along the line.
* @param d the distance of the point (0.0 at start).
* @return a point.
*/
public getPointAtDistance(d: float64): Coordinate {
return this.getPoint(d / this.getLength());
}
/**
* Get a point along the line.
* @param d the distance of the point (0.0 at start).
* @param point the result point (must be mutable).
*/
public getPointAtDistanceTo(d: float64, point: Coordinate): void {
this.getPointTo(d / this.getLength(), point);
}
/**
* Get the position for a fixed x value.
* @param x the x value.
* @return the position on the line.
*/
public getPointAtX(x: float64): float64 {
return (x - this.p0.getX()) / (this.p1.getX() - this.p0.getX());
}
/**
* Get a point along the line.
* @param x the x value.
* @param point the result point (must be mutable).
*/
public getPointAtXTo(x: float64, point: Coordinate): void {
this.getPointTo(this.getPointAtX(x), point);
point.setX(x);
}
/**
* Get the position for a fixed y value.
* @param y the y value.
* @return the position on the line.
*/
public getPointAtY(y: float64): float64 {
return (y - this.p0.getY()) / (this.p1.getY() - this.p0.getY());
}
/**
* Get a point along the line.
* @param y the y value.
* @param point the result point (must be mutable).
*/
public getPointAtYTo(y: float64, point: Coordinate): void {
this.getPointTo(this.getPointAtY(y), point);
point.setY(y);
}
/**
* Get the position for a fixed z value.
* @param z the z value.
* @return the position on the line.
*/
public getPointAtZ(z: float64): float64 {
return (z - this.p0.getZ()) / (this.p1.getZ() - this.p0.getZ());
}
/**
* Get a point along the line.
* @param z the z value.
* @param point the result point (must be mutable).
*/
public getPointAtZTo(z: float64, point: Coordinate): void {
this.getPointTo(this.getPointAtZ(z), point);
point.setZ(z);
}
/**
* Get the direction vector (P1-P0).
* @return the direction vector.
*/
public getDirection(): Coordinate {
/* Return the direction */
return this.p1.subtract(this.p0);
}
/**
* Get the direction vector (P1-P0).
* @param direction the result direction vector.
*/
public getDirectionTo(direction: Coordinate): void {
/* Return the direction */
direction.set(this.p1);
direction.subtract0(this.p0);
}
/**
* Get the direction vector (P1-P0).
* @return the direction vector.
*/
public getDifference(): Coordinate {
return this.getDirection();
}
/**
* Swap the orientation of the line (create a line from point1 to point0).
* @return a new line.
*/
public swapDirection(): Line {
return new Line(this.p1, this.p0);
}
/**
* Get the squared length of the segment.
* @return the squared length of the segment.
*/
public getSquaredLength(): float64 {
/* Get the direction */
let dx: float64 = (this.p1.getX() - this.p0.getX());
let dy: float64 = (this.p1.getY() - this.p0.getY());
let dz: float64 = (this.p1.getZ() - this.p0.getZ());
/* Return the length */
return (dx * dx + dy * dy + dz * dz);
}
/**
* Get the length of the segment.
* @return the length of the segment.
*/
public getLength(): float64 {
return Math.sqrt(this.getSquaredLength());
}
/**
* Project a point on the segment.
* @param point the point to project.
* @return the position of the projected point.
*/
public getProjection(point: Coordinate): float64 {
/* Get the direction of the point */
let pdx: float64 = (point.getX() - this.p0.getX());
let pdy: float64 = (point.getY() - this.p0.getY());
let pdz: float64 = (point.getZ() - this.p0.getZ());
/* Get the direction */
let dx: float64 = (this.p1.getX() - this.p0.getX());
let dy: float64 = (this.p1.getY() - this.p0.getY());
let dz: float64 = (this.p1.getZ() - this.p0.getZ());
/* Return the value */
return (pdx * dx + pdy * dy + pdz * dz) / this.getSquaredLength();
}
/**
* Project a point on the segment.
* @param point the point to project.
* @return the projected point.
*/
public getProjectionPoint(point: Coordinate): Coordinate {
return this.getPoint(this.getProjection(point));
}
/**
* Get the distance from a point to the line.
* @param point the point.
* @return the distance.
*/
public getDistance(point: Coordinate): float64 {
/* Project the point */
let projected: Coordinate = this.getPoint(this.getProjection(point));
/* Return the square distance */
return projected.distance3D(point);
}
/**
* Get the distance from a point to the segment between point 0 and point 1.
* @param point the point.
* @return the distance.
*/
public getSegmentDistance(point: Coordinate): float64 {
/* Clip the projection */
let t: float64 = this.getProjection(point);
if (t < 0.0) t = 0.0; else if (t > 1.0) t = 1.0;
/* Return the distance */
let closest: Coordinate = this.getPoint(t);
return closest.distance3D(point);
}
/**
* Check if the denominator of an intersection is zero (parallel lines).
* @param value the denominator value.
* @return true if zero (like -7.105427357601002E-15, -3.8944125702045085E-10 or -3.808708481679941E-9 for perfectly parallel lines).
*/
public static isZero(value: float64): boolean {
if (value == 0.0) return true;
return (Math.abs(value) < 1.0e-6);
}
/**
* Check if the lines is parallel with another line.
* @param line the other line.
* @return true if the lines are parallel.
*/
public isParallel(line: Line): boolean {
/* Get the direction vectors */
let u: Coordinate = this.getDifference();
let v: Coordinate = line.getDifference();
/* Get the parameters for the equation */
let a: float64 = u.dotProduct(u);
let b: float64 = u.dotProduct(v);
let c: float64 = v.dotProduct(v);
/* Solve the equation */
return (Line.isZero(a * c - b * b));
}
/**
* Intersect with another line.
* The two lines should not be parallel, check with 'isParallel' first !
* @param line the line the intersect with.
* @return the position of the intersection point.
*/
public getIntersection(line: Line): float64 {
// Algorithm copied from:
// http://softsurfer.com/Archive/algorithm_0106/algorithm_0106.htm
//
/* Get the direction vectors */
let u: Coordinate = this.getDifference();
let v: Coordinate = line.getDifference();
/* Get the translation vector */
let w0: Coordinate = this.p0.subtract(line.p0);
/* Get the parameters for the equation */
let a: float64 = u.dotProduct(u);
let b: float64 = u.dotProduct(v);
let c: float64 = v.dotProduct(v);
let d: float64 = u.dotProduct(w0);
let e: float64 = v.dotProduct(w0);
/* Parallel */
let denominator: float64 = (a * c - b * b);
ASystem.assert0(Line.isZero(denominator) == false, "Lines " + this + " and " + line + " are parallel when intersecting");
/* Solve the equation */
return (b * e - c * d) / denominator;
}
/**
* Intersect with another line.
* @param line the line the intersect with.
* @return the intersection point (null if the lines are parallell).
*/
public getIntersectionPoint(line: Line): Coordinate {
if (this.isParallel(line)) return null;
return this.getPoint(this.getIntersection(line));
}
/**
* Interpolate a point.
* @param point1 the first point on the line.
* @param point2 the second point on the line.
* @param t the point parameter.
* @param point the target point.
*/
public static interpolate(point1: Coordinate, point2: Coordinate, t: float64, point: Coordinate): void {
let x: float64 = point1.getX() + t * (point2.getX() - point1.getX());
let y: float64 = point1.getY() + t * (point2.getY() - point1.getY());
let z: float64 = point1.getZ() + t * (point2.getZ() - point1.getZ());
point.setXYZ(x, y, z);
}
/**
* The standard toString method.
* @see Object#toString
*/
public toString(): string {
return "[Line:p0=" + this.p0 + ",p1=" + this.p1 + "]";
}
} | the_stack |
import type * as ts from "typescript";
import * as fs from "fs";
import * as path from "path";
import type { Application } from "../application";
import type { Theme } from "./theme";
import { RendererEvent, PageEvent } from "./events";
import type { ProjectReflection } from "../models/reflections/project";
import type { UrlMapping } from "./models/UrlMapping";
import { remove, writeFileSync } from "../utils/fs";
import { DefaultTheme } from "./themes/default/DefaultTheme";
import { RendererComponent } from "./components";
import { Component, ChildableComponent } from "../utils/component";
import { BindOption } from "../utils";
import { loadHighlighter } from "../utils/highlighter";
import type { Theme as ShikiTheme } from "shiki";
import { Reflection } from "../models";
/**
* The renderer processes a {@link ProjectReflection} using a {@link Theme} instance and writes
* the emitted html documents to a output directory. You can specify which theme should be used
* using the `--theme <name>` command line argument.
*
* {@link Renderer} is a subclass of {@link EventDispatcher} and triggers a series of events while
* a project is being processed. You can listen to these events to control the flow or manipulate
* the output.
*
* * {@link Renderer.EVENT_BEGIN}<br>
* Triggered before the renderer starts rendering a project. The listener receives
* an instance of {@link RendererEvent}. By calling {@link RendererEvent.preventDefault} the entire
* render process can be canceled.
*
* * {@link Renderer.EVENT_BEGIN_PAGE}<br>
* Triggered before a document will be rendered. The listener receives an instance of
* {@link PageEvent}. By calling {@link PageEvent.preventDefault} the generation of the
* document can be canceled.
*
* * {@link Renderer.EVENT_END_PAGE}<br>
* Triggered after a document has been rendered, just before it is written to disc. The
* listener receives an instance of {@link PageEvent}. When calling
* {@link PageEvent.preventDefault} the the document will not be saved to disc.
*
* * {@link Renderer.EVENT_END}<br>
* Triggered after the renderer has written all documents. The listener receives
* an instance of {@link RendererEvent}.
*/
@Component({ name: "renderer", internal: true, childClass: RendererComponent })
export class Renderer extends ChildableComponent<
Application,
RendererComponent
> {
private themes = new Map<string, new (renderer: Renderer) => Theme>([
["default", DefaultTheme],
]);
private unknownSymbolResolvers = new Map<
string,
Array<(symbol: string) => string | undefined>
>();
/** @event */
static readonly EVENT_BEGIN_PAGE = PageEvent.BEGIN;
/** @event */
static readonly EVENT_END_PAGE = PageEvent.END;
/** @event */
static readonly EVENT_BEGIN = RendererEvent.BEGIN;
/** @event */
static readonly EVENT_END = RendererEvent.END;
/**
* The theme that is used to render the documentation.
*/
theme?: Theme;
/** @internal */
@BindOption("theme")
themeName!: string;
/** @internal */
@BindOption("cleanOutputDir")
cleanOutputDir!: boolean;
/** @internal */
@BindOption("gaID")
gaID!: string;
/** @internal */
@BindOption("gaSite")
gaSite!: string;
/** @internal */
@BindOption("githubPages")
githubPages!: boolean;
/** @internal */
@BindOption("hideGenerator")
hideGenerator!: boolean;
/** @internal */
@BindOption("lightHighlightTheme")
lightTheme!: ShikiTheme;
/** @internal */
@BindOption("darkHighlightTheme")
darkTheme!: ShikiTheme;
/**
* Define a new theme that can be used to render output.
* This API will likely be changing in TypeDoc 0.23.
* (sorry... changing as soon as it's introduced)
* As it is, it provides reasonable flexibility, but doesn't give users a sufficiently
* easy way to overwrite parts of a theme.
* @param name
* @param theme
*/
defineTheme(name: string, theme: new (renderer: Renderer) => Theme) {
if (this.themes.has(name)) {
throw new Error(`The theme "${name}" has already been defined.`);
}
this.themes.set(name, theme);
}
/**
* Adds a new resolver that the theme can used to try to figure out how to link to a symbol
* declared by a third-party library which is not included in the documentation.
* @param packageName the npm package name that this resolver can handle to limit which files it will be tried on.
* If the resolver will create links for Node builtin types, it should be set to `@types/node`.
* Links for builtin types live in the default lib files under `typescript`.
* @param resolver a function that will be called to create links for a given symbol name in the registered path.
* If the provided name is not contained within the docs, should return `undefined`.
* @since 0.22.0
*/
addUnknownSymbolResolver(
packageName: string,
resolver: (name: string) => string | undefined
) {
const existing = this.unknownSymbolResolvers.get(packageName);
if (existing) {
existing.push(resolver);
} else {
this.unknownSymbolResolvers.set(packageName, [resolver]);
}
}
/**
* Marked as internal for now. Using this requires the internal `getSymbol()` method on ReferenceType.
* Someday that needs to be fixed so that this can be made public. ReferenceTypes really shouldn't store
* symbols so that we don't need to keep the program around forever.
* @internal
*/
attemptExternalResolution(
symbol: ts.Symbol | undefined
): string | undefined {
const symbolPath = symbol?.declarations?.[0]
?.getSourceFile()
.fileName.replace(/\\/g, "/");
if (!symbolPath) {
return;
}
let startIndex = symbolPath.indexOf("node_modules/");
if (startIndex === -1) {
return;
}
startIndex += "node_modules/".length;
let stopIndex = symbolPath.indexOf("/", startIndex);
// Scoped package, e.g. `@types/node`
if (symbolPath[startIndex] === "@") {
stopIndex = symbolPath.indexOf("/", stopIndex + 1);
}
const packageName = symbolPath.substring(startIndex, stopIndex);
const resolvers = this.unknownSymbolResolvers.get(packageName);
for (const resolver of resolvers || []) {
const resolved = resolver(symbol!.name);
if (resolved) return resolved;
}
}
/**
* Render the given project reflection to the specified output directory.
*
* @param project The project that should be rendered.
* @param outputDirectory The path of the directory the documentation should be rendered to.
*/
async render(
project: ProjectReflection,
outputDirectory: string
): Promise<void> {
const start = Date.now();
await loadHighlighter(this.lightTheme, this.darkTheme);
this.application.logger.verbose(
`Renderer: Loading highlighter took ${Date.now() - start}ms`
);
if (
!this.prepareTheme() ||
!(await this.prepareOutputDirectory(outputDirectory))
) {
return;
}
const output = new RendererEvent(
RendererEvent.BEGIN,
outputDirectory,
project
);
output.urls = this.theme!.getUrls(project);
this.trigger(output);
if (!output.isDefaultPrevented) {
output.urls.forEach((mapping: UrlMapping) => {
this.renderDocument(output.createPageEvent(mapping));
});
this.trigger(RendererEvent.END, output);
}
this.theme = void 0;
}
/**
* Render a single page.
*
* @param page An event describing the current page.
* @return TRUE if the page has been saved to disc, otherwise FALSE.
*/
private renderDocument(page: PageEvent): boolean {
this.trigger(PageEvent.BEGIN, page);
if (page.isDefaultPrevented) {
return false;
}
if (page.model instanceof Reflection) {
page.contents = this.theme!.render(page as PageEvent<Reflection>);
} else {
throw new Error("Should be unreachable");
}
this.trigger(PageEvent.END, page);
if (page.isDefaultPrevented) {
return false;
}
try {
writeFileSync(page.filename, page.contents);
} catch (error) {
this.application.logger.error(`Could not write ${page.filename}`);
return false;
}
return true;
}
/**
* Ensure that a theme has been setup.
*
* If a the user has set a theme we try to find and load it. If no theme has
* been specified we load the default theme.
*
* @returns TRUE if a theme has been setup, otherwise FALSE.
*/
private prepareTheme(): boolean {
if (!this.theme) {
const ctor = this.themes.get(this.themeName);
if (!ctor) {
this.application.logger.error(
`The theme '${
this.themeName
}' is not defined. The available themes are: ${[
...this.themes.keys(),
].join(", ")}`
);
return false;
} else {
this.theme = new ctor(this);
}
}
return true;
}
/**
* Prepare the output directory. If the directory does not exist, it will be
* created. If the directory exists, it will be emptied.
*
* @param directory The path to the directory that should be prepared.
* @returns TRUE if the directory could be prepared, otherwise FALSE.
*/
private async prepareOutputDirectory(directory: string): Promise<boolean> {
if (this.cleanOutputDir) {
try {
await remove(directory);
} catch (error) {
this.application.logger.warn(
"Could not empty the output directory."
);
return false;
}
}
try {
fs.mkdirSync(directory, { recursive: true });
} catch (error) {
this.application.logger.error(
`Could not create output directory ${directory}.`
);
return false;
}
if (this.githubPages) {
try {
const text =
"TypeDoc added this file to prevent GitHub Pages from " +
"using Jekyll. You can turn off this behavior by setting " +
"the `githubPages` option to false.";
fs.writeFileSync(path.join(directory, ".nojekyll"), text);
} catch (error) {
this.application.logger.warn(
"Could not create .nojekyll file."
);
return false;
}
}
return true;
}
}
// HACK: THIS HAS TO STAY DOWN HERE
// if you try to move it up to the top of the file, then you'll run into stuff being used before it has been defined.
import "./plugins"; | the_stack |
import { expect } from "chai";
import { Arc3d } from "../../curve/Arc3d";
import { CurveCurve } from "../../curve/CurveCurve";
import { GeometryQuery } from "../../curve/GeometryQuery";
import { LineSegment3d } from "../../curve/LineSegment3d";
import { Point3d } from "../../geometry3d/Point3dVector3d";
import { Checker } from "../Checker";
import { GeometryCoreTestIO } from "../GeometryCoreTestIO";
import { CurvePrimitive } from "../../curve/CurvePrimitive";
import { LineString3d } from "../../curve/LineString3d";
import { BSplineCurve3d } from "../../bspline/BSplineCurve";
/**
* Create line segments joining various fractional positions on two arcs.
* Compute close approach for each.
* @param _ck
* @param allGeometry
* @param geometryA
*/
function testVaryingLineSegments(_ck: Checker, allGeometry: GeometryQuery[], geometryA: CurvePrimitive) {
const path0 = Arc3d.createXY(geometryA.fractionToPoint(0.5), 4)!;
const path1 = Arc3d.createCircularStartMiddleEnd(Point3d.create(0, 9), Point3d.create(6, 3), Point3d.create(3, -3))!;
const fractions = [0.0, 0.1, 0.2, 0.3, 0.4, 0.6, 0.8, 0.9, 1.0];
let x0 = 0;
const maxDistance = 2.5;
for (const f0 of fractions) {
let y0 = 0;
for (const f1 of fractions) {
const lineB = LineSegment3d.create(path0.fractionToPoint(f0), path1.fractionToPoint(f1));
const approaches = CurveCurve.closeApproachProjectedXYPairs(geometryA, lineB, 2.5);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, geometryA, x0, y0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, lineB, x0, y0);
if (approaches.length > 0) {
for (const p of approaches)
if (p.detailA.point.isAlmostEqual(p.detailB.point))
GeometryCoreTestIO.createAndCaptureXYCircle(allGeometry, p.detailA.point, 0.0625, x0, y0);
else
GeometryCoreTestIO.captureGeometry(allGeometry, LineSegment3d.create(p.detailA.point, p.detailB.point), x0, y0);
} else {
GeometryCoreTestIO.createAndCaptureXYCircle(allGeometry, geometryA.startPoint(), maxDistance, x0, y0);
GeometryCoreTestIO.createAndCaptureXYCircle(allGeometry, geometryA.endPoint(), maxDistance, x0, y0);
GeometryCoreTestIO.createAndCaptureXYCircle(allGeometry, lineB.startPoint(), maxDistance, x0, y0);
GeometryCoreTestIO.createAndCaptureXYCircle(allGeometry, lineB.endPoint(), maxDistance, x0, y0);
}
y0 += 20;
}
x0 += 20;
}
}
/**
* Create partial curves in various fractional intervals of geometryB.
* Compute close approach for each.
* @param _ck
* @param allGeometry
* @param geometryA
*/
function testVaryingSubsets(_ck: Checker, allGeometry: GeometryQuery[], geometryA: CurvePrimitive, geometryB: CurvePrimitive,
maxDistance: number = 0.25,
fractions: number[] = [1.0, 0.9, 0.0, 0.2, 0.3, 0.4, 0.6, 0.8]) {
let x0 = 0;
GeometryCoreTestIO.createAndCaptureXYCircle(allGeometry, Point3d.create(x0, 0), maxDistance, x0, 0);
for (const f0 of fractions) {
let y0 = 0;
for (const f1 of fractions) {
if (f0 !== f1) {
let partialB: CurvePrimitive | undefined;
if (f0 === 0 && f1 === 1) {
partialB = geometryB.clone();
} else {
partialB = geometryB.clonePartialCurve(f0, f1);
}
if (!partialB)
continue;
const approaches = CurveCurve.closeApproachProjectedXYPairs(geometryA, partialB, maxDistance);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, geometryA, x0, y0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, partialB, x0, y0);
if (approaches.length > 0) {
for (const p of approaches)
if (p.detailA.point.isAlmostEqual(p.detailB.point))
GeometryCoreTestIO.createAndCaptureXYCircle(allGeometry, p.detailA.point, maxDistance / 5, x0, y0);
else
GeometryCoreTestIO.captureGeometry(allGeometry, LineSegment3d.create(p.detailA.point, p.detailB.point), x0, y0);
} else {
GeometryCoreTestIO.createAndCaptureXYCircle(allGeometry, geometryA.startPoint(), maxDistance, x0, y0);
GeometryCoreTestIO.createAndCaptureXYCircle(allGeometry, geometryA.endPoint(), maxDistance, x0, y0);
GeometryCoreTestIO.createAndCaptureXYCircle(allGeometry, partialB.startPoint(), maxDistance, x0, y0);
GeometryCoreTestIO.createAndCaptureXYCircle(allGeometry, partialB.endPoint(), maxDistance, x0, y0);
}
}
y0 += 20;
}
x0 += 20;
}
}
describe("CurveCurveCloseApproachXY", () => {
it("LineLine", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
testVaryingLineSegments(ck, allGeometry, LineSegment3d.createXYXY(1, 2, 5, 2));
GeometryCoreTestIO.saveGeometry(allGeometry, "CurveCurveCloseApproachXY", "LineLine");
expect(ck.getNumErrors()).equals(0);
});
it("LineLineString", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
testVaryingLineSegments(ck, allGeometry, LineString3d.create([[1, 2], [5, 2], [4, 3]]));
GeometryCoreTestIO.saveGeometry(allGeometry, "CurveCurveCloseApproachXY", "LineLineString");
expect(ck.getNumErrors()).equals(0);
});
it("LineArc", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const arc = Arc3d.createCircularStartMiddleEnd(Point3d.create(1, 2), Point3d.create(3, 3.5), Point3d.create(5, 2))!;
testVaryingLineSegments(ck, allGeometry, arc);
GeometryCoreTestIO.saveGeometry(allGeometry, "CurveCurveCloseApproachXY", "LineArc");
expect(ck.getNumErrors()).equals(0);
});
it("ArcArc", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const arcA = Arc3d.createCircularStartMiddleEnd(Point3d.create(1, 2), Point3d.create(3, 3.5), Point3d.create(5, 2))!;
const arcB = Arc3d.createCircularStartMiddleEnd(Point3d.create(3, 2), Point3d.create(-1, 1.5), Point3d.create(0, -2))!;
testVaryingSubsets(ck, allGeometry, arcA, arcB);
GeometryCoreTestIO.saveGeometry(allGeometry, "CurveCurveCloseApproachXY", "ArcArc");
expect(ck.getNumErrors()).equals(0);
});
it("ArcArcFar", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const arcA = Arc3d.createXY(Point3d.create(1, 1), 1.5);
const arcB = Arc3d.createXY(Point3d.create(5, 2), 2);
testVaryingSubsets(ck, allGeometry, arcA, arcB);
GeometryCoreTestIO.saveGeometry(allGeometry, "CurveCurveCloseApproachXY", "ArcArcFar");
expect(ck.getNumErrors()).equals(0);
});
it("ArcArcInside", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const arcA = Arc3d.createXY(Point3d.create(1, 1), 5);
const arcB = Arc3d.createXY(Point3d.create(2, 3), 2);
testVaryingSubsets(ck, allGeometry, arcA, arcB);
GeometryCoreTestIO.saveGeometry(allGeometry, "CurveCurveCloseApproachXY", "ArcArcInside");
expect(ck.getNumErrors()).equals(0);
});
it("LineStringLineString", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const cpA = LineString3d.create([[1, 2], [5, 2], [3, 5]]);
const cpB = LineString3d.create([[1, 3], [4, 2.5], [6, 4]]);
testVaryingSubsets(ck, allGeometry, cpA, cpB);
GeometryCoreTestIO.saveGeometry(allGeometry, "CurveCurveCloseApproachXY", "LineStringLineString");
expect(ck.getNumErrors()).equals(0);
});
it("LineStringLineStringLong", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const cpA = LineString3d.create();
const cpB = LineString3d.create();
for (let x = 0; x <= 10; x += 1) {
const f = x / 10;
cpA.addPointXYZ(x, 0, 0);
cpA.addPointXYZ(x + 0.5, 0.5, 0);
cpB.addPointXYZ(x + 0.125, 1, 0);
cpB.addPointXYZ(x + 0.6, 0.8 - f * f * 0.4, 0);
}
testVaryingSubsets(ck, allGeometry, cpA, cpB, 0.6);
GeometryCoreTestIO.saveGeometry(allGeometry, "CurveCurveCloseApproachXY", "LineStringLineStringLong06");
allGeometry.length = 0;
testVaryingSubsets(ck, allGeometry, cpA, cpB, 0.3);
GeometryCoreTestIO.saveGeometry(allGeometry, "CurveCurveCloseApproachXY", "LineStringLineStringLong03");
expect(ck.getNumErrors()).equals(0);
});
it("ArcLineString", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const cpA = Arc3d.createCircularStartMiddleEnd(Point3d.create(1, 2), Point3d.create(3, 3.5), Point3d.create(5, 2))!;
const cpB = LineString3d.create([[1, 3], [4, 2.5], [6, 4]]);
testVaryingSubsets(ck, allGeometry, cpA, cpB);
GeometryCoreTestIO.saveGeometry(allGeometry, "CurveCurveCloseApproachXY", "ArcLineString");
expect(ck.getNumErrors()).equals(0);
});
it("BsplineLineString", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const cpA = BSplineCurve3d.createUniformKnots([Point3d.create(0, 0, 0), Point3d.create(1, 0.5, 0), Point3d.create(2, 0, 0), Point3d.create(3, 2, 0), Point3d.create(4, 0, 0)], 4)!;
const cpB = LineString3d.create([[1, 3], [4, 2.5], [6, 3]]);
testVaryingSubsets(ck, allGeometry, cpA, cpB, 1, [0, 1]);
GeometryCoreTestIO.saveGeometry(allGeometry, "CurveCurveCloseApproachXY", "BsplineLineString1");
allGeometry.length = 0;
testVaryingSubsets(ck, allGeometry, cpA, cpB, 2, [0, 1]);
GeometryCoreTestIO.saveGeometry(allGeometry, "CurveCurveCloseApproachXY", "BsplineLineString2");
expect(ck.getNumErrors()).equals(0);
});
it("BsplineArc", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const cpA = BSplineCurve3d.createUniformKnots([Point3d.create(0, 3, 0), Point3d.create(1, 0.5, 0), Point3d.create(2, 0, 0), Point3d.create(5, 2, 0), Point3d.create(6, 4, 0)], 4)!;
const cpB = Arc3d.createCircularStartMiddleEnd(Point3d.create(1, 3), Point3d.create(4, 2.5), Point3d.create(6, 2))!;
testVaryingSubsets(ck, allGeometry, cpA, cpB, 2, [0, 1]);
GeometryCoreTestIO.saveGeometry(allGeometry, "CurveCurveCloseApproachXY", "BsplineArc");
allGeometry.length = 0;
const cpB1 = Arc3d.createCircularStartMiddleEnd(Point3d.create(1, -1), Point3d.create(4, 0), Point3d.create(6, -1))!;
testVaryingSubsets(ck, allGeometry, cpA, cpB1, 2, [0, 1]);
GeometryCoreTestIO.saveGeometry(allGeometry, "CurveCurveCloseApproachXY", "BsplineArcB");
allGeometry.length = 0;
testVaryingSubsets(ck, allGeometry, cpB, cpA, 2, [0, 1]);
GeometryCoreTestIO.saveGeometry(allGeometry, "CurveCurveCloseApproachXY", "ArcBspline");
allGeometry.length = 0;
const cpB2 = LineSegment3d.create (Point3d.create(1, -1), Point3d.create(6, -1));
testVaryingSubsets(ck, allGeometry, cpA, cpB2, 2, [0, 1]);
GeometryCoreTestIO.saveGeometry(allGeometry, "CurveCurveCloseApproachXY", "BsplineLine");
expect(ck.getNumErrors()).equals(0);
});
}); | 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_icon_button/cr_icon_button.m.js';
import 'chrome://resources/cr_elements/cr_icons_css.m.js';
import 'chrome://resources/cr_elements/cr_input/cr_input.m.js';
import 'chrome://resources/polymer/v3_0/iron-pages/iron-pages.js';
import 'chrome://resources/polymer/v3_0/paper-spinner/paper-spinner-lite.js';
import '../settings_shared_css.js';
import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js';
import {CrInputElement} from 'chrome://resources/cr_elements/cr_input/cr_input.m.js';
import {I18nMixin} from 'chrome://resources/js/i18n_mixin.js';
import {PluralStringProxyImpl} from 'chrome://resources/js/plural_string_proxy.js';
import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {loadTimeData} from '../i18n_setup.js';
import {SecurityKeysPINBrowserProxy, SecurityKeysPINBrowserProxyImpl} from './security_keys_browser_proxy.js';
export enum SetPINDialogPage {
INITIAL = 'initial',
NO_PIN_SUPPORT = 'noPINSupport',
REINSERT = 'reinsert',
LOCKED = 'locked',
ERROR = 'error',
PIN_PROMPT = 'pinPrompt',
SUCCESS = 'success',
}
interface SettingsSecurityKeysSetPinDialogElement {
$: {
confirmPIN: CrInputElement,
currentPIN: CrInputElement,
dialog: CrDialogElement,
newPIN: CrInputElement,
};
}
const SettingsSecurityKeysSetPinDialogElementBase = I18nMixin(PolymerElement);
class SettingsSecurityKeysSetPinDialogElement extends
SettingsSecurityKeysSetPinDialogElementBase {
static get is() {
return 'settings-security-keys-set-pin-dialog';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
/**
* Whether the value of the current PIN textbox is a valid PIN or not.
*/
currentPINValid_: Boolean,
newPINValid_: Boolean,
confirmPINValid_: Boolean,
/**
* Whether the dialog is in a state where the Set PIN button should be
* enabled. Read by Polymer.
*/
setPINButtonValid_: {
type: Boolean,
value: false,
},
/**
* The value of the new PIN textbox. Read/write by Polymer.
*/
newPIN_: {
type: String,
value: '',
},
confirmPIN_: {
type: String,
value: '',
},
currentPIN_: {
type: String,
value: '',
},
/**
* The minimum length for the currently set PIN.
*/
currentMinPinLength_: Number,
/**
* The minimum length to set a new PIN.
*/
newMinPinLength_: {
type: Number,
observer: 'newMinPinLengthChanged_',
},
/**
* The number of PIN attempts remaining.
*/
retries_: Number,
/**
* A CTAP error code when we don't recognise the specific error. Read by
* Polymer.
*/
errorCode_: Number,
/**
* Whether an entry for the current PIN should be displayed. (If no PIN
* has been set then it won't be shown.)
*/
showCurrentEntry_: {
type: Boolean,
value: false,
},
/**
* Error string to display under the current PIN entry, or empty.
*/
currentPINError_: {
type: String,
value: '',
},
/**
* Error string to display under the new PIN entry, or empty.
*/
newPINError_: {
type: String,
value: '',
},
/**
* Error string to display under the confirmation PIN entry, or empty.
*/
confirmPINError_: {
type: String,
value: '',
},
/**
* Whether the dialog process has completed, successfully or otherwise.
*/
complete_: {
type: Boolean,
value: false,
},
/**
* The id of an element on the page that is currently shown.
*/
shown_: {
type: String,
value: SetPINDialogPage.INITIAL,
},
/**
* Whether the contents of the PIN entries are visible, or are displayed
* like passwords.
*/
pinsVisible_: {
type: Boolean,
value: false,
},
title_: String,
newPINDialogDescription_: String,
};
}
private currentPINValid_: boolean;
private newPINValid_: boolean;
private confirmPINValid_: boolean;
private setPINButtonValid_: boolean;
private newPIN_: string;
private confirmPIN_: string;
private currentPIN_: string;
private currentMinPinLength_?: number;
private newMinPinLength_?: number;
private retries_?: number;
private errorCode_?: number;
private showCurrentEntry_: boolean;
private currentPINError_: string;
private newPINError_: string;
private confirmPINError_: string;
private complete_: boolean;
private shown_: SetPINDialogPage;
private pinsVisible_: boolean;
private title_: string;
private newPINDialogDescription_: string;
private browserProxy_: SecurityKeysPINBrowserProxy =
SecurityKeysPINBrowserProxyImpl.getInstance();
connectedCallback() {
super.connectedCallback();
this.title_ = this.i18n('securityKeysSetPINInitialTitle');
this.$.dialog.showModal();
this.browserProxy_.startSetPIN().then(
({done, error, currentMinPinLength, newMinPinLength, retries}) => {
if (done) {
// Operation is complete. error is a CTAP error code. See
// https://fidoalliance.org/specs/fido-v2.0-rd-20180702/fido-client-to-authenticator-protocol-v2.0-rd-20180702.html#error-responses
if (error === 1 /* INVALID_COMMAND */) {
this.shown_ = SetPINDialogPage.NO_PIN_SUPPORT;
this.finish_();
} else if (error === 52 /* temporarily locked */) {
this.shown_ = SetPINDialogPage.REINSERT;
this.finish_();
} else if (error === 50 /* locked */) {
this.shown_ = SetPINDialogPage.LOCKED;
this.finish_();
} else {
this.errorCode_ = error;
this.shown_ = SetPINDialogPage.ERROR;
this.finish_();
}
} else if (retries === 0) {
// A device can also signal that it is locked by returning zero
// retries.
this.shown_ = SetPINDialogPage.LOCKED;
this.finish_();
} else {
// Need to prompt for a pin. Initially set the text boxes to valid
// so that they don't all appear red without the user typing
// anything.
this.currentPINValid_ = true;
this.newPINValid_ = true;
this.confirmPINValid_ = true;
this.setPINButtonValid_ = true;
this.currentMinPinLength_ = currentMinPinLength;
this.newMinPinLength_ = newMinPinLength;
this.retries_ = retries;
// retries_ may be null to indicate that there is currently no PIN
// set.
let focusTarget: HTMLElement;
if (this.retries_ === null) {
this.showCurrentEntry_ = false;
focusTarget = this.$.newPIN;
this.title_ = this.i18n('securityKeysSetPINCreateTitle');
} else {
this.showCurrentEntry_ = true;
focusTarget = this.$.currentPIN;
this.title_ = this.i18n('securityKeysSetPINChangeTitle');
}
this.shown_ = SetPINDialogPage.PIN_PROMPT;
// Focus cannot be set directly from within a backend callback.
window.setTimeout(function() {
focusTarget.focus();
}, 0);
this.fire_('ui-ready'); // for test synchronization.
}
});
}
private fire_(eventName: string, detail?: any) {
this.dispatchEvent(
new CustomEvent(eventName, {bubbles: true, composed: true, detail}));
}
private closeDialog_() {
this.$.dialog.close();
this.finish_();
}
private finish_() {
if (this.complete_) {
return;
}
this.complete_ = true;
// Setting |complete_| to true hides the |pinSubmitNew| button while it
// has focus, which in turn causes the browser to move focus to the <body>
// element, which in turn prevents subsequent "Enter" keystrokes to be
// handled by cr-dialog itself. Re-focusing manually fixes this.
this.$.dialog.focus();
this.browserProxy_.close();
}
private onIronSelect_(e: Event) {
// Prevent this event from bubbling since it is unnecessarily triggering
// the listener within settings-animated-pages.
e.stopPropagation();
}
private onCurrentPINInput_() {
// Typing in the current PIN box after an error makes the error message
// disappear.
this.currentPINError_ = '';
}
private onNewPINInput_() {
// Typing in the new PIN box after an error makes the error message
// disappear.
this.newPINError_ = '';
}
private onConfirmPINInput_() {
// Typing in the confirm PIN box after an error makes the error message
// disappear.
this.confirmPINError_ = '';
}
/**
@param pin A candidate PIN.
@return An error string or else '' to indicate validity.
*/
private isValidPIN_(pin: string, minLength: number): string {
// The UTF-8 encoding of the PIN must be between minLength and 63 bytes, and
// the final byte cannot be zero.
const utf8Encoded = new TextEncoder().encode(pin);
if (utf8Encoded.length < minLength) {
return this.i18n('securityKeysPINTooShort');
}
if (utf8Encoded.length > 63 ||
// If the PIN somehow has a NUL at the end then it's invalid, but this
// is so obscure that we don't try to message it. Rather we just say
// that it's too long because trimming the final character is the best
// response by the user.
utf8Encoded[utf8Encoded.length - 1] === 0) {
return this.i18n('securityKeysPINTooLong');
}
// A PIN must contain at least four code-points. Javascript strings are
// UCS-2 and the |length| property counts UCS-2 elements, not code-points.
// (For example, '\u{1f6b4}'.length === 2, but it's a single code-point.)
// Therefore, iterate over the string (which does yield codepoints) and
// check that |minLength| or more were seen.
let length = 0;
for (const codepoint of pin) {
length++;
}
if (length < minLength) {
return this.i18n('securityKeysPINTooShort');
}
return '';
}
/**
* @param retries The number of PIN attempts remaining.
* @return The message to show under the text box.
*/
private mismatchError_(retries: number): string {
// Warn the user if the number of retries is getting low.
if (1 < retries && retries <= 3) {
return this.i18n('securityKeysPINIncorrectRetriesPl', retries.toString());
}
if (retries === 1) {
return this.i18n('securityKeysPINIncorrectRetriesSin');
}
return this.i18n('securityKeysPINIncorrect');
}
/**
* Called to set focus from inside a callback.
*/
private focusOn_(focusTarget: HTMLElement) {
// Focus cannot be set directly from within a backend callback. Also,
// directly focusing |currentPIN| doesn't always seem to work(!). Thus
// focus something else first, which is a hack that seems to solve the
// problem.
let preFocusTarget = this.$.newPIN;
if (preFocusTarget === focusTarget) {
preFocusTarget = this.$.currentPIN;
}
window.setTimeout(function() {
preFocusTarget.focus();
focusTarget.focus();
}, 0);
}
/**
* Called by Polymer when the Set PIN button is activated.
*/
private pinSubmitNew_() {
if (this.showCurrentEntry_) {
this.currentPINError_ =
this.isValidPIN_(this.currentPIN_, this.currentMinPinLength_!);
if (this.currentPINError_ !== '') {
this.focusOn_(this.$.currentPIN);
this.fire_('ui-ready'); // for test synchronization.
return;
}
}
this.newPINError_ = this.isValidPIN_(this.newPIN_, this.newMinPinLength_!);
if (this.newPINError_ !== '') {
this.focusOn_(this.$.newPIN);
this.fire_('ui-ready'); // for test synchronization.
return;
}
if (this.newPIN_ !== this.confirmPIN_) {
this.confirmPINError_ = this.i18n('securityKeysPINMismatch');
this.focusOn_(this.$.confirmPIN);
this.fire_('ui-ready'); // for test synchronization.
return;
}
if (this.newPIN_ === this.currentPIN_) {
this.newPINError_ = this.i18n('securityKeysSamePINAsCurrent');
this.focusOn_(this.$.newPIN);
this.fire_('ui-ready'); // for test synchronization.
return;
}
this.setPINButtonValid_ = false;
this.browserProxy_.setPIN(this.currentPIN_, this.newPIN_).then(response => {
const error = response.error;
// This call always completes the process so response.done is always
// true. error is a CTAP2 error code. See
// https://fidoalliance.org/specs/fido-v2.0-rd-20180702/fido-client-to-authenticator-protocol-v2.0-rd-20180702.html#error-responses
if (error === 0 /* SUCCESS */) {
this.shown_ = SetPINDialogPage.SUCCESS;
this.finish_();
} else if (error === 52 /* temporarily locked */) {
this.shown_ = SetPINDialogPage.REINSERT;
this.finish_();
} else if (error === 50 /* locked */) {
this.shown_ = SetPINDialogPage.LOCKED;
this.finish_();
} else if (error === 49 /* PIN_INVALID */) {
this.currentPINValid_ = false;
this.retries_!--;
this.currentPINError_ = this.mismatchError_(this.retries_!);
this.setPINButtonValid_ = true;
this.focusOn_(this.$.currentPIN);
this.fire_('ui-ready'); // for test synchronization.
} else {
// Unknown error.
this.errorCode_ = error;
this.shown_ = SetPINDialogPage.ERROR;
this.finish_();
}
});
}
/**
* onClick handler for the show/hide icon.
*/
private showPINsClick_() {
this.pinsVisible_ = !this.pinsVisible_;
}
/**
* Polymer helper function to detect when an error string is empty.
*/
private isNonEmpty_(s: string): boolean {
return s !== '';
}
/**
* Called by Polymer when |errorCode_| changes to set the error string.
*/
private pinFailed_() {
if (this.errorCode_ === null) {
return '';
}
return this.i18n('securityKeysPINError', this.errorCode_!.toString());
}
/**
* @return The class of the Ok / Cancel button.
*/
private maybeActionButton_(): string {
return this.complete_ ? 'action-button' : 'cancel-button';
}
/**
* @return The label of the Ok / Cancel button.
*/
private closeText_(): string {
return this.i18n(this.complete_ ? 'ok' : 'cancel');
}
private newMinPinLengthChanged_() {
PluralStringProxyImpl.getInstance()
.getPluralString('securityKeysNewPIN', this.newMinPinLength_!)
.then(string => this.newPINDialogDescription_ = string);
}
/**
* @return The class (and thus icon) to be displayed.
*/
private showPINsClass_(): string {
return 'icon-visibility' + (this.pinsVisible_ ? '-off' : '');
}
/**
* @return The tooltip for the icon.
*/
private showPINsTitle_(): string {
return this.i18n(
this.pinsVisible_ ? 'securityKeysHidePINs' : 'securityKeysShowPINs');
}
/**
* @return The PIN-input element type.
*/
private inputType_(): string {
return this.pinsVisible_ ? 'text' : 'password';
}
}
customElements.define(
SettingsSecurityKeysSetPinDialogElement.is,
SettingsSecurityKeysSetPinDialogElement); | the_stack |
import ApiClient = require('./apiclient');
import Application = require('application');
import Batch = require('./batch');
import BitmapFactory = require('./bitmap-factory');
import Enumerable = require('./enumerable');
import Moment = require('./moment');
import { ObservableArray } from 'data/observable-array';
import { VirtualArray } from 'data/virtual-array';
import XmlObjects = require('./xmlobjects');
/**
* Stores the application name.
*/
export declare var AppName: string;
/**
* List of device orientations.
*/
export declare enum DeviceOrientation {
/**
* Landscape
*/
Landscape = 2,
/**
* Portrait
*/
Portrait = 1,
}
/**
* A clipboard instance.
*/
export interface IClipboard {
/**
* Returns an object / value that is stored as JSON string in the clipboard.
*
* @param {Function} callback The callback with the result.
* @param {T} [tag] The custom object / value for the callback.
*/
getObject<O>(callback: (result: IGetClipboardResult<O>, tag?: any) => void, tag?: any): any;
/**
* Returns a text.
*
* @param {Function} callback The callback with the result.
* @param {T} [tag] The custom object / value for the callback.
*/
getText<T>(callback: (result: IGetClipboardResult<string>, tag?: T) => void, tag?: T): any;
/**
* Sets a value / object as JSON serialized string.
*
* @param {O} obj The object to set.
* @param {Function} [callback] The optional callback with the result.
* @param {T} [tag] The custom object / value for the callback.
*/
setObject<O, T>(obj: O, callback?: (result: ISetClipboardResult<O>, tag?: T) => void, tag?: T): any;
/**
* Sets a text.
*
* @param {String} txt The text to set.
* @param {Function} [callback] The optional callback with the result.
* @param {T} [tag] The custom object / value for the callback.
*/
setText<T>(txt: string, callback?: (result: ISetClipboardResult<string>, tag?: T) => void, tag?: T): any;
}
/**
* The result of closing
*/
export interface ICloseDatabaseResult {
/**
* The error (if occured).
*/
error?: any;
}
/**
* A cell.
*/
export interface ICell {
/**
* The zero based index.
*/
index: number;
/**
* The underlying row.
*/
row?: IRow;
/**
* The value.
*/
value: any;
}
/**
* Config data for executing an SQL statement.
*/
export interface IExecuteSqlConfig {
/**
* The argument for the statement.
*/
args: any[] | ObservableArray<any> | VirtualArray<any> | Enumerable.IEnumerable<any>;
/**
* The optional callback.
*/
callback?: (result: IExecuteSqlResult) => void;
/**
* The statement to execute.
*/
sql: string;
}
/**
* The result of a SQL execution.
*/
export interface IExecuteSqlResult {
/**
* The last inserted ID (if no error).
*/
id?: any;
/**
* The error (if occured).
*/
error?: any;
/**
* Contains the result set (if defined).
*/
result?: Enumerable.IEnumerable<IRow>;
}
/**
* The result of getting a value from the clipboard.
*/
export interface IGetClipboardResult<T> extends IResult {
/**
* The value (if no error)
*/
value?: T;
}
/**
* Configuration for 'invokeForConnectivity()' function.
*/
export interface IInvokeForConnectivityConfig<T> {
/**
* Is invoked on 'mobile' state.
*/
mobile?: (result: IInvokeForConnectivityResult<T>, tag?: T) => void;
/**
* Is invoked on 'mobile' state.
*/
none?: (result: IInvokeForConnectivityResult<T>, tag?: T) => void;
/**
* Is invoked on 'mobile' state.
*/
wifi?: (result: IInvokeForConnectivityResult<T>, tag?: T) => void;
/**
* Is invoked on 'mobile' state.
*/
unknown?: (result: IInvokeForConnectivityResult<T>, tag?: T) => void;
}
/**
* Result for a callback of 'invokeForConnectivity()' function call.
*/
export interface IInvokeForConnectivityResult<T> extends IResult {
/**
* The custom object for the callback.
*/
tag?: T;
/**
* The type
*/
type?: number;
}
/**
* Configuration for 'invokeForOrientation()' function.
*/
export interface IInvokeForOrientationConfig<T> {
/**
* The callback that is invoked if device is in landscape mode.
*/
landscape?: (orientation: DeviceOrientation, tag?: T) => any;
/**
* The callback that is invoked if device is in portrait mode.
*/
portrait?: (orientation: DeviceOrientation, tag?: T) => any;
/**
* The custom objects for the callbacks.
*/
tag?: T;
/**
* The callback that is invoked if device is in unknown mode.
*/
unknown?: (orientation: DeviceOrientation, tag?: T) => any;
}
/**
* Configuration for 'invokeForPlatform()' function.
*/
export interface IInvokeForPlatformConfig<T> {
/**
* Callback that is invoked on Android.
*/
android?: (platform: IPlatformData, tag?: T) => any;
/**
* Callback that is invoked on iOS.
*/
ios?: (platform: IPlatformData, tag?: T) => any;
/**
* The custom objects for the callbacks.
*/
tag?: T;
}
/**
* Config data for opening a database.
*/
export interface IOpenDatabaseConfig {
/**
* The callback for the result.
*/
callback: (result: IOpenDatabaseResult) => void;
/**
* The name of the database to open.
*/
name: string;
/**
* Open readonly or not. Default: (false)
*/
readOnly?: boolean;
}
/**
* The result of opening a database.
*/
export interface IOpenDatabaseResult {
/**
* Gets the connection if succeeded.
*/
db?: ISQLite;
/**
* Gets the error (if occurred.)
*/
error?: any;
/**
* Gets the name of the data the tries to be open.
*/
name: string;
}
/**
* Stores platform data.
*/
export interface IPlatformData {
/**
* Gets the underlying application object.
*/
app: Application.AndroidApplication | Application.iOSApplication;
/**
* Gets if the app runs on Android or not.
*/
android: boolean;
/**
* The application context.
*/
context: any;
/**
* Gets if the app runs on iOS or not.
*/
ios: boolean;
/**
* Gets the type of the platform
*/
type: Platform;
/**
* The native view.
*/
view: any;
}
/**
* A general callback result.
*/
export interface IResult {
/**
* The result code.
*/
code: number;
/**
* The error information (if occurred).
*/
error?: any;
}
/**
* A row.
*/
export interface IRow {
/**
* The cells of the row.
*/
cells?: ICell[];
/**
* The zero based index.
*/
index: number;
}
/**
* The result of setting a value in the clipboard.
*/
export interface ISetClipboardResult<T> extends IResult {
/**
* The value that has been tried to be stored.
*/
value: T;
}
/**
* Result object for the callback of 'setStatusBarVisibility()' function.
*/
export interface ISetStatusBarVisibilityResult<T> extends IResult {
/**
* The actual visibility (if defined)
*/
isVisible?: boolean;
/**
* The custom submitted object.
*/
tag?: T;
}
/**
* A SQLite connection.
*/
export interface ISQLite {
/**
* Closes the connection.
*
* @param {Function} [callback] The optional callback.
*/
close(callback?: (result: ICloseDatabaseResult) => void): any;
/**
* Gets the underlying SQLite object.
*/
conn: any;
/**
* Executes an SQL statement.
*/
execute(cfg: IExecuteSqlConfig): any;
/**
* Gets if the connection is open or not.
*/
isOpen: boolean;
/**
* Gets the name of the opened database.
*/
name: string;
/**
* Executes an SQL statement with a result.
*/
selectAll(cfg: IExecuteSqlConfig): any;
}
/**
* YAML decode options.
*/
export interface IYamlDecodeOptions {
/**
* String to be used as a file path in error/warning messages.
*/
filename?: string;
/**
* Compatibility with JSON.parse behaviour.
* If true, then duplicate keys in a mapping will override values rather than throwing an error.
*/
json?: boolean;
/**
* Function to call on warning messages.
* Loader will throw on warnings if this function is not provided.
*/
onWarning?: (error: any) => void;
/**
* Specifies a schema to use.
*/
schema?: string;
}
/**
* YAML encode options.
*/
export interface IYamlEncodeOptions {
/**
* Specifies level of nesting, when to switch from block to flow style for collections.
* -1 means block style everwhere
*/
flowLevel?: number;
/**
* Indentation width to use (in spaces).
*/
indent?: number;
/**
* Set max line width.
*/
lineWidth?: number;
/**
* If true don't try to be compatible with older yaml versions.
* Currently: don't quote "yes", "no" and so on, as required for YAML 1.1
*/
noCompatMode?: boolean;
/**
* If true, don't convert duplicate objects into references.
*/
noRefs?: boolean;
/**
* Specifies a schema to use.
*/
schema?: string;
/**
* Do not throw on invalid types (like function in the safe schema) and skip pairs and single values with such types.
*/
skipInvalid?: boolean;
/**
* If true, sort keys when dumping YAML. If a function, use the function to sort the keys.
*/
sortKeys?: boolean;
/**
* "tag" => "style" map. Each tag may have own set of styles.
*/
styles?: any;
}
/**
* List of known Markdown dialects
*/
export declare enum MarkdownDialect {
/**
* s. http://daringfireball.net/projects/markdown/syntax
*/
Gruber = 1,
/**
* s. http://maruku.rubyforge.org/maruku.html
*/
Maruku = 2,
}
/**
* List of known platforms.
*/
export declare enum Platform {
/**
* Android
*/
Android = 1,
/**
* iOS
*/
iOS = 2,
}
/**
* List of known target formats.
*/
export declare enum TargetFormat {
/**
* HTML
*/
Html = 1,
/**
* JSON
*/
Json = 2,
}
/**
* Allows the device to go to sleep mode.
*
* @param {Function} [callback] The custom result callback.
* @param {T} [tag] The custom object for the callback to use.
*/
export declare function allowToSleep<T>(callback?: (result: IResult, tag?: T) => void, tag?: T): void;
/**
* Returns a value as bitmap object.
*
* @param any v The input value.
* @param {Boolean} [throwException] Throw exception if 'v' is invalid or return (false).
*
* @throws Input value is invalid.
*
* @return {IBitmap} The output value or (false) if input value is invalid.
*/
export declare function asBitmap(v: any, throwException?: boolean): BitmapFactory.IBitmap;
/**
* Returns a value as sequence.
*
* @param any v The input value.
* @param {Boolean} [throwException] Throws an exception if input value is no valid value.
*
* @throws Invalid value.
*
* @return any The value as sequence or (false) if input value is no valid object.
*/
export declare function asEnumerable(v: any, throwException?: boolean): Enumerable.IEnumerable<any>;
/**
* Creates a new bitmap.
*
* @param {Number} width The width of the new image.
* @param {Number} [height] The optional height of the new image. If not defined, the width is taken as value.
* @param {ICreateBitmapOptions} [opts] Additional options for creating the bitmap.
*
* @return {IBitmap} The new bitmap.
*/
export declare function createBitmap(width: number, height?: number, opts?: BitmapFactory.ICreateBitmapOptions): BitmapFactory.IBitmap;
/**
* Decrypts a value / an object with AES.
*
* @param {String} v The value to decrypt.
*
* @return {T} The decrypted value.
*/
export declare function decrypt<T>(v: string, key: string): T;
/**
* Encrypts a value / an object with AES.
*
* @param any v The value to encrypt.
*
* @return {String} The encrypted value.
*/
export declare function encrypt(v: any, key: string): string;
/**
* Formats a string.
*
* @function format
*
* @param {String} formatStr The format string.
* @param ...any args One or more argument for the format string.
*
* @return {String} The formatted string.
*/
export declare function format(formatStr: string, ...args: any[]): string;
/**
* Formats a string.
*
* @function formatArray
*
* @param {String} formatStr The format string.
* @param {Array} args The list of arguments for the format string.
*
* @return {String} The formatted string.
*/
export declare function formatArray(formatStr: string, args: any[]): string;
/**
* Converts Markdown code.
*
* @param {String} md The Markdown.
* @param {TargetFormat} [format] The custom output format.
* @param {MarkdownDialect} [dialect] The dialect to use.
*
* @return {any} The converted data.
*/
export declare function fromMarkdown(md: string, format?: string | TargetFormat, dialect?: string | MarkdownDialect): any;
/**
* Alias for 'parseXml()'
*/
export declare function fromXml(xml: string, processNamespaces?: boolean, angularSyntax?: boolean): XmlObjects.XDocument;
/**
* Alias for 'parseYaml()'
*/
export declare function fromYaml<T>(y: any, opts?: IYamlDecodeOptions): T;
/**
* Tries to return the application context of the current app.
* For Android this is an 'android.content.Context' object.
* In iOS this is the app delegate.
*
* @return any The application context (if available.)
*/
export declare function getApplicationContext(): any;
/**
* Returns an object that handles the clipboard of the device.
*
* @return {IClipboard} The clipboard.
*/
export declare function getClipboard(): IClipboard;
/**
* Returns the native view of the app.
* For Android this is an activity.
* For iOS this the the root view controller.
*
* @return any The view object.
*/
export declare function getNativeView(): any;
/**
* Gets the current orientation of the device.
*
* @return {UIEnums.DeviceOrientation} The orientation (if defined).
*/
export declare function getOrientation(): DeviceOrientation;
/**
* Returns information of the current platform.
*
* @return {IPlatformData} The platform information.
*/
export declare function getPlatform(): IPlatformData;
/**
* Tries to return a value / object that is stored in the application settings.
*
* @param {string} key The name of the key (case insensitive).
* @param {T} defValue The default value.
*
* @return {T} The value or the default value if not found.
*/
export declare function getValue<T>(key: string, defValue?: T): T;
/**
* Alias for 'uuid()' function.
*/
export declare function guid(separator?: string): string;
/**
* Generic hash function.
*
* @param {any} v The value to hash.
* @param {string} [algo] The name of the algorithm to use (default: 'sha256').
*
* @return {string} The hash.
*/
export declare function hash(v: any, algo?: string): string;
/**
* Checks if a value / object is stored in the application settings.
*
* @param {string} key The name of the key (case insensitive).
*
* @return {Boolean} Is stored or not.
*/
export declare function hasValue(key: string): boolean;
/**
* Short hand function for 'setStatusBarVisibility()'.
*
* @param {Function} [callback] The custom result callback to invoke.
* @param {T} [tag] The custom value for the result callback.
*/
export declare function hideStatusBar<T>(callback?: (result: ISetStatusBarVisibilityResult<T>, tag?: T) => void, tag?: T): void;
/**
* Invokes logic for a specific connectivity type.
*
* @param {IInvokeForConnectivityConfig} cfg The configuration.
* @param {T} [tag] The custom value for callback to invoke.
*
* @return {any} The result of the invoked callback.
*/
export declare function invokeForConnectivity<T>(cfg: IInvokeForConnectivityConfig<T>, tag?: T): void;
/**
* Invokes a callback for specific orientation mode.
*
* @param {IInvokeForOrientationConfig} cfg The configuration.
*
* @return {any} The result of a callback.
*/
export declare function invokeForOrientation<T>(cfg: IInvokeForOrientationConfig<T>): any;
/**
* Invokes an action for a specific platform.
*
* @param {IInvokeForPlatformContext} cfg The config data.
*
* @return any The result of the invoked callback.
*/
export declare function invokeForPlatform<T>(cfg: IInvokeForPlatformConfig<T>): any;
/**
* Checks if the device is in debug mode or not.
*
* @return {Boolean} Device runs in debug mode or not.
*/
export declare function isDebug(): boolean;
/**
* Checks if a value is a sequence.
*
* @param any v The value to check.
*
* @return {Boolean} Is sequence or not.
*/
export declare function isEnumerable(v: any): boolean;
/**
* Keeps the device awake.
*
* @param {Function} [callback] The custom result callback.
* @param {T} [tag] The custom object for the callback.
*/
export declare function keepAwake<T>(callback?: (result: IResult, tag?: T) => void, tag?: T): void;
/**
* Converts Markdown code to parsable JSON object.
*
* @oaram {String} md The Markdown code.
* @param {MarkdownDialect} [dialect] The custom dialect to use.
*
* @return {Object} The Markdown as object.
*/
export declare function markdownToJson(md: string, dialect?: string | MarkdownDialect): any;
/**
* Converts Markdown code to simple HTML.
*
* @oaram {String} md The Markdown code.
* @param {MarkdownDialect} [dialect] The custom dialect to use.
*
* @return {String} The Markdown as HTML code.
*/
export declare function markdownToHtml(md: string, dialect?: string | MarkdownDialect): string;
/**
* Returns the MD5 hash of a value.
*
* @param any v The value to hash.
*
* @return {String} The hash.
*/
export declare function md5(v: any): string;
/**
* Creates a new batch.
*
* @return {IBatchOperation} The first operation of the created batch.
*/
export declare function newBatch(firstAction: (ctx: Batch.IBatchOperationContext) => void): Batch.IBatchOperation;
/**
* Creates a new client.
*
* @param any config The configuration data / base URL for the client.
*
* @return {IApiClient} The new client.
*/
export declare function newClient(config: ApiClient.IApiClientConfig | string): ApiClient.IApiClient;
/**
* Gets the current time.
*
* @return {Moment} The current time.
*/
export declare function now(): Moment.Moment;
/**
* Opens a database connection.
*
* @param {String} dbName The name of the database to open.
* @param {Function} callback The callback with the result data.
*/
export declare function openDatabase(cfg: IOpenDatabaseConfig): void;
/**
* Opens a URL on the device.
*
* @param {String} url The URL to open.
*
* @return {Boolean} Operation was successful or not.
*/
export declare function openUrl(url: string): boolean;
/**
* Opens the WiFi settings on the device.
*
* @return {Boolean} Operation was successful or not.
*/
export declare function openWifiSettings(): boolean;
/**
* Parses a XML string.
*
* @param {String} xml The string to parse.
* @param {Boolean} [processNamespaces] Process namespaces or not.
* @param {Boolean} [angularSyntax] Handle Angular syntax or not.
*
* @return {XDocument} The new document.
*
* @throws Parse error.
*/
export declare function parseXml(xml: string, processNamespaces?: boolean, angularSyntax?: boolean): XmlObjects.XDocument;
/**
* Parses YAML data to an object.
*
* @param any y The YAML data.
* @param {IYamlDecodeOptions} [opts] The custom options to use.
*
* @return {T} The YAML data as object.
*
* @throws Parse error.
*/
export declare function parseYaml<T>(y: any, opts?: IYamlDecodeOptions): T;
/**
* Removes a value.
*
* @param {string} key The name of the key (case insensitive).
*
* @return {Boolean} Value was removed or not.
*/
export declare function removeValue(key: string): boolean;
/**
* Runs an action on the UI thread.
*
* @param {Function} action The action to invoke.
* @param {T} [state] The optional state object for the action.
* @param {Function} onError The custom action that is invoked on error.
*
* @return {Boolean} Operation was successful or not.
*/
export declare function runOnUI<T>(action: (state: T) => void, state?: T, onError?: (err: any, state: T) => void): boolean;
/**
* Changes the visibility of the device's status bar.
*
* @param {Boolean} isVisible Status bar should be visible (true) or not (false)
* @param {Function} [callback] The optional callback to call.
* @param {T} [tag] The custom object for the callback.
*/
export declare function setStatusBarVisibility<T>(isVisible: boolean, callback?: (result: ISetStatusBarVisibilityResult<T>) => void, tag?: T): void;
/**
* Stores a value / object in the application settings.
*
* @param {T} v The value / object to store.
* @param {string} key The name of the key (case insensitive).
*
* @return {Boolean} Operation was successfull or not.
*/
export declare function setValue<T>(v: T, key: string): boolean;
/**
* Returns the SHA-1 hash of a value.
*
* @param any v The value to hash.
*
* @return {String} The hash.
*/
export declare function sha1(v: any): string;
/**
* Returns the SHA-256 hash of a value.
*
* @param any v The value to hash.
*
* @return {String} The hash.
*/
export declare function sha256(v: any): string;
/**
* Returns the SHA-3 hash of a value.
*
* @param any v The value to hash.
*
* @return {String} The hash.
*/
export declare function sha3(v: any): string;
/**
* Returns the SHA-384 hash of a value.
*
* @param any v The value to hash.
*
* @return {String} The hash.
*/
export declare function sha384(v: any): string;
/**
* Returns the SHA-512 hash of a value.
*
* @param any v The value to hash.
*
* @return {String} The hash.
*/
export declare function sha512(v: any): string;
/**
* Short hand function for 'setStatusBarVisibility()'.
*
* @param {Function} [callback] The custom result callback to invoke.
* @param {T} [tag] The custom value for the result callback.
*/
export declare function showStatusBar<T>(callback?: (result: ISetStatusBarVisibilityResult<T>, tag?: T) => void, tag?: T): void;
/**
* Starts monitoring for connectivity (changes).
*
* @param {IInvokeForConnectivityConfig} cfg The configuration.
* @param {T} [tag] The custom value for callback to invoke.
*/
export declare function startMonitoringForConnectivity<T>(cfg: IInvokeForConnectivityConfig<T>, tag?: T): void;
/**
* Stops monitoring for connectivity.
*/
export declare function stopMonitoringForConnectivity(): void;
/**
* Converts an object / a value to YAML.
*
* @param any v The value to convert.
* @param {IYamlEncodeOptions} [opts] The custom options to use.
*
* @return {String} The YAML data.
*/
export declare function toYaml(v: any, opts?: IYamlEncodeOptions): string;
/**
* Creates a new unique ID / GUID.
*
* @param {string} [separator] The custom separator to use.
*
* s. http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
*/
export declare function uuid(separator?: string): string;
/**
* Prefix for value keys.
*/
export declare var ValueKeyPrefix: string;
/**
* Vibrates the device.
*
* @param {number} [msec] The custom number of milliseconds. Default: 500
*/
export declare function vibrate(msec?: number): any; | the_stack |
import { commands, ExtensionContext, window } from "vscode";
import * as vscode from "vscode";
import { LanguageClient } from "vscode-languageclient/node";
import { logError, OUTPUT_CHANNEL } from "../channel";
const RF_INTERACTIVE_LOCAL_RESOURCE_ROOT = process.env.RF_INTERACTIVE_LOCAL_RESOURCE_ROOT;
function getWebviewOptions(localResourceRoot: vscode.Uri): vscode.WebviewOptions & vscode.WebviewPanelOptions {
return {
// Enable javascript in the webview
enableScripts: true,
// We may have a lot of context in the interactive shell webview, and it may be tricky to save/restore it all.
retainContextWhenHidden: true,
// And restrict the webview to only loading content from our extension's directory.
localResourceRoots: [localResourceRoot],
};
}
async function executeCheckedCommand(commandId: string, args: any) {
try {
return await commands.executeCommand(commandId, args);
} catch (err) {
return {
"success": false,
"message": "" + err.message,
"result": undefined,
};
}
}
let _lastActive: InteractiveShellPanel | undefined = undefined;
interface IPersistable {
setState(state: object): void;
getState(): object | undefined;
}
class InteractiveShellPanel {
public static readonly viewType = "InteractiveShellPanel";
private readonly _panel: vscode.WebviewPanel;
private readonly _interpreterId: number;
private readonly _localResourceRoot: vscode.Uri;
private readonly _persistable: IPersistable;
public readonly disposables: vscode.Disposable[] = [];
private _finishInitialized;
public readonly initialized: Promise<boolean>;
private _lastMessageId: number = 0;
nextMessageSeq(): number {
this._lastMessageId += 1;
return this._lastMessageId;
}
public static async create(
extensionUri: vscode.Uri,
interpreterId: number,
persistable: IPersistable
): Promise<InteractiveShellPanel> {
const column = vscode.window.activeTextEditor ? vscode.window.activeTextEditor.viewColumn : undefined;
let localResourceRoot = vscode.Uri.joinPath(
extensionUri,
"src",
"robotframework_ls",
"vendored",
"vscode-interpreter-webview"
);
if (RF_INTERACTIVE_LOCAL_RESOURCE_ROOT) {
localResourceRoot = vscode.Uri.file(RF_INTERACTIVE_LOCAL_RESOURCE_ROOT);
}
const panel = vscode.window.createWebviewPanel(
InteractiveShellPanel.viewType,
"Robot Framework Interactive Console",
(column || vscode.ViewColumn.One) + 1,
getWebviewOptions(localResourceRoot)
);
let interactiveShellPanel = new InteractiveShellPanel(panel, localResourceRoot, interpreterId, persistable);
_lastActive = interactiveShellPanel;
panel.onDidChangeViewState(() => {
if (panel.active) {
OUTPUT_CHANNEL.appendLine("Changed active: " + interactiveShellPanel._interpreterId);
_lastActive = interactiveShellPanel;
}
});
panel.onDidDispose(() => {
if (_lastActive === interactiveShellPanel) {
_lastActive = undefined;
}
});
return interactiveShellPanel;
}
private constructor(
panel: vscode.WebviewPanel,
localResourceRoot: vscode.Uri,
interpreterId: number,
persistable: IPersistable
) {
this._panel = panel;
this._localResourceRoot = localResourceRoot;
this._interpreterId = interpreterId;
this._persistable = persistable;
let interactiveShell = this;
this.initialized = new Promise((resolve, reject) => {
interactiveShell._finishInitialized = resolve;
});
// Set the webview's initial html content
const webview = this._panel.webview;
this._panel.webview.html = this._getHtmlForWebview(webview);
// Listen for when the panel is disposed
// This happens when the user closes the panel or when the panel is closed programmatically
this._panel.onDidDispose(() => this.dispose(), null, this.disposables);
let nextMessageSeq = this.nextMessageSeq.bind(this);
async function handleEvaluate(message) {
let result: any = { "success": false, "message": "<error evaluating>", "result": undefined };
try {
let code = message.arguments["expression"];
result = await executeCheckedCommand("robot.internal.rfinteractive.evaluate", {
"interpreter_id": interpreterId,
"code": code,
});
} catch (err) {
logError("Error in evaluation.", err);
} finally {
let response: any = {
type: "response",
seq: nextMessageSeq(),
command: message.command,
request_seq: message.seq,
body: "<evaluated from vscode>",
};
webview.postMessage(response); // Send the response, even if it was an error.
}
// Errors should be shown in the console already...
// if (!result['success']) {
// window.showErrorMessage('Error evaluating in interactive console: ' + result['message'])
// }
}
async function handleSemanticTokens(message) {
let result = undefined;
try {
let code = message.arguments["code"];
// result is {'data': [...], 'resultId': ...}
result = await commands.executeCommand("robot.internal.rfinteractive.semanticTokens", {
"interpreter_id": interpreterId,
"code": code,
});
} catch (err) {
logError("Error getting semantic tokens.", err);
} finally {
let response: any = {
type: "response",
seq: nextMessageSeq(),
command: message.command,
request_seq: message.seq,
body: result,
};
webview.postMessage(response);
}
}
async function handleCompletions(message) {
let result = undefined;
try {
let code = message.arguments["code"];
let position = message.arguments["position"];
let context = message.arguments["context"];
// result is {'suggestions': [...], ...}
result = await commands.executeCommand("robot.internal.rfinteractive.completions", {
"interpreter_id": interpreterId,
"code": code,
"position": {
"line": position["lineNumber"] - 1,
"character": position["column"] - 1,
},
"context": context,
});
} catch (err) {
logError("Error getting completions.", err);
} finally {
let response: any = {
type: "response",
seq: nextMessageSeq(),
command: message.command,
request_seq: message.seq,
body: result,
};
webview.postMessage(response);
}
}
async function handlePersistState(message) {
let result = undefined;
try {
let stateToPersist = message.arguments["state"];
persistable.setState(stateToPersist);
} catch (err) {
logError("Error persisting state.", err);
} finally {
let response: any = {
type: "response",
seq: nextMessageSeq(),
command: message.command,
request_seq: message.seq,
body: result,
};
webview.postMessage(response);
}
}
// Handle messages from the webview
this._panel.webview.onDidReceiveMessage(
async (message) => {
if (message.type == "request") {
let result = undefined;
switch (message.command) {
case "evaluate":
await handleEvaluate(message);
return;
case "semanticTokens":
await handleSemanticTokens(message);
return;
case "completions":
await handleCompletions(message);
return;
case "persistState":
await handlePersistState(message);
return;
}
} else if (message.type == "event") {
if (message.event == "initialized") {
interactiveShell._finishInitialized();
}
}
},
null,
this.disposables
);
}
public onOutput(category: string, output: string) {
this._panel.webview.postMessage({
"type": "event",
"seq": this.nextMessageSeq(),
"event": "output",
"category": category,
"output": output,
});
}
public dispose() {
// Clean up our resources
this._panel.dispose();
while (this.disposables.length) {
const x = this.disposables.pop();
if (x) {
x.dispose();
}
}
}
private _getHtmlForWebview(webview: vscode.Webview) {
// Note: we can't really load from file://
// See: https://github.com/microsoft/vscode/issues/87282
const scriptUri = webview.asWebviewUri(vscode.Uri.joinPath(this._localResourceRoot, "bundle.js"));
const initialState = JSON.stringify(this._persistable.getState());
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Robot Framework Interactive Console</title>
<script>
const vscode = acquireVsCodeApi();
const initialState = ${initialState};
</script>
<script defer src="${scriptUri}"></script>
</head>
<body style="padding: 0 0 0 0">
</body>
</html>`;
}
evaluate(args: _InteractiveShellEvaluateArgs) {
const webview = this._panel.webview;
let request: any = {
type: "request",
seq: this.nextMessageSeq(),
command: "evaluate",
body: args,
};
// We have to ask the UI to evaluate it (to add it to the UI and
// then actually do the work in the backend).
webview.postMessage(request);
}
}
interface _InteractiveShellEvaluateArgs {
uri: string;
code: string;
}
export async function registerInteractiveCommands(context: ExtensionContext, languageClient: LanguageClient) {
let extensionUri = context.extensionUri;
async function interactiveShellCreateOrSendContentToEvaluate(args: undefined | _InteractiveShellEvaluateArgs) {
let uri: string;
if (args) {
// If we have an active window, use it.
if (_lastActive) {
_lastActive.evaluate(args);
return;
}
uri = args.uri;
} else {
let activeFile = vscode.window.activeTextEditor?.document;
let currUri = activeFile?.uri;
let msg =
"Unable to create Robot Framework Interactive Console. Please open the related .robot/.resource file to provide the path used to create the Interactive Console.";
if (!currUri) {
window.showErrorMessage(msg);
return;
}
if (!currUri.fsPath.endsWith(".robot") && !currUri.fsPath.endsWith(".resource")) {
window.showErrorMessage(msg);
return;
}
uri = currUri.toString();
}
let interpreterId = -1;
let buffered: string[] = new Array();
let interactiveShellPanel: undefined | InteractiveShellPanel = undefined;
async function onOutput(args) {
if (args["interpreter_id"] === interpreterId) {
let category: string = args["category"];
let output: string = args["output"];
interactiveShellPanel?.onOutput(category, output);
}
}
let disposeNotification = languageClient.onNotification("interpreter/output", (args) => {
if (buffered !== undefined) {
buffered.push(args);
} else {
onOutput(args);
}
});
context.subscriptions.push(disposeNotification);
// Note that during the creation, it's possible that we already have output, so, we
// need to buffer anything up to the point where we actually have the interpreter.
let result = await commands.executeCommand("robot.internal.rfinteractive.start", { "uri": uri });
if (!result["success"]) {
window.showErrorMessage("Error creating interactive console: " + result["message"]);
return;
}
interpreterId = result["result"]["interpreter_id"];
const SAVE_IN_KEY = "interactiveConsoleState";
let persistable: IPersistable = {
setState: (state: object) => {
let currState = persistable.getState();
if (!currState) {
context.globalState.update(SAVE_IN_KEY, state);
} else {
// Note: merge the keys in the existing state.
Object.entries(state).forEach(([key, value]) => (currState[key] = value));
context.globalState.update(SAVE_IN_KEY, currState);
}
},
getState: () => {
return context.globalState.get(SAVE_IN_KEY);
},
};
interactiveShellPanel = await InteractiveShellPanel.create(extensionUri, interpreterId, persistable);
interactiveShellPanel.disposables.push(disposeNotification);
function disposeInterpreter() {
executeCheckedCommand("robot.internal.rfinteractive.stop", {
"interpreter_id": interpreterId,
});
}
interactiveShellPanel.disposables.push({
"dispose": disposeInterpreter,
});
OUTPUT_CHANNEL.appendLine(
"Waiting for Robot Framework Interactive Console UI (id: " + interpreterId + ") initialization."
);
await interactiveShellPanel.initialized;
OUTPUT_CHANNEL.appendLine("Robot Framework Interactive Console UI (id: " + interpreterId + ") initialized.");
while (buffered.length) {
buffered.splice(0, buffered.length).forEach((el) => {
onOutput(el);
});
}
// Start sending contents directly to the interactive shell now that we processed the
// output backlog from the startup.
buffered = undefined;
if (args) {
interactiveShellPanel.evaluate(args);
}
}
context.subscriptions.push(
commands.registerCommand("robot.interactiveShell", interactiveShellCreateOrSendContentToEvaluate)
);
} | the_stack |
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js";
import * as msRest from "@azure/ms-rest-js";
export { BaseResource, CloudError };
/**
* Contains the localized display information for this particular operation / action.
*/
export interface OperationDisplay {
/**
* The localized friendly form of the resource provider name.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provider?: string;
/**
* The localized friendly form of the resource type related to this action/operation.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly resource?: string;
/**
* The localized friendly name for the operation.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly operation?: string;
/**
* The localized friendly description for the operation.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly description?: string;
}
/**
* A Time Series Insights REST API operation
*/
export interface Operation {
/**
* The name of the operation being performed on this particular object.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* Contains the localized display information for this particular operation / action.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly display?: OperationDisplay;
}
/**
* Time Series Insights resource
*/
export interface Resource extends BaseResource {
/**
* Resource Id
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* Resource name
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* Resource type
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
}
/**
* Time Series Insights resource that is tracked by Azure Resource Manager.
*/
export interface TrackedResource extends Resource {
/**
* Resource location
*/
location: string;
/**
* Resource tags
*/
tags?: { [propertyName: string]: string };
}
/**
* Properties that are common to all tracked resources.
*/
export interface ResourceProperties {
/**
* Provisioning state of the resource. Possible values include: 'Accepted', 'Creating',
* 'Updating', 'Succeeded', 'Failed', 'Deleting'
*/
provisioningState?: ProvisioningState;
/**
* The time the resource was created.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly creationTime?: Date;
}
/**
* The sku determines the capacity of the environment, the SLA (in queries-per-minute and total
* capacity), and the billing rate.
*/
export interface Sku {
/**
* The name of this SKU. Possible values include: 'S1', 'S2'
*/
name: SkuName;
/**
* The capacity of the sku. This value can be changed to support scale out of environments after
* they have been created.
*/
capacity: number;
}
/**
* Properties required to create any resource tracked by Azure Resource Manager.
*/
export interface CreateOrUpdateTrackedResourceProperties {
/**
* The location of the resource.
*/
location: string;
/**
* Key-value pairs of additional properties for the resource.
*/
tags?: { [propertyName: string]: string };
}
/**
* The structure of the property that a partition key can have. An environment can have multiple
* such properties.
*/
export interface PartitionKeyProperty {
/**
* The name of the property.
*/
name?: string;
/**
* The type of the property. Possible values include: 'String'
*/
type?: PropertyType;
}
/**
* Parameters supplied to the CreateOrUpdate Environment operation.
*/
export interface EnvironmentCreateOrUpdateParameters extends CreateOrUpdateTrackedResourceProperties {
/**
* The sku determines the capacity of the environment, the SLA (in queries-per-minute and total
* capacity), and the billing rate.
*/
sku: Sku;
/**
* ISO8601 timespan specifying the minimum number of days the environment's events will be
* available for query.
*/
dataRetentionTime: string;
/**
* The behavior the Time Series Insights service should take when the environment's capacity has
* been exceeded. If "PauseIngress" is specified, new events will not be read from the event
* source. If "PurgeOldData" is specified, new events will continue to be read and old events
* will be deleted from the environment. The default behavior is PurgeOldData. Possible values
* include: 'PurgeOldData', 'PauseIngress'
*/
storageLimitExceededBehavior?: StorageLimitExceededBehavior;
/**
* The list of partition keys according to which the data in the environment will be ordered.
*/
partitionKeyProperties?: PartitionKeyProperty[];
}
/**
* Parameters supplied to the Update Environment operation.
*/
export interface EnvironmentUpdateParameters {
/**
* The sku of the environment.
*/
sku?: Sku;
/**
* Key-value pairs of additional properties for the environment.
*/
tags?: { [propertyName: string]: string };
/**
* ISO8601 timespan specifying the minimum number of days the environment's events will be
* available for query.
*/
dataRetentionTime?: string;
/**
* The behavior the Time Series Insights service should take when the environment's capacity has
* been exceeded. If "PauseIngress" is specified, new events will not be read from the event
* source. If "PurgeOldData" is specified, new events will continue to be read and old events
* will be deleted from the environment. The default behavior is PurgeOldData. Possible values
* include: 'PurgeOldData', 'PauseIngress'
*/
storageLimitExceededBehavior?: StorageLimitExceededBehavior;
/**
* The list of event properties which will be used to partition data in the environment.
*/
partitionKeyProperties?: PartitionKeyProperty[];
}
/**
* An object that contains the details about an environment's state.
*/
export interface EnvironmentStateDetails {
/**
* Contains the code that represents the reason of an environment being in a particular state.
* Can be used to programmatically handle specific cases.
*/
code?: string;
/**
* A message that describes the state in detail.
*/
message?: string;
}
/**
* An object that represents the status of ingress on an environment.
*/
export interface IngressEnvironmentStatus {
/**
* This string represents the state of ingress operations on an environment. It can be
* "Disabled", "Ready", "Running", "Paused" or "Unknown". Possible values include: 'Disabled',
* 'Ready', 'Running', 'Paused', 'Unknown'
*/
state?: IngressState;
/**
* An object that contains the details about an environment's state.
*/
stateDetails?: EnvironmentStateDetails;
}
/**
* An object that represents the status of the environment, and its internal state in the Time
* Series Insights service.
*/
export interface EnvironmentStatus {
/**
* An object that represents the status of ingress on an environment.
*/
ingress?: IngressEnvironmentStatus;
}
/**
* An environment is a set of time-series data available for query, and is the top level Azure Time
* Series Insights resource.
*/
export interface EnvironmentResource extends TrackedResource {
/**
* The sku determines the capacity of the environment, the SLA (in queries-per-minute and total
* capacity), and the billing rate.
*/
sku?: Sku;
/**
* ISO8601 timespan specifying the minimum number of days the environment's events will be
* available for query.
*/
dataRetentionTime: string;
/**
* The behavior the Time Series Insights service should take when the environment's capacity has
* been exceeded. If "PauseIngress" is specified, new events will not be read from the event
* source. If "PurgeOldData" is specified, new events will continue to be read and old events
* will be deleted from the environment. The default behavior is PurgeOldData. Possible values
* include: 'PurgeOldData', 'PauseIngress'
*/
storageLimitExceededBehavior?: StorageLimitExceededBehavior;
/**
* The list of partition keys according to which the data in the environment will be ordered.
*/
partitionKeyProperties?: PartitionKeyProperty[];
/**
* Provisioning state of the resource. Possible values include: 'Accepted', 'Creating',
* 'Updating', 'Succeeded', 'Failed', 'Deleting'
*/
provisioningState?: ProvisioningState;
/**
* The time the resource was created.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly creationTime?: Date;
/**
* An id used to access the environment data, e.g. to query the environment's events or upload
* reference data for the environment.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly dataAccessId?: string;
/**
* The fully qualified domain name used to access the environment data, e.g. to query the
* environment's events or upload reference data for the environment.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly dataAccessFqdn?: string;
/**
* An object that represents the status of the environment, and its internal state in the Time
* Series Insights service.
*/
status?: EnvironmentStatus;
}
/**
* The response of the List Environments operation.
*/
export interface EnvironmentListResponse {
/**
* Result of the List Environments operation.
*/
value?: EnvironmentResource[];
}
/**
* Contains the possible cases for EventSourceCreateOrUpdateParameters.
*/
export type EventSourceCreateOrUpdateParametersUnion = EventSourceCreateOrUpdateParameters | EventHubEventSourceCreateOrUpdateParameters | IoTHubEventSourceCreateOrUpdateParameters;
/**
* Parameters supplied to the Create or Update Event Source operation.
*/
export interface EventSourceCreateOrUpdateParameters {
/**
* Polymorphic Discriminator
*/
kind: "EventSourceCreateOrUpdateParameters";
/**
* The location of the resource.
*/
location: string;
/**
* Key-value pairs of additional properties for the resource.
*/
tags?: { [propertyName: string]: string };
}
/**
* Parameters supplied to the Create or Update Event Source operation for an EventHub event source.
*/
export interface EventHubEventSourceCreateOrUpdateParameters {
/**
* Polymorphic Discriminator
*/
kind: "Microsoft.EventHub";
/**
* The location of the resource.
*/
location: string;
/**
* Key-value pairs of additional properties for the resource.
*/
tags?: { [propertyName: string]: string };
/**
* Provisioning state of the resource. Possible values include: 'Accepted', 'Creating',
* 'Updating', 'Succeeded', 'Failed', 'Deleting'
*/
provisioningState?: ProvisioningState;
/**
* The time the resource was created.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly creationTime?: Date;
/**
* The event property that will be used as the event source's timestamp. If a value isn't
* specified for timestampPropertyName, or if null or empty-string is specified, the event
* creation time will be used.
*/
timestampPropertyName?: string;
/**
* The resource id of the event source in Azure Resource Manager.
*/
eventSourceResourceId: string;
/**
* The name of the service bus that contains the event hub.
*/
serviceBusNamespace: string;
/**
* The name of the event hub.
*/
eventHubName: string;
/**
* The name of the event hub's consumer group that holds the partitions from which events will be
* read.
*/
consumerGroupName: string;
/**
* The name of the SAS key that grants the Time Series Insights service access to the event hub.
* The shared access policies for this key must grant 'Listen' permissions to the event hub.
*/
keyName: string;
/**
* The value of the shared access key that grants the Time Series Insights service read access to
* the event hub. This property is not shown in event source responses.
*/
sharedAccessKey: string;
}
/**
* Parameters supplied to the Create or Update Event Source operation for an IoTHub event source.
*/
export interface IoTHubEventSourceCreateOrUpdateParameters {
/**
* Polymorphic Discriminator
*/
kind: "Microsoft.IoTHub";
/**
* The location of the resource.
*/
location: string;
/**
* Key-value pairs of additional properties for the resource.
*/
tags?: { [propertyName: string]: string };
/**
* Provisioning state of the resource. Possible values include: 'Accepted', 'Creating',
* 'Updating', 'Succeeded', 'Failed', 'Deleting'
*/
provisioningState?: ProvisioningState;
/**
* The time the resource was created.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly creationTime?: Date;
/**
* The event property that will be used as the event source's timestamp. If a value isn't
* specified for timestampPropertyName, or if null or empty-string is specified, the event
* creation time will be used.
*/
timestampPropertyName?: string;
/**
* The resource id of the event source in Azure Resource Manager.
*/
eventSourceResourceId: string;
/**
* The name of the iot hub.
*/
iotHubName: string;
/**
* The name of the iot hub's consumer group that holds the partitions from which events will be
* read.
*/
consumerGroupName: string;
/**
* The name of the Shared Access Policy key that grants the Time Series Insights service access
* to the iot hub. This shared access policy key must grant 'service connect' permissions to the
* iot hub.
*/
keyName: string;
/**
* The value of the Shared Access Policy key that grants the Time Series Insights service read
* access to the iot hub. This property is not shown in event source responses.
*/
sharedAccessKey: string;
}
/**
* Parameters supplied to the Update Event Source operation.
*/
export interface EventSourceUpdateParameters {
/**
* Key-value pairs of additional properties for the event source.
*/
tags?: { [propertyName: string]: string };
}
/**
* Parameters supplied to the Update Event Source operation to update an EventHub event source.
*/
export interface EventHubEventSourceUpdateParameters extends EventSourceUpdateParameters {
/**
* The event property that will be used as the event source's timestamp. If a value isn't
* specified for timestampPropertyName, or if null or empty-string is specified, the event
* creation time will be used.
*/
timestampPropertyName?: string;
/**
* An object that represents the local timestamp property. It contains the format of local
* timestamp that needs to be used and the corresponding timezone offset information. If a value
* isn't specified for localTimestamp, or if null, then the local timestamp will not be ingressed
* with the events.
*/
localTimestamp?: LocalTimestamp;
/**
* The value of the shared access key that grants the Time Series Insights service read access to
* the event hub. This property is not shown in event source responses.
*/
sharedAccessKey?: string;
}
/**
* Parameters supplied to the Update Event Source operation to update an IoTHub event source.
*/
export interface IoTHubEventSourceUpdateParameters extends EventSourceUpdateParameters {
/**
* The event property that will be used as the event source's timestamp. If a value isn't
* specified for timestampPropertyName, or if null or empty-string is specified, the event
* creation time will be used.
*/
timestampPropertyName?: string;
/**
* An object that represents the local timestamp property. It contains the format of local
* timestamp that needs to be used and the corresponding timezone offset information. If a value
* isn't specified for localTimestamp, or if null, then the local timestamp will not be ingressed
* with the events.
*/
localTimestamp?: LocalTimestamp;
/**
* The value of the shared access key that grants the Time Series Insights service read access to
* the iot hub. This property is not shown in event source responses.
*/
sharedAccessKey?: string;
}
/**
* Contains the possible cases for EventSourceResource.
*/
export type EventSourceResourceUnion = EventSourceResource | EventHubEventSourceResource | IoTHubEventSourceResource;
/**
* An environment receives data from one or more event sources. Each event source has associated
* connection info that allows the Time Series Insights ingress pipeline to connect to and pull
* data from the event source
*/
export interface EventSourceResource {
/**
* Polymorphic Discriminator
*/
kind: "EventSourceResource";
/**
* Resource Id
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* Resource name
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* Resource type
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
/**
* Resource location
*/
location: string;
/**
* Resource tags
*/
tags?: { [propertyName: string]: string };
}
/**
* The response of the List EventSources operation.
*/
export interface EventSourceListResponse {
/**
* Result of the List EventSources operation.
*/
value?: EventSourceResourceUnion[];
}
/**
* An event source that receives its data from an Azure EventHub.
*/
export interface EventHubEventSourceResource {
/**
* Polymorphic Discriminator
*/
kind: "Microsoft.EventHub";
/**
* Resource Id
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* Resource name
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* Resource type
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
/**
* Resource location
*/
location: string;
/**
* Resource tags
*/
tags?: { [propertyName: string]: string };
/**
* Provisioning state of the resource. Possible values include: 'Accepted', 'Creating',
* 'Updating', 'Succeeded', 'Failed', 'Deleting'
*/
provisioningState?: ProvisioningState;
/**
* The time the resource was created.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly creationTime?: Date;
/**
* The event property that will be used as the event source's timestamp. If a value isn't
* specified for timestampPropertyName, or if null or empty-string is specified, the event
* creation time will be used.
*/
timestampPropertyName?: string;
/**
* The resource id of the event source in Azure Resource Manager.
*/
eventSourceResourceId: string;
/**
* The name of the service bus that contains the event hub.
*/
serviceBusNamespace: string;
/**
* The name of the event hub.
*/
eventHubName: string;
/**
* The name of the event hub's consumer group that holds the partitions from which events will be
* read.
*/
consumerGroupName: string;
/**
* The name of the SAS key that grants the Time Series Insights service access to the event hub.
* The shared access policies for this key must grant 'Listen' permissions to the event hub.
*/
keyName: string;
}
/**
* An event source that receives its data from an Azure IoTHub.
*/
export interface IoTHubEventSourceResource {
/**
* Polymorphic Discriminator
*/
kind: "Microsoft.IotHub";
/**
* Resource Id
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* Resource name
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* Resource type
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
/**
* Resource location
*/
location: string;
/**
* Resource tags
*/
tags?: { [propertyName: string]: string };
/**
* Provisioning state of the resource. Possible values include: 'Accepted', 'Creating',
* 'Updating', 'Succeeded', 'Failed', 'Deleting'
*/
provisioningState?: ProvisioningState;
/**
* The time the resource was created.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly creationTime?: Date;
/**
* The event property that will be used as the event source's timestamp. If a value isn't
* specified for timestampPropertyName, or if null or empty-string is specified, the event
* creation time will be used.
*/
timestampPropertyName?: string;
/**
* The resource id of the event source in Azure Resource Manager.
*/
eventSourceResourceId: string;
/**
* The name of the iot hub.
*/
iotHubName: string;
/**
* The name of the iot hub's consumer group that holds the partitions from which events will be
* read.
*/
consumerGroupName: string;
/**
* The name of the Shared Access Policy key that grants the Time Series Insights service access
* to the iot hub. This shared access policy key must grant 'service connect' permissions to the
* iot hub.
*/
keyName: string;
}
/**
* Properties of the event source.
*/
export interface EventSourceCommonProperties extends ResourceProperties {
/**
* The event property that will be used as the event source's timestamp. If a value isn't
* specified for timestampPropertyName, or if null or empty-string is specified, the event
* creation time will be used.
*/
timestampPropertyName?: string;
}
/**
* Properties of an event source that reads events from an event broker in Azure.
*/
export interface AzureEventSourceProperties extends EventSourceCommonProperties {
/**
* The resource id of the event source in Azure Resource Manager.
*/
eventSourceResourceId: string;
}
/**
* Properties of the EventHub event source.
*/
export interface EventHubEventSourceCommonProperties extends AzureEventSourceProperties {
/**
* The name of the service bus that contains the event hub.
*/
serviceBusNamespace: string;
/**
* The name of the event hub.
*/
eventHubName: string;
/**
* The name of the event hub's consumer group that holds the partitions from which events will be
* read.
*/
consumerGroupName: string;
/**
* The name of the SAS key that grants the Time Series Insights service access to the event hub.
* The shared access policies for this key must grant 'Listen' permissions to the event hub.
*/
keyName: string;
}
/**
* Properties of the IoTHub event source.
*/
export interface IoTHubEventSourceCommonProperties extends AzureEventSourceProperties {
/**
* The name of the iot hub.
*/
iotHubName: string;
/**
* The name of the iot hub's consumer group that holds the partitions from which events will be
* read.
*/
consumerGroupName: string;
/**
* The name of the Shared Access Policy key that grants the Time Series Insights service access
* to the iot hub. This shared access policy key must grant 'service connect' permissions to the
* iot hub.
*/
keyName: string;
}
/**
* An object that represents the offset information for the local timestamp format specified.
* Should not be specified for LocalTimestampFormat - Embedded.
*/
export interface LocalTimestampTimeZoneOffset {
/**
* The event property that will be contain the offset information to calculate the local
* timestamp. When the LocalTimestampFormat is Iana, the property name will contain the name of
* the column which contains IANA Timezone Name (eg: Americas/Los Angeles). When
* LocalTimestampFormat is Timespan, it contains the name of property which contains values
* representing the offset (eg: P1D or 1.00:00:00)
*/
propertyName?: string;
}
/**
* An object that represents the local timestamp property. It contains the format of local
* timestamp that needs to be used and the corresponding timezone offset information. If a value
* isn't specified for localTimestamp, or if null, then the local timestamp will not be ingressed
* with the events.
*/
export interface LocalTimestamp {
/**
* An enum that represents the format of the local timestamp property that needs to be set.
* Possible values include: 'Embedded', 'Iana', 'TimeSpan'
*/
format?: LocalTimestampFormat;
/**
* An object that represents the offset information for the local timestamp format specified.
* Should not be specified for LocalTimestampFormat - Embedded.
*/
timeZoneOffset?: LocalTimestampTimeZoneOffset;
}
/**
* An object that represents a set of mutable event source resource properties.
*/
export interface EventSourceMutableProperties {
/**
* The event property that will be used as the event source's timestamp. If a value isn't
* specified for timestampPropertyName, or if null or empty-string is specified, the event
* creation time will be used.
*/
timestampPropertyName?: string;
/**
* An object that represents the local timestamp property. It contains the format of local
* timestamp that needs to be used and the corresponding timezone offset information. If a value
* isn't specified for localTimestamp, or if null, then the local timestamp will not be ingressed
* with the events.
*/
localTimestamp?: LocalTimestamp;
}
/**
* A key property for the reference data set. A reference data set can have multiple key
* properties.
*/
export interface ReferenceDataSetKeyProperty {
/**
* The name of the key property.
*/
name?: string;
/**
* The type of the key property. Possible values include: 'String', 'Double', 'Bool', 'DateTime'
*/
type?: ReferenceDataKeyPropertyType;
}
/**
* An interface representing ReferenceDataSetCreateOrUpdateParameters.
*/
export interface ReferenceDataSetCreateOrUpdateParameters extends CreateOrUpdateTrackedResourceProperties {
/**
* The list of key properties for the reference data set.
*/
keyProperties: ReferenceDataSetKeyProperty[];
/**
* The reference data set key comparison behavior can be set using this property. By default, the
* value is 'Ordinal' - which means case sensitive key comparison will be performed while joining
* reference data with events or while adding new reference data. When 'OrdinalIgnoreCase' is
* set, case insensitive comparison will be used. Possible values include: 'Ordinal',
* 'OrdinalIgnoreCase'
*/
dataStringComparisonBehavior?: DataStringComparisonBehavior;
}
/**
* Parameters supplied to the Update Reference Data Set operation.
*/
export interface ReferenceDataSetUpdateParameters {
/**
* Key-value pairs of additional properties for the reference data set.
*/
tags?: { [propertyName: string]: string };
}
/**
* A reference data set provides metadata about the events in an environment. Metadata in the
* reference data set will be joined with events as they are read from event sources. The metadata
* that makes up the reference data set is uploaded or modified through the Time Series Insights
* data plane APIs.
*/
export interface ReferenceDataSetResource extends TrackedResource {
/**
* The list of key properties for the reference data set.
*/
keyProperties: ReferenceDataSetKeyProperty[];
/**
* The reference data set key comparison behavior can be set using this property. By default, the
* value is 'Ordinal' - which means case sensitive key comparison will be performed while joining
* reference data with events or while adding new reference data. When 'OrdinalIgnoreCase' is
* set, case insensitive comparison will be used. Possible values include: 'Ordinal',
* 'OrdinalIgnoreCase'
*/
dataStringComparisonBehavior?: DataStringComparisonBehavior;
/**
* Provisioning state of the resource. Possible values include: 'Accepted', 'Creating',
* 'Updating', 'Succeeded', 'Failed', 'Deleting'
*/
provisioningState?: ProvisioningState;
/**
* The time the resource was created.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly creationTime?: Date;
}
/**
* The response of the List Reference Data Sets operation.
*/
export interface ReferenceDataSetListResponse {
/**
* Result of the List Reference Data Sets operation.
*/
value?: ReferenceDataSetResource[];
}
/**
* An interface representing AccessPolicyCreateOrUpdateParameters.
*/
export interface AccessPolicyCreateOrUpdateParameters {
/**
* The objectId of the principal in Azure Active Directory.
*/
principalObjectId?: string;
/**
* An description of the access policy.
*/
description?: string;
/**
* The list of roles the principal is assigned on the environment.
*/
roles?: AccessPolicyRole[];
}
/**
* An interface representing AccessPolicyUpdateParameters.
*/
export interface AccessPolicyUpdateParameters {
/**
* An description of the access policy.
*/
description?: string;
/**
* The list of roles the principal is assigned on the environment.
*/
roles?: AccessPolicyRole[];
}
/**
* An access policy is used to grant users and applications access to the environment. Roles are
* assigned to service principals in Azure Active Directory. These roles define the actions the
* principal can perform through the Time Series Insights data plane APIs.
*/
export interface AccessPolicyResource extends Resource {
/**
* The objectId of the principal in Azure Active Directory.
*/
principalObjectId?: string;
/**
* An description of the access policy.
*/
description?: string;
/**
* The list of roles the principal is assigned on the environment.
*/
roles?: AccessPolicyRole[];
}
/**
* The response of the List access policies operation.
*/
export interface AccessPolicyListResponse {
/**
* Result of the List access policies operation.
*/
value?: AccessPolicyResource[];
}
/**
* Optional Parameters.
*/
export interface EnvironmentsGetOptionalParams extends msRest.RequestOptionsBase {
/**
* Setting $expand=status will include the status of the internal services of the environment in
* the Time Series Insights service.
*/
expand?: string;
}
/**
* An interface representing TimeSeriesInsightsClientOptions.
*/
export interface TimeSeriesInsightsClientOptions extends AzureServiceClientOptions {
baseUri?: string;
}
/**
* @interface
* Result of the request to list Time Series Insights operations. It contains a list of operations
* and a URL link to get the next set of results.
* @extends Array<Operation>
*/
export interface OperationListResult extends Array<Operation> {
/**
* URL to get the next set of operation list results if there are any.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextLink?: string;
}
/**
* Defines values for ProvisioningState.
* Possible values include: 'Accepted', 'Creating', 'Updating', 'Succeeded', 'Failed', 'Deleting'
* @readonly
* @enum {string}
*/
export type ProvisioningState = 'Accepted' | 'Creating' | 'Updating' | 'Succeeded' | 'Failed' | 'Deleting';
/**
* Defines values for SkuName.
* Possible values include: 'S1', 'S2'
* @readonly
* @enum {string}
*/
export type SkuName = 'S1' | 'S2';
/**
* Defines values for StorageLimitExceededBehavior.
* Possible values include: 'PurgeOldData', 'PauseIngress'
* @readonly
* @enum {string}
*/
export type StorageLimitExceededBehavior = 'PurgeOldData' | 'PauseIngress';
/**
* Defines values for PropertyType.
* Possible values include: 'String'
* @readonly
* @enum {string}
*/
export type PropertyType = 'String';
/**
* Defines values for IngressState.
* Possible values include: 'Disabled', 'Ready', 'Running', 'Paused', 'Unknown'
* @readonly
* @enum {string}
*/
export type IngressState = 'Disabled' | 'Ready' | 'Running' | 'Paused' | 'Unknown';
/**
* Defines values for LocalTimestampFormat.
* Possible values include: 'Embedded', 'Iana', 'TimeSpan'
* @readonly
* @enum {string}
*/
export type LocalTimestampFormat = 'Embedded' | 'Iana' | 'TimeSpan';
/**
* Defines values for ReferenceDataKeyPropertyType.
* Possible values include: 'String', 'Double', 'Bool', 'DateTime'
* @readonly
* @enum {string}
*/
export type ReferenceDataKeyPropertyType = 'String' | 'Double' | 'Bool' | 'DateTime';
/**
* Defines values for DataStringComparisonBehavior.
* Possible values include: 'Ordinal', 'OrdinalIgnoreCase'
* @readonly
* @enum {string}
*/
export type DataStringComparisonBehavior = 'Ordinal' | 'OrdinalIgnoreCase';
/**
* Defines values for AccessPolicyRole.
* Possible values include: 'Reader', 'Contributor'
* @readonly
* @enum {string}
*/
export type AccessPolicyRole = 'Reader' | 'Contributor';
/**
* Contains response data for the list operation.
*/
export type OperationsListResponse = OperationListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: OperationListResult;
};
};
/**
* Contains response data for the listNext operation.
*/
export type OperationsListNextResponse = OperationListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: OperationListResult;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type EnvironmentsCreateOrUpdateResponse = EnvironmentResource & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EnvironmentResource;
};
};
/**
* Contains response data for the get operation.
*/
export type EnvironmentsGetResponse = EnvironmentResource & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EnvironmentResource;
};
};
/**
* Contains response data for the update operation.
*/
export type EnvironmentsUpdateResponse = EnvironmentResource & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EnvironmentResource;
};
};
/**
* Contains response data for the listByResourceGroup operation.
*/
export type EnvironmentsListByResourceGroupResponse = EnvironmentListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EnvironmentListResponse;
};
};
/**
* Contains response data for the listBySubscription operation.
*/
export type EnvironmentsListBySubscriptionResponse = EnvironmentListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EnvironmentListResponse;
};
};
/**
* Contains response data for the beginCreateOrUpdate operation.
*/
export type EnvironmentsBeginCreateOrUpdateResponse = EnvironmentResource & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EnvironmentResource;
};
};
/**
* Contains response data for the beginUpdate operation.
*/
export type EnvironmentsBeginUpdateResponse = EnvironmentResource & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EnvironmentResource;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type EventSourcesCreateOrUpdateResponse = EventSourceResourceUnion & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EventSourceResourceUnion;
};
};
/**
* Contains response data for the get operation.
*/
export type EventSourcesGetResponse = EventSourceResourceUnion & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EventSourceResourceUnion;
};
};
/**
* Contains response data for the update operation.
*/
export type EventSourcesUpdateResponse = EventSourceResourceUnion & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EventSourceResourceUnion;
};
};
/**
* Contains response data for the listByEnvironment operation.
*/
export type EventSourcesListByEnvironmentResponse = EventSourceListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EventSourceListResponse;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type ReferenceDataSetsCreateOrUpdateResponse = ReferenceDataSetResource & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ReferenceDataSetResource;
};
};
/**
* Contains response data for the get operation.
*/
export type ReferenceDataSetsGetResponse = ReferenceDataSetResource & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ReferenceDataSetResource;
};
};
/**
* Contains response data for the update operation.
*/
export type ReferenceDataSetsUpdateResponse = ReferenceDataSetResource & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ReferenceDataSetResource;
};
};
/**
* Contains response data for the listByEnvironment operation.
*/
export type ReferenceDataSetsListByEnvironmentResponse = ReferenceDataSetListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ReferenceDataSetListResponse;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type AccessPoliciesCreateOrUpdateResponse = AccessPolicyResource & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AccessPolicyResource;
};
};
/**
* Contains response data for the get operation.
*/
export type AccessPoliciesGetResponse = AccessPolicyResource & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AccessPolicyResource;
};
};
/**
* Contains response data for the update operation.
*/
export type AccessPoliciesUpdateResponse = AccessPolicyResource & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AccessPolicyResource;
};
};
/**
* Contains response data for the listByEnvironment operation.
*/
export type AccessPoliciesListByEnvironmentResponse = AccessPolicyListResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AccessPolicyListResponse;
};
}; | the_stack |
import * as assert from 'assert';
import * as sinon from 'sinon';
import { ConfigurationChangeEvent, Disposable, Uri, WorkspaceFolder, WorkspaceFoldersChangeEvent } from 'vscode';
import { JediLanguageServerManager } from '../../client/activation/jedi/manager';
import { LspNotebooksExperiment } from '../../client/activation/node/lspNotebooksExperiment';
import { NodeLanguageServerManager } from '../../client/activation/node/manager';
import { ILanguageServerOutputChannel, LanguageServerType } from '../../client/activation/types';
import { IApplicationShell, ICommandManager, IWorkspaceService } from '../../client/common/application/types';
import { IFileSystem } from '../../client/common/platform/types';
import {
IConfigurationService,
IExperimentService,
IExtensions,
IInterpreterPathService,
} from '../../client/common/types';
import { LanguageService } from '../../client/common/utils/localize';
import { IEnvironmentVariablesProvider } from '../../client/common/variables/types';
import { IInterpreterHelper, IInterpreterService } from '../../client/interpreter/contracts';
import { IServiceContainer } from '../../client/ioc/types';
import { JediLSExtensionManager } from '../../client/languageServer/jediLSExtensionManager';
import { NoneLSExtensionManager } from '../../client/languageServer/noneLSExtensionManager';
import { PylanceLSExtensionManager } from '../../client/languageServer/pylanceLSExtensionManager';
import { LanguageServerWatcher } from '../../client/languageServer/watcher';
import * as Logging from '../../client/logging';
import { PythonEnvironment } from '../../client/pythonEnvironments/info';
suite('Language server watcher', () => {
let watcher: LanguageServerWatcher;
const sandbox = sinon.createSandbox();
setup(() => {
watcher = new LanguageServerWatcher(
{} as IServiceContainer,
{} as ILanguageServerOutputChannel,
{
getSettings: () => ({ languageServer: LanguageServerType.None }),
} as IConfigurationService,
{} as IExperimentService,
({
getActiveWorkspaceUri: () => undefined,
} as unknown) as IInterpreterHelper,
({
onDidChange: () => {
/* do nothing */
},
} as unknown) as IInterpreterPathService,
({
getActiveInterpreter: () => 'python',
onDidChangeInterpreterInformation: () => {
/* do nothing */
},
} as unknown) as IInterpreterService,
{} as IEnvironmentVariablesProvider,
({
getWorkspaceFolder: (uri: Uri) => ({ uri }),
onDidChangeConfiguration: () => {
/* do nothing */
},
onDidChangeWorkspaceFolders: () => {
/* do nothing */
},
} as unknown) as IWorkspaceService,
({
registerCommand: () => {
/* do nothing */
},
} as unknown) as ICommandManager,
{} as IFileSystem,
({
getExtension: () => undefined,
onDidChange: () => {
/* do nothing */
},
} as unknown) as IExtensions,
{} as IApplicationShell,
{} as LspNotebooksExperiment,
[] as Disposable[],
);
});
teardown(() => {
sandbox.restore();
});
test('The constructor should add a listener to onDidChange to the list of disposables if it is a trusted workspace', () => {
const disposables: Disposable[] = [];
watcher = new LanguageServerWatcher(
{} as IServiceContainer,
{} as ILanguageServerOutputChannel,
{
getSettings: () => ({ languageServer: LanguageServerType.None }),
} as IConfigurationService,
{} as IExperimentService,
{} as IInterpreterHelper,
({
onDidChange: () => {
/* do nothing */
},
} as unknown) as IInterpreterPathService,
({
onDidChangeInterpreterInformation: () => {
/* do nothing */
},
} as unknown) as IInterpreterService,
{} as IEnvironmentVariablesProvider,
({
isTrusted: true,
getWorkspaceFolder: (uri: Uri) => ({ uri }),
onDidChangeConfiguration: () => {
/* do nothing */
},
onDidChangeWorkspaceFolders: () => {
/* do nothing */
},
} as unknown) as IWorkspaceService,
{} as ICommandManager,
{} as IFileSystem,
({
getExtension: () => undefined,
onDidChange: () => {
/* do nothing */
},
} as unknown) as IExtensions,
{} as IApplicationShell,
{} as LspNotebooksExperiment,
disposables,
);
assert.strictEqual(disposables.length, 5);
});
test('The constructor should not add a listener to onDidChange to the list of disposables if it is not a trusted workspace', () => {
const disposables: Disposable[] = [];
watcher = new LanguageServerWatcher(
{} as IServiceContainer,
{} as ILanguageServerOutputChannel,
{
getSettings: () => ({ languageServer: LanguageServerType.None }),
} as IConfigurationService,
{} as IExperimentService,
{} as IInterpreterHelper,
({
onDidChange: () => {
/* do nothing */
},
} as unknown) as IInterpreterPathService,
({
onDidChangeInterpreterInformation: () => {
/* do nothing */
},
} as unknown) as IInterpreterService,
{} as IEnvironmentVariablesProvider,
({
isTrusted: false,
getWorkspaceFolder: (uri: Uri) => ({ uri }),
onDidChangeConfiguration: () => {
/* do nothing */
},
onDidChangeWorkspaceFolders: () => {
/* do nothing */
},
} as unknown) as IWorkspaceService,
{} as ICommandManager,
{} as IFileSystem,
({
getExtension: () => undefined,
onDidChange: () => {
/* do nothing */
},
} as unknown) as IExtensions,
{} as IApplicationShell,
{} as LspNotebooksExperiment,
disposables,
);
assert.strictEqual(disposables.length, 4);
});
test(`When starting the language server, the language server extension manager should not be undefined`, async () => {
// First start
await watcher.startLanguageServer(LanguageServerType.None);
const extensionManager = watcher.languageServerExtensionManager!;
assert.notStrictEqual(extensionManager, undefined);
});
test(`If the interpreter changed, the existing language server should be stopped if there is one`, async () => {
const getActiveInterpreterStub = sandbox.stub();
getActiveInterpreterStub.onFirstCall().returns('python');
getActiveInterpreterStub.onSecondCall().returns('other/python');
const interpreterService = ({
getActiveInterpreter: getActiveInterpreterStub,
onDidChangeInterpreterInformation: () => {
/* do nothing */
},
} as unknown) as IInterpreterService;
watcher = new LanguageServerWatcher(
({
get: () => {
/* do nothing */
},
} as unknown) as IServiceContainer,
{} as ILanguageServerOutputChannel,
{
getSettings: () => ({ languageServer: LanguageServerType.None }),
} as IConfigurationService,
{} as IExperimentService,
({
getActiveWorkspaceUri: () => undefined,
} as unknown) as IInterpreterHelper,
({
onDidChange: () => {
/* do nothing */
},
} as unknown) as IInterpreterPathService,
interpreterService,
({
onDidEnvironmentVariablesChange: () => {
/* do nothing */
},
} as unknown) as IEnvironmentVariablesProvider,
({
isTrusted: true,
getWorkspaceFolder: (uri: Uri) => ({ uri }),
onDidChangeConfiguration: () => {
/* do nothing */
},
onDidChangeWorkspaceFolders: () => {
/* do nothing */
},
} as unknown) as IWorkspaceService,
({
registerCommand: () => {
/* do nothing */
},
} as unknown) as ICommandManager,
{} as IFileSystem,
({
getExtension: () => undefined,
onDidChange: () => {
/* do nothing */
},
} as unknown) as IExtensions,
{} as IApplicationShell,
{} as LspNotebooksExperiment,
[] as Disposable[],
);
// First start, get the reference to the extension manager.
await watcher.startLanguageServer(LanguageServerType.None);
const extensionManager = watcher.languageServerExtensionManager!;
const stopLanguageServerSpy = sandbox.spy(extensionManager, 'stopLanguageServer');
// Second start, check if the first server manager was stopped and disposed of.
await watcher.startLanguageServer(LanguageServerType.None);
assert.ok(stopLanguageServerSpy.calledOnce);
});
test(`When starting the language server, if the language server can be started, it should call startLanguageServer on the language server extension manager`, async () => {
const startLanguageServerStub = sandbox.stub(NoneLSExtensionManager.prototype, 'startLanguageServer');
startLanguageServerStub.returns(Promise.resolve());
await watcher.startLanguageServer(LanguageServerType.None);
assert.ok(startLanguageServerStub.calledOnce);
});
test(`When starting the language server, if the language server can be started, there should be logs written in the output channel`, async () => {
let output = '';
sandbox.stub(Logging, 'traceLog').callsFake((...args: unknown[]) => {
output = output.concat(...(args as string[]));
});
watcher = new LanguageServerWatcher(
{} as IServiceContainer,
{} as ILanguageServerOutputChannel,
{
getSettings: () => ({ languageServer: LanguageServerType.None }),
} as IConfigurationService,
{} as IExperimentService,
({
getActiveWorkspaceUri: () => ({ folderUri: Uri.parse('workspace') }),
} as unknown) as IInterpreterHelper,
({
onDidChange: () => {
/* do nothing */
},
} as unknown) as IInterpreterPathService,
({
getActiveInterpreter: () => 'python',
onDidChangeInterpreterInformation: () => {
/* do nothing */
},
} as unknown) as IInterpreterService,
{} as IEnvironmentVariablesProvider,
({
getWorkspaceFolder: (uri: Uri) => ({ uri }),
onDidChangeConfiguration: () => {
/* do nothing */
},
onDidChangeWorkspaceFolders: () => {
/* do nothing */
},
} as unknown) as IWorkspaceService,
({
registerCommand: () => {
/* do nothing */
},
} as unknown) as ICommandManager,
{} as IFileSystem,
({
getExtension: () => undefined,
onDidChange: () => {
/* do nothing */
},
} as unknown) as IExtensions,
{} as IApplicationShell,
{} as LspNotebooksExperiment,
[] as Disposable[],
);
await watcher.startLanguageServer(LanguageServerType.None);
assert.strictEqual(output, LanguageService.startingNone);
});
test(`When starting the language server, if the language server can be started, this.languageServerType should reflect the new language server type`, async () => {
await watcher.startLanguageServer(LanguageServerType.None);
assert.deepStrictEqual(watcher.languageServerType, LanguageServerType.None);
});
test(`When starting the language server, if the language server cannot be started, it should call languageServerNotAvailable`, async () => {
const canStartLanguageServerStub = sandbox.stub(NoneLSExtensionManager.prototype, 'canStartLanguageServer');
canStartLanguageServerStub.returns(false);
const languageServerNotAvailableStub = sandbox.stub(
NoneLSExtensionManager.prototype,
'languageServerNotAvailable',
);
languageServerNotAvailableStub.returns(Promise.resolve());
await watcher.startLanguageServer(LanguageServerType.None);
assert.ok(canStartLanguageServerStub.calledOnce);
assert.ok(languageServerNotAvailableStub.calledOnce);
});
test('When the config settings change, but the python.languageServer setting is not affected, the watcher should not restart the language server', async () => {
let onDidChangeConfigListener: (event: ConfigurationChangeEvent) => Promise<void> = () => Promise.resolve();
const workspaceService = ({
getWorkspaceFolder: (uri: Uri) => ({ uri }),
onDidChangeConfiguration: (listener: (event: ConfigurationChangeEvent) => Promise<void>) => {
onDidChangeConfigListener = listener;
},
onDidChangeWorkspaceFolders: () => {
/* do nothing */
},
} as unknown) as IWorkspaceService;
watcher = new LanguageServerWatcher(
{} as IServiceContainer,
{} as ILanguageServerOutputChannel,
{
getSettings: () => ({ languageServer: LanguageServerType.None }),
} as IConfigurationService,
{} as IExperimentService,
({
getActiveWorkspaceUri: () => undefined,
} as unknown) as IInterpreterHelper,
({
onDidChange: () => {
/* do nothing */
},
} as unknown) as IInterpreterPathService,
({
getActiveInterpreter: () => 'python',
onDidChangeInterpreterInformation: () => {
/* do nothing */
},
} as unknown) as IInterpreterService,
{} as IEnvironmentVariablesProvider,
workspaceService,
({
registerCommand: () => {
/* do nothing */
},
} as unknown) as ICommandManager,
{} as IFileSystem,
({
getExtension: () => undefined,
onDidChange: () => {
/* do nothing */
},
} as unknown) as IExtensions,
{} as IApplicationShell,
{} as LspNotebooksExperiment,
[] as Disposable[],
);
const startLanguageServerSpy = sandbox.spy(watcher, 'startLanguageServer');
await watcher.startLanguageServer(LanguageServerType.None);
await onDidChangeConfigListener({ affectsConfiguration: () => false });
// Check that startLanguageServer was only called once: When we called it above.
assert.ok(startLanguageServerSpy.calledOnce);
});
test('When the config settings change, and the python.languageServer setting is affected, the watcher should restart the language server', async () => {
let onDidChangeConfigListener: (event: ConfigurationChangeEvent) => Promise<void> = () => Promise.resolve();
const workspaceService = ({
getWorkspaceFolder: (uri: Uri) => ({ uri }),
onDidChangeConfiguration: (listener: (event: ConfigurationChangeEvent) => Promise<void>) => {
onDidChangeConfigListener = listener;
},
onDidChangeWorkspaceFolders: () => {
/* do nothing */
},
workspaceFolders: [{ uri: Uri.parse('workspace') }],
} as unknown) as IWorkspaceService;
const getSettingsStub = sandbox.stub();
getSettingsStub.onFirstCall().returns({ languageServer: LanguageServerType.None });
getSettingsStub.onSecondCall().returns({ languageServer: LanguageServerType.Node });
const configService = ({
getSettings: getSettingsStub,
} as unknown) as IConfigurationService;
watcher = new LanguageServerWatcher(
{} as IServiceContainer,
{} as ILanguageServerOutputChannel,
configService,
{} as IExperimentService,
({
getActiveWorkspaceUri: () => undefined,
} as unknown) as IInterpreterHelper,
({
onDidChange: () => {
/* do nothing */
},
} as unknown) as IInterpreterPathService,
({
getActiveInterpreter: () => 'python',
onDidChangeInterpreterInformation: () => {
/* do nothing */
},
} as unknown) as IInterpreterService,
{} as IEnvironmentVariablesProvider,
workspaceService,
({
registerCommand: () => {
/* do nothing */
},
} as unknown) as ICommandManager,
{} as IFileSystem,
({
getExtension: () => undefined,
onDidChange: () => {
/* do nothing */
},
} as unknown) as IExtensions,
{} as IApplicationShell,
{} as LspNotebooksExperiment,
[] as Disposable[],
);
// Use a fake here so we don't actually start up language servers.
const startLanguageServerFake = sandbox.fake.resolves(undefined);
sandbox.replace(watcher, 'startLanguageServer', startLanguageServerFake);
await watcher.startLanguageServer(LanguageServerType.None);
await onDidChangeConfigListener({ affectsConfiguration: () => true });
// Check that startLanguageServer was called twice: When we called it above, and implicitly because of the event.
assert.ok(startLanguageServerFake.calledTwice);
});
test('When starting a language server with a Python 2.7 interpreter and the python.languageServer setting is Jedi, do not instantiate a language server', async () => {
const startLanguageServerStub = sandbox.stub(NoneLSExtensionManager.prototype, 'startLanguageServer');
startLanguageServerStub.returns(Promise.resolve());
watcher = new LanguageServerWatcher(
{} as IServiceContainer,
{} as ILanguageServerOutputChannel,
{
getSettings: () => ({ languageServer: LanguageServerType.Jedi }),
} as IConfigurationService,
{} as IExperimentService,
({
getActiveWorkspaceUri: () => undefined,
} as unknown) as IInterpreterHelper,
({
onDidChange: () => {
/* do nothing */
},
} as unknown) as IInterpreterPathService,
({
getActiveInterpreter: () => ({ version: { major: 2, minor: 7 } }),
onDidChangeInterpreterInformation: () => {
/* do nothing */
},
} as unknown) as IInterpreterService,
{} as IEnvironmentVariablesProvider,
({
getWorkspaceFolder: (uri: Uri) => ({ uri }),
onDidChangeConfiguration: () => {
/* do nothing */
},
onDidChangeWorkspaceFolders: () => {
/* do nothing */
},
} as unknown) as IWorkspaceService,
({
registerCommand: () => {
/* do nothing */
},
} as unknown) as ICommandManager,
{} as IFileSystem,
({
getExtension: () => undefined,
onDidChange: () => {
/* do nothing */
},
} as unknown) as IExtensions,
{} as IApplicationShell,
{} as LspNotebooksExperiment,
[] as Disposable[],
);
await watcher.startLanguageServer(LanguageServerType.Jedi);
assert.ok(startLanguageServerStub.calledOnce);
});
test('When starting a language server with a Python 2.7 interpreter and the python.languageServer setting is default, use Pylance', async () => {
const startLanguageServerStub = sandbox.stub(PylanceLSExtensionManager.prototype, 'startLanguageServer');
startLanguageServerStub.returns(Promise.resolve());
sandbox.stub(PylanceLSExtensionManager.prototype, 'canStartLanguageServer').returns(true);
watcher = new LanguageServerWatcher(
{} as IServiceContainer,
{} as ILanguageServerOutputChannel,
{
getSettings: () => ({
languageServer: LanguageServerType.Jedi,
languageServerIsDefault: true,
}),
} as IConfigurationService,
{} as IExperimentService,
({
getActiveWorkspaceUri: () => undefined,
} as unknown) as IInterpreterHelper,
({
onDidChange: () => {
/* do nothing */
},
} as unknown) as IInterpreterPathService,
({
getActiveInterpreter: () => ({ version: { major: 2, minor: 7 } }),
onDidChangeInterpreterInformation: () => {
/* do nothing */
},
} as unknown) as IInterpreterService,
{} as IEnvironmentVariablesProvider,
({
getWorkspaceFolder: (uri: Uri) => ({ uri }),
onDidChangeConfiguration: () => {
/* do nothing */
},
onDidChangeWorkspaceFolders: () => {
/* do nothing */
},
} as unknown) as IWorkspaceService,
({
registerCommand: () => {
/* do nothing */
},
} as unknown) as ICommandManager,
{} as IFileSystem,
({
getExtension: () => undefined,
onDidChange: () => {
/* do nothing */
},
} as unknown) as IExtensions,
({
showWarningMessage: () => Promise.resolve(undefined),
} as unknown) as IApplicationShell,
{} as LspNotebooksExperiment,
[] as Disposable[],
);
await watcher.startLanguageServer(LanguageServerType.Node);
assert.ok(startLanguageServerStub.calledOnce);
});
test('When starting a language server in an untrusted workspace with Jedi, do not instantiate a language server', async () => {
const startLanguageServerStub = sandbox.stub(NoneLSExtensionManager.prototype, 'startLanguageServer');
startLanguageServerStub.returns(Promise.resolve());
watcher = new LanguageServerWatcher(
{} as IServiceContainer,
{} as ILanguageServerOutputChannel,
{
getSettings: () => ({ languageServer: LanguageServerType.Jedi }),
} as IConfigurationService,
{} as IExperimentService,
({
getActiveWorkspaceUri: () => undefined,
} as unknown) as IInterpreterHelper,
({
onDidChange: () => {
/* do nothing */
},
} as unknown) as IInterpreterPathService,
({
getActiveInterpreter: () => ({ version: { major: 2, minor: 7 } }),
onDidChangeInterpreterInformation: () => {
/* do nothing */
},
} as unknown) as IInterpreterService,
{} as IEnvironmentVariablesProvider,
({
isTrusted: false,
getWorkspaceFolder: (uri: Uri) => ({ uri }),
onDidChangeConfiguration: () => {
/* do nothing */
},
onDidChangeWorkspaceFolders: () => {
/* do nothing */
},
} as unknown) as IWorkspaceService,
({
registerCommand: () => {
/* do nothing */
},
} as unknown) as ICommandManager,
{} as IFileSystem,
({
getExtension: () => undefined,
onDidChange: () => {
/* do nothing */
},
} as unknown) as IExtensions,
{} as IApplicationShell,
{} as LspNotebooksExperiment,
[] as Disposable[],
);
await watcher.startLanguageServer(LanguageServerType.Jedi);
assert.ok(startLanguageServerStub.calledOnce);
});
[
{
languageServer: LanguageServerType.Jedi,
multiLS: true,
extensionLSCls: JediLSExtensionManager,
lsManagerCls: JediLanguageServerManager,
},
{
languageServer: LanguageServerType.Node,
multiLS: false,
extensionLSCls: PylanceLSExtensionManager,
lsManagerCls: NodeLanguageServerManager,
},
{
languageServer: LanguageServerType.None,
multiLS: false,
extensionLSCls: NoneLSExtensionManager,
lsManagerCls: undefined,
},
].forEach(({ languageServer, multiLS, extensionLSCls, lsManagerCls }) => {
test(`When starting language servers with different resources, ${
multiLS ? 'multiple' : 'a single'
} language server${multiLS ? 's' : ''} should be instantiated when using ${languageServer}`, async () => {
const getActiveInterpreterStub = sandbox.stub();
getActiveInterpreterStub.onFirstCall().returns({ path: 'folder1/python', version: { major: 3, minor: 9 } });
getActiveInterpreterStub
.onSecondCall()
.returns({ path: 'folder2/python', version: { major: 3, minor: 10 } });
const startLanguageServerStub = sandbox.stub(extensionLSCls.prototype, 'startLanguageServer');
startLanguageServerStub.returns(Promise.resolve());
const stopLanguageServerStub = sandbox.stub(extensionLSCls.prototype, 'stopLanguageServer');
sandbox.stub(extensionLSCls.prototype, 'canStartLanguageServer').returns(true);
watcher = new LanguageServerWatcher(
{} as IServiceContainer,
{} as ILanguageServerOutputChannel,
{
getSettings: () => ({ languageServer }),
} as IConfigurationService,
{} as IExperimentService,
({
getActiveWorkspaceUri: () => undefined,
} as unknown) as IInterpreterHelper,
({
onDidChange: () => {
/* do nothing */
},
} as unknown) as IInterpreterPathService,
({
getActiveInterpreter: getActiveInterpreterStub,
onDidChangeInterpreterInformation: () => {
/* do nothing */
},
} as unknown) as IInterpreterService,
{} as IEnvironmentVariablesProvider,
({
isTrusted: true,
getWorkspaceFolder: (uri: Uri) => ({ uri }),
onDidChangeConfiguration: () => {
/* do nothing */
},
onDidChangeWorkspaceFolders: () => {
/* do nothing */
},
} as unknown) as IWorkspaceService,
({
registerCommand: () => {
/* do nothing */
},
} as unknown) as ICommandManager,
{} as IFileSystem,
({
getExtension: () => undefined,
onDidChange: () => {
/* do nothing */
},
} as unknown) as IExtensions,
({
showWarningMessage: () => Promise.resolve(undefined),
} as unknown) as IApplicationShell,
{} as LspNotebooksExperiment,
[] as Disposable[],
);
await watcher.startLanguageServer(languageServer, Uri.parse('folder1'));
await watcher.startLanguageServer(languageServer, Uri.parse('folder2'));
// If multiLS set to true, then we expect to have called startLanguageServer twice.
// If multiLS set to false, then we expect to have called startLanguageServer once.
assert.ok(startLanguageServerStub.calledTwice === multiLS);
assert.ok(startLanguageServerStub.calledOnce === !multiLS);
assert.ok(getActiveInterpreterStub.calledTwice);
assert.ok(stopLanguageServerStub.notCalled);
});
test(`${languageServer} language server(s) should ${
multiLS ? '' : 'not'
} be stopped if a workspace gets removed from the current project`, async () => {
sandbox.stub(extensionLSCls.prototype, 'startLanguageServer').returns(Promise.resolve());
if (lsManagerCls) {
sandbox.stub(lsManagerCls.prototype, 'dispose').returns();
}
const stopLanguageServerStub = sandbox.stub(extensionLSCls.prototype, 'stopLanguageServer');
stopLanguageServerStub.returns(Promise.resolve());
let onDidChangeWorkspaceFoldersListener: (event: WorkspaceFoldersChangeEvent) => Promise<void> = () =>
Promise.resolve();
const workspaceService = ({
getWorkspaceFolder: (uri: Uri) => ({ uri }),
onDidChangeConfiguration: () => {
/* do nothing */
},
onDidChangeWorkspaceFolders: (listener: (event: WorkspaceFoldersChangeEvent) => Promise<void>) => {
onDidChangeWorkspaceFoldersListener = listener;
},
workspaceFolders: [{ uri: Uri.parse('workspace1') }, { uri: Uri.parse('workspace2') }],
isTrusted: true,
} as unknown) as IWorkspaceService;
watcher = new LanguageServerWatcher(
{} as IServiceContainer,
{} as ILanguageServerOutputChannel,
{
getSettings: () => ({ languageServer }),
} as IConfigurationService,
{} as IExperimentService,
({
getActiveWorkspaceUri: () => undefined,
} as unknown) as IInterpreterHelper,
({
onDidChange: () => {
/* do nothing */
},
} as unknown) as IInterpreterPathService,
({
getActiveInterpreter: () => ({ version: { major: 3, minor: 7 } }),
onDidChangeInterpreterInformation: () => {
/* do nothing */
},
} as unknown) as IInterpreterService,
{} as IEnvironmentVariablesProvider,
workspaceService,
({
registerCommand: () => {
/* do nothing */
},
} as unknown) as ICommandManager,
{} as IFileSystem,
({
getExtension: () => undefined,
onDidChange: () => {
/* do nothing */
},
} as unknown) as IExtensions,
({
showWarningMessage: () => Promise.resolve(undefined),
} as unknown) as IApplicationShell,
{} as LspNotebooksExperiment,
[] as Disposable[],
);
await watcher.startLanguageServer(languageServer, Uri.parse('workspace1'));
await watcher.startLanguageServer(languageServer, Uri.parse('workspace2'));
await onDidChangeWorkspaceFoldersListener({
added: [],
removed: [{ uri: Uri.parse('workspace2') } as WorkspaceFolder],
});
// If multiLS set to true, then we expect to have stopped a language server.
// If multiLS set to false, then we expect to not have stopped a language server.
assert.ok(stopLanguageServerStub.calledOnce === multiLS);
assert.ok(stopLanguageServerStub.notCalled === !multiLS);
});
});
test('The language server should be restarted if the interpreter info changed', async () => {
const info = ({
envPath: 'foo',
path: 'path/to/foo/bin/python',
} as unknown) as PythonEnvironment;
let onDidChangeInfoListener: (event: PythonEnvironment) => Promise<void> = () => Promise.resolve();
const interpreterService = ({
onDidChangeInterpreterInformation: (
listener: (event: PythonEnvironment) => Promise<void>,
thisArg: unknown,
): void => {
onDidChangeInfoListener = listener.bind(thisArg);
},
getActiveInterpreter: () => ({
envPath: 'foo',
path: 'path/to/foo',
}),
} as unknown) as IInterpreterService;
watcher = new LanguageServerWatcher(
({
get: () => {
/* do nothing */
},
} as unknown) as IServiceContainer,
{} as ILanguageServerOutputChannel,
{
getSettings: () => ({ languageServer: LanguageServerType.None }),
} as IConfigurationService,
{} as IExperimentService,
({
getActiveWorkspaceUri: () => undefined,
} as unknown) as IInterpreterHelper,
({
onDidChange: () => {
/* do nothing */
},
} as unknown) as IInterpreterPathService,
interpreterService,
({
onDidEnvironmentVariablesChange: () => {
/* do nothing */
},
} as unknown) as IEnvironmentVariablesProvider,
({
isTrusted: true,
getWorkspaceFolder: (uri: Uri) => ({ uri }),
onDidChangeConfiguration: () => {
/* do nothing */
},
onDidChangeWorkspaceFolders: () => {
/* do nothing */
},
} as unknown) as IWorkspaceService,
({
registerCommand: () => {
/* do nothing */
},
} as unknown) as ICommandManager,
{} as IFileSystem,
({
getExtension: () => undefined,
onDidChange: () => {
/* do nothing */
},
} as unknown) as IExtensions,
{} as IApplicationShell,
{} as LspNotebooksExperiment,
[] as Disposable[],
);
const startLanguageServerSpy = sandbox.spy(watcher, 'startLanguageServer');
await watcher.startLanguageServer(LanguageServerType.None);
await onDidChangeInfoListener(info);
// Check that startLanguageServer was called twice: Once above, and once after the interpreter info changed.
assert.ok(startLanguageServerSpy.calledTwice);
});
test('The language server should not be restarted if the interpreter info did not change', async () => {
const info = ({
envPath: 'foo',
path: 'path/to/foo',
} as unknown) as PythonEnvironment;
let onDidChangeInfoListener: (event: PythonEnvironment) => Promise<void> = () => Promise.resolve();
const interpreterService = ({
onDidChangeInterpreterInformation: (
listener: (event: PythonEnvironment) => Promise<void>,
thisArg: unknown,
): void => {
onDidChangeInfoListener = listener.bind(thisArg);
},
getActiveInterpreter: () => info,
} as unknown) as IInterpreterService;
watcher = new LanguageServerWatcher(
({
get: () => {
/* do nothing */
},
} as unknown) as IServiceContainer,
{} as ILanguageServerOutputChannel,
{
getSettings: () => ({ languageServer: LanguageServerType.None }),
} as IConfigurationService,
{} as IExperimentService,
({
getActiveWorkspaceUri: () => undefined,
} as unknown) as IInterpreterHelper,
({
onDidChange: () => {
/* do nothing */
},
} as unknown) as IInterpreterPathService,
interpreterService,
({
onDidEnvironmentVariablesChange: () => {
/* do nothing */
},
} as unknown) as IEnvironmentVariablesProvider,
({
isTrusted: true,
getWorkspaceFolder: (uri: Uri) => ({ uri }),
onDidChangeConfiguration: () => {
/* do nothing */
},
onDidChangeWorkspaceFolders: () => {
/* do nothing */
},
} as unknown) as IWorkspaceService,
({
registerCommand: () => {
/* do nothing */
},
} as unknown) as ICommandManager,
{} as IFileSystem,
({
getExtension: () => undefined,
onDidChange: () => {
/* do nothing */
},
} as unknown) as IExtensions,
{} as IApplicationShell,
{} as LspNotebooksExperiment,
[] as Disposable[],
);
const startLanguageServerSpy = sandbox.spy(watcher, 'startLanguageServer');
await watcher.startLanguageServer(LanguageServerType.None);
await onDidChangeInfoListener(info);
// Check that startLanguageServer was called once: Only when startLanguageServer() was called above.
assert.ok(startLanguageServerSpy.calledOnce);
});
test('The language server should not be restarted if the interpreter info changed but the env path is an empty string', async () => {
const info = ({
envPath: '',
path: 'path/to/foo',
} as unknown) as PythonEnvironment;
let onDidChangeInfoListener: (event: PythonEnvironment) => Promise<void> = () => Promise.resolve();
const interpreterService = ({
onDidChangeInterpreterInformation: (
listener: (event: PythonEnvironment) => Promise<void>,
thisArg: unknown,
): void => {
onDidChangeInfoListener = listener.bind(thisArg);
},
getActiveInterpreter: () => ({
envPath: 'foo',
path: 'path/to/foo',
}),
} as unknown) as IInterpreterService;
watcher = new LanguageServerWatcher(
({
get: () => {
/* do nothing */
},
} as unknown) as IServiceContainer,
{} as ILanguageServerOutputChannel,
{
getSettings: () => ({ languageServer: LanguageServerType.None }),
} as IConfigurationService,
{} as IExperimentService,
({
getActiveWorkspaceUri: () => undefined,
} as unknown) as IInterpreterHelper,
({
onDidChange: () => {
/* do nothing */
},
} as unknown) as IInterpreterPathService,
interpreterService,
({
onDidEnvironmentVariablesChange: () => {
/* do nothing */
},
} as unknown) as IEnvironmentVariablesProvider,
({
isTrusted: true,
getWorkspaceFolder: (uri: Uri) => ({ uri }),
onDidChangeConfiguration: () => {
/* do nothing */
},
onDidChangeWorkspaceFolders: () => {
/* do nothing */
},
} as unknown) as IWorkspaceService,
({
registerCommand: () => {
/* do nothing */
},
} as unknown) as ICommandManager,
{} as IFileSystem,
({
getExtension: () => undefined,
onDidChange: () => {
/* do nothing */
},
} as unknown) as IExtensions,
{} as IApplicationShell,
{} as LspNotebooksExperiment,
[] as Disposable[],
);
const startLanguageServerSpy = sandbox.spy(watcher, 'startLanguageServer');
await watcher.startLanguageServer(LanguageServerType.None);
await onDidChangeInfoListener(info);
// Check that startLanguageServer was called once: Only when startLanguageServer() was called above.
assert.ok(startLanguageServerSpy.calledOnce);
});
test('The language server should not be restarted if the interpreter info changed but the env path is undefined', async () => {
const info = ({
envPath: undefined,
path: 'path/to/foo',
} as unknown) as PythonEnvironment;
let onDidChangeInfoListener: (event: PythonEnvironment) => Promise<void> = () => Promise.resolve();
const interpreterService = ({
onDidChangeInterpreterInformation: (
listener: (event: PythonEnvironment) => Promise<void>,
thisArg: unknown,
): void => {
onDidChangeInfoListener = listener.bind(thisArg);
},
getActiveInterpreter: () => ({
envPath: 'foo',
path: 'path/to/foo',
}),
} as unknown) as IInterpreterService;
watcher = new LanguageServerWatcher(
({
get: () => {
/* do nothing */
},
} as unknown) as IServiceContainer,
{} as ILanguageServerOutputChannel,
{
getSettings: () => ({ languageServer: LanguageServerType.None }),
} as IConfigurationService,
{} as IExperimentService,
({
getActiveWorkspaceUri: () => undefined,
} as unknown) as IInterpreterHelper,
({
onDidChange: () => {
/* do nothing */
},
} as unknown) as IInterpreterPathService,
interpreterService,
({
onDidEnvironmentVariablesChange: () => {
/* do nothing */
},
} as unknown) as IEnvironmentVariablesProvider,
({
isTrusted: true,
getWorkspaceFolder: (uri: Uri) => ({ uri }),
onDidChangeConfiguration: () => {
/* do nothing */
},
onDidChangeWorkspaceFolders: () => {
/* do nothing */
},
} as unknown) as IWorkspaceService,
({
registerCommand: () => {
/* do nothing */
},
} as unknown) as ICommandManager,
{} as IFileSystem,
({
getExtension: () => undefined,
onDidChange: () => {
/* do nothing */
},
} as unknown) as IExtensions,
{} as IApplicationShell,
{} as LspNotebooksExperiment,
[] as Disposable[],
);
const startLanguageServerSpy = sandbox.spy(watcher, 'startLanguageServer');
await watcher.startLanguageServer(LanguageServerType.None);
await onDidChangeInfoListener(info);
// Check that startLanguageServer was called once: Only when startLanguageServer() was called above.
assert.ok(startLanguageServerSpy.calledOnce);
});
}); | the_stack |
import { ClassReflection, ParameterReflection, PropertyReflection, reflect, reflection } from "@plumier/reflect"
import debug from "debug"
import { Class, entityHelper, isCustomClass, memoize } from "./common"
import { ResponseTypeDecorator } from "./decorator/common"
import { EntityIdDecorator, RelationDecorator } from "./decorator/entity"
import { HttpStatus } from "./http-status"
import {
AccessModifier,
ActionContext,
ActionResult,
AuthorizationContext,
Authorizer,
AuthPolicy,
Configuration,
HttpStatusError,
Invocation,
Metadata,
MetadataImpl,
Middleware,
RouteAnalyzerFunction,
RouteAnalyzerIssue,
RouteInfo,
RouteMetadata,
} from "./types"
// --------------------------------------------------------------------- //
// ------------------------------- TYPES ------------------------------- //
// --------------------------------------------------------------------- //
const log = {
debug: debug("@plumier/core:authorization"),
}
type AuthorizerFunction = (info: AuthorizationContext) => boolean | Promise<boolean>
interface AuthorizeDecorator {
type: "plumier-meta:authorize",
policies: string[]
access: AccessModifier
tag: string,
location: "Class" | "Parameter" | "Method",
evaluation: "Static" | "Dynamic",
appliedClass: Class
}
type CustomAuthorizer = Authorizer
type CustomAuthorizerFunction = AuthorizerFunction
type AuthorizerContext = AuthorizationContext
/* ------------------------------------------------------------------------------- */
/* ------------------------------- HELPERS --------------------------------------- */
/* ------------------------------------------------------------------------------- */
function createDecoratorFilter(predicate: (x: AuthorizeDecorator) => boolean) {
return (x: AuthorizeDecorator): x is AuthorizeDecorator => x.type === "plumier-meta:authorize" && predicate(x)
}
function getGlobalDecorators(globalDecorator: string | string[]) {
const policies = typeof globalDecorator === "string" ? [globalDecorator] : globalDecorator
return [<AuthorizeDecorator>{
type: "plumier-meta:authorize",
policies,
tag: policies.join("|"),
access: "route",
evaluation: "Dynamic",
location: "Method",
appliedClass: Object
}]
}
function getRouteAuthorizeDecorators(info: RouteInfo, globalDecorator?: string | string[]) {
// if action has decorators then return immediately to prioritize the action decorator
const actionDecs = info.action.decorators.filter(createDecoratorFilter(x => x.access === "route"))
if (actionDecs.length > 0) return actionDecs
// if controller has decorators then return immediately
const controllerDecs = info.controller.decorators.filter(createDecoratorFilter(x => x.access === "route"))
if (controllerDecs.length > 0) return controllerDecs
if (!globalDecorator) return []
return getGlobalDecorators(globalDecorator)
}
function createAuthContext(ctx: ActionContext, access: AccessModifier): AuthorizationContext {
const { route, state } = ctx
return <AuthorizationContext>{
user: state.user, route, ctx, access, policyIds: [],
metadata: new MetadataImpl(ctx.parameters, ctx.route, {} as any),
}
}
function throwAuthError(ctx: AuthorizerContext, msg?: string) {
if (ctx.user) throw new HttpStatusError(HttpStatus.Forbidden, msg ?? "Forbidden")
else throw new HttpStatusError(HttpStatus.Unauthorized, msg ?? "Unauthorized")
}
function getErrorLocation(metadata: Metadata) {
const current = metadata.current!
if (current.kind === "Class")
return `class ${current.name}`
return `${current.kind.toLowerCase()} ${current.parent!.name}.${current.name}`
}
// --------------------------------------------------------------------- //
// ------------------------ AUTHORIZATION POLICY ----------------------- //
// --------------------------------------------------------------------- //
const Public = "Public"
const Authenticated = "Authenticated"
const AuthorizeReadonly = "plumier::readonly"
const AuthorizeWriteonly = "plumier::writeonly"
type EntityProviderQuery<T = any> = (entity: Class, id: any) => Promise<T>
interface EntityPolicyProviderDecorator { kind: "plumier-meta:entity-policy-provider", entity: Class, idParam: string }
type EntityPolicyAuthorizerFunction = (ctx: AuthorizerContext, id: any) => boolean | Promise<boolean>
class PolicyAuthorizer implements Authorizer {
constructor(private policies: Class<AuthPolicy>[], private keys: string[]) { }
async authorize(ctx: AuthorizationContext): Promise<boolean> {
for (const Auth of this.policies.reverse()) {
const authPolicy = new Auth()
for (const policy of this.keys) {
if (authPolicy.equals(policy, ctx)) {
const authorize = await authPolicy.authorize(ctx)
log.debug("%s -> %s.%s by %s",
authorize ? "AUTHORIZED" : "FORBIDDEN",
ctx.metadata.current!.parent?.name ?? "",
ctx.metadata.current!.name,
authPolicy.friendlyName())
if (authorize) return true
}
}
}
return false
}
}
class CustomAuthPolicy implements AuthPolicy {
constructor(public name: string, private authorizer: CustomAuthorizerFunction | CustomAuthorizer) { }
equals(id: string, ctx: AuthorizationContext): boolean {
return id === this.name
}
async authorize(ctx: AuthorizationContext): Promise<boolean> {
try {
if (typeof this.authorizer === "function")
return await this.authorizer(ctx)
else
return await this.authorizer.authorize(ctx)
}
catch (e) {
const message = e instanceof Error ? e.stack : e
const location = getErrorLocation(ctx.metadata)
throw new Error(`Error occur inside authorization policy ${this.name} on ${location} \n ${message}`)
}
}
conflict(other: AuthPolicy): boolean {
return this.name === other.name
}
friendlyName() {
return `AuthPolicy { name: "${this.name}" }`
}
}
class PublicAuthPolicy extends CustomAuthPolicy {
constructor() { super(Public, {} as any) }
async authorize(ctx: AuthorizationContext): Promise<boolean> {
return true
}
}
class AuthenticatedAuthPolicy extends CustomAuthPolicy {
constructor() { super(Authenticated, {} as any) }
async authorize(ctx: AuthorizationContext): Promise<boolean> {
return !!ctx.user
}
}
class ReadonlyAuthPolicy extends CustomAuthPolicy {
constructor() { super(AuthorizeReadonly, {} as any) }
async authorize(ctx: AuthorizationContext): Promise<boolean> {
return false
}
}
class WriteonlyAuthPolicy extends CustomAuthPolicy {
constructor() { super(AuthorizeWriteonly, {} as any) }
async authorize(ctx: AuthorizationContext): Promise<boolean> {
return false
}
}
class EntityAuthPolicy<T> implements AuthPolicy {
constructor(public name: string, public entity: Class<T>, private authorizer: EntityPolicyAuthorizerFunction) { }
private getEntity(ctx: AuthorizerContext): { entity: Class, id: any } {
if (ctx.access === "route" || ctx.access === "write") {
// when the entity provider is Route
// take the provided Entity from decorator
// take the entity ID value from the Action Parameter
const dec: EntityPolicyProviderDecorator | undefined = ctx.metadata.action.decorators
.find((x: EntityPolicyProviderDecorator) => x.kind === "plumier-meta:entity-policy-provider")
if (!dec) {
const meta = ctx.metadata
throw new Error(`Action ${meta.controller.name}.${meta.action.name} doesn't have Entity Policy Provider information`)
}
const id = ctx.metadata.actionParams!.get(dec.idParam)
return { entity: dec.entity, id }
}
else {
// when the entity provider is Read/Write/Filter
// take the provided entity from the parent type from context
// take the entity ID value using @primaryId() decorator
const entity = ctx.metadata.current!.parent!
const prop = entityHelper.getIdProp(entity)
if (!prop)
throw new Error(`Entity ${entity.name} doesn't have primary ID information required for entity policy`)
const id = ctx.parentValue[prop.name]
return { entity, id }
}
}
equals(id: string, ctx: AuthorizationContext): boolean {
if (id === this.name) {
const provider = this.getEntity(ctx)
return this.entity === provider.entity
}
return false
}
async authorize(ctx: AuthorizationContext): Promise<boolean> {
const provider = this.getEntity(ctx)
try {
return await this.authorizer(ctx, provider.id)
}
catch (e) {
const message = e instanceof Error ? e.stack : e
const location = getErrorLocation(ctx.metadata)
throw new Error(`Error occur inside authorization policy ${this.name} for entity ${this.entity.name} on ${location} \n ${message}`)
}
}
conflict(other: AuthPolicy): boolean {
if (other instanceof EntityAuthPolicy)
return this.name === other.name && this.entity === other.entity
else
return this.name === other.name
}
friendlyName() {
return `EntityPolicy { name: "${this.name}", entity: ${this.entity.name} }`
}
}
class AuthPolicyBuilder {
constructor(private globalCache: Class<AuthPolicy>[]) { }
/**
* Define AuthPolicy class on the fly
* @param id Id of the authorization policy that will be used in @authorize decorator
* @param authorizer Authorization logic, a lambda function return true to authorize otherwise false
*/
define(id: string, authorizer: CustomAuthorizerFunction | CustomAuthorizer): Class<AuthPolicy> {
class Policy extends CustomAuthPolicy {
constructor() { super(id, authorizer) }
}
return Policy
}
/**
* Register authorization policy into authorization cache
* @param id Id of the authorization policy that will be used in @authorize decorator
* @param authorizer Authorization logic, a lambda function return true to authorize otherwise false
*/
register(id: string, authorizer: CustomAuthorizerFunction | CustomAuthorizer): AuthPolicyBuilder {
const Policy = this.define(id, authorizer)
this.globalCache.push(Policy)
return this
}
}
class EntityPolicyBuilder<T> {
constructor(private entity: Class<T>, private globalCache: Class<AuthPolicy>[]) { }
/**
* Define AuthPolicy class on the fly
* @param id Id of the authorization policy that will be used in @authorize decorator
* @param authorizer Authorization logic, a lambda function return true to authorize otherwise false
*/
define(id: string, authorizer: EntityPolicyAuthorizerFunction): Class<AuthPolicy> {
const entity = this.entity
class Policy extends EntityAuthPolicy<T> {
constructor() { super(id, entity, authorizer) }
}
return Policy
}
/**
* Register authorization policy into authorization cache
* @param id Id of the authorization policy that will be used in @authorize decorator
* @param authorizer Authorization logic, a lambda function return true to authorize otherwise false
*/
register(id: string, authorizer: EntityPolicyAuthorizerFunction): EntityPolicyBuilder<T> {
const Policy = this.define(id, authorizer)
this.globalCache.push(Policy)
return this
}
}
const globalPolicies: Class<AuthPolicy>[] = []
function authPolicy() {
return new AuthPolicyBuilder(globalPolicies)
}
function entityPolicy<T>(entity: Class<T>) {
return new EntityPolicyBuilder<T>(entity, globalPolicies)
}
// --------------------------------------------------------------------- //
// ---------------------- MAIN AUTHORIZER FUNCTION --------------------- //
// --------------------------------------------------------------------- //
function executeAuthorizer(decorator: AuthorizeDecorator | AuthorizeDecorator[], info: AuthorizationContext) {
const policies = Array.isArray(decorator) ? decorator.map(x => x.policies).flatten() : decorator.policies
const instance = new PolicyAuthorizer(info.ctx.config.authPolicies, policies)
return instance.authorize(info)
}
// --------------------------------------------------------------------- //
// ----------------- CONTROLLER OR ACTION AUTHORIZATION ---------------- //
// --------------------------------------------------------------------- //
function fixContext(decorator: AuthorizeDecorator, info: AuthorizerContext) {
if (decorator.location === "Class") {
info.metadata.current = info.ctx.route.controller
}
if (decorator.location === "Method") {
info.metadata.current = { ...info.ctx.route.action, parent: info.ctx.route.controller.type }
}
return info
}
async function checkUserAccessToRoute(decorators: AuthorizeDecorator[], info: AuthorizationContext) {
const conditions = await Promise.all(decorators.map(x => executeAuthorizer(x, fixContext(x, info))))
// if authorized once then pass
if (conditions.some(x => x === true)) return
// if not then throw error accordingly
throwAuthError(info)
}
// --------------------------------------------------------------------- //
// ---------------------- PARAMETER AUTHORIZATION ---------------------- //
// --------------------------------------------------------------------- //
interface ParamCheckContext {
path: string[]
info: AuthorizationContext
parent: Class
parentValue?: any
}
function createContext(ctx: ParamCheckContext, value: any, meta: ClassReflection | PropertyReflection | ParameterReflection) {
const info = { ...ctx.info }
const metadata = { ...info.metadata }
metadata.current = { ...meta, parent: ctx.parent }
info.value = value
info.parentValue = ctx.parentValue
info.metadata = metadata
return info
}
async function checkParameter(meta: PropertyReflection | ParameterReflection, value: any, ctx: ParamCheckContext): Promise<string[]> {
if (value === undefined || value === null) return []
// skip check on GET method
if (ctx.info.ctx.method === "GET") return []
const decorators = meta.decorators.filter(createDecoratorFilter(x => x.access === "write"))
if (decorators.length > 0) {
const info = createContext(ctx, value, meta)
const allowed = await executeAuthorizer(decorators, info)
if (!allowed) return [ctx.path.join(".")]
}
// if the property is a relation property just skip checking, since we allow set relation using ID
const isRelation = meta.decorators.some((x: RelationDecorator) => x.kind === "plumier-meta:relation")
if (isRelation) return []
// loop through property of type array
if (Array.isArray(meta.type)) {
const newMeta = { ...meta, type: meta.type[0] };
const result: string[] = []
for (let i = 0; i < value.length; i++) {
const val = value[i];
result.push(...await checkParameter(newMeta, val, { ...ctx, path: ctx.path.concat(i.toString()) }))
}
return result
}
// loop through custom class properties
if (isCustomClass(meta.type)) {
const classMeta = reflect(<Class>meta.type)
const values = classMeta.properties.map(x => value[x.name])
return checkParameters(classMeta.properties, values, { ...ctx, parent: meta.type, parentValue: value })
}
// everything when fine then just return []
return []
}
async function checkParameters(meta: (PropertyReflection | ParameterReflection)[], value: any[], ctx: ParamCheckContext) {
const result: string[] = []
for (let i = 0; i < meta.length; i++) {
const prop = meta[i];
const issues = await checkParameter(prop, value[i], { ...ctx, path: ctx.path.concat(prop.name), })
result.push(...issues)
}
return result
}
async function checkUserAccessToParameters(meta: ParameterReflection[], values: any[], info: AuthorizationContext) {
const unauthorizedPaths = await checkParameters(meta, values, { info, path: [], parent: info.ctx.route.controller.type })
if (unauthorizedPaths.length > 0)
throwAuthError(info, `Unauthorized to populate parameter paths (${unauthorizedPaths.join(", ")})`)
}
// --------------------------------------------------------------------- //
// ----------------------- RESPONSE AUTHORIZATION ---------------------- //
// --------------------------------------------------------------------- //
type FilterNode = ArrayNode | ClassNode | ValueNode
interface ValueNode {
kind: "Value"
}
interface ArrayNode {
kind: "Array"
child: FilterNode
}
interface ClassNode {
kind: "Class"
properties: {
name: string,
meta: PropertyReflection & { parent?: Class },
authorizer: boolean | Authorizer,
type: FilterNode
}[]
}
async function createPropertyNode(prop: PropertyReflection, authPolicies: Class<AuthPolicy>[]) {
const decorators = prop.decorators.filter(createDecoratorFilter(x => x.access === "read"))
let policies = []
for (const dec of decorators) {
policies.push(...dec.policies)
}
// if no authorize decorator then always allow to access
const authorizer = policies.length === 0 ? true : new PolicyAuthorizer(authPolicies, policies)
return { name: prop.name, authorizer }
}
async function compileType(type: Class | Class[], authPolicies: Class<AuthPolicy>[], parentTypes: Class[]): Promise<FilterNode> {
if (Array.isArray(type))
return { kind: "Array", child: await compileType(type[0], authPolicies, parentTypes) }
if (isCustomClass(type)) {
// CIRCULAR: just return basic node if circular dependency happened
if (parentTypes.some(x => x === type)) return { kind: "Class", properties: [] }
const meta = reflect(type)
const properties = []
for (const prop of meta.properties) {
const meta = { ...prop, parent: type }
const propNode = await createPropertyNode(prop, authPolicies)
properties.push({
...propNode, meta,
type: await compileType(prop.type, authPolicies, parentTypes.concat(type))
})
}
return { kind: "Class", properties }
}
return { kind: "Value" }
}
async function getAuthorize(authorizers: boolean | Authorizer, ctx: AuthorizerContext) {
if (typeof authorizers === "boolean") return authorizers
return authorizers.authorize(ctx)
}
async function filterType(raw: any, node: FilterNode, ctx: AuthorizerContext): Promise<any> {
if (node.kind === "Array") {
const result = []
if (!Array.isArray(raw))
throw new Error(`Action ${ctx.ctx.route.controller.name}.${ctx.ctx.route.action.name} expecting return value of type Array but got ${raw.constructor.name}`)
for (const item of raw) {
const val = await filterType(item, node.child, ctx)
if (val !== undefined)
result.push(val)
}
return result.length === 0 ? undefined : result
}
else if (node.kind === "Class") {
const result: any = {}
for (const prop of node.properties) {
const value = raw[prop.name]
if (value === null || value === undefined) continue
const authorized = await getAuthorize(prop.authorizer, {
...ctx, value,
parentValue: raw,
metadata: { ...ctx.metadata, current: prop.meta }
})
if (authorized) {
const candidate = await filterType(value, prop.type, ctx)
const transform = ctx.ctx.config.responseTransformer ?? ((a, b) => b)
const val = transform(prop.meta, candidate)
if (val !== undefined)
result[prop.name] = val
}
}
return Object.keys(result).length === 0 && result.constructor === Object ? undefined : result
}
else return raw
}
async function responseAuthorize(raw: ActionResult, ctx: ActionContext): Promise<ActionResult> {
const getType = (resp: ResponseTypeDecorator | undefined) => {
return !!resp ? (reflection.isCallback(resp.type) ? resp.type({}) : resp.type) as (Class | Class[]) : undefined
}
const responseType = ctx.route.action.decorators.find((x: ResponseTypeDecorator): x is ResponseTypeDecorator => x.kind === "plumier-meta:response-type")
const type = getType(responseType) ?? ctx.route.action.returnType
if (type !== Promise && type && raw.status === 200 && raw.body) {
const info = createAuthContext(ctx, "read")
const node = await compileType(type, ctx.config.authPolicies, [])
raw.body = Array.isArray(raw.body) && raw.body.length === 0 ? [] : await filterType(raw.body, node, info)
return raw
}
else {
return raw;
}
}
// --------------------------------------------------------------------- //
// ----------------------------- MIDDLEWARE ---------------------------- //
// --------------------------------------------------------------------- //
async function checkAuthorize(ctx: ActionContext) {
if (ctx.config.enableAuthorization) {
const { route, parameters, config } = ctx
const info = createAuthContext(ctx, "route")
const decorator = getRouteAuthorizeDecorators(route, config.globalAuthorizations)
//check user access
await checkUserAccessToRoute(decorator, info)
//if ok check parameter access
await checkUserAccessToParameters(route.action.parameters, parameters, { ...info, access: "write" })
}
}
class AuthorizerMiddleware implements Middleware {
constructor() { }
async execute(invocation: Readonly<Invocation<ActionContext>>): Promise<ActionResult> {
Object.assign(invocation.ctx, { user: invocation.ctx.state.user })
await checkAuthorize(invocation.ctx)
const result = await invocation.proceed()
return responseAuthorize(result, invocation.ctx)
}
}
export {
AuthorizerFunction, Authorizer, checkAuthorize, AuthorizeDecorator,
getRouteAuthorizeDecorators, AuthorizerMiddleware,
CustomAuthorizer, CustomAuthorizerFunction, AuthorizationContext, AuthorizerContext,
AccessModifier, EntityPolicyProviderDecorator, EntityProviderQuery, PublicAuthPolicy, AuthenticatedAuthPolicy,
authPolicy, entityPolicy, EntityPolicyAuthorizerFunction, PolicyAuthorizer, Public, Authenticated,
AuthPolicy, CustomAuthPolicy, EntityAuthPolicy, globalPolicies,
AuthorizeReadonly, AuthorizeWriteonly, ReadonlyAuthPolicy, WriteonlyAuthPolicy,
createAuthContext, executeAuthorizer, throwAuthError
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.