text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { Observable, of } from 'rxjs';
import { RestApiConnectorService } from '../services/connectors/rest-api/rest-api-connector.service';
import { Serializable, ValidationData } from './serializable';
import { VersionNumber } from './version-number';
import { logger } from "../util/logger";
// https://github.com/center-for-threat-informed-defense/attack-workbench-frontend/blob/develop/docs/collections.md#collection-version-properties
export class CollectionVersion extends Serializable {
public version: VersionNumber;
public modified: Date;
public url: string;
public taxii_url: string;
public release_notes: string;
constructor(raw?: any) {
super();
if (raw) this.deserialize(raw);
}
/**
* Parse the object from the record returned from the back-end
* @param {*} raw the raw object
*/
public deserialize(raw: any) {
let version = raw;
if ("version" in version) {
if (typeof(version.version) === "string") this.version = new VersionNumber(version.version);
else logger.error("TypeError: version field is not a string:", version.version, "(", typeof(version.version), ")");
} else this.version = new VersionNumber("0.1");
if ("modified" in version) {
if (typeof(version.modified) === "string") this.modified = new Date(version.modified);
else logger.error("TypeError: modified field is not a string:", version.modified, "(", typeof(version.modified), ")");
} else this.modified = new Date();
if ("url" in version) {
if (typeof(version.url) === "string") this.url = version.url;
else logger.error("TypeError: url field is not a string:", version.url, "(", typeof(version.url), ")");
}
else if ("taxii_url" in version) {
if (typeof(version.taxii_url) === "string") this.taxii_url = version.taxii_url;
else logger.error("TypeError: taxii_url field is not a string:", version.taxii_url, "(", typeof(version.taxii_url), ")");
}
else throw new Error("error deserializing CollectionVersion: either 'url' or 'taxii_url' must be specified\n" + JSON.stringify(version))
if ("release_notes" in version) {
if (typeof(version.release_notes) === "string") this.release_notes = version.release_notes;
else logger.error("TypeError: release_notes field is not a string:", version.release_notes, "(", typeof(version.release_notes), ")");
}
}
/**
* Transform the current object into a raw object for sending to the back-end, stripping any unnecessary fields
* @returns {*} the raw object
*/
public serialize(): any {
return {
"version": this.version.toString(),
"modified": this.modified,
"url": this.url,
"taxii_url": this.taxii_url,
"release_notes": this.release_notes,
}
}
/**
* Validate the current object state and return information on the result of the validation
* @param {RestApiConnectorService} restAPIService: the REST API connector through which asynchronous validation can be completed
* @returns {Observable<ValidationData>} the validation warnings and errors once validation is complete.
*/
public validate(restAPIService: RestApiConnectorService): Observable<ValidationData> {
return of(new ValidationData()) //TODO
}
}
// https://github.com/center-for-threat-informed-defense/attack-workbench-frontend/blob/develop/docs/collections.md#collection-reference-properties
export class CollectionReference extends Serializable {
public id: string;
public name: string;
public description: string;
public created: Date;
public versions: CollectionVersion[];
public subscribed: boolean; //TODO how does this get determined
public lastModified: Date; //must be updated whenever the versions field is updated (get function won't work here)
constructor(raw?: any) {
super();
if (raw) this.deserialize(raw);
}
/**
* Parse the object from the record returned from the back-end
* @param {*} raw the raw object
*/
public deserialize(raw: any) {
let ref = raw;
if ("id" in ref) {
if (typeof(ref.id) === "string") this.id = ref.id;
else logger.error("TypeError: id field is not a string:", ref.id, "(", typeof(ref.id), ")");
}
if ("name" in ref) {
if (typeof(ref.name) === "string") this.name = ref.name;
else logger.error("TypeError: name field is not a string:", ref.name, "(", typeof(ref.name), ")");
}
if ("description" in ref) {
if (typeof(ref.description) === "string") this.description = ref.description;
else logger.error("TypeError: description field is not a string:", ref.description, "(", typeof(ref.description), ")");
}
if ("created" in ref) {
if (typeof(ref.created) === "string") this.created = new Date(ref.created);
else logger.error("TypeError: created field is not a string:", ref.created, "(", typeof(ref.created), ")");
} else this.created = new Date();
if ("versions" in ref) {
if (typeof(ref.versions) === "object") {
this.versions = ref.versions.map(version => new CollectionVersion(version));
this.versions.sort((a:CollectionVersion,b:CollectionVersion) => b.version.compareTo(a.version)); //sort by modified date
this.lastModified = this.versions[0].modified;
} else logger.error("TypeError: versions field is not an object:", ref.versions, "(", typeof(ref.versions), ")");
}
}
/**
* Transform the current object into a raw object for sending to the back-end, stripping any unnecessary fields
* @returns {*} the raw object
*/
public serialize(): any {
return {
"id": this.id,
"name": this.name,
"description": this.description,
"created": this.created,
"versions": this.versions.map(version => version.serialize())
}
}
/**
* Validate the current object state and return information on the result of the validation
* @param {RestApiConnectorService} restAPIService: the REST API connector through which asynchronous validation can be completed
* @returns {Observable<ValidationData>} the validation warnings and errors once validation is complete.
*/
public validate(restAPIService: RestApiConnectorService): Observable<ValidationData> {
return of(new ValidationData()) //TODO
}
}
// https://github.com/center-for-threat-informed-defense/attack-workbench-frontend/blob/develop/docs/collections.md#collection-index-properties
export class CollectionIndex extends Serializable {
public collection_index: {
id: string,
name: string,
description: string,
created: Date,
modified: Date,
collections: CollectionReference[]
};
public workspace: {
remote_url: string, //url of the index
update_policy?: {
automatic: boolean, //if true, automatically fetch updates
interval?: number, //seconds between refreshes
last_retrieval?: Date,
subscriptions?: string[] // stix IDs of collection-references
}
};
constructor(raw?: any) {
super();
if (raw) this.deserialize(raw);
}
/**
* Parse the object from the record returned from the back-end
* @param {*} raw the raw object
*/
public deserialize(raw: any) {
if (raw.collection_index) {
let collection_index: any = {};
if ("id" in raw.collection_index) {
if (typeof(raw.collection_index.id) === "string") collection_index.id = raw.collection_index.id;
else logger.error("TypeError: id field is not a string:", raw.collection_index.id, "(", typeof(raw.collection_index.id), ")");
}
if ("name" in raw.collection_index) {
if (typeof(raw.collection_index.name) === "string") collection_index.name = raw.collection_index.name;
else logger.error("TypeError: name field is not a string:", raw.collection_index.name, "(", typeof(raw.collection_index.name), ")");
}
if ("description" in raw.collection_index) {
if (typeof(raw.collection_index.description) === "string") collection_index.description = raw.collection_index.description;
else logger.error("TypeError: description field is not a string:", raw.collection_index.description, "(", typeof(raw.collection_index.description), ")");
}
if ("created" in raw.collection_index) {
if (typeof(raw.collection_index.created) === "string") collection_index.created = new Date(raw.collection_index.created);
else logger.error("TypeError: created field is not a string:", raw.collection_index.created, "(", typeof(raw.collection_index.created), ")");
} else collection_index.created = new Date();
if ("modified" in raw.collection_index) {
if (typeof(raw.collection_index.modified) === "string") collection_index.modified = new Date(raw.collection_index.modified);
else logger.error("TypeError: modified field is not a string:", raw.collection_index.modified, "(", typeof(raw.collection_index.modified), ")");
} else collection_index.modified = new Date();
if ("collections" in raw.collection_index) {
if (typeof(raw.collection_index.collections) === "object") {
collection_index.collections = raw.collection_index.collections.map(rawRef => {
let ref = new CollectionReference();
ref.deserialize(rawRef);
if (raw.workspace && "update_policy" in raw.workspace) ref.subscribed = raw.workspace.update_policy.subscriptions.includes(ref.id);
return ref;
});
} else logger.error("TypeError: collections field is not an object:", raw.collection_index.collections, "(", typeof(raw.collection_index.collections), ")");
}
this.collection_index = collection_index;
}
if (raw.workspace) {
let workspace: any = {};
if ("remote_url" in raw.workspace) {
if (typeof(raw.workspace.remote_url) === "string") workspace.remote_url = raw.workspace.remote_url;
else logger.error("TypeError: remote_url field is not a string:", raw.workspace.remote_url, "(", typeof(raw.workspace.remote_url), ")");
}
if ("update_policy" in raw.workspace) {
let update_policy = raw.workspace.update_policy;
let tmp_policy: any = {};
if ("automatic" in update_policy) {
if (typeof(update_policy.automatic) === "boolean") tmp_policy.automatic = update_policy.automatic;
else logger.error("TypeError: automatic field is not a boolean:", update_policy.automatic, "(", typeof(update_policy.automatic), ")");
}
if ("interval" in update_policy) {
if (typeof(update_policy.interval) === "number") tmp_policy.interval = update_policy.interval;
else logger.error("TypeError: interval field is not a number:", update_policy.interval, "(", typeof(update_policy.interval), ")");
}
if ("last_retrieval" in update_policy) {
if (typeof(update_policy.last_retrieval) === "string") tmp_policy.last_retrieval = new Date(update_policy.last_retrieval);
else logger.error("TypeError: last_retrieval field is not a string:", update_policy.last_retrieval, "(", typeof(update_policy.last_retrieval), ")");
}
if ("subscriptions" in update_policy) {
if (typeof(update_policy.subscriptions) === "object") tmp_policy.subscriptions = update_policy.subscriptions;
else logger.error("TypeError: subscriptions field is not an object:", update_policy.subscriptions, "(", typeof(update_policy.subscriptions), ")");
}
workspace.update_policy = tmp_policy;
}
this.workspace = workspace;
}
}
/**
* Transform the current object into a raw object for sending to the back-end, stripping any unnecessary fields
* @returns {*} the raw object
*/
public serialize(): any {
let representation = {
"collection_index": this.collection_index,
"workspace": this.workspace
}
representation.collection_index.collections = representation.collection_index.collections.map(ref => ref.serialize())
return representation;
}
/**
* Validate the current object state and return information on the result of the validation
* @param {RestApiConnectorService} restAPIService: the REST API connector through which asynchronous validation can be completed
* @returns {Observable<ValidationData>} the validation warnings and errors once validation is complete.
*/
public validate(restAPIService: RestApiConnectorService): Observable<ValidationData> {
return of(new ValidationData()) //TODO
}
/**
* Check the current object is a valid collection index
*/
public valid(): boolean {
return ( this.collection_index.id && this.collection_index.name && this.collection_index.name.length > 0 &&
this.collection_index.created && this.collection_index.modified && this.collection_index.collections !== undefined );
}
} | the_stack |
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { fakeAsync, TestBed, tick } from '@angular/core/testing';
import { AccountService } from 'app/core/auth/account.service';
import { JhiWebsocketService } from 'app/core/websocket/websocket.service';
import { UserSettingsService } from 'app/shared/user-settings/user-settings.service';
import { UserSettingsCategory } from 'app/shared/constants/user-settings.constants';
import { MockWebsocketService } from '../../../helpers/mocks/service/mock-websocket.service';
import { MockAccountService } from '../../../helpers/mocks/service/mock-account.service';
import { TranslateTestingModule } from '../../../helpers/mocks/service/mock-translate.service';
import { Setting, UserSettingsStructure } from 'app/shared/user-settings/user-settings.model';
import { notificationSettingsStructure, NotificationSetting } from 'app/shared/user-settings/notification-settings/notification-settings-structure';
import { notificationSettingsForTesting } from './notification-settings.service.spec';
describe('User Settings Service', () => {
// general & common
let userSettingsService: UserSettingsService;
let httpMock: HttpTestingController;
let userSettingsCategory: UserSettingsCategory;
let resultingUserSettings: UserSettingsStructure<Setting>;
// notification settings specific
const notificationSettingsResourceUrl = SERVER_API_URL + 'api/notification-settings';
/**
* Updates the NotificationSettings of the provided NotificationSettings by using provided Settings
* @param settingsStructure to be updated
* @param providedSettings are used to find matching settings and update them
*/
function updateNotificationSettingsStructureByProvidedNotificationSettings(
settingsStructure: UserSettingsStructure<NotificationSetting>,
providedSettings: NotificationSetting[],
) {
providedSettings.forEach((providedSetting) => {
for (const group of settingsStructure.groups) {
for (const setting of group.settings) {
if (setting.settingId === providedSetting.settingId) {
setting.webapp = providedSetting.webapp;
setting.email = providedSetting.email;
break;
}
}
}
});
}
/**
* Updates the original NotificationSettings by using provided Settings
* @param originalSettings which should be updated
* @param providedSettings which are used to update the settings
*/
function updateNotificationSettings(originalSettings: NotificationSetting[], providedSettings: NotificationSetting[]) {
providedSettings.forEach((providedSetting) => {
for (const originalSetting of originalSettings) {
if (originalSetting.settingId === providedSetting.settingId) {
originalSetting.webapp = providedSetting.webapp;
originalSetting.email = providedSetting.email;
break;
}
}
});
}
/**
* Checks if the provided (newly updated) settings are a subset of the expected settings
* @param providedNotificationSettings which should be part of the expected ones
* @param expectedNotificationSettings the array of settings which should contain the provided settings
*/
function checkIfProvidedNotificationSettingsArePartOfExpectedSettings(
providedNotificationSettings: NotificationSetting[],
expectedNotificationSettings: NotificationSetting[],
) {
providedNotificationSettings.forEach((providedSetting) => {
for (const expectedNotificationSetting of expectedNotificationSettings) {
if (providedSetting.settingId === expectedNotificationSetting.settingId) {
expect(providedSetting.webapp).toEqual(expectedNotificationSetting.webapp);
expect(providedSetting.email).toEqual(expectedNotificationSetting.email);
break;
}
}
});
}
/**
* extracts individual settings from provided settingsStructure
* @param settingsStructure where the settings should be extracted from
* @return extracted settingsStructure
*/
function extractSettingsFromSettingsStructure(settingsStructure: UserSettingsStructure<Setting>): Setting[] {
const extractedSettings: Setting[] = [];
settingsStructure.groups.forEach((group) => {
group.settings.forEach((setting) => {
extractedSettings.push(setting);
});
});
return extractedSettings;
}
/**
* Compares settings structures correctly by first checking for the same "signature/structure"
* afterwards extracting the individual settings and comparing them
* @param expectedSettingsStructure
* @param resultingSettingsStructure
*/
function compareSettingsStructure(expectedSettingsStructure: UserSettingsStructure<Setting>, resultingSettingsStructure: UserSettingsStructure<Setting>) {
// this step alone is not enough due to the polymorphic nature of the settings
expect(expectedSettingsStructure).toEqual(resultingSettingsStructure);
const expectedIndividualSettings = extractSettingsFromSettingsStructure(expectedSettingsStructure);
const resultingIndividualSettings = extractSettingsFromSettingsStructure(resultingSettingsStructure);
expect(expectedIndividualSettings).toEqual(resultingIndividualSettings);
}
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule, TranslateTestingModule],
providers: [
{ provide: JhiWebsocketService, useClass: MockWebsocketService },
{ provide: AccountService, useClass: MockAccountService },
],
})
.compileComponents()
.then(() => {
userSettingsService = TestBed.inject(UserSettingsService);
httpMock = TestBed.inject(HttpTestingController);
});
});
afterEach(() => {
httpMock.verify();
});
describe('Service methods with Category Notification Settings', () => {
userSettingsCategory = UserSettingsCategory.NOTIFICATION_SETTINGS;
describe('test loading methods', () => {
it('should call correct URL to fetch all settings', () => {
userSettingsService.loadSettings(userSettingsCategory).subscribe();
const req = httpMock.expectOne({ method: 'GET' });
expect(req.request.url).toEqual(notificationSettingsResourceUrl);
});
it('should load correct default settings as foundation', () => {
// to make sure the default settings are not modified
resultingUserSettings = userSettingsService.loadSettingsSuccessAsSettingsStructure([], userSettingsCategory);
compareSettingsStructure(notificationSettingsStructure, resultingUserSettings);
});
it('should correctly update and return settings based on received settings', () => {
const expectedUserSettings: UserSettingsStructure<NotificationSetting> = notificationSettingsStructure;
updateNotificationSettingsStructureByProvidedNotificationSettings(expectedUserSettings, notificationSettingsForTesting);
resultingUserSettings = userSettingsService.loadSettingsSuccessAsSettingsStructure(notificationSettingsForTesting, userSettingsCategory);
compareSettingsStructure(expectedUserSettings, resultingUserSettings);
});
it('should correctly update and return settings based on received settings', () => {
const expectedNotificationSettings: NotificationSetting[] = userSettingsService.extractIndividualSettingsFromSettingsStructure(
notificationSettingsStructure,
) as NotificationSetting[];
updateNotificationSettings(expectedNotificationSettings, notificationSettingsForTesting);
let resultingSettings: NotificationSetting[];
resultingSettings = userSettingsService.loadSettingsSuccessAsIndividualSettings(notificationSettingsForTesting, userSettingsCategory) as NotificationSetting[];
expect(resultingSettings.length).toEqual(expectedNotificationSettings.length);
checkIfProvidedNotificationSettingsArePartOfExpectedSettings(resultingSettings, expectedNotificationSettings);
});
});
describe('test saving methods', () => {
it('should call correct URL to save settings', () => {
userSettingsService.saveSettings(notificationSettingsForTesting, userSettingsCategory).subscribe();
const req = httpMock.expectOne({ method: 'PUT' });
expect(req.request.url).toEqual(notificationSettingsResourceUrl);
});
it('should correctly update and return settings based on received settings', () => {
const expectedUserSettings: UserSettingsStructure<NotificationSetting> = notificationSettingsStructure;
updateNotificationSettingsStructureByProvidedNotificationSettings(expectedUserSettings, notificationSettingsForTesting);
resultingUserSettings = userSettingsService.saveSettingsSuccess(expectedUserSettings, notificationSettingsForTesting);
compareSettingsStructure(expectedUserSettings, resultingUserSettings);
});
it('server response should contain inputted settings', fakeAsync(() => {
userSettingsService.saveSettings(notificationSettingsForTesting, userSettingsCategory).subscribe((resp) => {
checkIfProvidedNotificationSettingsArePartOfExpectedSettings(resp.body as NotificationSetting[], notificationSettingsForTesting);
});
const req = httpMock.expectOne({ method: 'PUT' });
req.flush(notificationSettingsForTesting);
tick();
}));
});
});
}); | the_stack |
import {Trs80File} from "trs80-base";
import {PageTab} from "./PageTab";
import {
defer,
formatDate,
makeIcon,
makeIconButton,
makeTagCapsule,
makeTextButton,
TagCapsuleOptions,
TRASH_TAG
} from "./Utils";
import {LibraryModifyEvent, LibraryRemoveEvent} from "./Library";
import {clearElement, withCommas} from "teamten-ts-utils";
import {CanvasScreen} from "trs80-emulator-web";
import isEmpty from "lodash/isEmpty";
import {File} from "./File";
import {IFilePanel} from "./IFilePanel";
import type firebase from "firebase";
import {TagSet} from "./TagSet";
type UpdateData = firebase.firestore.UpdateData;
const SCREENSHOT_ATTR = `data-screenshot`;
/**
* Handles the file info tab in the file panel.
*/
export class FileInfoTab extends PageTab {
private readonly filePanel: IFilePanel;
private readonly trs80File: Trs80File;
private readonly editable: boolean;
private readonly nameInput: HTMLInputElement;
private readonly filenameInput: HTMLInputElement;
private readonly noteInput: HTMLTextAreaElement;
private readonly authorInput: HTMLInputElement;
private readonly releaseYearInput: HTMLInputElement;
private readonly typeInput: HTMLInputElement;
private readonly sizeInput: HTMLInputElement;
private readonly addedAtInput: HTMLInputElement;
private readonly modifiedAtInput: HTMLInputElement;
private readonly tags = new TagSet();
private readonly allTags = new TagSet();
private readonly tagsInput: HTMLElement;
private readonly sharedInput: HTMLInputElement;
private readonly screenshotsDiv: HTMLElement;
private readonly deleteButton: HTMLButtonElement;
private readonly undeleteButton: HTMLButtonElement;
private readonly revertButton: HTMLButtonElement;
private readonly saveButton: HTMLButtonElement;
private readonly cancelLibrarySubscription: () => void;
constructor(filePanel: IFilePanel, trs80File: Trs80File) {
super("File Info");
this.filePanel = filePanel;
this.trs80File = trs80File;
this.editable = filePanel.context.user?.uid === filePanel.file.uid;
// Make union of all tags in all files. Do this here once so that if the user deletes a tag
// that only this file has, it'll stay in this set so it can be added again easily.
for (const file of this.filePanel.context.library.getAllFiles()) {
this.allTags.add(... file.tags);
}
// We have buttons for adding/removing the trash tag.
this.allTags.remove(TRASH_TAG);
// Make our own copy of tags that will reflect what's in the UI.
this.tags.add(...filePanel.file.tags);
this.element.classList.add("file-info-tab", this.editable ? "file-info-tab-editable" : "file-info-tab-readonly");
// Container of form.
const formContainer = document.createElement("div");
formContainer.classList.add("file-panel-form-container");
this.element.append(formContainer);
// Form for editing file info.
const form = document.createElement("div");
form.classList.add("file-panel-form");
formContainer.append(form);
const makeInputBox = (label: string, cssClass: string | undefined, enabled: boolean): HTMLInputElement => {
const labelElement = document.createElement("label");
if (cssClass !== undefined) {
labelElement.classList.add(cssClass);
}
labelElement.innerText = label;
form.append(labelElement);
const inputElement = document.createElement("input");
inputElement.disabled = !enabled || !this.editable;
labelElement.append(inputElement);
return inputElement;
};
this.nameInput = makeInputBox("Name", "name", true);
this.filenameInput = makeInputBox("Filename", "filename", true);
const noteLabel = document.createElement("label");
noteLabel.classList.add("note");
noteLabel.innerText = "Note";
form.append(noteLabel);
this.noteInput = document.createElement("textarea");
this.noteInput.rows = 10;
this.noteInput.disabled = !this.editable;
noteLabel.append(this.noteInput);
this.authorInput = makeInputBox("Author", undefined, true);
this.releaseYearInput = makeInputBox("Release year", undefined, true);
this.typeInput = makeInputBox("Type", undefined, false);
this.addedAtInput = makeInputBox("Added", undefined, false);
this.sizeInput = makeInputBox("Size", undefined, false);
this.modifiedAtInput = makeInputBox("Last modified", undefined, false);
{
// Tags editor.
const labelElement = document.createElement("label");
labelElement.innerText = "Tags";
form.append(labelElement);
this.tagsInput = document.createElement("div");
this.tagsInput.classList.add("tags-editor");
labelElement.append(this.tagsInput);
}
{
// Shared editor.
const labelElement = document.createElement("label");
labelElement.classList.add("shared");
labelElement.innerText = "Shared";
form.append(labelElement);
this.sharedInput = document.createElement("input");
this.sharedInput.type = "checkbox";
this.sharedInput.disabled = !this.editable;
const offIcon = makeIcon("toggle_off");
offIcon.classList.add("off-state");
const onIcon = makeIcon("toggle_on");
onIcon.classList.add("on-state");
labelElement.append(this.sharedInput, offIcon, onIcon);
}
this.screenshotsDiv = document.createElement("div");
this.screenshotsDiv.classList.add("screenshots");
form.append(this.screenshotsDiv);
const actionBar = document.createElement("div");
actionBar.classList.add("action-bar");
this.element.append(actionBar);
const exportButton = makeTextButton("Export", "get_app", "export-button", () => {
// Download binary.
const a = document.createElement("a");
const contents = this.filePanel.file.binary;
const blob = new Blob([contents], {type: "application/octet-stream"});
a.href = window.URL.createObjectURL(blob);
a.download = this.filePanel.file.filename;
a.click();
});
actionBar.append(exportButton);
if (this.trs80File.className === "Cassette") {
const cassette = this.trs80File;
const mountButton = makeTextButton("Mount", "input", "mount-button", () => {
this.filePanel.context.mountCassette(this.filePanel.file, cassette);
this.filePanel.context.panelManager.close();
});
actionBar.append(mountButton);
}
const runButton = makeTextButton("Run", "play_arrow", "play-button", () => {
this.filePanel.context.runProgram(this.filePanel.file, this.trs80File);
this.filePanel.context.panelManager.close();
});
actionBar.append(runButton);
this.deleteButton = makeTextButton("Delete File", "delete", "delete-button", () => {
const oldFile = this.filePanel.file;
const tags = new TagSet();
tags.add(...oldFile.tags, TRASH_TAG);
const newFile = oldFile.builder()
.withTags(tags.asArray())
.withModifiedAt(new Date())
.build();
this.filePanel.context.db.updateFile(oldFile, newFile)
.then(() => {
this.filePanel.context.library.modifyFile(newFile);
this.filePanel.context.panelManager.popPanel();
})
.catch(error => {
// TODO.
console.error(error);
});
});
this.undeleteButton = makeTextButton("Undelete File", "restore_from_trash", "delete-button", () => {
const oldFile = this.filePanel.file;
const tags = new TagSet();
tags.add(...oldFile.tags);
tags.remove(TRASH_TAG);
const newFile = oldFile.builder()
.withTags(tags.asArray())
.withModifiedAt(new Date())
.build();
this.filePanel.context.db.updateFile(oldFile, newFile)
.then(() => {
this.filePanel.context.library.modifyFile(newFile);
})
.catch(error => {
// TODO.
console.error(error);
});
});
this.revertButton = makeTextButton("Revert", "undo", "revert-button", undefined);
this.saveButton = makeTextButton("Save",
["save", "cached", "check"], "save-button", undefined);
this.saveButton.title = "Ctrl-Enter to save and close";
if (this.editable) {
actionBar.append(this.deleteButton, this.undeleteButton, this.revertButton, this.saveButton);
}
for (const input of [this.nameInput, this.filenameInput, this.noteInput, this.authorInput, this.releaseYearInput]) {
input.addEventListener("input", () => this.updateButtonStatus());
}
this.sharedInput.addEventListener("change", () => this.updateButtonStatus());
this.nameInput.addEventListener("input", () => this.filePanel.setHeaderText(this.fileFromUi().name));
this.revertButton.addEventListener("click", () => this.updateUi());
this.saveButton.addEventListener("click", () => this.save());
this.cancelLibrarySubscription = this.filePanel.context.library.onEvent.subscribe(event => {
if (event instanceof LibraryModifyEvent && event.newFile.id === this.filePanel.file.id) {
// Make sure we don't clobber any user-entered data in the input fields.
const updateData = this.filePanel.file.getUpdateDataComparedTo(event.newFile);
this.filePanel.file = event.newFile;
this.updateUi(updateData);
}
if (event instanceof LibraryRemoveEvent && event.oldFile.id === this.filePanel.file.id) {
// We've been deleted.
this.filePanel.context.panelManager.popPanel();
}
});
this.updateUi();
}
onKeyDown(e: KeyboardEvent): boolean {
// Ctrl-Enter to save and close the panel.
if (e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey && e.key === "Enter") {
this.saveAndClose();
return true;
}
return super.onKeyDown(e);
}
onDestroy(): void {
this.cancelLibrarySubscription();
super.onDestroy();
}
/**
* Save if necessary, then close the panel.
*/
private saveAndClose(): void {
const isSame = isEmpty(this.fileFromUi().getUpdateDataComparedTo(this.filePanel.file));
if (isSame) {
this.filePanel.context.panelManager.popPanel();
} else {
this.save(() => {
this.filePanel.context.panelManager.popPanel();
});
}
}
/**
* Save the current changes to the file, then optionally call the callback.
*/
private save(callback?: () => void): void {
const newFile = this.fileFromUi().builder().withModifiedAt(new Date()).build();
this.saveButton.classList.add("saving");
// Disable right away so it's not clicked again.
this.saveButton.disabled = true;
this.filePanel.context.db.updateFile(this.filePanel.file, newFile)
.then(() => {
this.saveButton.classList.remove("saving");
this.saveButton.classList.add("success");
setTimeout(() => {
this.saveButton.classList.remove("success");
}, 2000);
this.filePanel.file = newFile;
this.filePanel.context.library.modifyFile(newFile);
this.updateUi();
if (callback) {
callback();
}
})
.catch(error => {
this.saveButton.classList.remove("saving");
// TODO show error.
// The document probably doesn't exist.
console.error("Error updating document: ", error);
this.updateUi();
});
}
/**
* Update UI after a change to file.
*
* @param updateData if specified, only fields defined in the object will be updated. (The _values_ of
* those fields are ignored -- only their presence is important because that indicates that the data
* is fresh in the file object.) The purpose is to avoid clobbering user-entered data in the various
* input fields when the file object changes elsewhere in unrelated ways, such as new screenshots.
*/
private updateUi(updateData?: UpdateData): void {
const file = this.filePanel.file;
if (updateData === undefined || updateData.hasOwnProperty("name")) {
this.nameInput.value = file.name;
}
if (updateData === undefined || updateData.hasOwnProperty("filename")) {
this.filenameInput.value = file.filename;
}
if (updateData === undefined || updateData.hasOwnProperty("note")) {
this.noteInput.value = file.note;
}
if (updateData === undefined || updateData.hasOwnProperty("author")) {
this.authorInput.value = file.author;
}
if (updateData === undefined || updateData.hasOwnProperty("releaseYear")) {
this.releaseYearInput.value = file.releaseYear;
}
this.typeInput.value = this.trs80File.getDescription();
this.sizeInput.value = withCommas(file.binary.length) + " byte" + (file.binary.length === 1 ? "" : "s");
this.addedAtInput.value = formatDate(file.addedAt);
this.modifiedAtInput.value = formatDate(file.modifiedAt);
if (updateData === undefined || updateData.hasOwnProperty("tags")) {
this.tags.clear();
this.tags.add(...file.tags);
this.updateTagsInput();
}
this.sharedInput.checked = file.shared;
if (updateData === undefined || updateData.hasOwnProperty("screenshots")) {
this.populateScreenshots();
}
this.updateButtonStatus();
}
/**
* Update the UI for showing and editing the tags on this file.
*
* @param newTagFocus whether to put the input focus on the new tag input field.
*/
private updateTagsInput(newTagFocus?: boolean): void {
clearElement(this.tagsInput);
const tagListElement = document.createElement("div");
tagListElement.classList.add("tag-list");
this.tagsInput.append(tagListElement);
let count = 0;
for (const tag of this.allTags.asArray()) {
if (this.tags.has(tag) || this.editable) {
const tagOptions: TagCapsuleOptions = {
tag: tag,
};
// Add clear/add actions if editable.
if (this.editable) {
if (this.tags.has(tag)) {
tagOptions.iconName = "clear";
tagOptions.clickCallback = () => {
this.tags.remove(tag);
this.updateTagsInput();
this.updateButtonStatus();
};
} else {
tagOptions.faint = true;
tagOptions.iconName = "add";
tagOptions.clickCallback = () => {
this.tags.add(tag);
this.updateTagsInput();
this.updateButtonStatus();
};
}
}
tagListElement.append(makeTagCapsule(tagOptions));
count += 1;
}
}
// Form to add a new tag.
if (this.editable) {
const newTagForm = document.createElement("form");
newTagForm.classList.add("new-tag-form");
newTagForm.addEventListener("submit", event => {
const newTag = newTagInput.value.trim();
if (newTag !== "" && newTag !== TRASH_TAG) {
this.tags.add(newTag);
this.allTags.add(newTag);
this.updateTagsInput(true);
this.updateButtonStatus();
}
event.preventDefault();
event.stopPropagation();
});
tagListElement.append(newTagForm);
const newTagInput = document.createElement("input");
newTagInput.placeholder = "New tag";
if (newTagFocus) {
setTimeout(() => newTagInput.focus(), 0);
}
newTagForm.append(newTagInput);
} else if (count === 0) {
const instructions = document.createElement("div");
instructions.classList.add("tags-instructions");
instructions.innerText = "There are to tags for this file.";
tagListElement.append(instructions);
}
}
/**
* Fill the screenshots UI with those from the file.
*/
private populateScreenshots(): void {
clearElement(this.screenshotsDiv);
const labelElement = document.createElement("label");
labelElement.innerText = "Screenshots";
this.screenshotsDiv.append(labelElement);
if (this.filePanel.file.screenshots.length === 0) {
const instructions = document.createElement("div");
instructions.classList.add("screenshots-instructions");
if (this.editable) {
instructions.innerText = "To take a screenshot, run the program and click the camera icon.";
} else {
instructions.innerText = "There are no screenshots for this file.";
}
this.screenshotsDiv.append(instructions);
}
for (const screenshot of this.filePanel.file.screenshots) {
const screenshotDiv = document.createElement("div");
screenshotDiv.setAttribute(SCREENSHOT_ATTR, screenshot);
screenshotDiv.classList.add("screenshot");
if (this.editable) {
const deleteButton = makeIconButton(makeIcon("delete"), "Delete screenshot", () => {
screenshotDiv.remove();
this.updateButtonStatus();
});
screenshotDiv.append(deleteButton);
}
this.screenshotsDiv.append(screenshotDiv);
// Defer this so that if we have a lot of screenshots it doesn't hang the browser when
// creating this panel.
defer(() => {
const screen = new CanvasScreen();
screen.displayScreenshot(screenshot);
screen.asImageAsync().then(image => screenshotDiv.append(image));
});
}
}
/**
* Update the save/restore buttons' enabled status based on input fields.
*/
private updateButtonStatus(): void {
const file = this.filePanel.file;
const newFile = this.fileFromUi();
const isSame = isEmpty(newFile.getUpdateDataComparedTo(file));
const isValid = newFile.name.length > 0 &&
newFile.filename.length > 0;
this.revertButton.disabled = isSame;
this.saveButton.disabled = isSame || !isValid;
this.deleteButton.classList.toggle("hidden", file.isDeleted);
this.undeleteButton.classList.toggle("hidden", !file.isDeleted);
}
/**
* Make a new File object based on the user's inputs.
*/
private fileFromUi(): File {
// Collect screenshots from UI.
const screenshots: string[] = [];
for (const screenshotDiv of this.screenshotsDiv.children) {
// Skip label and instructions.
let screenshot = screenshotDiv.getAttribute(SCREENSHOT_ATTR);
if (screenshot !== null) {
screenshots.push(screenshot);
}
}
return this.filePanel.file.builder()
.withName(this.nameInput.value.trim())
.withFilename(this.filenameInput.value.trim())
.withNote(this.noteInput.value.trim())
.withAuthor(this.authorInput.value.trim())
.withReleaseYear(this.releaseYearInput.value.trim())
.withShared(this.sharedInput.checked)
.withTags(this.tags.asArray())
.withScreenshots(screenshots)
.build();
}
} | the_stack |
import { TORUS_BUILD_ENV_TYPE, VerifierArgs } from '@toruslabs/torus-embed';
import React from 'react';
import { encrypt, recoverTypedMessage } from 'eth-sig-util';
import { ethers } from 'ethers';
import { keccak256 } from 'ethers/lib/utils';
import { getV3TypedData, getV4TypedData, whiteLabelData } from './data';
import web3Obj from './helper';
const tokenAbi = require('human-standard-token-abi');
class App extends React.Component {
state = {
publicAddress: '',
chainId: 4,
verifierId: '',
selectedVerifier: 'google',
placeholder: 'Enter google email',
chainIdNetworkMap: {
1: 'mainnet',
3: 'ropsten',
4: 'rinkeby',
5: 'goerli',
42: 'kovan',
97: 'bsc_testnet',
56: 'bsc_mainnet',
} as Record<string, string>,
messageToEncrypt: '',
encryptionKey: '',
messageEncrypted: '',
buildEnv: 'testing' as TORUS_BUILD_ENV_TYPE,
}
async componentDidMount(): Promise<void> {
const torusEnv = sessionStorage.getItem('pageUsingTorus');
if (torusEnv) {
await this.login();
}
}
login = async (): Promise<void> => {
try {
const { torus, web3 } = web3Obj;
const { buildEnv, chainIdNetworkMap, chainId } = this.state;
await torus.init({
buildEnv,
enabledVerifiers: {
reddit: false,
},
enableLogging: true,
network: {
host: chainIdNetworkMap[chainId.toString()], // mandatory
chainId,
// chainId: 336,
// networkName: 'DES Network',
// host: 'https://quorum.block360.io/https',
// ticker: 'DES',
// tickerName: 'DES Coin',
},
showTorusButton: true,
integrity: {
version: '1.11.0',
check: false,
// hash: 'sha384-jwXOV6VJu+PM89ksbCSZyQRjf5FdX8n39nWfE/iQBMh4r5m027ua2tkQ+83FPdp9'
},
loginConfig: buildEnv === 'lrc' ? {
'torus-auth0-email-passwordless': {
name: 'torus-auth0-email-passwordless',
typeOfLogin: 'passwordless',
showOnModal: false,
},
} : undefined,
whiteLabel: whiteLabelData,
skipTKey: true,
});
const acc = await torus.login(); // await torus.ethereum.enable()
console.log('acc', acc);
sessionStorage.setItem('pageUsingTorus', buildEnv);
web3Obj.setweb3(torus.provider);
torus.provider.on('chainChanged', (resp) => {
console.log(resp, 'chainchanged');
this.setState({
chainId: resp,
});
});
torus.provider.on('accountsChanged', (accounts) => {
console.log(accounts, 'accountsChanged');
this.setState({
publicAddress: (Array.isArray(accounts) && accounts[0]) || '',
});
});
const accounts = await web3.eth.getAccounts();
console.log('accounts[0]', accounts[0]);
// const ac = [...accounts][0];
this.setState({
publicAddress: (Array.isArray(accounts) && accounts[0]) || '',
});
web3.eth.getBalance(accounts[0]).then(console.log).catch(console.error);
} catch (error) {
console.error(error, 'caught in vue-app');
}
}
toggleTorusWidget = (): void => {
const { torus } = web3Obj;
if (torus.torusWidgetVisibility) {
torus.hideTorusButton();
} else {
torus.showTorusButton();
}
}
onSelectedVerifierChanged = (e: React.ChangeEvent<HTMLSelectElement>): void => {
const verifier = e.target.value;
let placeholder = 'Enter google email';
switch (verifier) {
case 'google':
placeholder = 'Enter google email';
break;
case 'reddit':
placeholder = 'Enter reddit username';
break;
case 'discord':
placeholder = 'Enter discord ID';
break;
default:
placeholder = 'Enter google email';
break;
}
this.setState({
selectedVerifier: verifier,
placeholder,
});
}
changeProvider = async () => {
await web3Obj.torus.setProvider({ host: 'mainnet' });
this.console('finished changing provider');
}
createPaymentTx = async (): Promise<void> => {
try {
const { torus } = web3Obj;
const res = await torus.initiateTopup('mercuryo', {
selectedCurrency: 'USD',
});
console.log(res);
} catch (error) {
console.error(error);
}
}
sendEth = (): void => {
const { web3 } = web3Obj;
const { publicAddress } = this.state;
web3.eth
.sendTransaction({ from: publicAddress, to: publicAddress, value: web3.utils.toWei('0.01') })
.then((resp) => this.console(resp))
.catch(console.error);
}
signMessageWithoutPopup = (): void => {
const { web3 } = web3Obj;
const { publicAddress } = this.state;
// hex message
const message = 'Hello world';
const customPrefix = `\u0019${window.location.hostname} Signed Message:\n`;
const prefixWithLength = Buffer.from(`${customPrefix}${message.length.toString()}`, 'utf-8');
const hashedMsg = keccak256(Buffer.concat([prefixWithLength, Buffer.from(message)]));
(web3.currentProvider as any)?.send(
{
method: 'eth_sign',
params: [publicAddress, hashedMsg, { customPrefix, customMessage: message }],
jsonrpc: '2.0',
},
(err: Error, result: any) => {
if (err) {
return console.error(err);
}
const signerAddress = ethers.utils.recoverAddress(hashedMsg, result.result);
return this.console(
'sign message => true',
`message: ${prefixWithLength + message}`,
`msgHash: ${hashedMsg}`,
`sig: ${result.result}`,
`signer: ${signerAddress}`,
);
},
);
}
signMessage = (): void => {
const { web3 } = web3Obj;
const { publicAddress } = this.state;
// hex message
const message = '0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad';
(web3.currentProvider as any)?.send(
{
method: 'eth_sign',
params: [publicAddress, message],
jsonrpc: '2.0',
},
(err: Error, result: any) => {
if (err) {
return console.error(err);
}
return this.console('sign message => true', result);
},
);
}
signTypedDataV1 = (): void => {
const { publicAddress } = this.state;
const typedData = [
{
type: 'string',
name: 'message',
value: 'Hi, Alice!',
},
{
type: 'uint8',
name: 'value',
value: 10,
},
];
const currentProvider = web3Obj.web3.currentProvider as any;
currentProvider.send(
{
method: 'eth_signTypedData',
params: [typedData, publicAddress],
jsonrpc: '2.0',
},
(err: Error, result: any) => {
if (err) {
return console.error(err);
}
const recovered = recoverTypedMessage(
{
data: typedData,
sig: result.result,
},
'V1',
);
if (publicAddress && recovered.toLowerCase() === publicAddress?.toLowerCase()) {
return this.console(`sign typed message v1 => true, Singature: ${result.result} Recovered signer: ${publicAddress}`, result);
}
return this.console(`Failed to verify signer, got: ${recovered}`);
},
);
}
signTypedDataV3 = (): void => {
const { chainId, publicAddress } = this.state;
const typedData = getV3TypedData(chainId);
const currentProvider = web3Obj.web3.currentProvider as any;
currentProvider.send(
{
method: 'eth_signTypedData_v3',
params: [publicAddress, JSON.stringify(typedData)],
jsonrpc: '2.0',
},
(err: Error, result: any) => {
if (err) {
return console.error(err);
}
const recovered = recoverTypedMessage(
{
data: typedData as any,
sig: result.result,
},
'V3',
);
if (recovered.toLowerCase() === publicAddress?.toLowerCase()) {
return this.console(`sign typed message v3 => true, Singature: ${result.result} Recovered signer: ${publicAddress}`, result);
}
return this.console(`Failed to verify signer, got: ${recovered}`);
},
);
}
signTypedDataV4 = (): void => {
const { chainId, publicAddress } = this.state;
const { web3 } = web3Obj;
const typedData = getV4TypedData(chainId);
(web3.currentProvider as any)?.send(
{
method: 'eth_signTypedData_v4',
params: [publicAddress, JSON.stringify(typedData)],
jsonrpc: '2.0',
},
(err: Error, result: any) => {
if (err) {
return console.error(err);
}
const recovered = recoverTypedMessage(
{
data: typedData as any,
sig: result.result,
},
'V4',
);
if (recovered.toLowerCase() === publicAddress.toLowerCase()) {
return this.console('sign typed message v4 => true', result.result, `Recovered signer: ${publicAddress}`, result);
}
return this.console(`Failed to verify signer, got: ${recovered}`);
},
);
}
console = (...args: any[]): void => {
const el = document.querySelector('#console>p');
if (el) {
el.innerHTML = JSON.stringify(args || {}, null, 2);
}
}
sendDai = async (): Promise<void> => {
try {
const { chainId, publicAddress } = this.state;
const { torus, web3 } = web3Obj;
if (chainId !== 1) {
await torus.setProvider({ host: 'mainnet' });
}
const instance = new web3.eth.Contract(tokenAbi, '0x6b175474e89094c44da98b954eedeac495271d0f');
const balance = await instance.methods.balanceOf(publicAddress).call();
console.log(balance, 'dai balance');
const value = Math.floor(parseFloat('0.01') * 10 ** parseFloat('18')).toString();
if (Number(balance) < Number(value)) {
// eslint-disable-next-line no-alert
window.alert('You do not have enough dai tokens for transfer');
return;
}
instance.methods.transfer(publicAddress, value).send(
{
from: publicAddress,
},
(err: Error, hash: string) => {
if (err) this.console(err);
else this.console(hash);
},
);
} catch (error) {
console.error(error);
}
}
approveKnc = async (): Promise<void> => {
try {
const { chainId, publicAddress } = this.state;
const { torus, web3 } = web3Obj;
console.log(chainId, 'current chain id');
if (chainId !== 1) {
await torus.setProvider({ host: 'mainnet' });
}
const instance = new web3.eth.Contract(tokenAbi, '0xdd974D5C2e2928deA5F71b9825b8b646686BD200');
let value = Math.floor(parseFloat('0.01') * 10 ** parseFloat('18')).toString();
const allowance = await instance.methods.allowance(publicAddress, '0x3E2a1F4f6b6b5d281Ee9a9B36Bb33F7FBf0614C3').call();
console.log(allowance, 'current allowance');
if (Number(allowance) > 0) value = '0';
instance.methods.approve('0x3E2a1F4f6b6b5d281Ee9a9B36Bb33F7FBf0614C3', value).send(
{
from: publicAddress,
},
(err: Error, hash: string) => {
if (err) this.console(err);
else this.console(hash);
},
);
} catch (error) {
console.error(error);
}
}
signPersonalMsg = async () : Promise<void> => {
try {
const { web3 } = web3Obj;
const { publicAddress } = this.state;
const message = 'Some string';
const hash = web3.utils.sha3(message) as string;
const sig = await web3.eth.personal.sign(hash, publicAddress, '');
const hostnamealAddress = await web3.eth.personal.ecRecover(hash, sig);
if (publicAddress.toLowerCase() === hostnamealAddress.toLowerCase()) this.console('Success');
else this.console('Failed');
} catch (error) {
console.error(error);
this.console('failed');
}
}
getUserInfo = (): void => {
const { torus } = web3Obj;
torus.getUserInfo('').then(this.console).catch(this.console);
}
getPublicAddress = (): void => {
const { torus } = web3Obj;
const { selectedVerifier, verifierId } = this.state;
console.log(selectedVerifier, verifierId);
torus.getPublicAddress({ verifier: selectedVerifier, verifierId } as VerifierArgs).then(this.console).catch(console.error);
}
getEncryptionKey = (): void => {
const { web3 } = web3Obj;
const { publicAddress } = this.state;
(web3.currentProvider as any)?.send(
{
method: 'eth_getEncryptionPublicKey',
params: [publicAddress],
jsonrpc: '2.0',
},
(err: Error, result: any) => {
if (err) {
return console.error(err);
}
this.setState({
encryptionKey: result.result,
});
return this.console(`encryption public key => ${result.result}`);
},
);
}
encryptMessage = (): void => {
try {
const { encryptionKey, messageToEncrypt } = this.state;
const messageEncrypted = encrypt(encryptionKey, { data: messageToEncrypt }, 'x25519-xsalsa20-poly1305');
const encryptedMessage = this.stringifiableToHex(messageEncrypted);
this.setState({
messageEncrypted: encryptedMessage,
});
this.console(`encrypted message => ${encryptedMessage}`);
} catch (error) {
console.error(error);
}
}
decryptMessage = (): void => {
const { web3 } = web3Obj;
const { messageEncrypted, publicAddress } = this.state;
(web3.currentProvider as any)?.send(
{
method: 'eth_decrypt',
params: [messageEncrypted, publicAddress],
jsonrpc: '2.0',
},
(err: Error, result: any) => {
if (err) {
return console.error(err);
}
const decMsg = result.result;
return this.console(`decrypted message => ${decMsg}`);
},
);
}
stringifiableToHex = (value: any): string => ethers.utils.hexlify(Buffer.from(JSON.stringify(value)))
logout = (): void => {
web3Obj.torus.cleanUp()
.then(() => {
this.setState({
publicAddress: '',
});
return undefined;
})
.catch(console.error);
}
render() {
const {
messageEncrypted, encryptionKey, messageToEncrypt, buildEnv, selectedVerifier,
verifierId, placeholder, publicAddress, chainIdNetworkMap, chainId,
} = this.state;
return (
<div className="App">
<div>
<h3>Login With Torus</h3>
<section>
<p>
Build Environment :
{' '}
{buildEnv.toString()}
</p>
{
!publicAddress
? (
<div>
<select name="buildEnv" value={buildEnv} onChange={(e) => this.setState({ buildEnv: e.target.value })}>
<option value="production">Production</option>
<option value="binance">Binance</option>
<option selected value="testing">Testing</option>
<option value="development">Development</option>
<option value="lrc">LRC</option>
<option value="beta">Beta</option>
</select>
<button onClick={this.login}>Login</button>
</div>
)
: <button onClick={this.logout}>Logout</button>
}
</section>
{
publicAddress
&& (
<section
style={{
fontSize: '12px',
}}
>
<section>
<div>
Public Address:
<i>{publicAddress.toString()}</i>
</div>
<div>
Network:
<i>{chainIdNetworkMap[chainId.toString()]}</i>
</div>
</section>
<section style={{ marginTop: '20px' }}>
<h4>Torus Specific Info (Scroll to check actions output in console box below)</h4>
<button onClick={this.toggleTorusWidget}>Show/Hide Torus Button</button>
<button onClick={this.getUserInfo}>Get User Info</button>
<button onClick={this.createPaymentTx}>Create Payment Tx</button>
<button onClick={this.changeProvider}>Change Provider</button>
<div style={{ marginTop: '20px' }}>
<select defaultValue="google" name="verifier" value={selectedVerifier} onChange={(e) => this.onSelectedVerifierChanged(e)}>
<option value="google">Google</option>
<option value="reddit">Reddit</option>
<option value="discord">Discord</option>
</select>
<input
style={{ marginLeft: '20px' }}
value={verifierId}
placeholder={placeholder}
onChange={(e) => {
this.setState({
verifierId: e.target.value,
});
}}
/>
</div>
<button disabled={!verifierId} style={{ marginTop: '20px' }} onClick={this.getPublicAddress}>Get Public Address</button>
</section>
<section style={{ marginTop: '20px' }}>
<h4>Blockchain Apis</h4>
<section>
<h5>Signing</h5>
<button onClick={this.signMessageWithoutPopup}>sign_eth_no_popup</button>
<button onClick={this.signPersonalMsg}>personal_sign</button>
<button onClick={this.signMessage}>sign_eth</button>
<button onClick={this.signTypedDataV1}>sign typed data v1</button>
<button onClick={this.signTypedDataV3}>sign typed data v3</button>
<button onClick={this.signTypedDataV4}>sign typed data v4</button>
</section>
<section>
<h5>Transactions</h5>
<button onClick={this.sendEth}>Send Eth</button>
<button onClick={this.sendDai}>Send DAI</button>
<button onClick={this.approveKnc}>Approve Knc</button>
</section>
<section>
<h5>Encrypt / Decrypt</h5>
<button onClick={this.getEncryptionKey}>Get Encryption Key</button>
<div>
<input
style={{ marginLeft: '20px' }}
value={messageToEncrypt}
placeholder="Message to encrypt"
onChange={(e) => {
this.setState({
messageToEncrypt: e.target.value,
});
}}
/>
<button disabled={!encryptionKey} onClick={this.encryptMessage}>Encrypt</button>
</div>
<button disabled={!messageEncrypted} onClick={this.decryptMessage}>Decrypt</button>
</section>
</section>
</section>
)
}
</div>
{
publicAddress
&& (
<div id="console" style={{ whiteSpace: 'pre-line' }}>
<p style={{ whiteSpace: 'pre-line' }} />
</div>
)
}
</div>
);
}
}
export default App; | the_stack |
import type {
APIContext,
AstroComponentMetadata,
AstroGlobalPartial,
EndpointHandler,
Params,
SSRElement,
SSRLoadedRenderer,
SSRResult,
} from '../../@types/astro';
import { escapeHTML, HTMLString, markHTMLString } from './escape.js';
import { extractDirectives, generateHydrateScript, serializeProps } from './hydration.js';
import { serializeListValue } from './util.js';
import { shorthash } from './shorthash.js';
export { markHTMLString, markHTMLString as unescapeHTML } from './escape.js';
export type { Metadata } from './metadata';
export { createMetadata } from './metadata.js';
const voidElementNames =
/^(area|base|br|col|command|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)$/i;
const htmlBooleanAttributes =
/^(allowfullscreen|async|autofocus|autoplay|controls|default|defer|disabled|disablepictureinpicture|disableremoteplayback|formnovalidate|hidden|loop|nomodule|novalidate|open|playsinline|readonly|required|reversed|scoped|seamless|itemscope)$/i;
const htmlEnumAttributes = /^(contenteditable|draggable|spellcheck|value)$/i;
// Note: SVG is case-sensitive!
const svgEnumAttributes = /^(autoReverse|externalResourcesRequired|focusable|preserveAlpha)$/i;
// INVESTIGATE:
// 2. Less anys when possible and make it well known when they are needed.
// Used to render slots and expressions
// INVESTIGATE: Can we have more specific types both for the argument and output?
// If these are intentional, add comments that these are intention and why.
// Or maybe type UserValue = any; ?
async function _render(child: any): Promise<any> {
child = await child;
if (child instanceof HTMLString) {
return child;
} else if (Array.isArray(child)) {
return markHTMLString((await Promise.all(child.map((value) => _render(value)))).join(''));
} else if (typeof child === 'function') {
// Special: If a child is a function, call it automatically.
// This lets you do {() => ...} without the extra boilerplate
// of wrapping it in a function and calling it.
return _render(child());
} else if (typeof child === 'string') {
return markHTMLString(escapeHTML(child));
} else if (!child && child !== 0) {
// do nothing, safe to ignore falsey values.
}
// Add a comment explaining why each of these are needed.
// Maybe create clearly named function for what this is doing.
else if (
child instanceof AstroComponent ||
Object.prototype.toString.call(child) === '[object AstroComponent]'
) {
return markHTMLString(await renderAstroComponent(child));
} else {
return child;
}
}
// The return value when rendering a component.
// This is the result of calling render(), should this be named to RenderResult or...?
export class AstroComponent {
private htmlParts: TemplateStringsArray;
private expressions: any[];
constructor(htmlParts: TemplateStringsArray, expressions: any[]) {
this.htmlParts = htmlParts;
this.expressions = expressions;
}
get [Symbol.toStringTag]() {
return 'AstroComponent';
}
*[Symbol.iterator]() {
const { htmlParts, expressions } = this;
for (let i = 0; i < htmlParts.length; i++) {
const html = htmlParts[i];
const expression = expressions[i];
yield markHTMLString(html);
yield _render(expression);
}
}
}
function isAstroComponent(obj: any): obj is AstroComponent {
return (
typeof obj === 'object' && Object.prototype.toString.call(obj) === '[object AstroComponent]'
);
}
export async function render(htmlParts: TemplateStringsArray, ...expressions: any[]) {
return new AstroComponent(htmlParts, expressions);
}
// The callback passed to to $$createComponent
export interface AstroComponentFactory {
(result: any, props: any, slots: any): ReturnType<typeof render> | Response;
isAstroComponentFactory?: boolean;
}
// Used in creating the component. aka the main export.
export function createComponent(cb: AstroComponentFactory) {
// Add a flag to this callback to mark it as an Astro component
// INVESTIGATE does this need to cast
(cb as any).isAstroComponentFactory = true;
return cb;
}
export async function renderSlot(_result: any, slotted: string, fallback?: any) {
if (slotted) {
return await _render(slotted);
}
return fallback;
}
export const Fragment = Symbol('Astro.Fragment');
function guessRenderers(componentUrl?: string): string[] {
const extname = componentUrl?.split('.').pop();
switch (extname) {
case 'svelte':
return ['@astrojs/svelte'];
case 'vue':
return ['@astrojs/vue'];
case 'jsx':
case 'tsx':
return ['@astrojs/react', '@astrojs/preact'];
default:
return ['@astrojs/react', '@astrojs/preact', '@astrojs/vue', '@astrojs/svelte'];
}
}
function formatList(values: string[]): string {
if (values.length === 1) {
return values[0];
}
return `${values.slice(0, -1).join(', ')} or ${values[values.length - 1]}`;
}
export async function renderComponent(
result: SSRResult,
displayName: string,
Component: unknown,
_props: Record<string | number, any>,
slots: any = {}
) {
Component = await Component;
if (Component === Fragment) {
const children = await renderSlot(result, slots?.default);
if (children == null) {
return children;
}
return markHTMLString(children);
}
if (Component && (Component as any).isAstroComponentFactory) {
const output = await renderToString(result, Component as any, _props, slots);
return markHTMLString(output);
}
if (Component === null && !_props['client:only']) {
throw new Error(
`Unable to render ${displayName} because it is ${Component}!\nDid you forget to import the component or is it possible there is a typo?`
);
}
const { renderers } = result._metadata;
const metadata: AstroComponentMetadata = { displayName };
const { hydration, props } = extractDirectives(_props);
let html = '';
if (hydration) {
metadata.hydrate = hydration.directive as AstroComponentMetadata['hydrate'];
metadata.hydrateArgs = hydration.value;
metadata.componentExport = hydration.componentExport;
metadata.componentUrl = hydration.componentUrl;
}
const probableRendererNames = guessRenderers(metadata.componentUrl);
if (
Array.isArray(renderers) &&
renderers.length === 0 &&
typeof Component !== 'string' &&
!componentIsHTMLElement(Component)
) {
const message = `Unable to render ${metadata.displayName}!
There are no \`integrations\` set in your \`astro.config.mjs\` file.
Did you mean to add ${formatList(probableRendererNames.map((r) => '`' + r + '`'))}?`;
throw new Error(message);
}
const children = await renderSlot(result, slots?.default);
// Call the renderers `check` hook to see if any claim this component.
let renderer: SSRLoadedRenderer | undefined;
if (metadata.hydrate !== 'only') {
let error;
for (const r of renderers) {
try {
if (await r.ssr.check(Component, props, children)) {
renderer = r;
break;
}
} catch (e) {
error ??= e;
}
}
if (error) {
throw error;
}
if (!renderer && typeof HTMLElement === 'function' && componentIsHTMLElement(Component)) {
const output = renderHTMLElement(result, Component as typeof HTMLElement, _props, slots);
return output;
}
} else {
// Attempt: use explicitly passed renderer name
if (metadata.hydrateArgs) {
const rendererName = metadata.hydrateArgs;
renderer = renderers.filter(
({ name }) => name === `@astrojs/${rendererName}` || name === rendererName
)[0];
}
// Attempt: user only has a single renderer, default to that
if (!renderer && renderers.length === 1) {
renderer = renderers[0];
}
// Attempt: can we guess the renderer from the export extension?
if (!renderer) {
const extname = metadata.componentUrl?.split('.').pop();
renderer = renderers.filter(
({ name }) => name === `@astrojs/${extname}` || name === extname
)[0];
}
}
// If no one claimed the renderer
if (!renderer) {
if (metadata.hydrate === 'only') {
// TODO: improve error message
throw new Error(`Unable to render ${metadata.displayName}!
Using the \`client:only\` hydration strategy, Astro needs a hint to use the correct renderer.
Did you mean to pass <${metadata.displayName} client:only="${probableRendererNames
.map((r) => r.replace('@astrojs/', ''))
.join('|')}" />
`);
} else if (typeof Component !== 'string') {
const matchingRenderers = renderers.filter((r) => probableRendererNames.includes(r.name));
const plural = renderers.length > 1;
if (matchingRenderers.length === 0) {
throw new Error(`Unable to render ${metadata.displayName}!
There ${plural ? 'are' : 'is'} ${renderers.length} renderer${
plural ? 's' : ''
} configured in your \`astro.config.mjs\` file,
but ${plural ? 'none were' : 'it was not'} able to server-side render ${metadata.displayName}.
Did you mean to enable ${formatList(probableRendererNames.map((r) => '`' + r + '`'))}?`);
} else if (matchingRenderers.length === 1) {
// We already know that renderer.ssr.check() has failed
// but this will throw a much more descriptive error!
renderer = matchingRenderers[0];
({ html } = await renderer.ssr.renderToStaticMarkup(Component, props, children, metadata));
} else {
throw new Error(`Unable to render ${metadata.displayName}!
This component likely uses ${formatList(probableRendererNames)},
but Astro encountered an error during server-side rendering.
Please ensure that ${metadata.displayName}:
1. Does not unconditionally access browser-specific globals like \`window\` or \`document\`.
If this is unavoidable, use the \`client:only\` hydration directive.
2. Does not conditionally return \`null\` or \`undefined\` when rendered on the server.
If you're still stuck, please open an issue on GitHub or join us at https://astro.build/chat.`);
}
}
} else {
if (metadata.hydrate === 'only') {
html = await renderSlot(result, slots?.fallback);
} else {
({ html } = await renderer.ssr.renderToStaticMarkup(Component, props, children, metadata));
}
}
// This is a custom element without a renderer. Because of that, render it
// as a string and the user is responsible for adding a script tag for the component definition.
if (!html && typeof Component === 'string') {
html = await renderAstroComponent(
await render`<${Component}${spreadAttributes(props)}${markHTMLString(
(children == null || children == '') && voidElementNames.test(Component)
? `/>`
: `>${children == null ? '' : children}</${Component}>`
)}`
);
}
if (!hydration) {
return markHTMLString(html.replace(/\<\/?astro-fragment\>/g, ''));
}
// Include componentExport name, componentUrl, and props in hash to dedupe identical islands
const astroId = shorthash(
`<!--${metadata.componentExport!.value}:${metadata.componentUrl}-->\n${html}\n${serializeProps(
props
)}`
);
// Rather than appending this inline in the page, puts this into the `result.scripts` set that will be appended to the head.
// INVESTIGATE: This will likely be a problem in streaming because the `<head>` will be gone at this point.
result.scripts.add(
await generateHydrateScript(
{ renderer: renderer!, result, astroId, props },
metadata as Required<AstroComponentMetadata>
)
);
// Render a template if no fragment is provided.
const needsAstroTemplate = children && !/<\/?astro-fragment\>/.test(html);
const template = needsAstroTemplate ? `<template data-astro-template>${children}</template>` : '';
return markHTMLString(
`<astro-root uid="${astroId}"${needsAstroTemplate ? ' tmpl' : ''}>${
html ?? ''
}${template}</astro-root>`
);
}
/** Create the Astro.fetchContent() runtime function. */
function createDeprecatedFetchContentFn() {
return () => {
throw new Error('Deprecated: Astro.fetchContent() has been replaced with Astro.glob().');
};
}
/** Create the Astro.glob() runtime function. */
function createAstroGlobFn() {
const globHandler = (importMetaGlobResult: Record<string, any>, globValue: () => any) => {
let allEntries = [...Object.values(importMetaGlobResult)];
if (allEntries.length === 0) {
throw new Error(`Astro.glob(${JSON.stringify(globValue())}) - no matches found.`);
}
// Map over the `import()` promises, calling to load them.
return Promise.all(allEntries.map((fn) => fn()));
};
// Cast the return type because the argument that the user sees (string) is different from the argument
// that the runtime sees post-compiler (Record<string, Module>).
return globHandler as unknown as AstroGlobalPartial['glob'];
}
// This is used to create the top-level Astro global; the one that you can use
// Inside of getStaticPaths.
export function createAstro(
filePathname: string,
_site: string,
projectRootStr: string
): AstroGlobalPartial {
const site = new URL(_site);
const url = new URL(filePathname, site);
const projectRoot = new URL(projectRootStr);
return {
site,
fetchContent: createDeprecatedFetchContentFn(),
glob: createAstroGlobFn(),
// INVESTIGATE is there a use-case for multi args?
resolve(...segments: string[]) {
let resolved = segments.reduce((u, segment) => new URL(segment, u), url).pathname;
// When inside of project root, remove the leading path so you are
// left with only `/src/images/tower.png`
if (resolved.startsWith(projectRoot.pathname)) {
resolved = '/' + resolved.slice(projectRoot.pathname.length);
}
return resolved;
},
};
}
const toAttributeString = (value: any, shouldEscape = true) =>
shouldEscape ? String(value).replace(/&/g, '&').replace(/"/g, '"') : value;
const STATIC_DIRECTIVES = new Set(['set:html', 'set:text']);
// A helper used to turn expressions into attribute key/value
export function addAttribute(value: any, key: string, shouldEscape = true) {
if (value == null) {
return '';
}
if (value === false) {
if (htmlEnumAttributes.test(key) || svgEnumAttributes.test(key)) {
return markHTMLString(` ${key}="false"`);
}
return '';
}
// compiler directives cannot be applied dynamically, log a warning and ignore.
if (STATIC_DIRECTIVES.has(key)) {
// eslint-disable-next-line no-console
console.warn(`[astro] The "${key}" directive cannot be applied dynamically at runtime. It will not be rendered as an attribute.
Make sure to use the static attribute syntax (\`${key}={value}\`) instead of the dynamic spread syntax (\`{...{ "${key}": value }}\`).`);
return '';
}
// support "class" from an expression passed into an element (#782)
if (key === 'class:list') {
return markHTMLString(` ${key.slice(0, -5)}="${toAttributeString(serializeListValue(value))}"`);
}
// Boolean values only need the key
if (value === true && (key.startsWith('data-') || htmlBooleanAttributes.test(key))) {
return markHTMLString(` ${key}`);
} else {
return markHTMLString(` ${key}="${toAttributeString(value, shouldEscape)}"`);
}
}
// Adds support for `<Component {...value} />
export function spreadAttributes(values: Record<any, any>, shouldEscape = true) {
let output = '';
for (const [key, value] of Object.entries(values)) {
output += addAttribute(value, key, shouldEscape);
}
return markHTMLString(output);
}
// Adds CSS variables to an inline style tag
export function defineStyleVars(selector: string, vars: Record<any, any>) {
let output = '\n';
for (const [key, value] of Object.entries(vars)) {
output += ` --${key}: ${value};\n`;
}
return markHTMLString(`${selector} {${output}}`);
}
// Adds variables to an inline script.
export function defineScriptVars(vars: Record<any, any>) {
let output = '';
for (const [key, value] of Object.entries(vars)) {
output += `let ${key} = ${JSON.stringify(value)};\n`;
}
return markHTMLString(output);
}
function getHandlerFromModule(mod: EndpointHandler, method: string) {
// If there was an exact match on `method`, return that function.
if (mod[method]) {
return mod[method];
}
// Handle `del` instead of `delete`, since `delete` is a reserved word in JS.
if (method === 'delete' && mod['del']) {
return mod['del'];
}
// If a single `all` handler was used, return that function.
if (mod['all']) {
return mod['all'];
}
// Otherwise, no handler found.
return undefined;
}
/** Renders an endpoint request to completion, returning the body. */
export async function renderEndpoint(mod: EndpointHandler, request: Request, params: Params) {
const chosenMethod = request.method?.toLowerCase();
const handler = getHandlerFromModule(mod, chosenMethod);
if (!handler || typeof handler !== 'function') {
throw new Error(
`Endpoint handler not found! Expected an exported function for "${chosenMethod}"`
);
}
if (handler.length > 1) {
// eslint-disable-next-line no-console
console.warn(`
API routes with 2 arguments have been deprecated. Instead they take a single argument in the form of:
export function get({ params, request }) {
//...
}
Update your code to remove this warning.`);
}
const context = {
request,
params,
};
const proxy = new Proxy(context, {
get(target, prop) {
if (prop in target) {
return Reflect.get(target, prop);
} else if (prop in params) {
// eslint-disable-next-line no-console
console.warn(`
API routes no longer pass params as the first argument. Instead an object containing a params property is provided in the form of:
export function get({ params }) {
// ...
}
Update your code to remove this warning.`);
return Reflect.get(params, prop);
} else {
return undefined;
}
},
}) as APIContext & Params;
return handler.call(mod, proxy, request);
}
async function replaceHeadInjection(result: SSRResult, html: string): Promise<string> {
let template = html;
// <!--astro:head--> injected by compiler
// Must be handled at the end of the rendering process
if (template.indexOf('<!--astro:head-->') > -1) {
template = template.replace('<!--astro:head-->', await renderHead(result));
}
return template;
}
// Calls a component and renders it into a string of HTML
export async function renderToString(
result: SSRResult,
componentFactory: AstroComponentFactory,
props: any,
children: any
): Promise<string> {
const Component = await componentFactory(result, props, children);
if (!isAstroComponent(Component)) {
const response: Response = Component;
throw response;
}
let template = await renderAstroComponent(Component);
return replaceHeadInjection(result, template);
}
export async function renderPage(
result: SSRResult,
componentFactory: AstroComponentFactory,
props: any,
children: any
): Promise<{ type: 'html'; html: string } | { type: 'response'; response: Response }> {
try {
const response = await componentFactory(result, props, children);
if (isAstroComponent(response)) {
let template = await renderAstroComponent(response);
const html = await replaceHeadInjection(result, template);
return {
type: 'html',
html,
};
} else {
return {
type: 'response',
response,
};
}
} catch (err) {
if (err instanceof Response) {
return {
type: 'response',
response: err,
};
} else {
throw err;
}
}
}
// Filter out duplicate elements in our set
const uniqueElements = (item: any, index: number, all: any[]) => {
const props = JSON.stringify(item.props);
const children = item.children;
return (
index === all.findIndex((i) => JSON.stringify(i.props) === props && i.children == children)
);
};
// Renders a page to completion by first calling the factory callback, waiting for its result, and then appending
// styles and scripts into the head.
export async function renderHead(result: SSRResult): Promise<string> {
const styles = Array.from(result.styles)
.filter(uniqueElements)
.map((style) => renderElement('style', style));
let needsHydrationStyles = false;
const scripts = Array.from(result.scripts)
.filter(uniqueElements)
.map((script, i) => {
if ('data-astro-component-hydration' in script.props) {
needsHydrationStyles = true;
}
return renderElement('script', {
...script,
props: { ...script.props, 'astro-script': result._metadata.pathname + '/script-' + i },
});
});
if (needsHydrationStyles) {
styles.push(
renderElement('style', {
props: {},
children: 'astro-root, astro-fragment { display: contents; }',
})
);
}
const links = Array.from(result.links)
.filter(uniqueElements)
.map((link) => renderElement('link', link, false));
return markHTMLString(
links.join('\n') + styles.join('\n') + scripts.join('\n') + '\n' + '<!--astro:head:injected-->'
);
}
export async function renderAstroComponent(component: InstanceType<typeof AstroComponent>) {
let template = [];
for await (const value of component) {
if (value || value === 0) {
template.push(value);
}
}
return markHTMLString(await _render(template));
}
function componentIsHTMLElement(Component: unknown) {
return typeof HTMLElement !== 'undefined' && HTMLElement.isPrototypeOf(Component as object);
}
export async function renderHTMLElement(
result: SSRResult,
constructor: typeof HTMLElement,
props: any,
slots: any
) {
const name = getHTMLElementName(constructor);
let attrHTML = '';
for (const attr in props) {
attrHTML += ` ${attr}="${toAttributeString(await props[attr])}"`;
}
return markHTMLString(
`<${name}${attrHTML}>${await renderSlot(result, slots?.default)}</${name}>`
);
}
function getHTMLElementName(constructor: typeof HTMLElement) {
const definedName = (
customElements as CustomElementRegistry & { getName(_constructor: typeof HTMLElement): string }
).getName(constructor);
if (definedName) return definedName;
const assignedName = constructor.name
.replace(/^HTML|Element$/g, '')
.replace(/[A-Z]/g, '-$&')
.toLowerCase()
.replace(/^-/, 'html-');
return assignedName;
}
function renderElement(
name: string,
{ props: _props, children = '' }: SSRElement,
shouldEscape = true
) {
// Do not print `hoist`, `lang`, `is:global`
const { lang: _, 'data-astro-id': astroId, 'define:vars': defineVars, ...props } = _props;
if (defineVars) {
if (name === 'style') {
if (props['is:global']) {
children = defineStyleVars(`:root`, defineVars) + '\n' + children;
} else {
children = defineStyleVars(`.astro-${astroId}`, defineVars) + '\n' + children;
}
delete props['is:global'];
delete props['is:scoped'];
}
if (name === 'script') {
delete props.hoist;
children = defineScriptVars(defineVars) + '\n' + children;
}
}
return `<${name}${spreadAttributes(props, shouldEscape)}>${children}</${name}>`;
} | the_stack |
declare var beforeAll: jest.Lifecycle;
declare var beforeEach: jest.Lifecycle;
declare var afterAll: jest.Lifecycle;
declare var afterEach: jest.Lifecycle;
declare var describe: jest.Describe;
declare var fdescribe: jest.Describe;
declare var xdescribe: jest.Describe;
declare var it: jest.It;
declare var fit: jest.It;
declare var xit: jest.It;
declare var test: jest.It;
declare var xtest: jest.It;
declare function expect(actual: any): jest.Matchers;
interface NodeRequire {
/** Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not. */
requireActual(moduleName: string): any;
/** Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not. */
requireMock(moduleName: string): any;
}
declare namespace jest {
function addMatchers(matchers: jasmine.CustomMatcherFactories): void;
/** Disables automatic mocking in the module loader. */
function autoMockOff(): void;
/** Enables automatic mocking in the module loader. */
function autoMockOn(): void;
/** Removes any pending timers from the timer system. If any timers have been scheduled, they will be cleared and will never have the opportunity to execute in the future. */
function clearAllTimers(): void;
/** Indicates that the module system should never return a mocked version of the specified module, including all of the specificied module's dependencies. */
function deepUnmock(moduleName: string): void;
/** Disables automatic mocking in the module loader. */
function disableAutomock(): void;
/** Mocks a module with an auto-mocked version when it is being required. */
function doMock(moduleName: string): void;
/** Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module). */
function dontMock(moduleName: string): void;
/** Enables automatic mocking in the module loader. */
function enableAutomock(): void;
/** Creates a mock function. Optionally takes a mock implementation. */
function fn<T>(implementation?: Function): Mock<T>;
/** Use the automatic mocking system to generate a mocked version of the given module. */
function genMockFromModule<T>(moduleName: string): T;
/** Returns whether the given function is a mock function. */
function isMockFunction(fn: any): fn is Mock<any>;
/** Mocks a module with an auto-mocked version when it is being required. */
function mock(moduleName: string, factory?: any, options?: MockOptions): void;
/** Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests. */
function resetModuleRegistry(): void;
/** Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests. */
function resetModules(): void;
/** Exhausts tasks queued by setImmediate(). */
function runAllImmediates(): void;
/** Exhausts the micro-task queue (usually interfaced in node via process.nextTick). */
function runAllTicks(): void;
/** Exhausts the macro-task queue (i.e., all tasks queued by setTimeout() and setInterval()). */
function runAllTimers(): void;
/** Executes only the macro-tasks that are currently pending (i.e., only the tasks that have been queued by setTimeout() or setInterval() up to this point).
* If any of the currently pending macro-tasks schedule new macro-tasks, those new tasks will not be executed by this call. */
function runOnlyPendingTimers(): void;
/** Explicitly supplies the mock object that the module system should return for the specified module. */
function setMock<T>(moduleName: string, moduleExports: T): void;
/** Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module). */
function unmock(moduleName: string): void;
/** Instructs Jest to use fake versions of the standard timer functions. */
function useFakeTimers(): void;
/** Instructs Jest to use the real versions of the standard timer functions. */
function useRealTimers(): void;
interface MockOptions {
virtual?: boolean;
}
interface EmptyFunction {
(): void;
}
interface DoneCallback {
(...args: any[]): any
fail(error?: string | { message: string }): any;
}
interface ProvidesCallback {
(cb?: DoneCallback): any;
}
interface Lifecycle {
(fn: ProvidesCallback): any;
}
interface It {
(name: string, fn: ProvidesCallback): void;
only: It;
skip: It;
}
interface Describe {
(name: string, fn: EmptyFunction): void
only: Describe;
skip: Describe;
}
interface Matchers {
not: Matchers;
lastCalledWith(...args: any[]): void;
toBe(expected: any): void;
toBeCalled(): void;
toBeCalledWith(...args: any[]): void;
toBeCloseTo(expected: number, delta: number): void;
toBeDefined(): void;
toBeFalsy(): void;
toBeGreaterThan(expected: number): void;
toBeGreaterThanOrEqual(expected: number): void;
toBeInstanceOf(expected: any): void
toBeLessThan(expected: number): void;
toBeLessThanOrEqual(expected: number): void;
toBeNull(): void;
toBeTruthy(): void;
toBeUndefined(): void;
toContain(expected: any): void;
toEqual(expected: any): void;
toHaveBeenCalled(): boolean;
toHaveBeenCalledTimes(expected: number): boolean;
toHaveBeenCalledWith(...params: any[]): boolean;
toMatch(expected: string | RegExp): void;
toMatchSnapshot(): void;
toThrow(): void;
toThrowError(error?: string | Constructable | RegExp): void;
}
interface Constructable {
new (...args: any[]): any
}
interface Mock<T> extends Function {
new (): T;
(...args: any[]): any;
mock: MockContext<T>;
mockClear(): void;
mockImplementation(fn: Function): Mock<T>;
mockImplementationOnce(fn: Function): Mock<T>;
mockReturnThis(): Mock<T>;
mockReturnValue(value: any): Mock<T>;
mockReturnValueOnce(value: any): Mock<T>;
}
interface MockContext<T> {
calls: any[][];
instances: T[];
}
}
//Jest ships with a copy of Jasmine. They monkey-patch its APIs and divergence/deprecation are expected.
//Relevant parts of Jasmine's API are below so they can be changed and removed over time.
//This file can't reference jasmine.d.ts since the globals aren't compatible.
declare function spyOn(object: any, method: string): jasmine.Spy;
/** If you call the function pending anywhere in the spec body, no matter the expectations, the spec will be marked pending. */
declare function pending(reason?: string): void;
/** Fails a test when called within one. */
declare function fail(error?: any): void;
declare namespace jasmine {
var clock: () => Clock;
function any(aclass: any): Any;
function anything(): Any;
function arrayContaining(sample: any[]): ArrayContaining;
function objectContaining(sample: any): ObjectContaining;
function createSpy(name: string, originalFn?: Function): Spy;
function createSpyObj(baseName: string, methodNames: any[]): any;
function createSpyObj<T>(baseName: string, methodNames: any[]): T;
function pp(value: any): string;
function addCustomEqualityTester(equalityTester: CustomEqualityTester): void;
function addMatchers(matchers: CustomMatcherFactories): void;
function stringMatching(value: string | RegExp): Any;
interface Clock {
install(): void;
uninstall(): void;
/** Calls to any registered callback are triggered when the clock is ticked forward via the jasmine.clock().tick function, which takes a number of milliseconds. */
tick(ms: number): void;
mockDate(date?: Date): void;
}
interface Any {
new (expectedClass: any): any;
jasmineMatches(other: any): boolean;
jasmineToString(): string;
}
interface ArrayContaining {
new (sample: any[]): any;
asymmetricMatch(other: any): boolean;
jasmineToString(): string;
}
interface ObjectContaining {
new (sample: any): any;
jasmineMatches(other: any, mismatchKeys: any[], mismatchValues: any[]): boolean;
jasmineToString(): string;
}
interface Spy {
(...params: any[]): any;
identity: string;
and: SpyAnd;
calls: Calls;
mostRecentCall: { args: any[]; };
argsForCall: any[];
wasCalled: boolean;
}
interface SpyAnd {
/** By chaining the spy with and.callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation. */
callThrough(): Spy;
/** By chaining the spy with and.returnValue, all calls to the function will return a specific value. */
returnValue(val: any): Spy;
/** By chaining the spy with and.returnValues, all calls to the function will return specific values in order until it reaches the end of the return values list. */
returnValues(...values: any[]): Spy;
/** By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied function. */
callFake(fn: Function): Spy;
/** By chaining the spy with and.throwError, all calls to the spy will throw the specified value. */
throwError(msg: string): Spy;
/** When a calling strategy is used for a spy, the original stubbing behavior can be returned at any time with and.stub. */
stub(): Spy;
}
interface Calls {
/** By chaining the spy with calls.any(), will return false if the spy has not been called at all, and then true once at least one call happens. */
any(): boolean;
/** By chaining the spy with calls.count(), will return the number of times the spy was called */
count(): number;
/** By chaining the spy with calls.argsFor(), will return the arguments passed to call number index */
argsFor(index: number): any[];
/** By chaining the spy with calls.allArgs(), will return the arguments to all calls */
allArgs(): any[];
/** By chaining the spy with calls.all(), will return the context (the this) and arguments passed all calls */
all(): CallInfo[];
/** By chaining the spy with calls.mostRecent(), will return the context (the this) and arguments for the most recent call */
mostRecent(): CallInfo;
/** By chaining the spy with calls.first(), will return the context (the this) and arguments for the first call */
first(): CallInfo;
/** By chaining the spy with calls.reset(), will clears all tracking for a spy */
reset(): void;
}
interface CallInfo {
/** The context (the this) for the call */
object: any;
/** All arguments passed to the call */
args: any[];
/** The return value of the call */
returnValue: any;
}
interface CustomMatcherFactories {
[index: string]: CustomMatcherFactory;
}
interface CustomMatcherFactory {
(util: MatchersUtil, customEqualityTesters: Array<CustomEqualityTester>): CustomMatcher;
}
interface MatchersUtil {
equals(a: any, b: any, customTesters?: Array<CustomEqualityTester>): boolean;
contains<T>(haystack: ArrayLike<T> | string, needle: any, customTesters?: Array<CustomEqualityTester>): boolean;
buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: Array<any>): string;
}
interface CustomEqualityTester {
(first: any, second: any): boolean;
}
interface CustomMatcher {
compare<T>(actual: T, expected: T): CustomMatcherResult;
compare(actual: any, expected: any): CustomMatcherResult;
}
interface CustomMatcherResult {
pass: boolean;
message: string | (() => string);
}
interface ArrayLike<T> {
length: number;
[n: number]: T;
}
} | the_stack |
import {
render,
RenderOptions,
RenderResult,
screen,
waitFor,
} from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import fetchMock from "fetch-mock"
import { SnackbarProvider } from "notistack"
import React, { PropsWithChildren } from "react"
import { MemoryRouter } from "react-router"
import { AnalyticsAction } from "./analytics"
import {
cleanupMockAnalyticsCalls,
expectIncrs,
mockAnalyticsCalls,
nonAnalyticsCalls,
} from "./analytics_test_helpers"
import {
ApiButton,
ApiButtonType,
buttonsByComponent,
ButtonSet,
} from "./ApiButton"
import { mockUIButtonUpdates } from "./ApiButton.testhelpers"
import { accessorsForTesting, tiltfileKeyContext } from "./BrowserStorage"
import { HudErrorContextProvider } from "./HudErrorContext"
import {
boolFieldForUIButton,
disableButton,
hiddenFieldForUIButton,
oneUIButton,
textFieldForUIButton,
} from "./testdata"
import { UIButton, UIButtonStatus, UIInputSpec } from "./types"
const buttonInputsAccessor = accessorsForTesting(
`apibutton-TestButton`,
localStorage
)
type ApiButtonProviderProps = {
setError?: (error: string) => void
}
function ApiButtonProviders({
children,
setError,
}: PropsWithChildren<ApiButtonProviderProps>) {
return (
<MemoryRouter>
<HudErrorContextProvider setError={setError ?? (() => {})}>
<tiltfileKeyContext.Provider value="test">
<SnackbarProvider>{children}</SnackbarProvider>
</tiltfileKeyContext.Provider>
</HudErrorContextProvider>
</MemoryRouter>
)
}
// Following the custom render example from RTL:
// https://testing-library.com/docs/react-testing-library/setup/#custom-render
function customRender(
component: JSX.Element,
options?: RenderOptions,
providerProps?: ApiButtonProviderProps
) {
return render(component, {
wrapper: ({ children }) => (
<ApiButtonProviders {...providerProps} children={children} />
),
...options,
})
}
describe("ApiButton", () => {
beforeEach(() => {
localStorage.clear()
fetchMock.reset()
mockAnalyticsCalls()
mockUIButtonUpdates()
Date.now = jest.fn(() => 1482363367071)
})
afterEach(() => {
localStorage.clear()
cleanupMockAnalyticsCalls()
})
it("renders a simple button", () => {
const uibutton = oneUIButton({ iconName: "flight_takeoff" })
customRender(<ApiButton uiButton={uibutton} />)
const buttonElement = screen.getByLabelText(
`Trigger ${uibutton.spec!.text!}`
)
expect(buttonElement).toBeInTheDocument()
expect(buttonElement).toHaveTextContent(uibutton.spec!.text!)
expect(screen.getByText(uibutton.spec!.iconName!)).toBeInTheDocument()
})
it("sends analytics when clicked", async () => {
const uibutton = oneUIButton({})
customRender(<ApiButton uiButton={uibutton} />)
userEvent.click(screen.getByRole("button"))
await waitFor(() => {
expectIncrs({
name: "ui.web.uibutton",
tags: {
action: AnalyticsAction.Click,
component: ApiButtonType.Global,
},
})
})
})
it("sets a hud error when the api request fails", async () => {
// To add a mocked error response, reset the current mock
// for UIButton API call and add back the mock for analytics calls
// Reset the current mock for UIButton to add fake error response
fetchMock.reset()
mockAnalyticsCalls()
fetchMock.put(
(url) => url.startsWith("/proxy/apis/tilt.dev/v1alpha1/uibuttons"),
{ throws: "broken!" }
)
let error: string | undefined
const setError = (e: string) => (error = e)
const uibutton = oneUIButton({})
customRender(<ApiButton uiButton={uibutton} />, {}, { setError })
userEvent.click(screen.getByRole("button"))
await waitFor(() => {
expect(screen.getByRole("button")).not.toBeDisabled()
})
expect(error).toEqual("Error submitting button click: broken!")
})
describe("button with visible inputs", () => {
let uibutton: UIButton
let inputSpecs: UIInputSpec[]
beforeEach(() => {
inputSpecs = [
textFieldForUIButton("text_field"),
boolFieldForUIButton("bool_field", false),
textFieldForUIButton("text_field_with_default", "default text"),
hiddenFieldForUIButton("hidden_field", "hidden value 1"),
]
uibutton = oneUIButton({ inputSpecs })
customRender(<ApiButton uiButton={uibutton} />).rerender
})
it("renders an options button", () => {
expect(
screen.getByLabelText(`Open ${uibutton.spec!.text!} options`)
).toBeInTheDocument()
})
it("shows the options form with inputs when the options button is clicked", () => {
const optionButton = screen.getByLabelText(
`Open ${uibutton.spec!.text!} options`
)
userEvent.click(optionButton)
expect(
screen.getByText(`Options for ${uibutton.spec!.text!}`)
).toBeInTheDocument()
})
it("only shows inputs for visible inputs", () => {
// Open the options dialog first
const optionButton = screen.getByLabelText(
`Open ${uibutton.spec!.text!} options`
)
userEvent.click(optionButton)
inputSpecs.forEach((spec) => {
if (!spec.hidden) {
expect(screen.getByLabelText(spec.label!)).toBeInTheDocument()
}
})
})
it("allows an empty text string when there's a default value", async () => {
// Open the options dialog first
const optionButton = screen.getByLabelText(
`Open ${uibutton.spec!.text!} options`
)
userEvent.click(optionButton)
// Get the input element with the hardcoded default text
const inputWithDefault = screen.getByDisplayValue("default text")
userEvent.clear(inputWithDefault)
// Use the label text to select and verify the input's value
expect(screen.getByLabelText("text_field_with_default")).toHaveValue("")
})
it("propagates analytics tags to text inputs", async () => {
// Open the options dialog first
const optionButton = screen.getByLabelText(
`Open ${uibutton.spec!.text!} options`
)
userEvent.click(optionButton)
const booleanInput = screen.getByLabelText("bool_field")
userEvent.click(booleanInput)
expect(screen.getByLabelText("bool_field")).toBeChecked()
await waitFor(() => {
expectIncrs(
{
name: "ui.web.uibutton.inputMenu",
tags: {
action: AnalyticsAction.Click,
component: ApiButtonType.Global,
},
},
{
name: "ui.web.uibutton.inputValue",
tags: {
action: AnalyticsAction.Edit,
component: ApiButtonType.Global,
inputType: "bool",
},
}
)
})
})
it("submits the current options when the submit button is clicked", async () => {
// Open the options dialog first
const optionButton = screen.getByLabelText(
`Open ${uibutton.spec!.text!} options`
)
userEvent.click(optionButton)
// Make a couple changes to the inputs
userEvent.type(screen.getByLabelText("text_field"), "new_value")
userEvent.click(screen.getByLabelText("bool_field"))
userEvent.type(screen.getByLabelText("text_field_with_default"), "!!!!")
// Click the submit button
userEvent.click(screen.getByLabelText(`Trigger ${uibutton.spec!.text!}`))
// Wait for the button to be enabled again,
// which signals successful trigger button response
await waitFor(
() =>
expect(screen.getByLabelText(`Trigger ${uibutton.spec!.text!}`)).not
.toBeDisabled
)
const calls = nonAnalyticsCalls()
expect(calls.length).toEqual(1)
const call = calls[0]
expect(call[0]).toEqual(
"/proxy/apis/tilt.dev/v1alpha1/uibuttons/TestButton/status"
)
expect(call[1]).toBeTruthy()
expect(call[1]!.method).toEqual("PUT")
expect(call[1]!.body).toBeTruthy()
const actualStatus: UIButtonStatus = JSON.parse(
call[1]!.body!.toString()
).status
const expectedStatus: UIButtonStatus = {
lastClickedAt: "2016-12-21T23:36:07.071000+00:00",
inputs: [
{
name: inputSpecs[0].name,
text: {
value: "new_value",
},
},
{
name: inputSpecs[1].name,
bool: {
value: true,
},
},
{
name: inputSpecs[2].name,
text: {
value: "default text!!!!",
},
},
{
name: inputSpecs[3].name,
hidden: {
value: inputSpecs[3].hidden!.value,
},
},
],
}
expect(actualStatus).toEqual(expectedStatus)
})
it("submits default options when the submit button is clicked", async () => {
// The testing setup already includes a field with default text,
// so we can go ahead and click the submit button
userEvent.click(screen.getByLabelText(`Trigger ${uibutton.spec!.text!}`))
// Wait for the button to be enabled again,
// which signals successful trigger button response
await waitFor(
() =>
expect(screen.getByLabelText(`Trigger ${uibutton.spec!.text!}`)).not
.toBeDisabled
)
const calls = nonAnalyticsCalls()
expect(calls.length).toEqual(1)
const call = calls[0]
expect(call[0]).toEqual(
"/proxy/apis/tilt.dev/v1alpha1/uibuttons/TestButton/status"
)
expect(call[1]).toBeTruthy()
expect(call[1]!.method).toEqual("PUT")
expect(call[1]!.body).toBeTruthy()
const actualStatus: UIButtonStatus = JSON.parse(
call[1]!.body!.toString()
).status
const expectedStatus: UIButtonStatus = {
lastClickedAt: "2016-12-21T23:36:07.071000+00:00",
inputs: [
{
name: inputSpecs[0].name,
text: {},
},
{
name: inputSpecs[1].name,
bool: {
value: false,
},
},
{
name: inputSpecs[2].name,
text: {
value: "default text",
},
},
{
name: inputSpecs[3].name,
hidden: {
value: inputSpecs[3].hidden!.value,
},
},
],
}
expect(actualStatus).toEqual(expectedStatus)
})
})
describe("local storage for input values", () => {
let uibutton: UIButton
let inputSpecs: UIInputSpec[]
beforeEach(() => {
inputSpecs = [
textFieldForUIButton("text1"),
boolFieldForUIButton("bool1"),
]
uibutton = oneUIButton({ inputSpecs })
// Store previous values for input fields
buttonInputsAccessor.set({
text1: "text value",
bool1: true,
})
customRender(<ApiButton uiButton={uibutton} />)
})
it("are read from local storage", () => {
// Open the options dialog
userEvent.click(
screen.getByLabelText(`Open ${uibutton.spec!.text!} options`)
)
expect(screen.getByLabelText("text1")).toHaveValue("text value")
expect(screen.getByLabelText("bool1")).toBeChecked()
})
it("are written to local storage when edited", () => {
// Open the options dialog
userEvent.click(
screen.getByLabelText(`Open ${uibutton.spec!.text!} options`)
)
// Type a new value in the text field
const textField = screen.getByLabelText("text1")
userEvent.clear(textField)
userEvent.type(textField, "new value!")
// Uncheck the boolean field
userEvent.click(screen.getByLabelText("bool1"))
// Expect local storage values are updated
expect(buttonInputsAccessor.get()).toEqual({
text1: "new value!",
bool1: false,
})
})
})
describe("button with only hidden inputs", () => {
let uibutton: UIButton
beforeEach(() => {
const inputSpecs = [1, 2, 3].map((i) =>
hiddenFieldForUIButton(`hidden${i}`, `value${i}`)
)
uibutton = oneUIButton({ inputSpecs })
customRender(<ApiButton uiButton={oneUIButton({ inputSpecs })} />)
})
it("doesn't render an options button", () => {
expect(
screen.queryByLabelText(`Open ${uibutton.spec!.text!} options`)
).not.toBeInTheDocument()
})
it("doesn't render any input elements", () => {
expect(screen.queryAllByRole("input").length).toBe(0)
})
})
describe("buttons that require confirmation", () => {
let uibutton: UIButton
let rerender: RenderResult["rerender"]
beforeEach(() => {
uibutton = oneUIButton({ requiresConfirmation: true })
rerender = customRender(<ApiButton uiButton={uibutton} />).rerender
})
it("displays 'confirm' and 'cancel' buttons after a single click", () => {
const buttonBeforeClick = screen.getByLabelText(
`Trigger ${uibutton.spec!.text!}`
)
expect(buttonBeforeClick).toBeInTheDocument()
expect(buttonBeforeClick).toHaveTextContent(uibutton.spec!.text!)
userEvent.click(buttonBeforeClick)
const confirmButton = screen.getByLabelText(
`Confirm ${uibutton.spec!.text!}`
)
expect(confirmButton).toBeInTheDocument()
expect(confirmButton).toHaveTextContent("Confirm")
const cancelButton = screen.getByLabelText(
`Cancel ${uibutton.spec!.text!}`
)
expect(cancelButton).toBeInTheDocument()
})
it("clicking the 'confirm' button triggers a button API call", async () => {
// Click the submit button
userEvent.click(screen.getByLabelText(`Trigger ${uibutton.spec!.text!}`))
// Expect that it should not have submitted the click to the backend
expect(nonAnalyticsCalls().length).toEqual(0)
// Click the confirm submit button
userEvent.click(screen.getByLabelText(`Confirm ${uibutton.spec!.text!}`))
// Wait for the button to be enabled again,
// which signals successful trigger button response
await waitFor(
() =>
expect(screen.getByLabelText(`Trigger ${uibutton.spec!.text!}`)).not
.toBeDisabled
)
// Expect that the click was submitted and the button text resets
expect(nonAnalyticsCalls().length).toEqual(1)
expect(
screen.getByLabelText(`Trigger ${uibutton.spec!.text!}`)
).toHaveTextContent(uibutton.spec!.text!)
})
it("clicking the 'cancel' button resets the button", () => {
// Click the submit button
userEvent.click(screen.getByLabelText(`Trigger ${uibutton.spec!.text!}`))
// Expect that it should not have submitted the click to the backend
expect(nonAnalyticsCalls().length).toEqual(0)
// Click the cancel submit button
userEvent.click(screen.getByLabelText(`Cancel ${uibutton.spec!.text!}`))
// Expect that NO click was submitted and the button text resets
expect(nonAnalyticsCalls().length).toEqual(0)
expect(
screen.getByLabelText(`Trigger ${uibutton.spec!.text!}`)
).toHaveTextContent(uibutton.spec!.text!)
})
// This test makes sure that the `confirming` state resets if a user
// clicks a toggle button once, then navigates to another resource
// with a toggle button (which will have a different button name)
it("resets the `confirming` state when the button's name changes", () => {
// Click the button and verify the confirmation state
userEvent.click(screen.getByLabelText(`Trigger ${uibutton.spec!.text!}`))
expect(
screen.getByLabelText(`Confirm ${uibutton.spec!.text!}`)
).toBeInTheDocument()
expect(
screen.getByLabelText(`Cancel ${uibutton.spec!.text!}`)
).toBeInTheDocument()
// Then update the component's props with a new button
const anotherUIButton = oneUIButton({
buttonName: "another-button",
buttonText: "Click another button!",
requiresConfirmation: true,
})
rerender(<ApiButton uiButton={anotherUIButton} />)
// Verify that the button's confirmation state is reset
// and displays the new button text
const updatedButton = screen.getByLabelText(
`Trigger ${anotherUIButton.spec!.text!}`
)
expect(updatedButton).toBeInTheDocument()
expect(updatedButton).toHaveTextContent(anotherUIButton.spec!.text!)
})
})
describe("helper functions", () => {
describe("buttonsByComponent", () => {
it("returns an empty object if there are no buttons", () => {
expect(buttonsByComponent(undefined)).toStrictEqual(
new Map<string, ButtonSet>()
)
})
it("returns a map of resources names to button sets", () => {
const buttons = [
oneUIButton({ componentID: "frontend", buttonName: "Lint" }),
oneUIButton({ componentID: "frontend", buttonName: "Compile" }),
disableButton("frontend", true),
oneUIButton({ componentID: "backend", buttonName: "Random scripts" }),
disableButton("backend", false),
oneUIButton({ componentID: "data-warehouse", buttonName: "Flush" }),
oneUIButton({ componentID: "" }),
]
const expectedOutput = new Map<string, ButtonSet>([
[
"frontend",
{
default: [buttons[0], buttons[1]],
toggleDisable: buttons[2],
},
],
["backend", { default: [buttons[3]], toggleDisable: buttons[4] }],
["data-warehouse", { default: [buttons[5]] }],
])
expect(buttonsByComponent(buttons)).toStrictEqual(expectedOutput)
})
})
})
}) | the_stack |
import * as fs from 'fs';
import * as path from 'path';
import * as pkgUp from 'pkg-up';
// import * as util from 'util';
import { toMachine } from '../src/scxml';
import { StateNode } from '../src/StateNode';
import { interpret } from '../src/interpreter';
import { SimulatedClock } from '../src/SimulatedClock';
import { State } from '../src';
import { pathsToStateValue } from '../src/utils';
// import { StateValue } from '../src/types';
// import { Event, StateValue, ActionObject } from '../src/types';
// import { actionTypes } from '../src/actions';
const TEST_FRAMEWORK = path.dirname(
pkgUp.sync({
cwd: require.resolve('@scion-scxml/test-framework')
}) as string
);
const testGroups = {
actionSend: [
'send1',
'send2',
'send3',
'send4',
'send4b',
'send7',
'send7b',
'send8',
'send8b',
'send9'
],
assign: [
// 'assign_invalid', // TODO: handle error.execution event
// 'assign_obj_literal' // <script/> conversion not implemented
],
'assign-current-small-step': [
// 'test0', // <script/> conversion not implemented
'test1',
'test2',
'test3',
'test4'
],
basic: ['basic0', 'basic1', 'basic2'],
'cond-js': ['test0', 'test1', 'test2', 'TestConditionalTransition'],
data: [
// 'data_invalid',
'data_obj_literal'
],
'default-initial-state': ['initial1', 'initial2'],
delayedSend: ['send1', 'send2', 'send3'],
documentOrder: ['documentOrder0'],
error: [
// 'error', // not implemented
],
forEach: [
// 'test1', // not implemented
],
hierarchy: ['hier0', 'hier1', 'hier2'],
'hierarchy+documentOrder': ['test0', 'test1'],
history: [
'history0',
'history1',
'history2',
'history3',
// 'history4', // TODO: support history nodes on parallel states
'history4b',
'history5',
'history6'
],
'if-else': [
// 'test0', // microstep not implemented correctly
],
in: [
// 'TestInPredicate', // In() conversion not implemented yet
],
'internal-transitions': ['test0', 'test1'],
misc: ['deep-initial'],
'more-parallel': [
'test0',
'test1',
'test2',
'test2b',
'test3',
// 'test3b',
'test4',
'test5',
'test6',
// 'test6b',
'test7',
'test8',
'test9',
'test10',
'test10b'
],
'multiple-events-per-transition': [
// 'test1'
],
parallel: ['test0', 'test1', 'test2', 'test3'],
'parallel+interrupt': [
'test0',
// 'test1',
'test2',
'test3',
'test4',
// 'test5',
'test6',
// 'test7',
// 'test7b',
'test8',
'test9',
'test10',
'test11',
// 'test12',
'test13',
'test14',
// 'test15',
'test16',
'test17',
'test18',
'test19',
// 'test20',
// 'test21',
// 'test21b',
'test22',
'test23',
'test24',
// 'test25',
'test27',
'test28',
'test29',
'test30',
'test31'
],
// script: ['test0', 'test1', 'test2'], // <script/> conversion not implemented
// 'script-src': ['test0', 'test1', 'test2', 'test3'], // <script/> conversion not implemented
'scxml-prefix-event-name-matching': [
'star0'
// prefix event matching not implemented yet
// 'test0',
// 'test1'
],
// 'send-data': ['send1'],
// 'send-idlocation': ['test0'],
// 'send-internal': ['test0'],
'targetless-transition': ['test0', 'test1', 'test2', 'test3'],
'w3c-ecma': [
'test144.txml',
'test147.txml',
'test148.txml',
'test149.txml',
// 'test150.txml',
// 'test151.txml',
// 'test152.txml', // <foreach> not implemented yet
// 'test153.txml',
// 'test155.txml',
// 'test156.txml',
'test158.txml',
// 'test159.txml',
'test172.txml',
'test173.txml',
'test174.txml',
'test175.txml',
'test176.txml',
// 'test179.txml',
// 'test183.txml',
'test185.txml',
// 'test186.txml',
'test187.txml',
'test189.txml',
// 'test190.txml',
'test191.txml',
// 'test192.txml',
'test193.txml',
// 'test194.txml',
// 'test198.txml',
// 'test199.txml',
'test200.txml',
'test201.txml',
// 'test205.txml',
// 'test207.txml',
// 'test208.txml',
// 'test210.txml',
// 'test215.txml',
// 'test216.txml',
// 'test220.txml',
// 'test223.txml',
// 'test224.txml',
// 'test225.txml',
// 'test226.txml',
// 'test228.txml',
// 'test229.txml',
// 'test230.txml',
// 'test232.txml',
// 'test233.txml',
// 'test234.txml',
// 'test235.txml',
// 'test236.txml',
// 'test237.txml',
// 'test239.txml',
// 'test240.txml',
// 'test241.txml',
// 'test242.txml',
// 'test243.txml',
// 'test244.txml',
// 'test245.txml',
// 'test247.txml',
// 'test250.txml',
// 'test252.txml',
// 'test253.txml',
// 'test276.txml',
// 'test277.txml',
// 'test278.txml',
// 'test279.txml',
// 'test280.txml',
// 'test286.txml',
'test287.txml',
// 'test294.txml',
// 'test298.txml',
// 'test302.txml',
// 'test303-1.txml',
// 'test303-2.txml',
// 'test303.txml',
// 'test304.txml',
// 'test307.txml',
// 'test309.txml',
// 'test310.txml',
// 'test311.txml',
// 'test312.txml',
// 'test313.txml',
// 'test314.txml',
'test318.txml',
// 'test319.txml',
// 'test321.txml',
// 'test322.txml',
// 'test323.txml',
// 'test324.txml',
// 'test325.txml',
// 'test326.txml',
// 'test329.txml',
// 'test330.txml',
'test331.txml',
// 'test332.txml',
'test333.txml',
'test335.txml',
'test336.txml',
'test337.txml',
// 'test338.txml',
'test339.txml',
'test342.txml',
// 'test343.txml',
// 'test344.txml',
// 'test346.txml',
// 'test347.txml',
'test348.txml',
'test349.txml',
// 'test350.txml',
// 'test351.txml',
// 'test352.txml',
// 'test354.txml',
'test355.txml',
// 'test364.txml',
// 'test372.txml',
// 'test375.txml',
// 'test376.txml',
// 'test377.txml',
// 'test378.txml',
// 'test387.txml',
// 'test388.txml',
'test396.txml',
// 'test399.txml',
// 'test401.txml',
// 'test402.txml',
'test403a.txml',
// 'test403b.txml',
// 'test403c.txml',
'test404.txml',
'test405.txml',
'test406.txml',
'test407.txml',
// 'test409.txml', // conversion of In() predicate not implemented yet
// 'test411.txml',
// 'test412.txml',
// 'test413.txml',
'test416.txml',
'test417.txml',
'test419.txml',
'test421.txml',
// 'test422.txml',
// 'test423.txml',
// 'test436.txml',
// 'test444.txml',
'test445.txml',
// 'test446.txml',
// 'test448.txml',
'test449.txml',
// 'test451.txml',
// 'test452.txml',
'test453.txml',
// 'test456.txml',
// 'test457.txml',
// 'test459.txml',
// 'test460.txml',
// 'test487.txml',
// 'test488.txml',
// 'test495.txml',
// 'test496.txml',
// 'test500.txml',
// 'test501.txml',
'test503.txml',
// 'test504.txml',
// 'test505.txml',
// 'test506.txml',
// 'test521.txml',
// 'test525.txml',
// 'test527.txml',
// 'test528.txml',
// 'test529.txml',
// 'test530.txml',
// 'test533.txml',
// 'test550.txml',
// 'test551.txml',
// 'test552.txml',
// 'test553.txml',
// 'test554.txml',
// 'test557.txml',
// 'test558.txml',
// 'test560.txml',
// 'test561.txml',
// 'test562.txml',
// 'test569.txml',
'test570.txml'
// 'test576.txml'
// 'test578.txml',
// 'test579.txml',
// 'test580.txml',
]
};
const overrides = {
'assign-current-small-step': [
// original using <script/> to manipulate datamodel
'test0'
]
};
interface SCIONTest {
initialConfiguration: string[];
events: Array<{
after?: number;
event: { name: string };
nextConfiguration: string[];
}>;
}
async function runW3TestToCompletion(machine: StateNode): Promise<void> {
await new Promise<void>((resolve, reject) => {
let nextState: State<any>;
interpret(machine)
.onTransition((state) => {
nextState = state;
})
.onDone(() => {
if (nextState.value === 'pass') {
resolve();
} else {
reject(new Error('Reached "fail" state.'));
}
})
.start();
});
}
async function runTestToCompletion(
machine: StateNode,
test: SCIONTest
): Promise<void> {
if (!test.events.length && test.initialConfiguration[0] === 'pass') {
await runW3TestToCompletion(machine);
return;
}
const resolvedStateValue = machine.resolve(
pathsToStateValue(
test.initialConfiguration.map((id) => machine.getStateNodeById(id).path)
)
);
let done = false;
let nextState: State<any> = machine.getInitialState(resolvedStateValue);
const service = interpret(machine, {
clock: new SimulatedClock()
})
.onTransition((state) => {
nextState = state;
})
.onDone(() => {
done = true;
})
.start(nextState);
test.events.forEach(({ event, nextConfiguration, after }) => {
if (done) {
return;
}
if (after) {
(service.clock as SimulatedClock).increment(after);
}
service.send(event.name);
const stateIds = machine
.getStateNodes(nextState)
.map((stateNode) => stateNode.id);
expect(stateIds).toContain(nextConfiguration[0]);
});
}
describe('scxml', () => {
const testGroupKeys = Object.keys(testGroups);
// const testGroupKeys = ['scxml-prefix-event-name-matching'];
testGroupKeys.forEach((testGroupName) => {
testGroups[testGroupName].forEach((testName) => {
const scxmlSource =
overrides[testGroupName] &&
overrides[testGroupName].indexOf(testName) !== -1
? `./fixtures/scxml/${testGroupName}/${testName}.scxml`
: `${TEST_FRAMEWORK}/test/${testGroupName}/${testName}.scxml`;
const scxmlDefinition = fs.readFileSync(
path.resolve(__dirname, scxmlSource),
{ encoding: 'utf-8' }
);
const scxmlTest = JSON.parse(
fs.readFileSync(
path.resolve(
__dirname,
`${TEST_FRAMEWORK}/test/${testGroupName}/${testName}.json`
),
{ encoding: 'utf-8' }
)
) as SCIONTest;
it(`${testGroupName}/${testName}`, async () => {
const machine = toMachine(scxmlDefinition, {
delimiter: '$'
});
// console.dir(machine.config, { depth: null });
await runTestToCompletion(machine, scxmlTest);
});
});
});
}); | the_stack |
import type { Town } from '@lib'
import { encounters } from './encounters'
import { getEncounter, getEventDescription } from './events'
export interface Location {
summary: string
available: BiomeName[]
function?(town: Town, biome: BiomeName): string
}
export type BiomeName =
| 'mountain'
| 'desert'
| 'forest'
| 'road'
| 'trail'
| 'path'
/**
* @warn Uses `setup.misc`
* @warn Uses `setup.getEncounter`
* @warn Uses `setup.gravestone.create`
*/
export const locations: Location[] = [
{
summary: 'a cavern behind a waterfall',
available: ['mountain', 'forest'],
function: (town, biome) => {
const cavern = lib.cavern.create({ entrance: 'somewhat hidden behind a roaring waterfall' })
const readout = lib.cavern.readout(cavern)
// @ts-ignore
const contents = lib.contentsFetcher(setup.misc[biome].cave, encounters)(town, biome)
return `a cavern. ${readout} <blockquote>The cavern is now home to ${contents}.</blockquote>`
}
},
{
summary: 'a small cave in the bank of a creek',
available: ['mountain', 'forest'],
function: (town, biome) => {
const cavern = lib.cavern.create({ entrance: 'in the bank of a creek' })
const readout = lib.cavern.readout(cavern)
// @ts-ignore
const contents = lib.contentsFetcher(setup.misc[biome].cave, encounters)(town, biome)
return `a small cave. ${readout} <blockquote>The cave is home to ${contents}.</blockquote>`
}
},
{
summary: 'an entrance to a rocky cave',
available: ['mountain', 'forest'],
function: (town, biome) => {
const cavern = lib.cavern.create()
const readout = lib.cavern.readout(cavern)
// @ts-ignore
const contents = lib.contentsFetcher(setup.misc[biome].cave, encounters)(town, biome)
return `a rocky cave. ${readout} <blockquote>The cave is home to ${contents}.</blockquote>`
}
},
{
summary: 'a hole under a large tree',
available: ['forest'],
function: (_, biome) => {
// @ts-ignore
let contents = setup.misc[biome].hole.random()
// this is lazy. Will change hole from an array to an object once I make more creators.
if (contents === 'a spider') {
const spider = lib.createAutoTippy(lib.spider)('spider')
contents = `a ${spider}.`
}
if (biome === 'road' || biome === 'trail' || biome === 'path') {
throw new Error(`Invalid biome "${biome}"`)
}
const tree = lib.createAutoTippy(lib.tree, { biome })('tree')
return `a hole under a large ${tree}. <blockquote>Inside is ${contents}.</blockquote>`
}
},
{
summary: 'a hole under a sheer cliff',
available: ['mountain'],
function: (_, biome) => {
// @ts-ignore
const contents = setup.misc[biome].hole.random()
return `a hole under a sheer cliff. <blockquote> Inside is ${contents}.</blockquote>`
}
},
{
summary: 'a hole under a sheer cliff face',
available: ['mountain'],
function: (_, biome) => {
// @ts-ignore
const contents = setup.misc[biome].hole.random()
return `a hole under a sheer cliff face. <blockquote> Inside is ${contents}.</blockquote>`
}
},
{
summary: 'a large burrow',
available: ['desert', 'forest'],
function: (_, biome) => {
// @ts-ignore
const contents = setup.misc[biome].hole.random()
return `a large burrow <blockquote>Inside is ${contents}.</blockquote>`
}
},
{
summary: 'a peculiar cottage',
available: ['forest'],
function: (town, biome) => {
// @ts-ignore
const contents = lib.contentsFetcher(setup.misc[biome].cottageLives, encounters)(town, biome)
const cottage = lib.createAutoTippy(lib.cabin, { wordNoun: 'cottage' })('cottage')
return `a peculiar ${cottage}. <blockquote>${contents} lives here.</blockquote>`
}
},
{
summary: "a woodsman's cabin",
available: ['forest'],
function: (town, biome) => {
// @ts-ignore
const contents = lib.contentsFetcher(setup.misc[biome].cabinLives, encounters)(town, biome)
const cabin = lib.createAutoTippy(lib.cabin)('cabin')
// @ts-ignore
return `a woodsman's ${cabin}. <blockquote>${setup.misc[biome].cabinLived.random()} once lived here. Now, ${contents} lives here.</blockquote>`
}
},
{
summary: 'a cozy little cabin',
available: ['forest'],
function: (town, biome) => {
// @ts-ignore
const contents = lib.contentsFetcher(setup.misc[biome].cabinLives, encounters)(town, biome)
const cabin = lib.createAutoTippy(lib.cabin, { size: 'little' })('cabin')
// @ts-ignore
return `a cozy little ${cabin}. <blockquote>${setup.misc[biome].cabinLived.random()} once lived here. Now, ${contents} lives here.</blockquote>`
}
},
{
summary: 'an abandoned cabin',
available: ['forest', 'mountain'],
function: (town, biome) => {
// @ts-ignore
const contents = lib.contentsFetcher(setup.misc[biome].cabinLives, encounters)(town, biome)
const cabin = lib.createAutoTippy(lib.cabin)('cabin')
// @ts-ignore
return `an abandoned ${cabin}. <blockquote>${setup.misc[biome].cabinLived.random()} once lived here. Now, ${contents} lives here.</blockquote>`
}
},
{
summary: 'an abandoned campsite',
available: ['forest', 'mountain', 'road', 'desert'],
function: () => {
const contents = ['a party of orc scouts', 'a goblin raiding party', 'some miners or prospectors', 'some elves', 'some refugees or fugitives', 'someone whose purposes are unclear', 'someone who left in an awful hurry']
return `an abandoned campsite, which looks to have been occupied previously by ${contents.random()}`
}
},
{
summary: 'a sacred grove',
available: ['forest', 'mountain', 'desert']
},
{
summary: 'a shrine',
available: ['forest'],
function: (town) => {
// @ts-ignore
const shrine = setup.misc.religion.shrine.create(town)
return `a shrine dedicated to ${shrine.god}. The shrine is ${shrine.material} ${shrine.senses}`
}
},
{
summary: 'a grave with an illegible headstone',
available: ['forest', 'mountain', 'road', 'desert'],
function: (town) => {
const grave = setup.graveStone.create(town)
return grave.sentenceStrings
}
},
{
summary: 'ancient ruins',
available: ['forest'],
function: (town, biome) => {
// @ts-ignore
const biomeData = setup.misc[biome]
// @ts-ignore
const contents = lib.contentsFetcher(biomeData.ruinsLives, encounters)(town, biome)
return `ancient ruins. <blockquote>The ruins were built by ${biomeData.ruinsLived.random()}. Now, ${contents} lives here.</blockquote>`
}
},
{
summary: 'a cavern in a canyon wall',
available: ['desert'],
function: (town, biome) => {
const cavern = lib.cavern.create({ entrance: 'in a canyon wall' })
const readout = lib.cavern.readout(cavern)
const encounter = getEventDescription(getEncounter(biome), town, biome)
return `a cavern. ${readout} <blockquote>The cavern is home to ${encounter}.</blockquote>`
}
},
{
summary: 'a cave entrance, hidden by a boulder',
available: ['desert'],
function: (town, biome) => {
const cavern = lib.cavern.create({ entrance: 'hidden by a boulder' })
const readout = lib.cavern.readout(cavern)
const encounter = getEventDescription(getEncounter(biome), town, biome)
return `a cavern. ${readout} <blockquote>The cavern is home to ${encounter}.</blockquote>`
}
},
{
summary: 'a small cave in the crook of a rock wall',
available: ['mountain'],
function: (town, biome) => {
const cavern = lib.cavern.create({ entrance: 'in the crook of a rock wall' })
const readout = lib.cavern.readout(cavern)
// @ts-ignore
const contents = lib.contentsFetcher(setup.misc[biome].cave, encounters)(town, biome)
return `a small cave. ${readout} <blockquote>The cave is home to ${contents}.</blockquote>`
}
},
{
summary: 'a small cave next to a dry river bed',
available: ['desert'],
function: (town, biome) => {
const cavern = lib.cavern.create()
const readout = lib.cavern.readout(cavern)
const encounter = getEventDescription(getEncounter(biome), town, biome)
return `a cavern. ${readout} <blockquote>The cavern is home to ${encounter}.</blockquote>`
}
},
// mining is intentionally using the mountain biome
{
summary: 'an old mine in a canyon',
available: ['mountain'],
function: () => {
// @ts-ignore
const miner = setup.misc.mountain.miners.random()
// @ts-ignore
const goal = setup.misc.mountain.minersGoal().random()
return `an old mine in a canyon <blockquote>The mine was built by by ${miner}, looking for ${goal}.</blockquote>`
}
},
{
summary: 'an active mining camp',
available: ['mountain'],
function: () => {
// @ts-ignore
const miners = setup.misc.mountain.miners.random()
// @ts-ignore
const goal = setup.misc.mountain.minersGoal().random()
return `an active mining camp, manned by ${miners}, looking for ${goal}`
}
},
{
summary: 'a hole under a large boulder',
available: ['desert'],
function: () => {
// @ts-ignore
const content = setup.misc.desert.hole.random()
return `a hole under a large boulder <blockquote> Inside is ${content}</blockquote>`
}
},
{
summary: 'an abandoned stone house',
available: ['desert'],
function: (town, biome) => {
// @ts-ignore
const lived = setup.misc[biome].houseLived.random()
// @ts-ignore
const encounter = lib.contentsFetcher(setup.misc[biome].houseLives, encounters)(town, biome)
const house = lib.createAutoTippy(lib.cabin, { material: 'stone', wordNoun: 'house' })('stone house')
return `an abandoned ${house}. <blockquote>${lived} once lived here. Now, ${encounter} lives here.</blockquote>`
}
},
{
summary: 'a stone house',
available: ['desert'],
function: (town, biome) => {
// @ts-ignore
const lived = setup.misc[biome].houseLived.random()
// @ts-ignore
const encounter = lib.contentsFetcher(setup.misc[biome].houseLives, encounters)(town, biome)
const house = lib.createAutoTippy(lib.cabin, { material: 'stone', wordNoun: 'house' })('stone house')
return `a ${house} sheltered by a ${['canyon', 'gorge', 'bluff'].random()} <blockquote>${lived} once lived here. Now, ${encounter} lives here.</blockquote>`
}
},
{
summary: "a merchant caravan's camp",
available: ['mountain', 'desert', 'road', 'forest'],
function: (town) => {
// @ts-ignore
const caravan = setup.misc.caravan.create(town)
return `a merchant caravan's camp. ${caravan.readout}`
}
},
{
summary: 'a peculiar tent',
available: ['mountain', 'desert', 'road', 'forest'],
function: () => {
const lived = ['a party of orc scouts', 'a goblin raiding party', 'some miners or prospectors', 'some elves', 'some refugees or fugitives', 'someone whose purposes are unclear', 'someone who left in an awful hurry']
return `a peculiar tent, which looks to have been occupied previously by ${lived.random()}`
}
},
{
summary: 'an old watchtower',
available: ['mountain', 'desert', 'road', 'forest'],
function: (town, biome) => {
// intentionally uses the mountain biome
// @ts-ignore
const encounter = lib.contentsFetcher(setup.misc.mountain.watchtowerLives, encounters)(town, biome)
// @ts-ignore
return `an old, weathered watchtower. <blockquote>The watchtower was built by ${setup.misc.mountain.watchtowerBuilt.random()}. Now, it is controlled by ${encounter}.</blockquote>`
}
},
{
summary: 'an abandoned watchtower',
available: ['mountain', 'desert', 'road', 'forest'],
function: (town, biome) => {
// intentionally uses the mountain biome
// @ts-ignore
const encounter = lib.contentsFetcher(setup.misc.mountain.watchtowerLives, encounters)(town, biome)
// @ts-ignore
return `a run down, abandoned watchtower. <blockquote>The watchtower was built by ${setup.misc.mountain.watchtowerBuilt.random()}. Now, it is inhabited by ${encounter}.</blockquote>`
}
},
{
summary: 'a strategically located watchtower',
available: ['mountain', 'desert', 'road', 'forest'],
function: (town, biome) => {
// intentionally uses the mountain biome
// @ts-ignore
const encounter = lib.contentsFetcher(setup.misc.mountain.watchtowerLives, encounters)(town, biome)
// @ts-ignore
return `a strategically located watchtower. <blockquote>The watchtower was built by ${setup.misc.mountain.watchtowerBuilt.random()}. Now, it is controlled by ${encounter}.</blockquote>`
}
},
{
summary: 'ruins of an ancient city',
available: ['desert'],
function: (town, biome) => {
// @ts-ignore
const encounter = lib.contentsFetcher(setup.misc[biome].ruinsLives, encounters)(town, biome)
// intentionally uses forest
// @ts-ignore
return `ruins of an ancient city. <blockquote>The city was built by ${setup.misc.forest.ruinsLived.random()} Now, ${encounter} lives here.</blockquote>`
}
},
{
summary: 'a temple ruin',
available: ['desert'],
function: (town, biome) => {
// @ts-ignore
const encounter = lib.contentsFetcher(setup.misc[biome].ruinsLives, encounters)(town, biome)
// intentionally uses forest
// @ts-ignore
return `a temple ruin. <blockquote>The city was built by ${setup.misc.forest.ruinsLived.random()} Now, ${encounter} lives here.</blockquote>`
}
},
{
summary: 'an isolated monastery',
available: ['mountain'],
function: (_, biome) => {
// @ts-ignore
const lives = setup.misc[biome].religionLives.random()
return `an isolated monastery. <blockquote>Living inside lives ${lives}, hiding from the outside world.</blockquote>`
}
},
{
summary: 'a remote temple',
available: ['mountain'],
function: (_, biome) => {
// @ts-ignore
const lives = setup.misc[biome].religionLives.random()
return `a remote temple. <blockquote>Far from any civilization, this temple is home to ${lives} who have gone to great measures to hide their existence.</blockquote>`
}
},
{
summary: 'an ancient temple',
available: ['mountain'],
function: (_, biome) => {
// @ts-ignore
const lives = setup.misc[biome].religionLives.random()
return `an incredibly ancient temple. <blockquote>This ancient place has housed many things, but it is currently home to ${lives}.</blockquote>`
}
},
{
summary: 'a ruined monastery',
available: ['forest'],
function: (town, biome) => {
// @ts-ignore
const encounter = lib.contentsFetcher(setup.misc[biome].ruinsLives, encounters)(town, biome)
return `a ruined monastery. <blockquote>These ruins are currently occupied by ${encounter}.</blockquote>`
}
},
{
summary: 'a village of primitive canyon dwellers',
available: ['mountain']
},
{
summary: "some nomad's camp",
available: ['mountain', 'desert']
},
{
summary: 'an ancient tomb',
available: ['desert']
},
{
summary: 'a dark tunnel leading under the mountain',
available: ['mountain']
},
{
summary: 'a tunnel in a cliff face',
available: ['mountain']
},
{
summary: 'a tunnel leading into an abandoned mine',
available: ['mountain']
},
{
summary: 'the nest of an enormous bird',
available: ['mountain', 'forest']
},
{
summary: 'a poorly marked grave or tomb',
available: ['mountain', 'forest', 'desert', 'road'],
function: (town) => {
const grave = setup.graveStone.create(town)
return grave.sentenceStrings
}
}
] | the_stack |
import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams,
HttpResponse, HttpEvent, HttpParameterCodec } from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
import { LoopbackCount } from '../model/loopbackCount';
import { User } from '../model/user';
import { UserCredentials } from '../model/userCredentials';
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
@Injectable({
providedIn: 'root'
})
export class UserControllerService {
protected basePath = 'http://localhost:3000';
public defaultHeaders = new HttpHeaders();
public configuration = new Configuration();
public encoder: HttpParameterCodec;
constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) {
if (configuration) {
this.configuration = configuration;
}
if (typeof this.configuration.basePath !== 'string') {
if (typeof basePath !== 'string') {
basePath = this.basePath;
}
this.configuration.basePath = basePath;
}
this.encoder = this.configuration.encoder || new CustomHttpParameterCodec();
}
/**
* @param where
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public userControllerCount(where?: { [key: string]: object; }, observe?: 'body', reportProgress?: boolean): Observable<LoopbackCount>;
public userControllerCount(where?: { [key: string]: object; }, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<LoopbackCount>>;
public userControllerCount(where?: { [key: string]: object; }, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<LoopbackCount>>;
public userControllerCount(where?: { [key: string]: object; }, observe: any = 'body', reportProgress: boolean = false ): Observable<any> {
let queryParameters = new HttpParams({encoder: this.encoder});
if (where !== undefined && where !== null) {
queryParameters = queryParameters.set('where', <any>where);
}
let headers = this.defaultHeaders;
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts);
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
return this.httpClient.get<LoopbackCount>(`${this.configuration.basePath}/users/count`,
{
params: queryParameters,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* @param requestBody
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public userControllerCreate(requestBody?: { [key: string]: object; }, observe?: 'body', reportProgress?: boolean): Observable<UserCredentials>;
public userControllerCreate(requestBody?: { [key: string]: object; }, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<UserCredentials>>;
public userControllerCreate(requestBody?: { [key: string]: object; }, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<UserCredentials>>;
public userControllerCreate(requestBody?: { [key: string]: object; }, observe: any = 'body', reportProgress: boolean = false ): Observable<any> {
let headers = this.defaultHeaders;
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts);
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
headers = headers.set('Content-Type', httpContentTypeSelected);
}
return this.httpClient.post<User>(`${this.configuration.basePath}/user`,
requestBody,
{
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* @param id
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public userControllerDeleteById(id: string, observe?: 'body', reportProgress?: boolean): Observable<any>;
public userControllerDeleteById(id: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<any>>;
public userControllerDeleteById(id: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<any>>;
public userControllerDeleteById(id: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> {
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling patientControllerDeleteById.');
}
let headers = this.defaultHeaders;
// to determine the Accept header
const httpHeaderAccepts: string[] = [
];
const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts);
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
return this.httpClient.delete<any>(`${this.configuration.basePath}/users/${encodeURIComponent(String(id))}`,
{
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* @param filter
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public userControllerFind(filter?: object, observe?: 'body', reportProgress?: boolean): Observable<Array<User>>;
public userControllerFind(filter?: object, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<Array<User>>>;
public userControllerFind(filter?: object, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<Array<User>>>;
public userControllerFind(filter?: object, observe: any = 'body', reportProgress: boolean = false ): Observable<any> {
let queryParameters = new HttpParams({encoder: this.encoder});
if (filter !== undefined && filter !== null) {
queryParameters = queryParameters.set('filter', <any>filter);
}
let headers = this.defaultHeaders;
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts);
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
return this.httpClient.get<Array<UserCredentials>>(`${this.configuration.basePath}/user`,
{
params: queryParameters,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* @param id
* @param filter
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public userControllerFindById(id: string, filter?: object, observe?: 'body', reportProgress?: boolean): Observable<User>;
public userControllerFindById(id: string, filter?: object, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<User>>;
public userControllerFindById(id: string, filter?: object, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<User>>;
public userControllerFindById(id: string, filter?: object, observe: any = 'body', reportProgress: boolean = false ): Observable<any> {
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling userControllerFindById.');
}
let queryParameters = new HttpParams({encoder: this.encoder});
if (filter !== undefined && filter !== null) {
queryParameters = queryParameters.set('filter', <any>filter);
}
let headers = this.defaultHeaders;
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts);
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
return this.httpClient.get<UserCredentials>(`${this.configuration.basePath}/users/${encodeURIComponent(String(id))}`,
{
params: queryParameters,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* @param id
* @param requestBody
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public userControllerReplaceById(id: string, requestBody?: { [key: string]: object; }, observe?: 'body', reportProgress?: boolean): Observable<any>;
public userControllerReplaceById(id: string, requestBody?: { [key: string]: object; }, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<any>>;
public userControllerReplaceById(id: string, requestBody?: { [key: string]: object; }, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<any>>;
public userControllerReplaceById(id: string, requestBody?: { [key: string]: object; }, observe: any = 'body', reportProgress: boolean = false ): Observable<any> {
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling userControllerReplaceById.');
}
let headers = this.defaultHeaders;
// to determine the Accept header
const httpHeaderAccepts: string[] = [
];
const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts);
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
headers = headers.set('Content-Type', httpContentTypeSelected);
}
return this.httpClient.put<any>(`${this.configuration.basePath}/users/${encodeURIComponent(String(id))}`,
requestBody,
{
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* @param where
* @param requestBody
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public userControllerUpdateAll(where?: { [key: string]: object; }, requestBody?: { [key: string]: object; }, observe?: 'body', reportProgress?: boolean): Observable<LoopbackCount>;
public userControllerUpdateAll(where?: { [key: string]: object; }, requestBody?: { [key: string]: object; }, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<LoopbackCount>>;
public userControllerUpdateAll(where?: { [key: string]: object; }, requestBody?: { [key: string]: object; }, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<LoopbackCount>>;
public userControllerUpdateAll(where?: { [key: string]: object; }, requestBody?: { [key: string]: object; }, observe: any = 'body', reportProgress: boolean = false ): Observable<any> {
let queryParameters = new HttpParams({encoder: this.encoder});
if (where !== undefined && where !== null) {
queryParameters = queryParameters.set('where', <any>where);
}
let headers = this.defaultHeaders;
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts);
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
headers = headers.set('Content-Type', httpContentTypeSelected);
}
return this.httpClient.patch<LoopbackCount>(`${this.configuration.basePath}/patients`,
requestBody,
{
params: queryParameters,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* @param id
* @param requestBody
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public userControllerUpdateById(id: string, requestBody?: { [key: string]: object; }, observe?: 'body', reportProgress?: boolean): Observable<any>;
public userControllerUpdateById(id: string, requestBody?: { [key: string]: object; }, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<any>>;
public userControllerUpdateById(id: string, requestBody?: { [key: string]: object; }, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<any>>;
public userControllerUpdateById(id: string, requestBody?: { [key: string]: object; }, observe: any = 'body', reportProgress: boolean = false ): Observable<any> {
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling userControllerUpdateById.');
}
let headers = this.defaultHeaders;
// to determine the Accept header
const httpHeaderAccepts: string[] = [
];
const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts);
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
headers = headers.set('Content-Type', httpContentTypeSelected);
}
return this.httpClient.patch<any>(`${this.configuration.basePath}/users/${encodeURIComponent(String(id))}`,
requestBody,
{
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
} | the_stack |
import { ClaimsIdentity } from 'botframework-connector';
import { STATUS_CODES } from 'http';
import { StatusCodeError } from './statusCodeError';
import {
Activity,
AttachmentData,
ChannelAccount,
ConversationParameters,
ConversationResourceResponse,
ConversationsResult,
PagedMembersResult,
ResourceResponse,
StatusCodes,
Transcript,
} from 'botbuilder-core';
/**
* The ChannelServiceHandlerBase implements API to forward activity to a skill and
* implements routing ChannelAPI calls from the Skill up through the bot/adapter.
*/
export abstract class ChannelServiceHandlerBase {
/**
* Sends an [Activity](xref:botframework-schema.Activity) to the end of a conversation.
*
* @param authHeader The authentication header.
* @param conversationId The conversation Id.
* @param activity The [Activity](xref:botframework-schema.Activity) to send.
* @returns A `Promise` representing the [ResourceResponse](xref:botframework-schema.ResourceResponse) for the operation.
*/
async handleSendToConversation(
authHeader: string,
conversationId: string,
activity: Activity
): Promise<ResourceResponse> {
const claimsIdentity = await this.authenticate(authHeader);
return this.onSendToConversation(claimsIdentity, conversationId, activity);
}
/**
* Sends a reply to an [Activity](xref:botframework-schema.Activity).
*
* @param authHeader The authentication header.
* @param conversationId The conversation Id.
* @param activityId The activity Id the reply is to.
* @param activity The [Activity](xref:botframework-schema.Activity) to send.
* @returns A `Promise` representing the [ResourceResponse](xref:botframework-schema.ResourceResponse) for the operation.
*/
async handleReplyToActivity(
authHeader: string,
conversationId: string,
activityId: string,
activity: Activity
): Promise<ResourceResponse> {
const claimsIdentity = await this.authenticate(authHeader);
return this.onReplyToActivity(claimsIdentity, conversationId, activityId, activity);
}
/**
* Edits a previously sent existing [Activity](xref:botframework-schema.Activity).
*
* @param authHeader The authentication header.
* @param conversationId The conversation Id.
* @param activityId The activity Id to update.
* @param activity The replacement [Activity](xref:botframework-schema.Activity).
* @returns A `Promise` representing the [ResourceResponse](xref:botframework-schema.ResourceResponse) for the operation.
*/
async handleUpdateActivity(
authHeader: string,
conversationId: string,
activityId: string,
activity: Activity
): Promise<ResourceResponse> {
const claimsIdentity = await this.authenticate(authHeader);
return this.onUpdateActivity(claimsIdentity, conversationId, activityId, activity);
}
/**
* Deletes an existing [Activity](xref:botframework-schema.Activity).
*
* @param authHeader The authentication header.
* @param conversationId The conversation Id.
* @param activityId The activity Id to delete.
*/
async handleDeleteActivity(authHeader: string, conversationId: string, activityId: string): Promise<void> {
const claimsIdentity = await this.authenticate(authHeader);
await this.onDeleteActivity(claimsIdentity, conversationId, activityId);
}
/**
* Enumerates the members of an [Activity](xref:botframework-schema.Activity).
*
* @param authHeader The authentication header.
* @param conversationId The conversation Id.
* @param activityId The activity Id.
* @returns The enumerated [ChannelAccount](xref:botframework-schema.ChannelAccount) list.
*/
async handleGetActivityMembers(
authHeader: string,
conversationId: string,
activityId: string
): Promise<ChannelAccount[]> {
const claimsIdentity = await this.authenticate(authHeader);
return this.onGetActivityMembers(claimsIdentity, conversationId, activityId);
}
/**
* Creates a new Conversation.
*
* @param authHeader The authentication header.
* @param parameters [ConversationParameters](xref:botbuilder-core.ConversationParameters) to create the conversation from.
* @returns A `Promise` representation for the operation.
*/
async handleCreateConversation(
authHeader: string,
parameters: ConversationParameters
): Promise<ConversationResourceResponse> {
const claimsIdentity = await this.authenticate(authHeader);
return this.onCreateConversation(claimsIdentity, parameters);
}
/**
* Lists the Conversations in which the bot has participated.
*
* @param authHeader The authentication header.
* @param conversationId The conversation Id.
* @param continuationToken A skip or continuation token.
* @returns A `Promise` representation for the operation.
*/
async handleGetConversations(
authHeader: string,
conversationId: string,
continuationToken?: string /* some default */
): Promise<ConversationsResult> {
const claimsIdentity = await this.authenticate(authHeader);
return this.onGetConversations(claimsIdentity, conversationId, continuationToken);
}
/**
* Enumerates the members of a conversation.
*
* @param authHeader The authentication header.
* @param conversationId The conversation Id.
* @returns The enumerated [ChannelAccount](xref:botframework-schema.ChannelAccount) list.
*/
async handleGetConversationMembers(authHeader: string, conversationId: string): Promise<ChannelAccount[]> {
const claimsIdentity = await this.authenticate(authHeader);
return this.onGetConversationMembers(claimsIdentity, conversationId);
}
/**
* Enumerates the members of a conversation one page at a time.
*
* @param authHeader The authentication header.
* @param conversationId The conversation Id.
* @param pageSize Suggested page size.
* @param continuationToken A continuation token.
* @returns A `Promise` representing the [PagedMembersResult](xref:botframework-schema.PagedMembersResult) for the operation.
*/
async handleGetConversationPagedMembers(
authHeader: string,
conversationId: string,
pageSize = -1,
continuationToken?: string
): Promise<PagedMembersResult> {
const claimsIdentity = await this.authenticate(authHeader);
return this.onGetConversationPagedMembers(claimsIdentity, conversationId, pageSize, continuationToken);
}
/**
* Deletes a member from a conversation.
*
* @param authHeader The authentication header.
* @param conversationId The conversation Id.
* @param memberId Id of the member to delete from this conversation.
*/
async handleDeleteConversationMember(
authHeader: string,
conversationId: string,
memberId: string
): Promise<void> {
const claimsIdentity = await this.authenticate(authHeader);
await this.onDeleteConversationMember(claimsIdentity, conversationId, memberId);
}
/**
* Uploads the historic activities of the conversation.
*
* @param authHeader The authentication header.
* @param conversationId The conversation Id.
* @param transcript [Transcript](xref:botframework-schema.Transcript) of activities.
* @returns A `Promise` representing the [ResourceResponse](xref:botframework-schema.ResourceResponse) for the operation.
*/
async handleSendConversationHistory(
authHeader: string,
conversationId: string,
transcript: Transcript
): Promise<ResourceResponse> {
const claimsIdentity = await this.authenticate(authHeader);
return this.onSendConversationHistory(claimsIdentity, conversationId, transcript);
}
/**
* Stores data in a compliant store when dealing with enterprises.
*
* @param authHeader The authentication header.
* @param conversationId The conversation Id.
* @param attachmentUpload [AttachmentData](xref:botframework-schema.AttachmentData).
* @returns A `Promise` representing the [ResourceResponse](xref:botframework-schema.ResourceResponse) for the operation.
*/
async handleUploadAttachment(
authHeader: string,
conversationId: string,
attachmentUpload: AttachmentData
): Promise<ResourceResponse> {
const claimsIdentity = await this.authenticate(authHeader);
return this.onUploadAttachment(claimsIdentity, conversationId, attachmentUpload);
}
/**
* SendToConversation() API for Skill.
*
* @remarks
* This method allows you to send an activity to the end of a conversation.
* This is slightly different from ReplyToActivity().
* * SendToConversation(conversationId) - will append the activity to the end
* of the conversation according to the timestamp or semantics of the channel.
* * ReplyToActivity(conversationId,ActivityId) - adds the activity as a reply
* to another activity, if the channel supports it. If the channel does not
* support nested replies, ReplyToActivity falls back to SendToConversation.
*
* Use ReplyToActivity when replying to a specific activity in the
* conversation.
*
* Use SendToConversation in all other cases.
* @param _claimsIdentity ClaimsIdentity for the bot, should have AudienceClaim, AppIdClaim and ServiceUrlClaim.
* @param _conversationId Conversation identifier
* @param _activity Activity to send
*/
protected async onSendToConversation(
_claimsIdentity: ClaimsIdentity,
_conversationId: string,
_activity: Activity
): Promise<ResourceResponse> {
throw new StatusCodeError(
StatusCodes.NOT_IMPLEMENTED,
`ChannelServiceHandler.onSendToConversation(): ${StatusCodes.NOT_IMPLEMENTED}: ${
STATUS_CODES[StatusCodes.NOT_IMPLEMENTED]
}`
);
}
/**
* ReplyToActivity() API for Skill.
*
* @remarks
* This method allows you to reply to an activity.
*
* This is slightly different from SendToConversation().
* * SendToConversation(conversationId) - will append the activity to the end
* of the conversation according to the timestamp or semantics of the channel.
* * ReplyToActivity(conversationId,ActivityId) - adds the activity as a reply
* to another activity, if the channel supports it. If the channel does not
* support nested replies, ReplyToActivity falls back to SendToConversation.
*
* Use ReplyToActivity when replying to a specific activity in the
* conversation.
*
* Use SendToConversation in all other cases.
* @param _claimsIdentity ClaimsIdentity for the bot, should have AudienceClaim, AppIdClaim and ServiceUrlClaim.
* @param _conversationId Conversation ID.
* @param _activityId activityId the reply is to (OPTIONAL).
* @param _activity Activity to send.
*/
protected async onReplyToActivity(
_claimsIdentity: ClaimsIdentity,
_conversationId: string,
_activityId: string,
_activity: Activity
): Promise<ResourceResponse> {
throw new StatusCodeError(
StatusCodes.NOT_IMPLEMENTED,
`ChannelServiceHandler.onReplyToActivity(): ${StatusCodes.NOT_IMPLEMENTED}: ${
STATUS_CODES[StatusCodes.NOT_IMPLEMENTED]
}`
);
}
/**
* UpdateActivity() API for Skill.
*
* @remarks
* Edit an existing activity.
*
* Some channels allow you to edit an existing activity to reflect the new
* state of a bot conversation.
*
* For example, you can remove buttons after someone has clicked "Approve" button.
* @param _claimsIdentity ClaimsIdentity for the bot, should have AudienceClaim, AppIdClaim and ServiceUrlClaim.
* @param _conversationId Conversation ID.
* @param _activityId activityId to update.
* @param _activity replacement Activity.
*/
protected async onUpdateActivity(
_claimsIdentity: ClaimsIdentity,
_conversationId: string,
_activityId: string,
_activity: Activity
): Promise<ResourceResponse> {
throw new StatusCodeError(
StatusCodes.NOT_IMPLEMENTED,
`ChannelServiceHandler.onUpdateActivity(): ${StatusCodes.NOT_IMPLEMENTED}: ${
STATUS_CODES[StatusCodes.NOT_IMPLEMENTED]
}`
);
}
/**
* DeleteActivity() API for Skill.
*
* @remarks
* Delete an existing activity.
*
* Some channels allow you to delete an existing activity, and if successful
* this method will remove the specified activity.
*
*
* @param _claimsIdentity ClaimsIdentity for the bot, should have AudienceClaim, AppIdClaim and ServiceUrlClaim.
* @param _conversationId Conversation ID.
* @param _activityId activityId to delete.
*/
protected async onDeleteActivity(
_claimsIdentity: ClaimsIdentity,
_conversationId: string,
_activityId: string
): Promise<void> {
throw new StatusCodeError(
StatusCodes.NOT_IMPLEMENTED,
`ChannelServiceHandler.onDeleteActivity(): ${StatusCodes.NOT_IMPLEMENTED}: ${
STATUS_CODES[StatusCodes.NOT_IMPLEMENTED]
}`
);
}
/**
* GetActivityMembers() API for Skill.
*
* @remarks
* Enumerate the members of an activity.
*
* This REST API takes a ConversationId and a ActivityId, returning an array
* of ChannelAccount objects representing the members of the particular
* activity in the conversation.
* @param _claimsIdentity ClaimsIdentity for the bot, should have AudienceClaim, AppIdClaim and ServiceUrlClaim.
* @param _conversationId Conversation ID.
* @param _activityId Activity ID.
*/
protected async onGetActivityMembers(
_claimsIdentity: ClaimsIdentity,
_conversationId: string,
_activityId: string
): Promise<ChannelAccount[]> {
throw new StatusCodeError(
StatusCodes.NOT_IMPLEMENTED,
`ChannelServiceHandler.onGetActivityMembers(): ${StatusCodes.NOT_IMPLEMENTED}: ${
STATUS_CODES[StatusCodes.NOT_IMPLEMENTED]
}`
);
}
/**
* CreateConversation() API for Skill.
*
* @remarks
* Create a new Conversation.
*
* POST to this method with a
* * Bot being the bot creating the conversation
* * IsGroup set to true if this is not a direct message (default is false)
* * Array containing the members to include in the conversation
*
* The return value is a ResourceResponse which contains a conversation id
* which is suitable for use in the message payload and REST API uris.
*
* Most channels only support the semantics of bots initiating a direct
* message conversation.
*
* @param _claimsIdentity ClaimsIdentity for the bot, should have AudienceClaim, AppIdClaim and ServiceUrlClaim.
* @param _parameters Parameters to create the conversation from.
*/
protected async onCreateConversation(
_claimsIdentity: ClaimsIdentity,
_parameters: ConversationParameters
): Promise<ConversationResourceResponse> {
throw new StatusCodeError(
StatusCodes.NOT_IMPLEMENTED,
`ChannelServiceHandler.onCreateConversation(): ${StatusCodes.NOT_IMPLEMENTED}: ${
STATUS_CODES[StatusCodes.NOT_IMPLEMENTED]
}`
);
}
/**
* onGetConversations() API for Skill.
*
* @remarks
* List the Conversations in which this bot has participated.
*
* GET from this method with a skip token
*
* The return value is a ConversationsResult, which contains an array of
* ConversationMembers and a skip token. If the skip token is not empty, then
* there are further values to be returned. Call this method again with the
* returned token to get more values.
*
* Each ConversationMembers object contains the ID of the conversation and an
* array of ChannelAccounts that describe the members of the conversation.
*
* @param _claimsIdentity ClaimsIdentity for the bot, should have AudienceClaim, AppIdClaim and ServiceUrlClaim.
* @param _conversationId Conversation ID.
* @param _continuationToken Skip or continuation token.
*/
protected async onGetConversations(
_claimsIdentity: ClaimsIdentity,
_conversationId: string,
_continuationToken?: string
): Promise<ConversationsResult> {
throw new StatusCodeError(
StatusCodes.NOT_IMPLEMENTED,
`ChannelServiceHandler.onGetConversations(): ${StatusCodes.NOT_IMPLEMENTED}: ${
STATUS_CODES[StatusCodes.NOT_IMPLEMENTED]
}`
);
}
/**
* getConversationMembers() API for Skill.
*
* @remarks
* Enumerate the members of a conversation.
*
* This REST API takes a ConversationId and returns an array of ChannelAccount
* objects representing the members of the conversation.
* @param _claimsIdentity ClaimsIdentity for the bot, should have AudienceClaim, AppIdClaim and ServiceUrlClaim.
* @param _conversationId Conversation ID.
*/
protected async onGetConversationMembers(
_claimsIdentity: ClaimsIdentity,
_conversationId: string
): Promise<ChannelAccount[]> {
throw new StatusCodeError(
StatusCodes.NOT_IMPLEMENTED,
`ChannelServiceHandler.onGetConversationMembers(): ${StatusCodes.NOT_IMPLEMENTED}: ${
STATUS_CODES[StatusCodes.NOT_IMPLEMENTED]
}`
);
}
/**
* getConversationPagedMembers() API for Skill.
*
* @remarks
* Enumerate the members of a conversation one page at a time.
*
* This REST API takes a ConversationId. Optionally a pageSize and/or
* continuationToken can be provided. It returns a PagedMembersResult, which
* contains an array
* of ChannelAccounts representing the members of the conversation and a
* continuation token that can be used to get more values.
*
* One page of ChannelAccounts records are returned with each call. The number
* of records in a page may vary between channels and calls. The pageSize
* parameter can be used as
* a suggestion. If there are no additional results the response will not
* contain a continuation token. If there are no members in the conversation
* the Members will be empty or not present in the response.
*
* A response to a request that has a continuation token from a prior request
* may rarely return members from a previous request.
* @param _claimsIdentity ClaimsIdentity for the bot, should have AudienceClaim, AppIdClaim and ServiceUrlClaim.
* @param _conversationId Conversation ID.
* @param _pageSize Suggested page size.
* @param _continuationToken Continuation Token.
*/
protected async onGetConversationPagedMembers(
_claimsIdentity: ClaimsIdentity,
_conversationId: string,
_pageSize = -1,
_continuationToken?: string
): Promise<PagedMembersResult> {
throw new StatusCodeError(
StatusCodes.NOT_IMPLEMENTED,
`ChannelServiceHandler.onGetConversationPagedMembers(): ${StatusCodes.NOT_IMPLEMENTED}: ${
STATUS_CODES[StatusCodes.NOT_IMPLEMENTED]
}`
);
}
/**
* DeleteConversationMember() API for Skill.
*
* @remarks
* Deletes a member from a conversation.
*
* This REST API takes a ConversationId and a memberId (of type string) and
* removes that member from the conversation. If that member was the last member
* of the conversation, the conversation will also be deleted.
* @param _claimsIdentity ClaimsIdentity for the bot, should have AudienceClaim, AppIdClaim and ServiceUrlClaim.
* @param _conversationId Conversation ID.
* @param _memberId ID of the member to delete from this conversation.
*/
protected async onDeleteConversationMember(
_claimsIdentity: ClaimsIdentity,
_conversationId: string,
_memberId: string
): Promise<void> {
throw new StatusCodeError(
StatusCodes.NOT_IMPLEMENTED,
`ChannelServiceHandler.onDeleteConversationMember(): ${StatusCodes.NOT_IMPLEMENTED}: ${
STATUS_CODES[StatusCodes.NOT_IMPLEMENTED]
}`
);
}
/**
* SendConversationHistory() API for Skill.
*
* @remarks
* This method allows you to upload the historic activities to the
* conversation.
*
* Sender must ensure that the historic activities have unique ids and
* appropriate timestamps. The ids are used by the client to deal with
* duplicate activities and the timestamps are used by the client to render
* the activities in the right order.
* @param _claimsIdentity ClaimsIdentity for the bot, should have AudienceClaim, AppIdClaim and ServiceUrlClaim.
* @param _conversationId Conversation ID.
* @param _transcript Transcript of activities.
*/
protected async onSendConversationHistory(
_claimsIdentity: ClaimsIdentity,
_conversationId: string,
_transcript: Transcript
): Promise<ResourceResponse> {
throw new StatusCodeError(
StatusCodes.NOT_IMPLEMENTED,
`ChannelServiceHandler.onSendConversationHistory(): ${StatusCodes.NOT_IMPLEMENTED}: ${
STATUS_CODES[StatusCodes.NOT_IMPLEMENTED]
}`
);
}
/**
* UploadAttachment() API for Skill.
*
* @remarks
* Upload an attachment directly into a channel's blob storage.
*
* This is useful because it allows you to store data in a compliant store
* when dealing with enterprises.
*
* The response is a ResourceResponse which contains an AttachmentId which is
* suitable for using with the attachments API.
* @param _claimsIdentity ClaimsIdentity for the bot, should have AudienceClaim, AppIdClaim and ServiceUrlClaim.
* @param _conversationId Conversation ID.
* @param _attachmentUpload Attachment data.
*/
protected async onUploadAttachment(
_claimsIdentity: ClaimsIdentity,
_conversationId: string,
_attachmentUpload: AttachmentData
): Promise<ResourceResponse> {
throw new StatusCodeError(
StatusCodes.NOT_IMPLEMENTED,
`ChannelServiceHandler.onUploadAttachment(): ${StatusCodes.NOT_IMPLEMENTED}: ${
STATUS_CODES[StatusCodes.NOT_IMPLEMENTED]
}`
);
}
/**
* Helper to authenticate the header token and extract the claims.
*
* @param authHeader HTTP authorization header
* @returns a promise resolving to the authorization header claims
*/
protected abstract authenticate(authHeader: string): Promise<ClaimsIdentity>;
} | the_stack |
import { Observable, forkJoin, from, OperatorFunction, of } from 'rxjs';
import { RequestApiHelper, RequestApiHelperOptions } from './request-api.helper';
import { map, concatMap, flatMap } from 'rxjs/operators';
import { ModelApiInterface } from '../../api/generalmodel-api.interface';
import { Model, MinimalModelSummary, ModelScope, FetchQueries, ServerSideSorting } from '../../api/types';
import { createBlobFormDataFromStringContent, createBlobFormData } from '../../helpers/utils/createJsonBlob';
import { PaginatedEntries } from '@alfresco/js-api';
export interface ModelResponse<T extends Model> {
entry: T;
}
export interface ModelsResponse<T extends Model> {
list: {
entries: ModelResponse<T>[]
};
}
export interface ModelApiVariation<M extends MinimalModelSummary, C> {
readonly contentType: string;
readonly retrieveModelAfterUpdate: boolean;
serialize(content: Partial<C>): string;
createInitialMetadata(model: Partial<MinimalModelSummary>): Partial<M>;
createInitialContent(model: M): C;
createSummaryPatch(model: Partial<M>, content: Partial<C>): MinimalModelSummary;
patchModel(model: Partial<M>): M;
getFileToUpload(model: Partial<M>, content: Partial<C>): Blob;
getModelMimeType(model: Partial<M>): string;
getModelFileName(model: Partial<M>): string;
}
export class ModelApi<T extends Model, S> implements ModelApiInterface<T, S> {
constructor(protected modelVariation: ModelApiVariation<T, S>, protected requestApiHelper: RequestApiHelper) { }
public getList(containerId: string): Observable<T[]> {
return this.requestApiHelper
.get<ModelsResponse<T>>(
`/modeling-service/v1/projects/${containerId}/models`,
{ queryParams: { type: this.modelVariation.contentType, maxItems: 1000 } })
.pipe(
map((nodePaging) => {
return nodePaging.list.entries
.map(entry => entry.entry)
.map((entry) => this.createEntity(entry, containerId));
})
);
}
public create(model: Partial<MinimalModelSummary>, containerId: string): Observable<T> {
return this.requestApiHelper
.post<ModelResponse<T>>(
`/modeling-service/v1/projects/${containerId}/models`,
{ bodyParam: { ...this.modelVariation.createInitialMetadata(model), type: this.modelVariation.contentType } })
.pipe(
map(response => response.entry),
concatMap(createdEntity => {
// Patch: BE does not return the description...
const createdEntityWithDescription: T = <T>{
description: model.description,
...<object>createdEntity
};
return this.updateContent(createdEntityWithDescription, this.modelVariation.createInitialContent(createdEntityWithDescription));
}),
map(createdEntity => this.createEntity(createdEntity, containerId))
);
}
public retrieve(modelId: string, containerId: string, queryParams?: any): Observable<T> {
return this.requestApiHelper
.get<ModelResponse<T>>(
`/modeling-service/v1/models/${modelId}`,
{ queryParams: queryParams })
.pipe(
map(response => this.createEntity(response.entry, containerId))
);
}
public update(modelId: string, model: Partial<T>, content: S, containerId: string, ignoreContent?: boolean): Observable<T> {
const summary = this.modelVariation.createSummaryPatch(model, content);
return this.requestApiHelper
// It is supposed to be a patch, rather than a put. Waiting for BE to implement it...
.put<ModelResponse<T>>(`/modeling-service/v1/models/${modelId}`, { bodyParam: summary })
.pipe(
concatMap(response => ignoreContent ? of(response.entry) : this.updateContent(response.entry, content)),
map(updatedEntity => this.createEntity(updatedEntity, containerId))
);
}
private updateContent(model: T, content: Partial<S>): Observable<T> {
const file = createBlobFormData(this.modelVariation.getFileToUpload(model, content), this.modelVariation.getModelFileName(model));
const requestOptions: RequestApiHelperOptions = {
formParams: { file },
queryParams: { type: this.modelVariation.contentType },
contentTypes: ['multipart/form-data']
};
return this.requestApiHelper
.put<void>(`/modeling-service/v1/models/${model.id}/content`, requestOptions)
.pipe(this.getUpdateOperator(model));
}
private getUpdateOperator(model: T): OperatorFunction<void, T> {
if (this.modelVariation.retrieveModelAfterUpdate) {
return flatMap(() => this.retrieve(model.id, model.id));
} else {
return map(() => model);
}
}
public delete(modelId: string): Observable<void> {
return this.requestApiHelper
.delete(`/modeling-service/v1/models/${modelId}`);
}
public validate(modelId: string, content: S, containerId: string, modelExtensions?: any, validateUsage?: boolean): Observable<any> {
const requestOptions: RequestApiHelperOptions = {
queryParams: { projectId: containerId, validateUsage },
formParams: { file: new Blob([this.modelVariation.serialize(content)], { type: 'text/plain' }) },
contentTypes: ['multipart/form-data']
};
if (modelExtensions) {
return this.requestApiHelper
.post(`/modeling-service/v1/models/${modelId}/validate`, requestOptions).pipe(
concatMap(() => this.validateModelExtensions(modelId, modelExtensions))
);
} else {
return this.requestApiHelper
.post(`/modeling-service/v1/models/${modelId}/validate`, requestOptions);
}
}
private validateModelExtensions(modelId: string, modelExtensions: string) {
const requestOptions: RequestApiHelperOptions = {
formParams: {
file: createBlobFormDataFromStringContent(modelExtensions, `${modelId}-extensions.json`)
},
contentTypes: ['multipart/form-data']
};
return from(this.requestApiHelper
.post(`/modeling-service/v1/models/${modelId}/validate/extensions`, requestOptions));
}
public import(file: File, containerId: string): Observable<T> {
const requestOptions: RequestApiHelperOptions = {
formParams: { file },
queryParams: { type: this.modelVariation.contentType },
contentTypes: ['multipart/form-data']
};
return this.requestApiHelper
.post<ModelResponse<T>>(`/modeling-service/v1/projects/${containerId}/models/import`, requestOptions)
.pipe(
map(response => this.createEntity(response.entry, containerId))
);
}
public export(modelId: string, responseType?: 'arraybuffer' | 'blob' | 'document' | 'json' | 'text'): Observable<S> {
const requestOptions: RequestApiHelperOptions = {
responseType: responseType
};
return this.requestApiHelper.get<S>(`/modeling-service/v1/models/${modelId}/content`, requestOptions);
}
private createEntity(entity: Partial<T>, containerId: string): T {
return {
description: '',
version: '0.0.1',
// Patch: BE does not return empty or not yet defined properties at all, like extensions
...(this.modelVariation.patchModel(entity) as object)
} as T;
}
updateContentFile(modelId: string, file: File, responseType?: 'arraybuffer' | 'blob' | 'document' | 'json' | 'text'): Observable<[T, S]> {
const requestOptions: RequestApiHelperOptions = {
formParams: { file },
queryParams: { type: this.modelVariation.contentType },
contentTypes: ['multipart/form-data']
};
return this.requestApiHelper
.put<void>(`/modeling-service/v1/models/${modelId}/content`, requestOptions).pipe(
flatMap(() => {
const content$ = this.export(modelId, responseType),
model$ = this.retrieve(modelId, modelId);
return forkJoin(model$, content$);
})
);
}
addProjectModelRelationship(containerId: string, modelId: string, scope?: ModelScope, force?: boolean): Observable<T> {
return this.requestApiHelper
.put<ModelResponse<T>>(
`/modeling-service/v1/projects/${containerId}/models/${modelId}`,
{ queryParams: { scope, force } })
.pipe(
map(response => this.createEntity(response.entry, containerId))
);
}
deleteProjectModelRelationship(containerId: string, modelId: string): Observable<T> {
return this.requestApiHelper
.delete<ModelResponse<T>>(
`/modeling-service/v1/projects/${containerId}/models/${modelId}`)
.pipe(
map(response => this.createEntity(response.entry, containerId))
);
}
public getGlobalModels(
includeOrphans?: boolean,
fetchQueries: FetchQueries = { maxItems: 1000 },
sorting: ServerSideSorting = { key: 'name', direction: 'asc' }): Observable<PaginatedEntries<T>> {
const queryParams = {
...fetchQueries,
sort: `${sorting.key},${sorting.direction}`,
type: this.modelVariation.contentType,
includeOrphans: includeOrphans ? includeOrphans : false
};
return this.requestApiHelper
.get<ModelsResponse<T>>(
`/modeling-service/v1/models`, { queryParams })
.pipe(
map((nodePaging: any) => {
return {
pagination: nodePaging.list.pagination,
entries: nodePaging.list.entries.map(entry => this.createEntity(entry.entry, null))
};
})
);
}
public createGlobalModel(model: Partial<MinimalModelSummary>): Observable<T> {
return this.requestApiHelper
.post<ModelResponse<T>>(
`/modeling-service/v1/models`,
{ bodyParam: { ...this.modelVariation.createInitialMetadata(model), type: this.modelVariation.contentType, scope: ModelScope.GLOBAL } })
.pipe(
map(response => response.entry),
concatMap(createdEntity => {
// Patch: BE does not return the description...
const createdEntityWithDescription: T = <T>{
description: model.description,
...<object>createdEntity
};
return this.updateContent(createdEntityWithDescription, this.modelVariation.createInitialContent(createdEntityWithDescription));
}),
map(createdEntity => this.createEntity(createdEntity, null))
);
}
} | the_stack |
import { getDefaultComponentOptions, getProjectFromWorkspace } from '@angular/cdk/schematics';
import { strings, template as interpolateTemplate } from '@angular-devkit/core';
import { ProjectDefinition } from '@angular-devkit/core/src/workspace';
import {
apply,
applyTemplates,
branchAndMerge,
chain,
filter,
mergeWith,
move,
noop,
Rule,
SchematicsException,
Tree,
url
} from '@angular-devkit/schematics';
import { FileSystemSchematicContext } from '@angular-devkit/schematics/tools';
import { Schema as ComponentOptions, Style } from '@schematics/angular/component/schema';
import * as ts from '@schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript';
import {
addDeclarationToModule,
addExportToModule,
getDecoratorMetadata
} from '@schematics/angular/utility/ast-utils';
import { InsertChange } from '@schematics/angular/utility/change';
import { buildRelativePath, findModuleFromOptions } from '@schematics/angular/utility/find-module';
import { parseName } from '@schematics/angular/utility/parse-name';
import { validateHtmlSelector, validateName } from '@schematics/angular/utility/validation';
import { getWorkspace } from '@schematics/angular/utility/workspace';
import { ProjectType } from '@schematics/angular/utility/workspace-models';
import { readFileSync, statSync } from 'fs';
import { dirname, join, resolve } from 'path';
function findClassDeclarationParent(node: ts.Node): ts.ClassDeclaration|undefined {
if (ts.isClassDeclaration(node)) {
return node;
}
return node.parent && findClassDeclarationParent(node.parent);
}
function getFirstNgModuleName(source: ts.SourceFile): string|undefined {
// First, find the @NgModule decorators.
const ngModulesMetadata = getDecoratorMetadata(source, 'NgModule', '@angular/core');
if (ngModulesMetadata.length === 0) {
return undefined;
}
// Then walk parent pointers up the AST, looking for the ClassDeclaration parent of the NgModule
// metadata.
const moduleClass = findClassDeclarationParent(ngModulesMetadata[0]);
if (!moduleClass || !moduleClass.name) {
return undefined;
}
// Get the class name of the module ClassDeclaration.
return moduleClass.name.text;
}
export interface ZorroComponentOptions extends ComponentOptions {
classnameWithModule: boolean;
}
/**
* Build a default project path for generating.
*
* @param project The project to build the path for.
*/
function buildDefaultPath(project: ProjectDefinition): string {
const root = project.sourceRoot
? `/${project.sourceRoot}/`
: `/${project.root}/src/`;
const projectDirName = project.extensions.projectType === ProjectType.Application ? 'app' : 'lib';
return `${root}${projectDirName}`;
}
/**
* List of style extensions which are CSS compatible. All supported CLI style extensions can be
* found here: angular/angular-cli/master/packages/schematics/angular/ng-new/schema.json#L118-L122
*/
const supportedCssExtensions = [ 'css', 'scss', 'sass', 'less' ];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function readIntoSourceFile(host: Tree, modulePath: string): any {
const text = host.read(modulePath);
if (text === null) {
throw new SchematicsException(`File ${modulePath} does not exist.`);
}
return ts.createSourceFile(modulePath, text.toString('utf-8'), ts.ScriptTarget.Latest, true);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function getModuleClassnamePrefix(source: any): string {
const className = getFirstNgModuleName(source);
if (className) {
const execArray = /(\w+)Module/gi.exec(className);
return execArray?.[1] ?? null;
} else {
return null;
}
}
function addDeclarationToNgModule(options: ZorroComponentOptions): Rule {
return (host: Tree) => {
if (options.skipImport || !options.module) {
return host;
}
const modulePath = options.module;
let source = readIntoSourceFile(host, modulePath);
const componentPath = `/${options.path}/${options.flat ? '' : `${strings.dasherize(options.name) }/`}${strings.dasherize(options.name)}.component`;
const relativePath = buildRelativePath(modulePath, componentPath);
let classifiedName = strings.classify(`${options.name}Component`);
if (options.classnameWithModule) {
const modulePrefix = getModuleClassnamePrefix(source);
if (modulePrefix) {
classifiedName = `${modulePrefix}${classifiedName}`
}
}
const declarationChanges = addDeclarationToModule(
source,
modulePath,
classifiedName,
relativePath
);
const declarationRecorder = host.beginUpdate(modulePath);
for (const change of declarationChanges) {
if (change instanceof InsertChange) {
declarationRecorder.insertLeft(change.pos, change.toAdd);
}
}
host.commitUpdate(declarationRecorder);
if (options.export) {
// Need to refresh the AST because we overwrote the file in the host.
source = readIntoSourceFile(host, modulePath);
const exportRecorder = host.beginUpdate(modulePath);
const exportChanges = addExportToModule(
source,
modulePath,
strings.classify(`${options.name}Component`),
relativePath
);
for (const change of exportChanges) {
if (change instanceof InsertChange) {
exportRecorder.insertLeft(change.pos, change.toAdd);
}
}
host.commitUpdate(exportRecorder);
}
return host;
};
}
function buildSelector(options: ZorroComponentOptions, projectPrefix: string, modulePrefixName: string): string {
let selector = strings.dasherize(options.name);
let modulePrefix = '';
if (modulePrefixName) {
modulePrefix = `${strings.dasherize(modulePrefixName) }-`;
}
if (options.prefix) {
selector = `${options.prefix}-${modulePrefix}${selector}`;
} else if (options.prefix === undefined && projectPrefix) {
selector = `${projectPrefix}-${modulePrefix}${selector}`;
}
return selector;
}
/**
* Indents the text content with the amount of specified spaces. The spaces will be added after
* every line-break. This utility function can be used inside of EJS templates to properly
* include the additional files.
*/
function indentTextContent(text: string, numSpaces: number): string {
// In the Material project there should be only LF line-endings, but the schematic files
// are not being linted and therefore there can be also CRLF or just CR line-endings.
return text.replace(/(\r\n|\r|\n)/g, `$1${' '.repeat(numSpaces)}`);
}
/**
* Rule that copies and interpolates the files that belong to this schematic context. Additionally
* a list of file paths can be passed to this rule in order to expose them inside the EJS
* template context.
*
* This allows inlining the external template or stylesheet files in EJS without having
* to manually duplicate the file content.
*/
export function buildComponent(options: ZorroComponentOptions,
additionalFiles: { [ key: string ]: string } = {}): Rule {
return async (host: Tree, context: FileSystemSchematicContext) => {
const workspace = await getWorkspace(host);
const project = getProjectFromWorkspace(workspace, options.project);
const defaultZorroComponentOptions = getDefaultComponentOptions(project);
let modulePrefix = '';
// TODO(devversion): Remove if we drop support for older CLI versions.
// This handles an unreported breaking change from the @angular-devkit/schematics. Previously
// the description path resolved to the factory file, but starting from 6.2.0, it resolves
// to the factory directory.
const schematicPath = statSync(context.schematic.description.path).isDirectory() ?
context.schematic.description.path :
dirname(context.schematic.description.path);
const schematicFilesUrl = './files';
const schematicFilesPath = resolve(schematicPath, schematicFilesUrl);
options.style = options.style || Style.Css;
// Add the default component option values to the options if an option is not explicitly
// specified but a default component option is available.
Object.keys(options)
.filter(optionName => options[ optionName ] == null && defaultZorroComponentOptions[ optionName ])
.forEach(optionName => options[ optionName ] = defaultZorroComponentOptions[ optionName ]);
if (options.path === undefined) {
// TODO(jelbourn): figure out if the need for this `as any` is a bug due to two different
// incompatible `WorkspaceProject` classes in @angular-devkit
// eslint-disable-next-line @typescript-eslint/no-explicit-any
options.path = buildDefaultPath(project as any);
}
options.module = findModuleFromOptions(host, options);
const parsedPath = parseName(options.path!, options.name);
if (options.classnameWithModule && !options.skipImport && options.module) {
const source = readIntoSourceFile(host, options.module);
modulePrefix = getModuleClassnamePrefix(source);
}
options.name = parsedPath.name;
options.path = parsedPath.path;
options.selector = options.selector || buildSelector(options, project.prefix, modulePrefix);
validateName(options.name);
validateHtmlSelector(options.selector!);
// In case the specified style extension is not part of the supported CSS supersets,
// we generate the stylesheets with the "css" extension. This ensures that we don't
// accidentally generate invalid stylesheets (e.g. drag-drop-comp.styl) which will
// break the Angular CLI project. See: https://github.com/angular/material2/issues/15164
if (!supportedCssExtensions.includes(options.style!)) {
// TODO: Cast is necessary as we can't use the Style enum which has been introduced
// within CLI v7.3.0-rc.0. This would break the schematic for older CLI versions.
options.style = Style.Css;
}
const classifyCovered = (name: string) => {
return `${modulePrefix}${strings.classify(name)}`
};
// Object that will be used as context for the EJS templates.
const baseTemplateContext = {
...strings,
'if-flat': (s: string) => options.flat ? '' : s,
classify: classifyCovered,
...options
};
// Key-value object that includes the specified additional files with their loaded content.
// The resolved contents can be used inside EJS templates.
const resolvedFiles = {};
for (const key in additionalFiles) {
if (additionalFiles[ key ]) {
const fileContent = readFileSync(join(schematicFilesPath, additionalFiles[ key ]), 'utf-8');
// Interpolate the additional files with the base EJS template context.
resolvedFiles[ key ] = interpolateTemplate(fileContent)(baseTemplateContext);
}
}
const templateSource = apply(url(schematicFilesUrl), [
options.skipTests ? filter(path => !path.endsWith('.spec.ts.template')) : noop(),
options.inlineStyle ? filter(path => !path.endsWith('.__style__.template')) : noop(),
options.inlineTemplate ? filter(path => !path.endsWith('.html.template')) : noop(),
// Treat the template options as any, because the type definition for the template options
// is made unnecessarily explicit. Every type of object can be used in the EJS template.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
applyTemplates({ indentTextContent, resolvedFiles, ...baseTemplateContext } as any),
// TODO(devversion): figure out why we cannot just remove the first parameter
// See for example: angular-cli#schematics/angular/component/index.ts#L160
// eslint-disable-next-line @typescript-eslint/no-explicit-any
move(null as any, parsedPath.path)
]);
return () => chain([
branchAndMerge(chain([
addDeclarationToNgModule(options),
mergeWith(templateSource)
]))
])(host, context);
};
} | the_stack |
import 'core-js/stable';
import 'regenerator-runtime/runtime';
import fs from 'fs';
import { createHash } from 'crypto';
import path from 'path';
import child_process from 'child_process';
// @ts-ignore
import { Promise } from 'bluebird';
import progress from 'progress-stream';
import Service, { Message } from 'webos-service';
import fetch from 'node-fetch';
import { asyncStat, asyncExecFile, asyncPipeline, asyncUnlink, asyncWriteFile } from './adapter';
import rootAppInfo from '../appinfo.json';
import serviceInfo from './services.json';
import { makeError, makeSuccess } from './protocol';
import ServiceRemote from './webos-service-remote';
const kHomebrewChannelPackageId = rootAppInfo.id;
// Maps internal setting field name with filesystem flag name.
type FlagName = string;
const availableFlags = {
telnetDisabled: 'webosbrew_telnet_disabled',
failsafe: 'webosbrew_failsafe',
sshdEnabled: 'webosbrew_sshd_enabled',
blockUpdates: 'webosbrew_block_updates',
} as Record<string, FlagName>;
function runningAsRoot() {
return process.getuid() === 0;
}
function asyncCall<T extends Record<string, any>>(srv: Service, uri: string, args: Record<string, any>): Promise<T> {
return new Promise((resolve, reject) => {
srv.call(uri, args, ({ payload }) => {
if (payload.returnValue) {
resolve(payload as T);
} else {
reject(payload);
}
});
});
}
function createToast(message: string, service: Service): Promise<Record<string, any>> {
console.info(`[toast] ${message}`);
return asyncCall(service, 'luna://com.webos.notification/createToast', {
sourceId: serviceInfo.id,
message,
});
}
/**
* Generates local file checksum.
*/
async function hashFile(filePath: string, algorithm: string): Promise<string> {
const download = fs.createReadStream(filePath);
const hash = createHash(algorithm, { encoding: 'hex' });
await asyncPipeline(download, hash);
hash.end();
return hash.read();
}
/**
* Elevates a package by name.
*/
async function elevateService(pkg: string) {
if (runningAsRoot()) {
console.info('Elevating service...');
await asyncExecFile(path.join(__dirname, 'elevate-service'), [pkg]);
} else {
console.error('Trying to elevate service without running as root. Skipping.');
}
}
/**
* Returns the file path for a flag.
*/
function flagPath(flag: FlagName): string {
return `/var/luna/preferences/${flag}`;
}
/**
* Returns whether a flag is set or not.
*/
async function flagRead(flag: FlagName): Promise<boolean> {
try {
await asyncStat(flagPath(flag));
return true;
} catch (err) {
return false;
}
}
/**
* Sets the value of a flag.
*/
async function flagSet(flag: FlagName, enabled: boolean) {
if (enabled) {
// The file content is ignored, file presence is what matters. Writing '1' acts as a hint.
await asyncWriteFile(flagPath(flag), '1');
} else {
try {
await asyncUnlink(flagPath(flag));
} catch (err) {
// Already deleted is not a fatal error.
if (err.code !== 'ENOENT') throw err;
}
}
return flagRead(flag);
}
/**
* Package info
*/
async function packageInfo(filePath: string): Promise<Record<string, string> | null> {
try {
const control = await asyncExecFile('sh', ['-c', `ar -p ${filePath} control.tar.gz | tar zx --to-stdout`], { encoding: 'utf8' });
return Object.fromEntries(
control
.split('\n')
.filter((m) => m.length)
.map((p) => [p.slice(0, p.indexOf(': ')), p.slice(p.indexOf(': ') + 2)]),
);
} catch (err) {
console.warn('Error occured when fetching package info:', err);
return null;
}
}
/**
* Performs appInstallService/dev/install request.
*/
async function installPackage(filePath: string, service: Service): Promise<string> {
return new Promise((resolve, reject) => {
const req = service.subscribe('luna://com.webos.appInstallService/dev/install', {
id: 'testing',
ipkUrl: filePath,
subscribe: true,
});
req.on('response', (res) => {
console.info('appInstallService response:', res.payload);
if (res.payload.returnValue === false) {
reject(new Error(`${res.payload.errorCode}: ${res.payload.errorText}`));
req.cancel();
return;
}
if (res.payload.details && res.payload.details.errorCode !== undefined) {
reject(new Error(`${res.payload.details.errorCode}: ${res.payload.details.reason}`));
req.cancel();
return;
}
if (res.payload.statusValue === 30) {
resolve(res.payload.details.packageId);
req.cancel();
}
});
req.on('cancel', (msg) => {
if (msg.payload && msg.payload.errorText) {
reject(new Error(msg.payload.errorText));
} else {
reject(new Error('cancelled'));
}
});
});
}
/**
* Thin wrapper that responds with a successful message or an error in case of a JS exception.
*/
function tryRespond<T extends Record<string, any>>(runner: (message: Message) => T) {
return async (message: Message): Promise<void> => {
try {
const reply: T = await runner(message);
message.respond(makeSuccess(reply));
} catch (err) {
message.respond(makeError(err.message));
} finally {
message.cancel({});
}
};
}
function runService() {
const service = new Service(serviceInfo.id);
const serviceRemote = new ServiceRemote(service);
function getInstallerService(): Service {
if (runningAsRoot()) {
return service;
}
return serviceRemote as Service;
}
/**
* Installs the requested ipk from a URL.
*/
type InstallPayload = { ipkUrl: string; ipkHash: string };
service.register(
'install',
tryRespond(async (message: Message) => {
const payload = message.payload as InstallPayload;
const targetPath = `/tmp/.hbchannel-incoming-${Date.now()}.ipk`;
// Download
message.respond({ statusText: 'Downloading…' });
const res = await fetch(payload.ipkUrl);
if (!res.ok) {
throw new Error(res.statusText);
}
const progressReporter = progress({
length: parseInt(res.headers.get('content-length'), 10),
time: 300 /* ms */,
});
progressReporter.on('progress', (p) => {
message.respond({ statusText: 'Downloading…', progress: p.percentage });
});
const targetFile = fs.createWriteStream(targetPath);
await asyncPipeline(res.body, progressReporter, targetFile);
// Checksum
message.respond({ statusText: 'Verifying…' });
const checksum = await hashFile(targetPath, 'sha256');
if (checksum !== payload.ipkHash) {
throw new Error(`Invalid file checksum (${payload.ipkHash} expected, got ${checksum}`);
}
const pkginfo = await packageInfo(targetPath);
// If we are running as root we likely want to retain root
// execution/private bus permissions. During package install running app
// and its services (since webOS 4.x) are killed using SIGKILL (9) signal.
// In order to retain some part of our service still running as root
// during upgrade we fork off our process and do self-update installation
// in there. After a successful install we relevate the service and exit.
// Exiting cleanly is an important part, since forked process retains open
// luna bus socket, and thus a new service will not be able to launch
// until we do that.
//
// If reelevation fails for some reason the service should still be
// reelevated on reboot (since we launch elevate-service in startup.sh
// script)
if (pkginfo && pkginfo.Package === kHomebrewChannelPackageId && runningAsRoot()) {
message.respond({ statusText: 'Self-update…' });
await createToast('Performing self-update...', service);
child_process.fork(__filename, ['self-update', targetPath]);
service.activityManager.idleTimeout = 1;
return { statusText: 'Self-update' };
}
// Install
message.respond({ statusText: 'Installing…' });
const installedPackageId = await installPackage(targetPath, getInstallerService());
await createToast(`Application installed: ${installedPackageId}`, service);
return { statusText: 'Finished.', finished: true };
}),
() => {
// TODO: support cancellation.
},
);
/**
* Returns the current value of all available flags, plus whether we're running as root.
*/
service.register(
'getConfiguration',
tryRespond(async () => {
const futureFlags = Object.entries(availableFlags).map(
async ([field, flagName]) => [field, await flagRead(flagName)] as [string, boolean],
);
const flags = Object.fromEntries(await Promise.all(futureFlags));
return {
root: process.getuid() === 0,
...flags,
};
}),
);
/**
* Sets any of the available flags.
*/
type SetConfigurationPayload = Record<string, boolean>;
service.register(
'setConfiguration',
tryRespond(async (message) => {
const payload = message.payload as SetConfigurationPayload;
const futureFlagSets = Object.entries(payload)
.map(([field, value]) => [field, availableFlags[field], value] as [string, FlagName | undefined, boolean])
.filter(([, flagName]) => flagName !== undefined)
.map(async ([field, flagName, value]) => [field, await flagSet(flagName, value)]);
return Object.fromEntries(await Promise.all(futureFlagSets));
}),
);
/**
* Invokes a platform reboot.
*/
service.register(
'reboot',
tryRespond(async () => {
await asyncExecFile('reboot');
}),
);
/**
* Returns whether the service is running as root.
*/
service.register(
'checkRoot',
tryRespond(async () => runningAsRoot()),
);
/**
* Roughly replicates com.webos.applicationManager/getAppInfo request in an
* environment-independent way (non-root vs root).
*/
type GetAppInfoPayload = { id: string };
service.register(
'getAppInfo',
tryRespond(async (message) => {
const payload = message.payload as GetAppInfoPayload;
const appId: string = payload.id;
if (!appId) throw new Error('missing `id` string field');
const appList = await asyncCall<{ apps: { id: string }[] }>(
getInstallerService(),
'luna://com.webos.applicationManager/dev/listApps',
{},
);
const appInfo = appList.apps.find((app) => app.id === appId);
if (!appInfo) throw new Error(`Invalid appId, or unsupported application type: ${appId}`);
return { appId, appInfo };
}),
);
/**
* Executes a shell command and responds with exit code, stdout and stderr.
*/
type ExecPayload = { command: string };
service.register('exec', (message) => {
const payload = message.payload as ExecPayload;
child_process.exec(payload.command, { encoding: 'buffer' }, (error, stdout, stderr) => {
const response = {
error,
stdoutString: stdout.toString(),
stdoutBytes: stdout.toString('base64'),
stderrString: stderr.toString(),
stderrBytes: stderr.toString('base64'),
};
if (error) {
message.respond(makeError(error.message, response));
} else {
message.respond(makeSuccess(response));
}
});
});
/**
* Spawns a shell command and streams stdout & stderr bytes.
*/
service.register('spawn', (message) => {
const payload = message.payload as ExecPayload;
const respond = (event: string, args: Record<string, any>) => message.respond({ event, ...args });
const proc = child_process.spawn('/bin/sh', ['-c', payload.command]);
proc.stdout.on('data', (data) =>
respond('stdoutData', {
stdoutString: data.toString(),
stdoutBytes: data.toString('base64'),
}),
);
proc.stderr.on('data', (data) =>
respond('stderrData', {
stderrString: data.toString(),
stderrBytes: data.toString('base64'),
}),
);
proc.on('close', (closeCode) => respond('close', { closeCode }));
proc.on('exit', (exitCode) => respond('exit', { exitCode }));
});
/**
* Stub service that emulates luna://com.webos.service.sm/license/apps/getDrmStatus
*/
type GetDrmStatusPayload = { appId: string };
service.register(
'getDrmStatus',
tryRespond(async (message) => ({
appId: (message.payload as GetDrmStatusPayload).appId,
drmType: 'NCG DRM',
installBasePath: '/media/cryptofs',
returnValue: true,
isTimeLimited: false,
})),
);
}
if (process.argv[2] === 'self-update') {
process.on('SIGTERM', () => {
console.info('sigterm!');
});
(async () => {
const service = new ServiceRemote(null) as Service;
try {
await createToast('Performing self-update (inner)', service);
const installedPackageId = await installPackage(process.argv[3], service);
await createToast('Elevating...', service);
await elevateService(`${installedPackageId}.service`);
await createToast('Self-update finished!', service);
process.exit(0);
} catch (err) {
console.info(err);
await createToast(`Self-update failed: ${err.message}`, service);
process.exit(1);
}
})();
} else {
runService();
} | the_stack |
import {
h,
createApp,
defineComponent,
reactive,
FunctionalComponent,
ComponentPublicInstance,
ComponentOptionsWithObjectProps,
ComponentOptionsWithArrayProps,
ComponentOptionsWithoutProps,
ExtractPropTypes,
AppConfig,
VNodeProps,
ComponentOptionsMixin,
DefineComponent,
MethodOptions,
AllowedComponentProps,
ComponentCustomProps,
ExtractDefaultPropTypes,
EmitsOptions,
ComputedOptions,
ComponentPropsOptions,
ComponentOptions,
ConcreteComponent
} from 'vue'
import { MountingOptions, Slot } from './types'
import {
isFunctionalComponent,
isObjectComponent,
mergeGlobalProperties
} from './utils'
import { processSlot } from './utils/compileSlots'
import { VueWrapper } from './vueWrapper'
import { attachEmitListener } from './emit'
import { stubComponents, addToDoNotStubComponents, registerStub } from './stubs'
import {
isLegacyFunctionalComponent,
unwrapLegacyVueExtendComponent
} from './utils/vueCompatSupport'
import { trackInstance } from './utils/autoUnmount'
import { createVueWrapper } from './wrapperFactory'
// NOTE this should come from `vue`
type PublicProps = VNodeProps & AllowedComponentProps & ComponentCustomProps
const MOUNT_OPTIONS: Array<keyof MountingOptions<any>> = [
'attachTo',
'attrs',
'data',
'props',
'slots',
'global',
'shallow'
]
function getInstanceOptions(
options: MountingOptions<any> & Record<string, any>
): Record<string, any> {
if (options.methods) {
console.warn(
"Passing a `methods` option to mount was deprecated on Vue Test Utils v1, and it won't have any effect on v2. For additional info: https://vue-test-utils.vuejs.org/upgrading-to-v1/#setmethods-and-mountingoptions-methods"
)
delete options.methods
}
const resultOptions = { ...options }
for (const key of Object.keys(options)) {
if (MOUNT_OPTIONS.includes(key as keyof MountingOptions<any>)) {
delete resultOptions[key]
}
}
return resultOptions
}
// Class component - no props
export function mount<V>(
originalComponent: {
new (...args: any[]): V
registerHooks(keys: string[]): void
},
options?: MountingOptions<any> & Record<string, any>
): VueWrapper<ComponentPublicInstance<V>>
// Class component - props
export function mount<V, P>(
originalComponent: {
new (...args: any[]): V
props(Props: P): any
registerHooks(keys: string[]): void
},
options?: MountingOptions<P & PublicProps> & Record<string, any>
): VueWrapper<ComponentPublicInstance<V>>
// Functional component with emits
export function mount<Props, E extends EmitsOptions = {}>(
originalComponent: FunctionalComponent<Props, E>,
options?: MountingOptions<Props & PublicProps> & Record<string, any>
): VueWrapper<ComponentPublicInstance<Props>>
// Component declared with defineComponent
export function mount<
PropsOrPropOptions = {},
RawBindings = {},
D = {},
C extends ComputedOptions = ComputedOptions,
M extends MethodOptions = MethodOptions,
Mixin extends ComponentOptionsMixin = ComponentOptionsMixin,
Extends extends ComponentOptionsMixin = ComponentOptionsMixin,
E extends EmitsOptions = Record<string, any>,
EE extends string = string,
PP = PublicProps,
Props = Readonly<ExtractPropTypes<PropsOrPropOptions>>,
Defaults = ExtractDefaultPropTypes<PropsOrPropOptions>
>(
component: DefineComponent<
PropsOrPropOptions,
RawBindings,
D,
C,
M,
Mixin,
Extends,
E,
EE,
PP,
Props,
Defaults
>,
options?: MountingOptions<
Partial<Defaults> & Omit<Props & PublicProps, keyof Defaults>,
D
> &
Record<string, any>
): VueWrapper<
InstanceType<
DefineComponent<
PropsOrPropOptions,
RawBindings,
D,
C,
M,
Mixin,
Extends,
E,
EE,
PP,
Props,
Defaults
>
>
>
// Component declared with no props
export function mount<
Props = {},
RawBindings = {},
D = {},
C extends ComputedOptions = {},
M extends Record<string, Function> = {},
E extends EmitsOptions = Record<string, any>,
Mixin extends ComponentOptionsMixin = ComponentOptionsMixin,
Extends extends ComponentOptionsMixin = ComponentOptionsMixin,
EE extends string = string
>(
componentOptions: ComponentOptionsWithoutProps<
Props,
RawBindings,
D,
C,
M,
E,
Mixin,
Extends,
EE
>,
options?: MountingOptions<Props & PublicProps, D>
): VueWrapper<
ComponentPublicInstance<Props, RawBindings, D, C, M, E, VNodeProps & Props>
> &
Record<string, any>
// Component declared with { props: [] }
export function mount<
PropNames extends string,
RawBindings,
D,
C extends ComputedOptions = {},
M extends Record<string, Function> = {},
E extends EmitsOptions = Record<string, any>,
Mixin extends ComponentOptionsMixin = ComponentOptionsMixin,
Extends extends ComponentOptionsMixin = ComponentOptionsMixin,
EE extends string = string,
Props extends Readonly<{ [key in PropNames]?: any }> = Readonly<{
[key in PropNames]?: any
}>
>(
componentOptions: ComponentOptionsWithArrayProps<
PropNames,
RawBindings,
D,
C,
M,
E,
Mixin,
Extends,
EE,
Props
>,
options?: MountingOptions<Props & PublicProps, D>
): VueWrapper<ComponentPublicInstance<Props, RawBindings, D, C, M, E>>
// Component declared with { props: { ... } }
export function mount<
// the Readonly constraint allows TS to treat the type of { required: true }
// as constant instead of boolean.
PropsOptions extends Readonly<ComponentPropsOptions>,
RawBindings,
D,
C extends ComputedOptions = {},
M extends Record<string, Function> = {},
E extends EmitsOptions = Record<string, any>,
Mixin extends ComponentOptionsMixin = ComponentOptionsMixin,
Extends extends ComponentOptionsMixin = ComponentOptionsMixin,
EE extends string = string
>(
componentOptions: ComponentOptionsWithObjectProps<
PropsOptions,
RawBindings,
D,
C,
M,
E,
Mixin,
Extends,
EE
>,
options?: MountingOptions<ExtractPropTypes<PropsOptions> & PublicProps, D>
): VueWrapper<
ComponentPublicInstance<
ExtractPropTypes<PropsOptions>,
RawBindings,
D,
C,
M,
E,
VNodeProps & ExtractPropTypes<PropsOptions>
>
>
// implementation
export function mount(
inputComponent: any,
options?: MountingOptions<any> & Record<string, any>
): VueWrapper<any> {
// normalise the incoming component
let originalComponent = unwrapLegacyVueExtendComponent(inputComponent)
let component: ConcreteComponent
const instanceOptions = getInstanceOptions(options ?? {})
if (
isFunctionalComponent(originalComponent) ||
isLegacyFunctionalComponent(originalComponent)
) {
component = defineComponent({
compatConfig: {
MODE: 3,
INSTANCE_LISTENERS: false,
INSTANCE_ATTRS_CLASS_STYLE: false,
COMPONENT_FUNCTIONAL: isLegacyFunctionalComponent(originalComponent)
? 'suppress-warning'
: false
},
setup:
(_, { attrs, slots }) =>
() =>
h(originalComponent, attrs, slots),
...instanceOptions
})
addToDoNotStubComponents(originalComponent)
} else if (isObjectComponent(originalComponent)) {
component = { ...originalComponent, ...instanceOptions }
} else {
component = originalComponent
}
addToDoNotStubComponents(component)
registerStub({ source: originalComponent, stub: component })
const el = document.createElement('div')
if (options?.attachTo) {
let to: Element | null
if (typeof options.attachTo === 'string') {
to = document.querySelector(options.attachTo)
if (!to) {
throw new Error(
`Unable to find the element matching the selector ${options.attachTo} given as the \`attachTo\` option`
)
}
} else {
to = options.attachTo
}
to.appendChild(el)
}
function slotToFunction(slot: Slot) {
switch (typeof slot) {
case 'function':
return slot
case 'object':
return () => h(slot)
case 'string':
return processSlot(slot)
default:
throw Error(`Invalid slot received.`)
}
}
// handle any slots passed via mounting options
const slots =
options?.slots &&
Object.entries(options.slots).reduce(
(
acc: { [key: string]: Function },
[name, slot]: [string, Slot]
): { [key: string]: Function } => {
if (Array.isArray(slot)) {
const normalized = slot.map(slotToFunction)
acc[name] = (args: unknown) => normalized.map((f) => f(args))
return acc
}
acc[name] = slotToFunction(slot)
return acc
},
{}
)
// override component data with mounting options data
if (options?.data) {
const providedData = options.data()
if (isObjectComponent(originalComponent)) {
// component is guaranteed to be the same type as originalComponent
const objectComponent = component as ComponentOptions
const originalDataFn = originalComponent.data || (() => ({}))
objectComponent.data = (vm) => ({
...originalDataFn.call(vm, vm),
...providedData
})
} else {
throw new Error(
'data() option is not supported on functional and class components'
)
}
}
const MOUNT_COMPONENT_REF = 'VTU_COMPONENT'
// we define props as reactive so that way when we update them with `setProps`
// Vue's reactivity system will cause a rerender.
const props = reactive({
...options?.attrs,
...options?.propsData,
...options?.props,
ref: MOUNT_COMPONENT_REF
})
const global = mergeGlobalProperties(options?.global)
if (isObjectComponent(component)) {
component.components = { ...component.components, ...global.components }
}
// create the wrapper component
const Parent = defineComponent({
name: 'VTU_ROOT',
render() {
return h(component, props, slots)
}
})
addToDoNotStubComponents(Parent)
const setProps = (newProps: Record<string, unknown>) => {
for (const [k, v] of Object.entries(newProps)) {
props[k] = v
}
return vm.$nextTick()
}
// create the app
const app = createApp(Parent)
// add tracking for emitted events
// this must be done after `createApp`: https://github.com/vuejs/vue-test-utils-next/issues/436
attachEmitListener()
// global mocks mixin
if (global?.mocks) {
const mixin = {
beforeCreate() {
for (const [k, v] of Object.entries(
global.mocks as { [key: string]: any }
)) {
;(this as any)[k] = v
}
}
}
app.mixin(mixin)
}
// AppConfig
if (global.config) {
for (const [k, v] of Object.entries(global.config) as [
keyof Omit<AppConfig, 'isNativeTag'>,
any
][]) {
app.config[k] = v
}
}
// use and plugins from mounting options
if (global.plugins) {
for (const plugin of global.plugins) {
if (Array.isArray(plugin)) {
app.use(plugin[0], ...plugin.slice(1))
continue
}
app.use(plugin)
}
}
// use any mixins from mounting options
if (global.mixins) {
for (const mixin of global.mixins) app.mixin(mixin)
}
if (global.components) {
for (const key of Object.keys(global.components)) {
// avoid registering components that are stubbed twice
if (!(key in global.stubs)) {
app.component(key, global.components[key])
}
}
}
if (global.directives) {
for (const key of Object.keys(global.directives))
app.directive(key, global.directives[key])
}
// provide any values passed via provides mounting option
if (global.provide) {
for (const key of Reflect.ownKeys(global.provide)) {
// @ts-ignore: https://github.com/microsoft/TypeScript/issues/1863
app.provide(key, global.provide[key])
}
}
// stubs
// even if we are using `mount`, we will still
// stub out Transition and Transition Group by default.
stubComponents(global.stubs, options?.shallow, global?.renderStubDefaultSlot)
// users expect stubs to work with globally registered
// components so we register stubs as global components to avoid
// warning about not being able to resolve component
//
// component implementation provided here will never be called
// but we need name to make sure that stubComponents will
// properly stub this later by matching stub name
//
// ref: https://github.com/vuejs/vue-test-utils-next/issues/249
// ref: https://github.com/vuejs/vue-test-utils-next/issues/425
if (global?.stubs) {
for (const name of Object.keys(global.stubs)) {
if (!app.component(name)) {
app.component(name, { name })
}
}
}
// mount the app!
const vm = app.mount(el)
// Ingore Avoid app logic that relies on enumerating keys on a component instance... warning
const warnSave = console.warn
console.warn = () => {}
const appRef = vm.$refs[MOUNT_COMPONENT_REF] as ComponentPublicInstance
// we add `hasOwnProperty` so jest can spy on the proxied vm without throwing
appRef.hasOwnProperty = (property) => {
return Reflect.has(appRef, property)
}
console.warn = warnSave
const wrapper = createVueWrapper(app, appRef, setProps)
trackInstance(wrapper)
return wrapper
}
export const shallowMount: typeof mount = (component: any, options?: any) => {
return mount(component, { ...options, shallow: true })
} | the_stack |
import {
ForceConfigGet,
ForceOrgDisplay
} from '@salesforce/salesforcedx-utils-vscode/out/src/cli';
import { extractJsonObject } from '@salesforce/salesforcedx-utils-vscode/out/src/helpers';
import { RequestService } from '@salesforce/salesforcedx-utils-vscode/out/src/requestService';
import {
SFDX_CONFIG_ISV_DEBUGGER_SID,
SFDX_CONFIG_ISV_DEBUGGER_URL
} from '@salesforce/salesforcedx-utils-vscode/out/src/types';
import * as AsyncLock from 'async-lock';
import { basename } from 'path';
import {
DebugSession,
Event,
Handles,
InitializedEvent,
logger,
Logger,
LoggingDebugSession,
OutputEvent,
Scope,
Source,
StackFrame,
StoppedEvent,
TerminatedEvent,
Thread,
ThreadEvent,
Variable
} from 'vscode-debugadapter';
import { DebugProtocol } from 'vscode-debugprotocol';
import { ExceptionBreakpointInfo } from '../breakpoints/exceptionBreakpoint';
import {
LineBreakpointInfo,
LineBreakpointsInTyperef
} from '../breakpoints/lineBreakpoint';
import {
DebuggerResponse,
FrameCommand,
LocalValue,
Reference,
ReferencesCommand,
RunCommand,
StateCommand,
StepIntoCommand,
StepOutCommand,
StepOverCommand,
Tuple,
Value
} from '../commands';
import {
DEFAULT_IDLE_TIMEOUT_MS,
DEFAULT_IDLE_WARN1_MS,
DEFAULT_IDLE_WARN2_MS,
DEFAULT_IDLE_WARN3_MS,
DEFAULT_LOCK_TIMEOUT_MS,
EXCEPTION_BREAKPOINT_BREAK_MODE_ALWAYS,
EXCEPTION_BREAKPOINT_BREAK_MODE_NEVER,
EXCEPTION_BREAKPOINT_REQUEST,
HOTSWAP_REQUEST,
LIST_EXCEPTION_BREAKPOINTS_REQUEST,
SALESFORCE_EXCEPTION_PREFIX,
SHOW_MESSAGE_EVENT,
TRIGGER_EXCEPTION_PREFIX
} from '../constants';
import {
ApexDebuggerEventType,
BreakpointService,
DebuggerMessage,
SessionService,
StreamingClientInfo,
StreamingClientInfoBuilder,
StreamingService
} from '../core';
import {
VscodeDebuggerMessage,
VscodeDebuggerMessageType,
WorkspaceSettings
} from '../index';
import { nls } from '../messages';
import os = require('os');
const TRACE_ALL = 'all';
const TRACE_CATEGORY_VARIABLES = 'variables';
const TRACE_CATEGORY_LAUNCH = 'launch';
const TRACE_CATEGORY_PROTOCOL = 'protocol';
const TRACE_CATEGORY_BREAKPOINTS = 'breakpoints';
const TRACE_CATEGORY_STREAMINGAPI = 'streaming';
const CONNECT_TYPE_ISV_DEBUGGER = 'ISV_DEBUGGER';
export type TraceCategory =
| 'all'
| 'variables'
| 'launch'
| 'protocol'
| 'breakpoints'
| 'streaming';
export interface LaunchRequestArguments
extends DebugProtocol.LaunchRequestArguments {
// comma separated list of trace selectors (see TraceCategory)
trace?: boolean | string;
userIdFilter?: string[];
requestTypeFilter?: string[];
entryPointFilter?: string;
sfdxProject: string;
connectType?: string;
workspaceSettings: WorkspaceSettings;
lineBreakpointInfo?: LineBreakpointInfo[];
}
export interface SetExceptionBreakpointsArguments {
exceptionInfo: ExceptionBreakpointInfo;
}
export class ApexDebugStackFrameInfo {
public readonly requestId: string;
public readonly frameNumber: number;
public globals: Value[] = [];
public statics: Value[] = [];
public locals: LocalValue[] = [];
public references: Reference[] = [];
constructor(requestId: string, frameNumber: number) {
this.requestId = requestId;
this.frameNumber = frameNumber;
}
}
export enum ApexVariableKind {
Global = 10,
Static = 20,
Local = 30,
Field = 40,
Collection = 50
}
export class ApexVariable extends Variable {
public readonly declaredTypeRef: string;
public readonly type: string;
public readonly indexedVariables?: number;
public readonly evaluateName: string;
private readonly slot: number;
private readonly kind: ApexVariableKind;
constructor(
value: Value,
kind: ApexVariableKind,
variableReference?: number,
numOfChildren?: number
) {
super(
value.name,
ApexVariable.valueAsString(value),
variableReference,
numOfChildren
);
this.declaredTypeRef = value.declaredTypeRef;
this.kind = kind;
this.type = value.nameForMessages;
this.evaluateName = this.value;
if ((value as LocalValue).slot !== undefined) {
this.slot = (value as LocalValue).slot;
} else {
this.slot = Number.MAX_SAFE_INTEGER;
}
}
public static valueAsString(value: Value): string {
if (typeof value.value === 'undefined' || value.value === null) {
// We want to explicitly display null for null values (no type info for strings).
return 'null';
}
if (ApexVariable.isString(value)) {
// We want to explicitly quote string values like in Java. This allows us to differentiate null from 'null'.
return `'${value.value}'`;
}
return `${value.value}`;
}
public static compareVariables(v1: ApexVariable, v2: ApexVariable): number {
// group by kind
if (v1.kind !== v2.kind) {
return v1.kind - v2.kind;
}
// use slots when available
if (ApexVariable.isLocalOrField(v1)) {
return v1.slot - v2.slot;
}
// compare names
let n1 = v1.name;
let n2 = v2.name;
// convert [n], [n..m] -> n
n1 = ApexVariable.extractNumber(n1);
n2 = ApexVariable.extractNumber(n2);
const i1 = parseInt(n1, 10);
const i2 = parseInt(n2, 10);
const isNum1 = !isNaN(i1);
const isNum2 = !isNaN(i2);
if (isNum1 && !isNum2) {
return 1; // numbers after names
}
if (!isNum1 && isNum2) {
return -1; // names before numbers
}
if (isNum1 && isNum2) {
return i1 - i2;
}
return n1.localeCompare(n2);
}
private static extractNumber(s: string): string {
if (s[0] === '[' && s[s.length - 1] === ']') {
return s.substring(1, s.length - 1);
}
return s;
}
private static isLocalOrField(v1: ApexVariable) {
return (
v1.kind === ApexVariableKind.Local || v1.kind === ApexVariableKind.Field
);
}
private static isString(value: Value) {
return value.declaredTypeRef === 'java/lang/String';
}
}
export type FilterType = 'named' | 'indexed' | 'all';
export interface VariableContainer {
expand(
session: ApexDebug,
filter: FilterType,
start?: number,
count?: number
): Promise<ApexVariable[]>;
getNumberOfChildren(): number | undefined;
}
export type ScopeType = 'local' | 'static' | 'global';
export class ScopeContainer implements VariableContainer {
private type: ScopeType;
private frameInfo: ApexDebugStackFrameInfo;
public constructor(type: ScopeType, frameInfo: ApexDebugStackFrameInfo) {
this.type = type;
this.frameInfo = frameInfo;
}
public async expand(
session: ApexDebug,
filter: FilterType,
start?: number,
count?: number
): Promise<ApexVariable[]> {
if (
!this.frameInfo.locals &&
!this.frameInfo.statics &&
!this.frameInfo.globals
) {
await session.fetchFrameVariables(this.frameInfo);
}
let values: Value[] = [];
let variableKind: ApexVariableKind;
switch (this.type) {
case 'local':
values = this.frameInfo.locals ? this.frameInfo.locals : [];
variableKind = ApexVariableKind.Local;
break;
case 'static':
values = this.frameInfo.statics ? this.frameInfo.statics : [];
variableKind = ApexVariableKind.Static;
break;
case 'global':
values = this.frameInfo.globals ? this.frameInfo.globals : [];
variableKind = ApexVariableKind.Global;
break;
default:
return [];
}
return Promise.all(
values.map(async value => {
const variableReference = await session.resolveApexIdToVariableReference(
this.frameInfo.requestId,
value.ref
);
return new ApexVariable(
value,
variableKind,
variableReference,
session.getNumberOfChildren(variableReference)
);
})
);
}
public getNumberOfChildren(): number | undefined {
return undefined;
}
}
export class ObjectReferenceContainer implements VariableContainer {
protected reference: Reference;
protected requestId: string;
public readonly size: number | undefined;
public constructor(reference: Reference, requestId: string) {
this.reference = reference;
this.requestId = requestId;
this.size = reference.size;
}
public async expand(
session: ApexDebug,
filter: FilterType,
start?: number,
count?: number
): Promise<ApexVariable[]> {
if (!this.reference.fields) {
// this object is empty
return [];
}
return Promise.all(
this.reference.fields.map(async value => {
const variableReference = await session.resolveApexIdToVariableReference(
this.requestId,
value.ref
);
return new ApexVariable(
value,
ApexVariableKind.Field,
variableReference,
session.getNumberOfChildren(variableReference)
);
})
);
}
public getNumberOfChildren(): number | undefined {
return this.size;
}
}
export class CollectionReferenceContainer extends ObjectReferenceContainer {
public async expand(
session: ApexDebug,
filter: FilterType,
start?: number,
count?: number
): Promise<ApexVariable[]> {
if (!this.reference.value) {
// this object is empty
return [];
}
if (start === undefined) {
start = 0;
}
if (count === undefined) {
count = this.reference.value.length;
}
const apexVariables: ApexVariable[] = [];
for (
let i = start;
i < start + count && i < this.reference.value.length;
i++
) {
const variableReference = await session.resolveApexIdToVariableReference(
this.requestId,
this.reference.value[i].ref
);
apexVariables.push(
new ApexVariable(
this.reference.value[i],
ApexVariableKind.Collection,
variableReference,
session.getNumberOfChildren(variableReference)
)
);
}
return Promise.resolve(apexVariables);
}
}
export class MapReferenceContainer extends ObjectReferenceContainer {
public readonly tupleContainers: Map<number, MapTupleContainer> = new Map();
public addTupleContainer(
reference: number,
tupleContainer: MapTupleContainer
): void {
this.tupleContainers.set(reference, tupleContainer);
}
public async expand(
session: ApexDebug,
filter: FilterType,
start?: number,
count?: number
): Promise<ApexVariable[]> {
if (start === undefined) {
start = 0;
}
if (count === undefined) {
count = this.tupleContainers.size;
}
const apexVariables: ApexVariable[] = [];
let offset = 0;
this.tupleContainers.forEach((container, reference) => {
if (offset >= start! && offset < start! + count!) {
apexVariables.push(
new ApexVariable(
{
name: container.keyAsString(),
declaredTypeRef: '',
nameForMessages: container.keyAsString(),
value: container.valueAsString()
},
ApexVariableKind.Collection,
reference,
session.getNumberOfChildren(reference)
)
);
}
offset++;
});
return Promise.resolve(apexVariables);
}
}
export class MapTupleContainer implements VariableContainer {
private tuple: Tuple;
private requestId: string;
public constructor(tuple: Tuple, requestId: string) {
this.tuple = tuple;
this.requestId = requestId;
}
public keyAsString(): string {
return ApexVariable.valueAsString(this.tuple.key);
}
public valueAsString(): string {
return ApexVariable.valueAsString(this.tuple.value);
}
public async expand(
session: ApexDebug,
filter: FilterType,
start?: number,
count?: number
): Promise<ApexVariable[]> {
if (!this.tuple.key && !this.tuple.value) {
// this object is empty
return [];
}
const idsToFetch = [];
if (this.tuple.key && this.tuple.key.ref) {
idsToFetch.push(this.tuple.key.ref);
}
if (this.tuple.value && this.tuple.value.ref) {
idsToFetch.push(this.tuple.value.ref);
}
await session.fetchReferencesIfNecessary(this.requestId, idsToFetch);
const variables = [];
if (this.tuple.key) {
const keyVariableReference = this.tuple.key.ref
? await session.resolveApexIdToVariableReference(
this.requestId,
this.tuple.key.ref
)
: undefined;
variables.push(
new ApexVariable(
this.tuple.key,
ApexVariableKind.Collection,
keyVariableReference,
session.getNumberOfChildren(keyVariableReference)
)
);
}
if (this.tuple.value) {
const valueVariableReference = this.tuple.value.ref
? await session.resolveApexIdToVariableReference(
this.requestId,
this.tuple.value.ref
)
: undefined;
variables.push(
new ApexVariable(
this.tuple.value,
ApexVariableKind.Collection,
valueVariableReference,
session.getNumberOfChildren(valueVariableReference)
)
);
}
return variables;
}
public getNumberOfChildren(): number | undefined {
return undefined;
}
}
export class ApexDebug extends LoggingDebugSession {
protected myRequestService = new RequestService();
protected mySessionService!: SessionService;
protected myBreakpointService!: BreakpointService;
protected myStreamingService = StreamingService.getInstance();
protected sfdxProject!: string;
protected requestThreads: Map<number, string>;
protected threadId: number;
protected stackFrameInfos = new Handles<ApexDebugStackFrameInfo>();
protected variableHandles = new Handles<VariableContainer>();
protected variableContainerReferenceByApexId = new Map<number, number>();
private static LINEBREAK = `${os.EOL}`;
private initializedResponse?: DebugProtocol.InitializeResponse;
private trace: string[] | undefined;
private traceAll = false;
private lock = new AsyncLock({ timeout: DEFAULT_LOCK_TIMEOUT_MS });
protected idleTimers: NodeJS.Timer[] = [];
constructor() {
super('apex-debug-adapter.log');
this.setDebuggerLinesStartAt1(true);
this.setDebuggerPathFormat('uri');
this.requestThreads = new Map();
this.threadId = 1;
}
protected initializeRequest(
response: DebugProtocol.InitializeResponse,
args: DebugProtocol.InitializeRequestArguments
): void {
this.initializedResponse = response;
this.initializedResponse.body = {
supportsCompletionsRequest: false,
supportsConditionalBreakpoints: false,
supportsDelayedStackTraceLoading: false,
supportsEvaluateForHovers: false,
supportsExceptionInfoRequest: false,
supportsExceptionOptions: false,
supportsFunctionBreakpoints: false,
supportsHitConditionalBreakpoints: false,
supportsLoadedSourcesRequest: false,
supportsRestartFrame: false,
supportsSetVariable: false,
supportsStepBack: false,
supportsStepInTargetsRequest: false
};
this.initializedResponse.success = true;
this.sendResponse(this.initializedResponse);
}
protected attachRequest(
response: DebugProtocol.AttachResponse,
args: DebugProtocol.AttachRequestArguments
): void {
response.success = false;
this.sendResponse(response);
}
private getSessionIdleTimer(): NodeJS.Timer[] {
const timers: NodeJS.Timer[] = [];
timers.push(
setTimeout(() => {
this.warnToDebugConsole(
nls.localize(
'idle_warn_text',
DEFAULT_IDLE_WARN1_MS / 60000,
(DEFAULT_IDLE_TIMEOUT_MS - DEFAULT_IDLE_WARN1_MS) / 60000
)
);
}, DEFAULT_IDLE_WARN1_MS),
setTimeout(() => {
this.warnToDebugConsole(
nls.localize(
'idle_warn_text',
DEFAULT_IDLE_WARN2_MS / 60000,
(DEFAULT_IDLE_TIMEOUT_MS - DEFAULT_IDLE_WARN2_MS) / 60000
)
);
}, DEFAULT_IDLE_WARN2_MS),
setTimeout(() => {
this.warnToDebugConsole(
nls.localize(
'idle_warn_text',
DEFAULT_IDLE_WARN3_MS / 60000,
(DEFAULT_IDLE_TIMEOUT_MS - DEFAULT_IDLE_WARN3_MS) / 60000
)
);
}, DEFAULT_IDLE_WARN3_MS),
setTimeout(() => {
this.warnToDebugConsole(
nls.localize('idle_terminated_text', DEFAULT_IDLE_TIMEOUT_MS / 60000)
);
this.sendEvent(new TerminatedEvent());
}, DEFAULT_IDLE_TIMEOUT_MS)
);
return timers;
}
public clearIdleTimers(): void {
if (this.idleTimers) {
this.idleTimers.forEach(timer => clearTimeout(timer));
this.idleTimers = [];
}
}
public resetIdleTimer(): NodeJS.Timer[] {
this.clearIdleTimers();
this.idleTimers = this.getSessionIdleTimer();
return this.idleTimers;
}
protected async launchRequest(
response: DebugProtocol.LaunchResponse,
args: LaunchRequestArguments
): Promise<void> {
response.success = false;
this.initBreakpointSessionServices(args);
this.setValidBreakpointLines(args);
this.setupLogger(args);
this.sfdxProject = args.sfdxProject;
this.log(
TRACE_CATEGORY_LAUNCH,
`launchRequest: sfdxProject=${args.sfdxProject}`
);
if (!this.myBreakpointService.hasLineNumberMapping()) {
response.message = nls.localize('session_language_server_error_text');
return this.sendResponse(response);
}
try {
if (args.connectType === CONNECT_TYPE_ISV_DEBUGGER) {
const forceConfig = await new ForceConfigGet().getConfig(
args.sfdxProject,
SFDX_CONFIG_ISV_DEBUGGER_SID,
SFDX_CONFIG_ISV_DEBUGGER_URL
);
const isvDebuggerSid = forceConfig.get(SFDX_CONFIG_ISV_DEBUGGER_SID);
const isvDebuggerUrl = forceConfig.get(SFDX_CONFIG_ISV_DEBUGGER_URL);
if (
typeof isvDebuggerSid === 'undefined' ||
typeof isvDebuggerUrl === 'undefined'
) {
response.message = nls.localize('invalid_isv_project_config');
return this.sendResponse(response);
}
this.myRequestService.instanceUrl = isvDebuggerUrl;
this.myRequestService.accessToken = isvDebuggerSid;
} else {
const orgInfo = await new ForceOrgDisplay().getOrgInfo(
args.sfdxProject
);
this.myRequestService.instanceUrl = orgInfo.instanceUrl;
this.myRequestService.accessToken = orgInfo.accessToken;
}
const isStreamingConnected = await this.connectStreaming(
args.sfdxProject
);
if (!isStreamingConnected) {
return this.sendResponse(response);
}
const sessionId = await this.mySessionService
.forProject(args.sfdxProject)
.withUserFilter(this.toCommaSeparatedString(args.userIdFilter))
.withEntryFilter(args.entryPointFilter)
.withRequestFilter(this.toCommaSeparatedString(args.requestTypeFilter))
.start();
if (this.mySessionService.isConnected()) {
response.success = true;
this.printToDebugConsole(
nls.localize('session_started_text', sessionId)
);
this.sendEvent(new InitializedEvent());
this.resetIdleTimer();
} else {
this.errorToDebugConsole(
`${nls.localize('command_error_help_text')}:${os.EOL}${sessionId}`
);
}
} catch (error) {
this.tryToParseSfdxError(response, error);
}
this.sendResponse(response);
}
private initBreakpointSessionServices(args: LaunchRequestArguments): void {
if (args && args.workspaceSettings) {
const workspaceSettings: WorkspaceSettings = args.workspaceSettings;
this.myRequestService.proxyUrl = workspaceSettings.proxyUrl;
this.myRequestService.proxyStrictSSL = workspaceSettings.proxyStrictSSL;
this.myRequestService.proxyAuthorization = workspaceSettings.proxyAuth;
this.myRequestService.connectionTimeoutMs =
workspaceSettings.connectionTimeoutMs;
}
// initialize services
this.mySessionService = new SessionService(this.myRequestService);
this.myBreakpointService = new BreakpointService(this.myRequestService);
}
private setValidBreakpointLines(args: LaunchRequestArguments): void {
if (args && args.lineBreakpointInfo) {
const lineBpInfo: LineBreakpointInfo[] = args.lineBreakpointInfo;
if (lineBpInfo && lineBpInfo.length > 0) {
const lineNumberMapping: Map<
string,
LineBreakpointsInTyperef[]
> = new Map();
const typerefMapping: Map<string, string> = new Map();
for (const info of lineBpInfo) {
if (!lineNumberMapping.has(info.uri)) {
lineNumberMapping.set(info.uri, []);
}
const validLines: LineBreakpointsInTyperef = {
typeref: info.typeref,
lines: info.lines
};
lineNumberMapping.get(info.uri)!.push(validLines);
typerefMapping.set(info.typeref, info.uri);
}
this.myBreakpointService.setValidLines(
lineNumberMapping,
typerefMapping
);
}
}
}
private setupLogger(args: LaunchRequestArguments): void {
if (typeof args.trace === 'boolean') {
this.trace = args.trace ? [TRACE_ALL] : undefined;
this.traceAll = args.trace;
} else if (typeof args.trace === 'string') {
this.trace = args.trace.split(',').map(category => category.trim());
this.traceAll = this.trace.indexOf(TRACE_ALL) >= 0;
}
if (this.trace && this.trace.indexOf(TRACE_CATEGORY_PROTOCOL) >= 0) {
// only log debug adapter protocol if 'protocol' tracing flag is set, ignore traceAll here
logger.setup(Logger.LogLevel.Verbose, false);
} else {
logger.setup(Logger.LogLevel.Stop, false);
}
}
protected async disconnectRequest(
response: DebugProtocol.DisconnectResponse,
args: DebugProtocol.DisconnectArguments
): Promise<void> {
try {
response.success = false;
this.myStreamingService.disconnect();
if (this.mySessionService.isConnected()) {
try {
const terminatedSessionId = await this.mySessionService.stop();
if (!this.mySessionService.isConnected()) {
response.success = true;
this.printToDebugConsole(
nls.localize('session_terminated_text', terminatedSessionId)
);
} else {
this.errorToDebugConsole(
`${nls.localize('command_error_help_text')}:${
os.EOL
}${terminatedSessionId}`
);
}
} catch (error) {
this.tryToParseSfdxError(response, error);
}
} else {
response.success = true;
}
this.sendResponse(response);
} finally {
this.clearIdleTimers();
}
}
protected async setBreakPointsRequest(
response: DebugProtocol.SetBreakpointsResponse,
args: DebugProtocol.SetBreakpointsArguments
): Promise<void> {
if (args.source && args.source.path && args.lines) {
response.body = { breakpoints: [] };
const uri = this.convertClientPathToDebugger(args.source.path);
const unverifiedBreakpoints: number[] = [];
let verifiedBreakpoints: Set<number> = new Set();
try {
verifiedBreakpoints = await this.lock.acquire(
`breakpoint-${uri}`,
async () => {
this.log(
TRACE_CATEGORY_BREAKPOINTS,
`setBreakPointsRequest: uri=${uri}`
);
const knownBps = await this.myBreakpointService.reconcileLineBreakpoints(
this.sfdxProject,
uri,
this.mySessionService.getSessionId(),
args.lines!.map(line => this.convertClientLineToDebugger(line))
);
return Promise.resolve(knownBps);
}
);
// tslint:disable-next-line:no-empty
} catch (error) {}
verifiedBreakpoints.forEach(verifiedBreakpoint => {
const lineNumber = this.convertDebuggerLineToClient(verifiedBreakpoint);
response.body.breakpoints.push({
verified: true,
source: args.source,
line: lineNumber
});
});
args.lines.forEach(lineArg => {
if (!verifiedBreakpoints.has(lineArg)) {
const lineNumber = this.convertDebuggerLineToClient(lineArg);
response.body.breakpoints.push({
verified: false,
source: args.source,
line: lineNumber
});
unverifiedBreakpoints.push(lineNumber);
}
});
this.log(
TRACE_CATEGORY_BREAKPOINTS,
`setBreakPointsRequest: uri=${uri} args.lines=${args.lines.join(
','
)} verified=${Array.from(verifiedBreakpoints).join(
','
)} unverified=${unverifiedBreakpoints.join(',')}`
);
}
response.success = true;
this.sendResponse(response);
}
protected async continueRequest(
response: DebugProtocol.ContinueResponse,
args: DebugProtocol.ContinueArguments
): Promise<void> {
response.success = false;
response.body = { allThreadsContinued: false };
if (this.requestThreads.has(args.threadId)) {
const requestId = this.requestThreads.get(args.threadId)!;
try {
await this.myRequestService.execute(new RunCommand(requestId));
response.success = true;
} catch (error) {
response.message = error;
}
}
this.resetIdleTimer();
this.sendResponse(response);
}
protected async nextRequest(
response: DebugProtocol.NextResponse,
args: DebugProtocol.NextArguments
): Promise<void> {
response.success = false;
if (this.requestThreads.has(args.threadId)) {
const requestId = this.requestThreads.get(args.threadId)!;
try {
await this.myRequestService.execute(new StepOverCommand(requestId));
response.success = true;
} catch (error) {
response.message = error;
}
}
this.sendResponse(response);
}
protected async stepInRequest(
response: DebugProtocol.StepInResponse,
args: DebugProtocol.StepInArguments
): Promise<void> {
response.success = false;
if (this.requestThreads.has(args.threadId)) {
const requestId = this.requestThreads.get(args.threadId)!;
try {
await this.myRequestService.execute(new StepIntoCommand(requestId));
response.success = true;
} catch (error) {
response.message = error;
}
}
this.sendResponse(response);
}
protected async stepOutRequest(
response: DebugProtocol.StepOutResponse,
args: DebugProtocol.StepOutArguments
): Promise<void> {
response.success = false;
if (this.requestThreads.has(args.threadId)) {
const requestId = this.requestThreads.get(args.threadId)!;
try {
await this.myRequestService.execute(new StepOutCommand(requestId));
response.success = true;
} catch (error) {
response.message = error;
}
}
this.sendResponse(response);
}
protected threadsRequest(response: DebugProtocol.ThreadsResponse): void {
const debuggedThreads: Thread[] = [];
for (const threadId of this.requestThreads.keys()) {
debuggedThreads.push(
new Thread(threadId, `Request ID: ${this.requestThreads.get(threadId)}`)
);
}
response.success = true;
response.body = { threads: debuggedThreads };
this.sendResponse(response);
}
protected async stackTraceRequest(
response: DebugProtocol.StackTraceResponse,
args: DebugProtocol.StackTraceArguments
): Promise<void> {
response.success = false;
if (!this.requestThreads.has(args.threadId)) {
return this.sendResponse(response);
}
const requestId = this.requestThreads.get(args.threadId)!;
try {
const stateResponse = await this.lock.acquire('stacktrace', async () => {
this.log(
TRACE_CATEGORY_VARIABLES,
`stackTraceRequest: args threadId=${args.threadId} startFrame=${args.startFrame} levels=${args.levels}`
);
const responseString = await this.myRequestService.execute(
new StateCommand(requestId)
);
return Promise.resolve(responseString);
});
const stateRespObj: DebuggerResponse = JSON.parse(stateResponse);
const clientFrames: StackFrame[] = [];
if (this.hasStackFrames(stateRespObj)) {
const serverFrames = stateRespObj.stateResponse.state.stack.stackFrame;
for (let i = 0; i < serverFrames.length; i++) {
const sourcePath = this.myBreakpointService.getSourcePathFromTyperef(
serverFrames[i].typeRef
);
const frameInfo = new ApexDebugStackFrameInfo(
requestId,
serverFrames[i].frameNumber
);
const frameId = this.stackFrameInfos.create(frameInfo);
if (i === 0 && stateRespObj.stateResponse.state) {
// populate first stack frame with info from state response (saves a server round trip)
this.log(
TRACE_CATEGORY_VARIABLES,
'stackTraceRequest: state=' +
JSON.stringify(stateRespObj.stateResponse.state)
);
if (
stateRespObj.stateResponse.state.locals &&
stateRespObj.stateResponse.state.locals.local
) {
frameInfo.locals = stateRespObj.stateResponse.state.locals.local;
} else {
frameInfo.locals = [];
}
if (
stateRespObj.stateResponse.state.statics &&
stateRespObj.stateResponse.state.statics.static
) {
frameInfo.statics =
stateRespObj.stateResponse.state.statics.static;
} else {
frameInfo.statics = [];
}
if (
stateRespObj.stateResponse.state.globals &&
stateRespObj.stateResponse.state.globals.global
) {
frameInfo.globals =
stateRespObj.stateResponse.state.globals.global;
} else {
frameInfo.globals = [];
}
if (
stateRespObj.stateResponse.state.references &&
stateRespObj.stateResponse.state.references.references
) {
this.populateReferences(
stateRespObj.stateResponse.state.references.references,
frameInfo.requestId
);
}
}
clientFrames.push(
new StackFrame(
frameId,
serverFrames[i].fullName,
sourcePath
? new Source(
basename(sourcePath),
this.convertDebuggerPathToClient(sourcePath)
)
: undefined,
this.convertDebuggerLineToClient(serverFrames[i].lineNumber),
0
)
);
}
}
response.body = { stackFrames: clientFrames };
response.success = true;
} catch (error) {
response.message = error;
}
this.sendResponse(response);
}
private hasStackFrames(response: DebuggerResponse): boolean {
if (
response &&
response.stateResponse &&
response.stateResponse.state &&
response.stateResponse.state.stack &&
response.stateResponse.state.stack.stackFrame &&
response.stateResponse.state.stack.stackFrame.length > 0
) {
return true;
}
return false;
}
protected async customRequest(
command: string,
response: DebugProtocol.Response,
args: any
): Promise<void> {
response.success = true;
switch (command) {
case HOTSWAP_REQUEST:
this.warnToDebugConsole(nls.localize('hotswap_warn_text'));
break;
case EXCEPTION_BREAKPOINT_REQUEST:
const requestArgs: SetExceptionBreakpointsArguments = args;
if (requestArgs && requestArgs.exceptionInfo) {
try {
await this.lock.acquire('exception-breakpoint', async () => {
return this.myBreakpointService.reconcileExceptionBreakpoints(
this.sfdxProject,
this.mySessionService.getSessionId(),
requestArgs.exceptionInfo
);
});
if (
requestArgs.exceptionInfo.breakMode ===
EXCEPTION_BREAKPOINT_BREAK_MODE_ALWAYS
) {
this.printToDebugConsole(
nls.localize(
'created_exception_breakpoint_text',
requestArgs.exceptionInfo.label
)
);
} else if (
requestArgs.exceptionInfo.breakMode ===
EXCEPTION_BREAKPOINT_BREAK_MODE_NEVER
) {
this.printToDebugConsole(
nls.localize(
'removed_exception_breakpoint_text',
requestArgs.exceptionInfo.label
)
);
}
} catch (error) {
response.success = false;
this.log(
TRACE_CATEGORY_BREAKPOINTS,
`exceptionBreakpointRequest: error=${error}`
);
}
}
break;
case LIST_EXCEPTION_BREAKPOINTS_REQUEST:
const exceptionBreakpoints = this.myBreakpointService.getExceptionBreakpointCache();
response.body = {
typerefs: Array.from(exceptionBreakpoints.keys())
};
break;
default:
break;
}
this.sendResponse(response);
}
protected async scopesRequest(
response: DebugProtocol.ScopesResponse,
args: DebugProtocol.ScopesArguments
): Promise<void> {
response.success = true;
const frameInfo = this.stackFrameInfos.get(args.frameId);
if (!frameInfo) {
this.log(
TRACE_CATEGORY_VARIABLES,
`scopesRequest: no frame info found for stack frame ${args.frameId}`
);
response.body = { scopes: [] };
this.sendResponse(response);
return;
}
const scopes = new Array<Scope>();
scopes.push(
new Scope(
'Local',
this.variableHandles.create(new ScopeContainer('local', frameInfo)),
false
)
);
scopes.push(
new Scope(
'Static',
this.variableHandles.create(new ScopeContainer('static', frameInfo)),
false
)
);
scopes.push(
new Scope(
'Global',
this.variableHandles.create(new ScopeContainer('global', frameInfo)),
false
)
);
scopes.forEach(scope => {
this.log(
TRACE_CATEGORY_VARIABLES,
`scopesRequest: scope name=${scope.name} variablesReference=${scope.variablesReference}`
);
});
response.body = { scopes };
this.sendResponse(response);
}
protected async variablesRequest(
response: DebugProtocol.VariablesResponse,
args: DebugProtocol.VariablesArguments
): Promise<void> {
response.success = true;
const variablesContainer = this.variableHandles.get(
args.variablesReference
);
if (!variablesContainer) {
this.log(
TRACE_CATEGORY_VARIABLES,
`variablesRequest: no container for variablesReference=${args.variablesReference}`
);
// no container found: return empty variables array
response.body = { variables: [] };
this.sendResponse(response);
return;
} else {
this.log(
TRACE_CATEGORY_VARIABLES,
`variablesRequest: getting variable for variablesReference=${args.variablesReference} start=${args.start} count=${args.count}`
);
}
const filter: FilterType =
args.filter === 'indexed' || args.filter === 'named'
? args.filter
: 'all';
try {
const variables = await variablesContainer.expand(
this,
filter,
args.start,
args.count
);
variables.sort(ApexVariable.compareVariables);
response.body = { variables };
this.resetIdleTimer();
this.sendResponse(response);
} catch (error) {
this.log(
TRACE_CATEGORY_VARIABLES,
`variablesRequest: error reading variables ${error} ${error.stack}`
);
// in case of error return empty variables array
response.body = { variables: [] };
this.sendResponse(response);
}
}
public async fetchFrameVariables(
frameInfo: ApexDebugStackFrameInfo
): Promise<void> {
const frameResponse = await this.myRequestService.execute(
new FrameCommand(frameInfo.requestId, frameInfo.frameNumber)
);
const frameRespObj: DebuggerResponse = JSON.parse(frameResponse);
if (
frameRespObj &&
frameRespObj.frameResponse &&
frameRespObj.frameResponse.frame
) {
this.log(
TRACE_CATEGORY_VARIABLES,
`fetchFrameVariables: frame ${frameInfo.frameNumber} frame=` +
JSON.stringify(frameRespObj.frameResponse.frame)
);
if (
frameRespObj.frameResponse.frame.locals &&
frameRespObj.frameResponse.frame.locals.local
) {
frameInfo.locals = frameRespObj.frameResponse.frame.locals.local;
} else {
frameInfo.locals = [];
}
if (
frameRespObj.frameResponse.frame.statics &&
frameRespObj.frameResponse.frame.statics.static
) {
frameInfo.statics = frameRespObj.frameResponse.frame.statics.static;
} else {
frameInfo.statics = [];
}
if (
frameRespObj.frameResponse.frame.globals &&
frameRespObj.frameResponse.frame.globals.global
) {
frameInfo.globals = frameRespObj.frameResponse.frame.globals.global;
} else {
frameInfo.globals = [];
}
if (
frameRespObj.frameResponse.frame.references &&
frameRespObj.frameResponse.frame.references.references
) {
this.populateReferences(
frameRespObj.frameResponse.frame.references.references,
frameInfo.requestId
);
}
}
}
protected populateReferences(
references: Reference[],
requestId: string
): void {
references.map(reference => {
if (this.variableContainerReferenceByApexId.has(reference.id)) {
return;
}
let variableReference: number;
if (reference.type === 'object') {
variableReference = this.variableHandles.create(
new ObjectReferenceContainer(reference, requestId)
);
this.log(
TRACE_CATEGORY_VARIABLES,
`populateReferences: new object reference: ${variableReference} for ${reference.id} ${reference.nameForMessages}`
);
} else if (reference.type === 'list' || reference.type === 'set') {
variableReference = this.variableHandles.create(
new CollectionReferenceContainer(reference, requestId)
);
this.log(
TRACE_CATEGORY_VARIABLES,
`populateReferences: new ${reference.type} reference: ${variableReference} for ${reference.id} ${reference.nameForMessages} with size ${reference.size}`
);
} else if (reference.type === 'map') {
const mapContainer = new MapReferenceContainer(reference, requestId);
// explode all map entried so that we can drill down a map logically
if (reference.tuple) {
reference.tuple.forEach(tuple => {
const tupleContainer = new MapTupleContainer(tuple, requestId);
const tupleReference = this.variableHandles.create(tupleContainer);
mapContainer.addTupleContainer(tupleReference, tupleContainer);
});
}
variableReference = this.variableHandles.create(mapContainer);
this.log(
TRACE_CATEGORY_VARIABLES,
`populateReferences: new map reference: ${variableReference} for ${reference.id} ${reference.nameForMessages}`
);
} else {
const referenceInfo = JSON.stringify(reference);
this.log(
TRACE_CATEGORY_VARIABLES,
`populateReferences: unhandled reference: ${referenceInfo}`
);
return;
}
// map apex id to container reference
this.variableContainerReferenceByApexId.set(
reference.id,
variableReference
);
});
}
public getNumberOfChildren(
variableReference: number | undefined
): number | undefined {
if (variableReference !== undefined) {
const variableContainer = this.variableHandles.get(variableReference);
if (variableContainer) {
return variableContainer.getNumberOfChildren();
}
}
}
public async resolveApexIdToVariableReference(
requestId: string,
apexId: number | undefined
): Promise<number | undefined> {
if (typeof apexId === 'undefined') {
return;
}
if (!this.variableContainerReferenceByApexId.has(apexId)) {
await this.fetchReferences(requestId, apexId);
if (!this.variableContainerReferenceByApexId.has(apexId)) {
this.log(
TRACE_CATEGORY_VARIABLES,
`resolveApexIdToVariableReference: no reference found for apexId ${apexId} (request ${requestId})`
);
return;
}
}
const variableReference = this.variableContainerReferenceByApexId.get(
apexId
);
this.log(
TRACE_CATEGORY_VARIABLES,
`resolveApexIdToVariableReference: resolved apexId=${apexId} to variableReference=${variableReference}`
);
return variableReference;
}
public async fetchReferences(
requestId: string,
...apexIds: number[]
): Promise<void> {
this.log(
TRACE_CATEGORY_VARIABLES,
`fetchReferences: fetching references with apexIds=${apexIds} (request ${requestId})`
);
const referencesResponse = await this.myRequestService.execute(
new ReferencesCommand(requestId, ...apexIds)
);
const referencesResponseObj: DebuggerResponse = JSON.parse(
referencesResponse
);
if (
referencesResponseObj &&
referencesResponseObj.referencesResponse &&
referencesResponseObj.referencesResponse.references &&
referencesResponseObj.referencesResponse.references.references
) {
this.populateReferences(
referencesResponseObj.referencesResponse.references.references,
requestId
);
}
}
public async fetchReferencesIfNecessary(
requestId: string,
apexIds: number[]
): Promise<void> {
const apexIdsToFetch = apexIds.filter(
apexId => !this.variableContainerReferenceByApexId.has(apexId)
);
if (apexIdsToFetch.length === 0) {
return;
}
this.log(
TRACE_CATEGORY_VARIABLES,
`fetchReferences: fetching references with apexIds=${apexIdsToFetch} (request ${requestId})`
);
await this.fetchReferences(requestId, ...apexIdsToFetch);
}
protected evaluateRequest(
response: DebugProtocol.EvaluateResponse,
args: DebugProtocol.EvaluateArguments
): void {
response.body = {
result: args.expression,
variablesReference: 0
};
response.success = true;
this.sendResponse(response);
}
protected printToDebugConsole(
msg?: string,
sourceFile?: Source,
sourceLine?: number
): void {
if (msg && msg.length !== 0) {
const event: DebugProtocol.OutputEvent = new OutputEvent(
`${msg}${ApexDebug.LINEBREAK}`,
'stdout'
);
event.body.source = sourceFile;
event.body.line = sourceLine;
event.body.column = 0;
this.sendEvent(event);
}
}
protected warnToDebugConsole(msg?: string): void {
if (msg && msg.length !== 0) {
this.sendEvent(
new OutputEvent(`${msg}${ApexDebug.LINEBREAK}`, 'console')
);
}
}
protected errorToDebugConsole(msg?: string): void {
if (msg && msg.length !== 0) {
this.sendEvent(new OutputEvent(`${msg}${ApexDebug.LINEBREAK}`, 'stderr'));
}
}
public log(traceCategory: TraceCategory, message: string) {
if (
this.trace &&
(this.traceAll || this.trace.indexOf(traceCategory) >= 0)
) {
this.printToDebugConsole(`${process.pid}: ${message}`);
}
}
public tryToParseSfdxError(
response: DebugProtocol.Response,
error?: any
): void {
if (!error) {
return;
}
try {
response.success = false;
const errorObj = extractJsonObject(error);
if (errorObj && errorObj.message) {
const errorMessage: string = errorObj.message;
if (
errorMessage.includes(
'entity type cannot be inserted: Apex Debugger Session'
)
) {
response.message = nls.localize('session_no_entity_access_text');
} else {
response.message = errorMessage;
}
if (errorObj.action) {
this.errorToDebugConsole(
`${nls.localize('command_error_help_text')}:${os.EOL}${
errorObj.action
}`
);
}
} else {
response.message = nls.localize('unexpected_error_help_text');
this.errorToDebugConsole(
`${nls.localize('command_error_help_text')}:${os.EOL}${error}`
);
}
} catch (e) {
response.message =
response.message || nls.localize('unexpected_error_help_text');
this.errorToDebugConsole(
`${nls.localize('command_error_help_text')}:${os.EOL}${error}`
);
}
}
public async connectStreaming(projectPath: string): Promise<boolean> {
const clientInfos: StreamingClientInfo[] = [];
for (const channel of [
StreamingService.SYSTEM_EVENT_CHANNEL,
StreamingService.USER_EVENT_CHANNEL
]) {
const clientInfo = new StreamingClientInfoBuilder()
.forChannel(channel)
.withConnectedHandler(() => {
this.printToDebugConsole(
nls.localize('streaming_connected_text', channel)
);
})
.withDisconnectedHandler(() => {
this.printToDebugConsole(
nls.localize('streaming_disconnected_text', channel)
);
})
.withErrorHandler((reason: string) => {
this.errorToDebugConsole(reason);
})
.withMsgHandler((message: any) => {
const data = message as DebuggerMessage;
if (data && data.sobject && data.event) {
this.handleEvent(data);
}
})
.build();
clientInfos.push(clientInfo);
}
const systemChannelInfo = clientInfos[0];
const userChannelInfo = clientInfos[1];
return this.myStreamingService.subscribe(
projectPath,
this.myRequestService,
systemChannelInfo,
userChannelInfo
);
}
public handleEvent(message: DebuggerMessage): void {
const type: ApexDebuggerEventType = (ApexDebuggerEventType as any)[
message.sobject.Type
];
this.log(
TRACE_CATEGORY_STREAMINGAPI,
`handleEvent: received ${JSON.stringify(message)}`
);
if (
!this.mySessionService.isConnected() ||
this.mySessionService.getSessionId() !== message.sobject.SessionId ||
this.myStreamingService.hasProcessedEvent(type, message.event.replayId)
) {
this.log(TRACE_CATEGORY_STREAMINGAPI, `handleEvent: event ignored`);
return;
}
switch (type) {
case ApexDebuggerEventType.ApexException: {
this.handleApexException(message);
break;
}
case ApexDebuggerEventType.Debug: {
this.handleDebug(message);
break;
}
case ApexDebuggerEventType.RequestFinished: {
this.handleRequestFinished(message);
break;
}
case ApexDebuggerEventType.RequestStarted: {
this.handleRequestStarted(message);
break;
}
case ApexDebuggerEventType.Resumed: {
this.handleResumed(message);
break;
}
case ApexDebuggerEventType.SessionTerminated: {
this.handleSessionTerminated(message);
break;
}
case ApexDebuggerEventType.Stopped: {
this.handleStopped(message);
break;
}
case ApexDebuggerEventType.SystemGack: {
this.handleSystemGack(message);
break;
}
case ApexDebuggerEventType.SystemInfo: {
this.handleSystemInfo(message);
break;
}
case ApexDebuggerEventType.SystemWarning: {
this.handleSystemWarning(message);
break;
}
case ApexDebuggerEventType.LogLine:
case ApexDebuggerEventType.OrgChange:
case ApexDebuggerEventType.Ready:
default: {
break;
}
}
this.myStreamingService.markEventProcessed(type, message.event.replayId);
}
public logEvent(message: DebuggerMessage): void {
let eventDescriptionSourceFile: Source | undefined;
let eventDescriptionSourceLine: number | undefined;
let logMessage =
message.event.createdDate === null
? new Date().toUTCString()
: message.event.createdDate;
logMessage += ` | ${message.sobject.Type}`;
if (message.sobject.RequestId) {
logMessage += ` | Request: ${message.sobject.RequestId}`;
}
if (message.sobject.BreakpointId) {
logMessage += ` | Breakpoint: ${message.sobject.BreakpointId}`;
}
if (message.sobject.Line) {
logMessage += ` | Line: ${message.sobject.Line}`;
}
if (message.sobject.Description) {
logMessage += ` | ${message.sobject.Description}`;
const regExp: RegExp = /^(.*)\[(\d+)\]\|/;
const matches = message.sobject.Description.match(regExp);
if (matches && matches.length === 3) {
const possibleClassName = matches[1];
const possibleClassLine = parseInt(matches[2], 10);
const possibleSourcePath = this.myBreakpointService.getSourcePathFromPartialTyperef(
possibleClassName
);
if (possibleSourcePath) {
eventDescriptionSourceFile = new Source(
basename(possibleSourcePath),
this.convertDebuggerPathToClient(possibleSourcePath)
);
eventDescriptionSourceLine = this.convertDebuggerLineToClient(
possibleClassLine
);
}
}
}
if (message.sobject.Stacktrace) {
logMessage += ` |${os.EOL}${message.sobject.Stacktrace}`;
}
this.printToDebugConsole(
logMessage,
eventDescriptionSourceFile,
eventDescriptionSourceLine
);
}
private getThreadIdFromRequestId(
requestId: string | undefined
): number | undefined {
for (const threadId of this.requestThreads.keys()) {
if (this.requestThreads.get(threadId) === requestId) {
return threadId;
}
}
}
private handleApexException(message: DebuggerMessage): void {
this.logEvent(message);
}
private handleDebug(message: DebuggerMessage): void {
this.logEvent(message);
}
private handleRequestFinished(message: DebuggerMessage): void {
const threadId = this.getThreadIdFromRequestId(message.sobject.RequestId);
if (threadId !== undefined) {
this.logEvent(message);
this.requestThreads.delete(threadId);
this.sendEvent(new ThreadEvent('exited', threadId));
// cleanup everything that's no longer necessary after all request finished
if (this.requestThreads.size === 0) {
this.log(
TRACE_CATEGORY_VARIABLES,
'handleRequestFinished: clearing variable cache'
);
this.stackFrameInfos.reset();
this.variableHandles.reset();
this.variableContainerReferenceByApexId.clear();
}
}
}
private handleRequestStarted(message: DebuggerMessage): void {
if (message.sobject.RequestId) {
this.logEvent(message);
this.requestThreads.set(this.threadId++, message.sobject.RequestId);
}
}
private handleResumed(message: DebuggerMessage): void {
const threadId = this.getThreadIdFromRequestId(message.sobject.RequestId);
if (threadId !== undefined) {
this.logEvent(message);
}
}
private handleSessionTerminated(message: DebuggerMessage): void {
if (message.sobject.Description) {
this.errorToDebugConsole(message.sobject.Description);
this.sendEvent(
new Event(SHOW_MESSAGE_EVENT, {
type: VscodeDebuggerMessageType.Error,
message: message.sobject.Description
} as VscodeDebuggerMessage)
);
}
this.mySessionService.forceStop();
this.sendEvent(new TerminatedEvent());
}
private handleStopped(message: DebuggerMessage): void {
const threadId = this.getThreadIdFromRequestId(message.sobject.RequestId);
if (threadId !== undefined) {
// cleanup everything that's no longer valid after a stop event
// but only if only one request is currently debugged (we wan't to preserve the info for a second request)
if (this.requestThreads.size === 1) {
this.log(
TRACE_CATEGORY_VARIABLES,
'handleStopped: clearing variable cache'
);
this.stackFrameInfos.reset();
this.variableHandles.reset();
this.variableContainerReferenceByApexId.clear();
}
// log to console and notify client
this.logEvent(message);
let reason = '';
// if breakpointid is found in exception breakpoint cache
// set the reason for stopped event to that reason
if (message.sobject.BreakpointId) {
const cache: Map<
string,
string
> = this.myBreakpointService.getExceptionBreakpointCache();
cache.forEach((value, key) => {
if (value === message.sobject.BreakpointId) {
// typerefs for exceptions will change based on whether they are custom,
// defined as an inner class, defined in a trigger, or in a namespaced org
reason = key
.replace(SALESFORCE_EXCEPTION_PREFIX, '')
.replace(TRIGGER_EXCEPTION_PREFIX, '')
.replace('$', '.')
.replace('/', '.');
}
});
}
const stoppedEvent: DebugProtocol.StoppedEvent = new StoppedEvent(
reason,
threadId
);
this.sendEvent(stoppedEvent);
}
}
private handleSystemGack(message: DebuggerMessage): void {
this.logEvent(message);
if (message.sobject.Description) {
this.sendEvent(
new Event(SHOW_MESSAGE_EVENT, {
type: VscodeDebuggerMessageType.Error,
message: message.sobject.Description
} as VscodeDebuggerMessage)
);
}
}
private handleSystemInfo(message: DebuggerMessage): void {
this.logEvent(message);
}
private handleSystemWarning(message: DebuggerMessage): void {
this.logEvent(message);
if (message.sobject.Description) {
this.sendEvent(
new Event(SHOW_MESSAGE_EVENT, {
type: VscodeDebuggerMessageType.Warning,
message: message.sobject.Description
} as VscodeDebuggerMessage)
);
}
}
public toCommaSeparatedString(arg?: string[]): string {
if (arg && arg.length > 0) {
return Array.from(new Set(arg)).join(',');
}
return '';
}
}
DebugSession.run(ApexDebug); | the_stack |
import { ProtocolService, UiEventService } from '@airgap/angular-core'
import {
AirGapCoinWallet,
AirGapMarketWallet,
IACMessageType,
IAirGapTransaction,
ICoinProtocol,
MainProtocolSymbols,
SerializedAirGapWallet,
TezosProtocol
} from '@airgap/coinlib-core'
import { TezosProtocolNetwork, TezosProtocolOptions } from '@airgap/coinlib-core/protocols/tezos/TezosProtocolOptions'
import { AirGapWalletStatus } from '@airgap/coinlib-core/wallet/AirGapWallet'
import { Injectable } from '@angular/core'
import { Router } from '@angular/router'
import { PushNotificationSchema } from '@capacitor/push-notifications'
import { AlertController, LoadingController, PopoverController, ToastController } from '@ionic/angular'
import { Observable, ReplaySubject, Subject } from 'rxjs'
import { auditTime, map, take } from 'rxjs/operators'
import { DelegateAlertAction } from '../../models/actions/DelegateAlertAction'
import { AirGapTipUsAction } from '../../models/actions/TipUsAction'
import { AirGapMarketWalletGroup, InteractionSetting, SerializedAirGapMarketWalletGroup } from '../../models/AirGapMarketWalletGroup'
import { isType } from '../../utils/utils'
import { DataService } from '../data/data.service'
import { DrawChartService } from '../draw-chart/draw-chart.service'
import { InteractionService } from '../interaction/interaction.service'
import { OperationsProvider } from '../operations/operations'
import { PriceService } from '../price/price.service'
import { PushProvider } from '../push/push'
import { ErrorCategory, handleErrorSentry } from '../sentry-error-handler/sentry-error-handler'
import { WalletStorageKey, WalletStorageService } from '../storage/storage'
enum NotificationKind {
CTA_Tip = 'cta_tip',
CTA_Delegate = 'cta_delegate'
}
interface CTAInfo {
kind: NotificationKind
fromAddress: string
toAddress: string
amount: string
alertTitle: string
alertDescription: string
}
export interface WalletAddInfo {
walletToAdd: AirGapMarketWallet
groupId?: string
groupLabel?: string
options?: { override?: boolean; updateState?: boolean }
}
export type ImplicitWalletGroup = 'all'
export type ActiveWalletGroup = AirGapMarketWalletGroup | ImplicitWalletGroup
@Injectable({
providedIn: 'root'
})
export class AccountProvider {
private readonly activeGroup$: ReplaySubject<ActiveWalletGroup> = new ReplaySubject(1)
private readonly walletGroups: Map<string | undefined, AirGapMarketWalletGroup> = new Map()
public walletsHaveLoaded: ReplaySubject<boolean> = new ReplaySubject(1)
public refreshPageSubject: Subject<void> = new Subject()
public walletGroups$: ReplaySubject<AirGapMarketWalletGroup[]> = new ReplaySubject(1)
public wallets$: ReplaySubject<AirGapMarketWallet[]> = new ReplaySubject(1)
public allWallets$: ReplaySubject<AirGapMarketWallet[]> = new ReplaySubject(1)
public subWallets$: ReplaySubject<AirGapMarketWallet[]> = new ReplaySubject(1)
public usedProtocols$: ReplaySubject<ICoinProtocol[]> = new ReplaySubject(1)
private readonly walletChangedBehaviour: Subject<void> = new Subject()
get walletChangedObservable() {
return this.walletChangedBehaviour.asObservable().pipe(auditTime(50))
}
public get allWalletGroups(): AirGapMarketWalletGroup[] {
return Array.from(this.walletGroups.values())
}
private get allWallets(): AirGapMarketWallet[] {
return this.allWalletGroups.reduce((wallets: AirGapMarketWallet[], group: AirGapMarketWalletGroup) => wallets.concat(group.wallets), [])
}
constructor(
private readonly storageProvider: WalletStorageService,
private readonly pushProvider: PushProvider,
private readonly drawChartProvider: DrawChartService,
private readonly popoverController: PopoverController,
private readonly uiEventService: UiEventService,
private readonly alertController: AlertController,
private readonly toastController: ToastController,
private readonly loadingController: LoadingController,
private readonly opertaionsProvider: OperationsProvider,
private readonly dataService: DataService,
private readonly router: Router,
private readonly interactionService: InteractionService,
private readonly priceService: PriceService,
private readonly protocolService: ProtocolService
) {
this.loadWalletsFromStorage()
.then(() => {
this.walletsHaveLoaded.next(true)
})
.catch(console.error)
this.wallets$.pipe(map((wallets) => wallets.filter((wallet) => 'subProtocolType' in wallet.protocol))).subscribe(this.subWallets$)
this.wallets$.pipe(map((wallets) => this.getProtocolsFromWallets(wallets))).subscribe(this.usedProtocols$)
this.pushProvider.notificationCallback = (notification: PushNotificationSchema): void => {
// We need a timeout because otherwise routing might fail
const env = {
popoverController: this.popoverController,
loadingController: this.loadingController,
uiEventService: this.uiEventService,
alertController: this.alertController,
toastController: this.toastController,
operationsProvider: this.opertaionsProvider,
dataService: this.dataService,
accountService: this,
router: this.router
}
if (notification && isType<CTAInfo>(notification.data)) {
const tippingInfo: CTAInfo = notification.data
if (tippingInfo.kind === NotificationKind.CTA_Tip) {
const originWallet: AirGapMarketWallet = this.getWalletList().find((wallet: AirGapMarketWallet) =>
wallet.addresses.some((address: string) => address === tippingInfo.fromAddress)
)
setTimeout(() => {
const tipAction: AirGapTipUsAction = new AirGapTipUsAction({
wallet: originWallet,
tipAddress: tippingInfo.toAddress,
amount: tippingInfo.amount,
alertTitle: tippingInfo.alertTitle,
alertDescription: tippingInfo.alertDescription,
...env
})
tipAction.start()
}, 3500)
}
if (tippingInfo.kind === NotificationKind.CTA_Delegate) {
const originWallet: AirGapMarketWallet = this.getWalletList().find((wallet: AirGapMarketWallet) =>
wallet.addresses.some((address: string) => address === tippingInfo.fromAddress)
)
setTimeout(() => {
const delegateAlertAction: DelegateAlertAction = new DelegateAlertAction({
wallet: originWallet,
delegate: tippingInfo.toAddress,
alertTitle: tippingInfo.alertTitle,
alertDescription: tippingInfo.alertDescription,
...env
})
delegateAlertAction.start()
}, 3500)
}
}
}
}
public startInteraction(
wallet: AirGapMarketWallet,
interactionData: unknown,
type: IACMessageType,
airGapTxs?: IAirGapTransaction[],
isRelay: boolean = false,
generatedId?: number
) {
const group = this.walletGroupByWallet(wallet)
this.interactionService.startInteraction(group, wallet, interactionData, type, airGapTxs, isRelay, generatedId)
}
public getActiveWalletGroupObservable(): Observable<ActiveWalletGroup> {
return this.activeGroup$.asObservable()
}
public getWalletGroupsObservable(): Observable<AirGapMarketWalletGroup[]> {
return this.walletGroups$.asObservable().pipe(map((groups: AirGapMarketWalletGroup[]) => this.sortGroupsByLabel(groups)))
}
public triggerWalletChanged() {
this.walletChangedBehaviour.next()
}
private getProtocolsFromWallets(wallets: AirGapMarketWallet[]) {
const protocols: Map<string, ICoinProtocol> = new Map()
wallets.forEach((wallet) => {
if (!protocols.has(wallet.protocol.identifier)) {
protocols.set(wallet.protocol.identifier, wallet.protocol)
}
})
return Array.from(protocols.values())
}
public hasInactiveWallets(protocol: ICoinProtocol): boolean {
return this.allWallets.some(
(wallet: AirGapMarketWallet) => wallet.protocol.identifier === protocol.identifier && wallet.status !== AirGapWalletStatus.ACTIVE
)
}
private async loadWalletsFromStorage() {
const [rawGroups, rawWallets]: [
SerializedAirGapMarketWalletGroup[] | undefined,
SerializedAirGapWallet[] | undefined
] = await Promise.all([this.storageProvider.get(WalletStorageKey.WALLET_GROUPS), this.storageProvider.get(WalletStorageKey.WALLET)])
const groups = rawGroups || []
let wallets = rawWallets || []
// migrating double-serialization
if (!(rawWallets instanceof Array)) {
try {
wallets = JSON.parse(rawWallets)
} catch (e) {
wallets = []
}
}
// "wallets" can be undefined here
if (!wallets) {
wallets = []
}
const walletMap: Record<string, SerializedAirGapWallet | undefined> = wallets.reduce(
(obj: Record<string, SerializedAirGapWallet>, next: SerializedAirGapWallet) =>
Object.assign(obj, { [this.createWalletIdentifier(next.protocolIdentifier, next.publicKey)]: next }),
{}
)
const walletInitPromises: Promise<void>[] = []
// read groups
await Promise.all(
groups.map(async (group: SerializedAirGapMarketWalletGroup) => {
const wallets: AirGapMarketWallet[] = (
await Promise.all(
group.wallets.map(async ([protocolIdentifier, publicKey]: [string, string]) => {
const walletIdentifier: string = this.createWalletIdentifier(protocolIdentifier, publicKey)
const serializedWallet: SerializedAirGapWallet | undefined = walletMap[walletIdentifier]
if (serializedWallet === undefined) {
return undefined
}
walletMap[walletIdentifier] = undefined
const airGapWallet: AirGapMarketWallet = await this.readSerializedWallet(serializedWallet)
walletInitPromises.push(this.initializeWallet(airGapWallet))
return airGapWallet
})
)
).filter((wallet: AirGapMarketWallet | undefined) => wallet !== undefined)
const walletGroup: AirGapMarketWalletGroup = new AirGapMarketWalletGroup(group.id, group.label, group.interactionSetting, wallets)
this.walletGroups.set(walletGroup.id, walletGroup)
})
)
// read ungrouped wallets
const ungroupedWallets: AirGapMarketWallet[] = await Promise.all(
Object.values(walletMap)
.filter((serializedWallet: SerializedAirGapWallet | undefined) => serializedWallet !== undefined)
.map(async (serializedWallet: SerializedAirGapWallet) => {
const airGapWallet: AirGapMarketWallet = await this.readSerializedWallet(serializedWallet)
walletInitPromises.push(this.initializeWallet(airGapWallet))
return airGapWallet
})
)
if (ungroupedWallets.length > 0) {
const others: AirGapMarketWalletGroup = new AirGapMarketWalletGroup(undefined, undefined, undefined, ungroupedWallets, true)
this.walletGroups.set(others.id, others)
}
Promise.all(walletInitPromises).then(() => {
this.triggerWalletChanged()
})
/* Use for Testing of Skeleton
await new Promise(resolve => {
setTimeout(() => {
resolve()
}, 2000)
})
*/
if (this.allWallets.length > 0) {
this.pushProvider.setupPush()
}
this.setActiveGroup(this.allWalletGroups.length > 1 ? 'all' : this.allWalletGroups[0])
this.walletGroups$.next(this.allWalletGroups)
this.pushProvider.registerWallets(this.allWallets)
}
private async readSerializedWallet(serializedWallet: SerializedAirGapWallet): Promise<AirGapMarketWallet> {
const protocol: ICoinProtocol = await this.protocolService.getProtocol(
serializedWallet.protocolIdentifier,
serializedWallet.networkIdentifier
)
const airGapWallet: AirGapMarketWallet = new AirGapCoinWallet(
protocol,
serializedWallet.publicKey,
serializedWallet.isExtendedPublicKey,
serializedWallet.derivationPath,
serializedWallet.masterFingerprint || '',
serializedWallet.status || AirGapWalletStatus.ACTIVE,
this.priceService,
serializedWallet.addressIndex
)
// add derived addresses
airGapWallet.addresses = serializedWallet.addresses
return airGapWallet
}
private async initializeWallet(airGapWallet: AirGapMarketWallet): Promise<void> {
return new Promise<void>((resolve) => {
// if we have no addresses, derive using webworker and sync, else just sync
if (airGapWallet.addresses.length === 0 || (airGapWallet.isExtendedPublicKey && airGapWallet.addresses.length < 20)) {
const airGapWorker = new Worker('./assets/workers/airgap-coin-lib.js')
airGapWorker.onmessage = (event) => {
airGapWallet.addresses = event.data.addresses
airGapWallet
.synchronize()
.then(() => {
resolve()
})
.catch((error) => {
console.error(error)
resolve()
})
}
airGapWorker.postMessage({
protocolIdentifier: airGapWallet.protocol.identifier,
publicKey: airGapWallet.publicKey,
isExtendedPublicKey: airGapWallet.isExtendedPublicKey,
derivationPath: airGapWallet.derivationPath,
addressIndex: airGapWallet.addressIndex
})
} else {
airGapWallet
.synchronize()
.then(() => {
resolve()
})
.catch((error) => {
console.error(error)
resolve()
})
}
})
}
public getWalletList(): AirGapMarketWallet[] {
return this.allWallets
}
public setActiveGroup(groupToSet: AirGapMarketWalletGroup | ImplicitWalletGroup | undefined): void {
if (groupToSet === 'all') {
this.activeGroup$.next(groupToSet)
this.wallets$.next(this.allWallets)
} else if (groupToSet !== undefined && this.walletGroups.has(groupToSet.id)) {
const group: AirGapMarketWalletGroup = this.walletGroups.get(groupToSet.id)
const wallets: AirGapMarketWallet[] = group.wallets
this.activeGroup$.next(group)
this.wallets$.next(wallets)
} else {
this.wallets$.next([])
}
this.allWallets$.next(this.allWallets)
}
public async addWallets(walletAddInfos: WalletAddInfo[]): Promise<void> {
let existingWallets = []
for (let walletAddInfo of walletAddInfos) {
const defaultOptions = {
override: false,
updateState: true
}
const resolvedOptions = {
...defaultOptions,
...(walletAddInfo.options ?? {})
}
const alreadyExists: boolean = this.walletExists(walletAddInfo.walletToAdd)
if (alreadyExists) {
existingWallets.push(walletAddInfo.walletToAdd)
if (!resolvedOptions.override) {
throw new Error('wallet already exists')
}
}
await this.addWallet(walletAddInfo, resolvedOptions)
}
const activeNewWallets = walletAddInfos
.filter(
(walletAddInfo) =>
walletAddInfo.walletToAdd.status === AirGapWalletStatus.ACTIVE &&
!existingWallets.some(
(wallet: AirGapMarketWallet) =>
this.isSameWallet(wallet, walletAddInfo.walletToAdd) && wallet.status === walletAddInfo.walletToAdd.status
)
)
.map((walletAddInfo) => walletAddInfo.walletToAdd)
await this.registerToPushBackend(activeNewWallets)
this.drawChartProvider.drawChart()
}
private async addWallet(
walletAddInfo: WalletAddInfo,
resolvedOptions: {
override: boolean
updateState: boolean
}
): Promise<void> {
if (walletAddInfo.groupId === '') {
walletAddInfo.groupId = undefined
}
if (walletAddInfo.groupLabel === '') {
walletAddInfo.groupLabel = undefined
}
this.assertWalletGroupExists(walletAddInfo.groupId, walletAddInfo.groupLabel)
this.assertWalletGroupUpdated(walletAddInfo.groupId, walletAddInfo.groupLabel)
const walletGroup: AirGapMarketWalletGroup = this.walletGroups.get(walletAddInfo.groupId)
this.addToGroup(walletGroup, walletAddInfo.walletToAdd)
if (resolvedOptions.updateState) {
this.setActiveGroup(walletGroup)
this.walletGroups$.next(this.allWalletGroups)
return this.persist()
}
}
private assertWalletGroupExists(groupId: string | undefined, groupLabel: string | undefined): void {
if (!this.walletGroups.has(groupId)) {
this.walletGroups.set(groupId, new AirGapMarketWalletGroup(groupId, groupLabel, undefined, []))
}
}
private assertWalletGroupUpdated(groupId: string | undefined, groupLabel: string | undefined): void {
const walletGroup: AirGapMarketWalletGroup = this.walletGroups.get(groupId)
if (walletGroup.label !== undefined && walletGroup.label !== groupLabel && groupLabel !== undefined) {
walletGroup.updateLabel(groupLabel)
}
}
private addToGroup(group: AirGapMarketWalletGroup, wallet: AirGapMarketWallet): void {
const [oldGroupId, oldIndex]: [string | undefined, number] = this.findWalletGroupIdAndIndex(wallet)
if (oldGroupId !== group.id && oldIndex > -1) {
this.walletGroups.get(oldGroupId).wallets.splice(oldIndex, 1)
}
if (oldGroupId === group.id && oldIndex > -1) {
group.wallets[oldIndex] = wallet
} else {
group.wallets.push(wallet)
}
group.updateStatus()
}
public async activateWallet(
walletToActivate: AirGapMarketWallet,
groupId: string,
options: { updateState?: boolean } = {}
): Promise<void> {
const defaultOptions = {
updateState: true
}
const resolvedOptions = {
...defaultOptions,
...options
}
const walletGroup: AirGapMarketWalletGroup = this.walletGroups.get(groupId)
const index: number = walletGroup.wallets.findIndex((wallet: AirGapMarketWallet) => this.isSameWallet(wallet, walletToActivate))
if (index === -1) {
return
}
walletGroup.wallets[index].status = AirGapWalletStatus.ACTIVE
walletGroup.updateStatus()
if (resolvedOptions.updateState) {
this.setActiveGroup(walletGroup)
this.walletGroups$.next(this.allWalletGroups)
this.drawChartProvider.drawChart()
return this.persist()
}
}
public async removeWallet(walletToRemove: AirGapMarketWallet, options: { updateState?: boolean } = {}): Promise<void> {
const defaultOptions = {
updateState: true
}
const resolvedOptions = {
...defaultOptions,
...options
}
let group: AirGapMarketWalletGroup | undefined
const [groupId, index]: [string | undefined, number] = this.findWalletGroupIdAndIndex(walletToRemove)
if (this.walletGroups.has(groupId) && index > -1) {
group = this.walletGroups.get(groupId)
group.wallets[index].status = AirGapWalletStatus.DELETED
group.updateStatus()
}
this.unregisterFromPushBackend(walletToRemove)
if (resolvedOptions.updateState) {
const activeGroup: ActiveWalletGroup =
group !== undefined && group.status === AirGapWalletStatus.ACTIVE
? group
: this.allWalletGroups.length > 1
? 'all'
: this.allWalletGroups[0]
this.setActiveGroup(activeGroup)
this.walletGroups$.next(this.allWalletGroups)
this.drawChartProvider.drawChart()
return this.persist()
}
}
private async registerToPushBackend(wallets: AirGapMarketWallet[]): Promise<void> {
await this.pushProvider.setupPush()
this.pushProvider.registerWallets(wallets).catch(handleErrorSentry(ErrorCategory.PUSH))
}
private unregisterFromPushBackend(wallet: AirGapMarketWallet): void {
this.pushProvider.unregisterWallets([wallet]).catch(handleErrorSentry(ErrorCategory.PUSH))
}
public async setWalletNetwork(wallet: AirGapMarketWallet, network: TezosProtocolNetwork): Promise<void> {
await wallet.setProtocol(new TezosProtocol(new TezosProtocolOptions(network)))
await this.persist()
this.triggerWalletChanged()
}
public async updateWalletGroup(walletGroup: AirGapMarketWalletGroup) {
this.walletGroups.set(walletGroup.id, walletGroup)
return this.persist()
}
public walletGroupByWallet(wallet: AirGapMarketWallet): AirGapMarketWalletGroup {
return this.allWalletGroups.find((group: AirGapMarketWalletGroup) => group.includesWallet(wallet))
}
public setInteractionSettingForWalletGroupByWallet(wallet: AirGapMarketWallet, interactionSetting: InteractionSetting): void {
const group = this.walletGroupByWallet(wallet)
group.interactionSetting = interactionSetting
this.updateWalletGroup(group)
}
private async persist(): Promise<void> {
await Promise.all([
this.storageProvider.set(
WalletStorageKey.WALLET_GROUPS,
this.allWalletGroups
.filter((group: AirGapMarketWalletGroup) => !group.transient)
.map((group: AirGapMarketWalletGroup) => group.toJSON())
),
this.storageProvider.set(
WalletStorageKey.WALLET,
this.allWallets
.filter((wallet: AirGapMarketWallet) => wallet.status !== AirGapWalletStatus.TRANSIENT)
.map((wallet: AirGapMarketWallet) => wallet.toJSON())
)
])
}
public getAccountIdentifier(wallet: AirGapMarketWallet): string {
return wallet.addressIndex
? `${wallet.protocol.identifier}-${wallet.publicKey}-${wallet.protocol.options.network.identifier}-${wallet.addressIndex}`
: `${wallet.protocol.identifier}-${wallet.publicKey}-${wallet.protocol.options.network.identifier}`
}
public walletBySerializerAccountIdentifier(accountIdentifier: string, protocolIdentifier: string): AirGapMarketWallet {
return this.allWallets.find(
(wallet) => wallet.publicKey.endsWith(accountIdentifier) && wallet.protocol.identifier === protocolIdentifier
)
}
public walletByPublicKeyAndProtocolAndAddressIndex(
publicKey: string,
protocolIdentifier: string,
addressIndex?: number
): AirGapMarketWallet {
return this.allWallets.find(
(wallet) =>
wallet.publicKey === publicKey && wallet.protocol.identifier === protocolIdentifier && wallet.addressIndex === addressIndex
)
}
public walletExists(testWallet: AirGapMarketWallet): boolean {
return this.allWallets.some(
(wallet: AirGapMarketWallet) => this.isSameWallet(wallet, testWallet) && wallet.status === testWallet.status
)
}
public isSameWallet(wallet1: AirGapMarketWallet, wallet2: AirGapMarketWallet) {
if (!(wallet1 instanceof AirGapMarketWallet) || !(wallet2 instanceof AirGapMarketWallet)) {
return false
}
return (
wallet1.publicKey === wallet2.publicKey &&
wallet1.protocol.identifier === wallet2.protocol.identifier &&
wallet1.addressIndex === wallet2.addressIndex
)
}
public isSameGroup(group: ActiveWalletGroup, other: ActiveWalletGroup): boolean {
if (typeof group === 'string' && typeof other === 'string') {
return group === other
} else if (typeof group === 'string') {
return false
} else if (typeof other === 'string') {
return false
} else {
return group.id === other.id
}
}
public findWalletGroup(testWallet: AirGapMarketWallet): AirGapMarketWalletGroup | undefined {
for (const group of this.walletGroups.values()) {
const index: number = group.wallets.findIndex((wallet: AirGapMarketWallet) => this.isSameWallet(wallet, testWallet))
if (index !== -1) {
return group
}
}
return undefined
}
public findWalletGroupIdAndIndex(testWallet: AirGapMarketWallet): [string | undefined, number] {
for (const group of this.walletGroups.values()) {
const index: number = group.wallets.findIndex((wallet: AirGapMarketWallet) => this.isSameWallet(wallet, testWallet))
if (index !== -1) {
return [group.id, index]
}
}
return [undefined, -1]
}
public getKnownViewingKeys(): string[] {
return this.allWallets
.filter((wallet: AirGapMarketWallet) => wallet.protocol.identifier === MainProtocolSymbols.XTZ_SHIELDED)
.map((wallet: AirGapMarketWallet) => wallet.publicKey)
}
public async getCompatibleAndIncompatibleWalletsForAddress(
address: string
): Promise<{
compatibleWallets: AirGapMarketWallet[]
incompatibleWallets: AirGapMarketWallet[]
}> {
return this.usedProtocols$
.pipe(
take(1),
map((protocols) => {
const compatibleProtocols: Map<string, ICoinProtocol> = new Map()
protocols.forEach((protocol) => {
const match = address.match(protocol.addressValidationPattern)
if (match && match.length > 0) {
compatibleProtocols.set(protocol.identifier, protocol)
}
})
const compatibleWallets: AirGapMarketWallet[] = []
const incompatibleWallets: AirGapMarketWallet[] = []
this.allWallets.forEach((wallet) => {
if (compatibleProtocols.has(wallet.protocol.identifier)) {
compatibleWallets.push(wallet)
} else {
incompatibleWallets.push(wallet)
}
})
return {
compatibleWallets,
incompatibleWallets
}
})
)
.toPromise()
}
private sortGroupsByLabel(groups: AirGapMarketWalletGroup[]): AirGapMarketWalletGroup[] {
const othersIndex: number = groups.findIndex((group: AirGapMarketWalletGroup) => group.id === undefined)
const others: AirGapMarketWalletGroup | undefined = othersIndex > -1 ? groups[othersIndex] : undefined
const userDefinedGroups: AirGapMarketWalletGroup[] =
othersIndex > -1 ? groups.slice(0, othersIndex).concat(groups.slice(othersIndex + 1)) : groups
const sorted: AirGapMarketWalletGroup[] = userDefinedGroups.sort((a: AirGapMarketWalletGroup, b: AirGapMarketWalletGroup) =>
a.label.localeCompare(b.label)
)
return others !== undefined ? [...sorted, others] : sorted
}
private createWalletIdentifier(protocolIdentifier: string, publicKey: string): string {
return `${protocolIdentifier}_${publicKey}`
}
} | the_stack |
import { ESCAPE } from '@angular/cdk/keycodes';
import { OverlayContainer } from '@angular/cdk/overlay';
import {
ComponentFixture,
fakeAsync,
flush,
inject,
} from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import {
wrappedErrorMessage,
typeInElement,
dispatchKeyboardEvent,
} from '@dynatrace/testing/browser';
import { DtFilterField } from '../filter-field';
import { getDtFilterFieldRangeNoOperatorsError } from '../filter-field-errors';
import { TEST_DATA_RANGE } from '../testing/filter-field-test-data';
import {
TestApp,
setupFilterFieldTest,
getFilterFieldRange,
getOperatorButtonGroupItems,
getRangeInputFields,
getRangeApplyButton,
getFilterTags,
getOptions,
} from '../testing/filter-field-test-helpers';
import { dtRangeDef } from '../types';
describe('DtFilterField', () => {
let fixture: ComponentFixture<TestApp>;
let overlayContainerElement: HTMLElement;
let filterField: DtFilterField<any>;
let advanceFilterfieldCycle: (
simulateMicrotasks?: boolean,
simulateZoneExit?: boolean,
) => void;
let getAndClickOption: (
optionOverlayContainer: HTMLElement,
nthOption: number,
) => void;
beforeEach(() => {
({
fixture,
filterField,
overlayContainerElement,
advanceFilterfieldCycle,
getAndClickOption,
} = setupFilterFieldTest());
inject([OverlayContainer], (oc: OverlayContainer) => {
overlayContainerElement = oc.getContainerElement();
})();
});
describe('with range option', () => {
beforeEach(() => {
fixture.componentInstance.dataSource.data = TEST_DATA_RANGE;
fixture.detectChanges();
// Focus the filter field.
filterField.focus();
advanceFilterfieldCycle();
});
it('should open the range overlay if the range option is selected', () => {
let filterFieldRangeElements = getFilterFieldRange(
overlayContainerElement,
);
expect(filterFieldRangeElements.length).toBe(0);
getAndClickOption(overlayContainerElement, 0);
filterFieldRangeElements = getFilterFieldRange(overlayContainerElement);
expect(filterFieldRangeElements.length).toBe(1);
});
it('should have only range and greater-equal operators enabled', () => {
// Change the datasource at runtime
fixture.componentInstance.dataSource.data = {
autocomplete: [
{
name: 'Requests per minute',
range: {
operators: {
range: true,
greaterThanEqual: true,
},
unit: 's',
},
},
],
};
fixture.detectChanges();
// open the range overlay
filterField.focus();
advanceFilterfieldCycle();
const options = getOptions(overlayContainerElement);
options[0].click();
advanceFilterfieldCycle();
const operatorButtonElements = getOperatorButtonGroupItems(
overlayContainerElement,
);
expect(operatorButtonElements.length).toBe(2);
expect(operatorButtonElements[0].textContent).toBe('Range');
expect(operatorButtonElements[1].textContent).toBe('≥');
});
it('should have only one operator enabled', () => {
// Change the datasource at runtime
fixture.componentInstance.dataSource.data = {
autocomplete: [
{
name: 'Requests per minute',
range: {
operators: {
greaterThanEqual: true,
},
unit: 's',
},
},
],
};
fixture.detectChanges();
// open the range overlay
filterField.focus();
advanceFilterfieldCycle();
getAndClickOption(overlayContainerElement, 0);
const operatorButtonElements = getOperatorButtonGroupItems(
overlayContainerElement,
);
expect(operatorButtonElements.length).toBe(1);
expect(operatorButtonElements[0].textContent).toBe('≥');
});
describe('opened', () => {
beforeEach(() => {
// Open the filter-field-range overlay.
getAndClickOption(overlayContainerElement, 0);
});
it('should set the focus onto the first button-group-item by default', () => {
const firstButtonElement = overlayContainerElement.querySelector(
'dt-button-group-item',
);
expect(document.activeElement).toBe(firstButtonElement);
});
it('should have all operators enabled', () => {
const operatorButtonElements = getOperatorButtonGroupItems(
overlayContainerElement,
);
expect(operatorButtonElements.length).toBe(4);
});
it('should throw an error if there is no operator defined', fakeAsync(() => {
// Change the datasource at runtime
expect(() => {
fixture.componentInstance.dataSource.data = {
autocomplete: [
{
name: 'Requests per minute',
range: {
operators: {},
unit: 's',
},
},
],
};
flush();
}).toThrowError(
wrappedErrorMessage(getDtFilterFieldRangeNoOperatorsError()),
);
}));
it('should throw', () => {
expect(() => {
dtRangeDef({}, null, false, false, false, false, 's', false);
}).toThrowError(
wrappedErrorMessage(getDtFilterFieldRangeNoOperatorsError()),
);
});
it('should show two input fields when operator range is selected', () => {
const inputFieldsElements = getRangeInputFields(
overlayContainerElement,
);
expect(inputFieldsElements.length).toBe(2);
});
it('should show only one input field when the operator is not range', () => {
const operatorButtonElements = getOperatorButtonGroupItems(
overlayContainerElement,
);
operatorButtonElements[2].click();
fixture.detectChanges();
const inputFieldsElements = getRangeInputFields(
overlayContainerElement,
);
expect(inputFieldsElements.length).toBe(1);
});
it('should keep the apply button disabled until both entries are valid', () => {
const inputFieldsElements = getRangeInputFields(
overlayContainerElement,
);
let rangeApplyButton = getRangeApplyButton(overlayContainerElement)[0];
expect(rangeApplyButton.getAttribute('disabled')).toBeDefined();
typeInElement('15', inputFieldsElements[0]);
fixture.detectChanges();
rangeApplyButton = getRangeApplyButton(overlayContainerElement)[0];
expect(rangeApplyButton.getAttribute('disabled')).toBeDefined();
typeInElement('25', inputFieldsElements[1]);
fixture.detectChanges();
rangeApplyButton = getRangeApplyButton(overlayContainerElement)[0];
expect(rangeApplyButton.getAttribute('disabled')).toBeNull();
});
it('should keep the apply button disabled until the one required is valid', () => {
const operatorButtonElements = getOperatorButtonGroupItems(
overlayContainerElement,
);
operatorButtonElements[2].click();
fixture.detectChanges();
const inputFieldsElements = getRangeInputFields(
overlayContainerElement,
);
let rangeApplyButton = getRangeApplyButton(overlayContainerElement)[0];
expect(rangeApplyButton.getAttribute('disabled')).toBeDefined();
typeInElement('15', inputFieldsElements[0]);
fixture.detectChanges();
rangeApplyButton = getRangeApplyButton(overlayContainerElement)[0];
expect(rangeApplyButton.getAttribute('disabled')).toBeNull();
});
it('should close the range after the range-filter is submitted', () => {
const inputFieldsElements = getRangeInputFields(
overlayContainerElement,
);
typeInElement('15', inputFieldsElements[0]);
typeInElement('25', inputFieldsElements[1]);
fixture.detectChanges();
const rangeApplyButton = getRangeApplyButton(
overlayContainerElement,
)[0];
rangeApplyButton.click();
const rangeOverlay = getFilterFieldRange(overlayContainerElement);
expect(rangeOverlay.length).toBe(0);
});
it('should have the tag-filter committed in the filterfield and formatted for range', () => {
const inputFieldsElements = getRangeInputFields(
overlayContainerElement,
);
typeInElement('15', inputFieldsElements[0]);
typeInElement('25', inputFieldsElements[1]);
fixture.detectChanges();
const rangeApplyButton = getRangeApplyButton(
overlayContainerElement,
)[0];
rangeApplyButton.click();
fixture.detectChanges();
const tags = getFilterTags(fixture);
expect(tags[0].key).toBe('Requests per minute');
expect(tags[0].separator).toBe(':');
expect(tags[0].value.trim()).toBe('15s - 25s');
});
it('should have the tag-filter committed in the filterfield and formatted for greater-than operator', () => {
const operatorButtonElements = getOperatorButtonGroupItems(
overlayContainerElement,
);
operatorButtonElements[2].click();
fixture.detectChanges();
const inputFieldsElements = getRangeInputFields(
overlayContainerElement,
);
typeInElement('15', inputFieldsElements[0]);
fixture.detectChanges();
const rangeApplyButton = getRangeApplyButton(
overlayContainerElement,
)[0];
rangeApplyButton.click();
fixture.detectChanges();
const tags = getFilterTags(fixture);
expect(tags[0].key).toBe('Requests per minute');
expect(tags[0].separator).toBe('≥');
expect(tags[0].value.trim()).toBe('15s');
});
it('should close the filter-range when using the keyboard ESC', () => {
const operatorButtonElements = getOperatorButtonGroupItems(
overlayContainerElement,
);
dispatchKeyboardEvent(operatorButtonElements[0], 'keydown', ESCAPE);
fixture.detectChanges();
const rangeOverlay = getFilterFieldRange(overlayContainerElement);
expect(rangeOverlay.length).toBe(0);
});
it('should reapply previously set range operator and values when editing a range filter', () => {
const inputFieldsElements = getRangeInputFields(
overlayContainerElement,
);
typeInElement('15', inputFieldsElements[0]);
typeInElement('25', inputFieldsElements[1]);
fixture.detectChanges();
const rangeApplyButton = getRangeApplyButton(
overlayContainerElement,
)[0];
rangeApplyButton.click();
fixture.detectChanges();
const tagLabel = fixture.debugElement.queryAll(
By.css('.dt-filter-field-tag-label'),
)[0];
tagLabel.nativeElement.click();
advanceFilterfieldCycle();
// expect the range to open again
const filterFieldRangeElements = getFilterFieldRange(
overlayContainerElement,
);
expect(filterFieldRangeElements.length).toBe(1);
// expect the values to be filled
expect(filterField._filterfieldRange._selectedOperator).toEqual(
'range',
);
expect(filterField._filterfieldRange._valueFrom).toEqual('15');
expect(filterField._filterfieldRange._valueTo).toEqual('25');
});
it('should reapply previously set greater-equal operator and value when editing a range filter', () => {
const operatorButtonElements = getOperatorButtonGroupItems(
overlayContainerElement,
);
operatorButtonElements[2].click();
fixture.detectChanges();
const inputFieldsElements = getRangeInputFields(
overlayContainerElement,
);
typeInElement('27', inputFieldsElements[0]);
fixture.detectChanges();
const rangeApplyButton = getRangeApplyButton(
overlayContainerElement,
)[0];
rangeApplyButton.click();
fixture.detectChanges();
const tagLabel = fixture.debugElement.queryAll(
By.css('.dt-filter-field-tag-label'),
)[0];
tagLabel.nativeElement.click();
advanceFilterfieldCycle();
// expect the range to open again
const filterFieldRangeElements = getFilterFieldRange(
overlayContainerElement,
);
expect(filterFieldRangeElements.length).toBe(1);
// expect the values to be filled
expect(filterField._filterfieldRange._selectedOperator).toEqual(
'greater-equal',
);
expect(filterField._filterfieldRange._valueFrom).toEqual('27');
});
});
});
}); | the_stack |
{
assert(Date.UTC(1970, 0, 1) == 0);
assert(Date.UTC(1970, 0, 1, 0, 0, 0, 0) == 0);
assert(Date.UTC(70) == 0);
assert(Date.UTC(90) == 631152000000);
assert(Date.UTC(-90) == -65007360000000);
assert(Date.UTC(2018, 10, 10, 11, 0, 0, 1) == 1541847600001);
assert(Date.UTC(275760, 8, 13, 0, 0, 0, 0) == 8640000000000000);
// Date.UTC(275760, 8, 13, 0, 0, 0, 1); // Invalid Date
}
// Date get / set Time ////////////////////////////////////////////////////////////////////////////
{
let creationTime = 1541847600001;
let date = new Date(creationTime);
assert(date.getTime() == creationTime);
date.setTime(creationTime + 1);
assert(date.getTime() == creationTime + 1);
}
// Date getters ///////////////////////////////////////////////////////////////////////////////////
{
// from +189512-12-14T22:09:43.706Z"
let date = new Date(5918283958183706);
assert(date.getUTCFullYear() == 189512);
assert(date.getUTCMonth() == 11);
assert(date.getUTCDate() == 14);
assert(date.getUTCHours() == 22);
assert(date.getUTCMinutes() == 9);
assert(date.getUTCSeconds() == 43);
assert(date.getUTCMilliseconds() == 706);
}
{
// from 1973-12-04T01:03:11.274Z"
let date = new Date(123814991274);
assert(date.getUTCFullYear() == 1973);
assert(date.getUTCMonth() == 11);
assert(date.getUTCDate() == 4);
assert(date.getUTCHours() == 1);
assert(date.getUTCMinutes() == 3);
assert(date.getUTCSeconds() == 11);
assert(date.getUTCMilliseconds() == 274);
}
// Date#setUTCMilliseconds /////////////////////////////////////////////////////////////////////////
{
let date = new Date(399464523963984);
assert(date.getUTCMilliseconds() == 984);
date.setUTCMilliseconds(12);
assert(date.getUTCMilliseconds() == 12);
date.setUTCMilliseconds(568);
assert(date.getUTCMilliseconds() == 568);
// test in boundaries
date.setUTCMilliseconds(0);
assert(date.getTime() == 399464523963000);
date.setUTCMilliseconds(999);
assert(date.getTime() == 399464523963999);
// test out of boundaries
date.setUTCMilliseconds(2000);
assert(date.getUTCMilliseconds() == 0);
assert(date.getTime() == 399464523965000);
date.setUTCMilliseconds(-2000);
assert(date.getUTCMilliseconds() == 0);
assert(date.getTime() == 399464523963000);
}
// Date#setUTCSeconds //////////////////////////////////////////////////////////////////////////////
{
let date = new Date(372027318331986);
assert(date.getUTCSeconds() == 31);
date.setUTCSeconds(12);
assert(date.getUTCSeconds() == 12);
date.setUTCSeconds(50);
assert(date.getUTCSeconds() == 50);
// test boundaries
date.setUTCSeconds(0);
assert(date.getTime() == 372027318300986);
date.setUTCSeconds(59);
assert(date.getTime() == 372027318359986);
}
// Date#setUTCMinutes //////////////////////////////////////////////////////////////////////////////
{
let date = new Date(372027318331986);
assert(date.getUTCMinutes() == 45);
date.setUTCMinutes(12);
assert(date.getUTCMinutes() == 12);
date.setUTCMinutes(50);
assert(date.getUTCMinutes() == 50);
// test boundaries
date.setUTCMinutes(0);
assert(date.getTime() == 372027315631986);
date.setUTCMinutes(59);
assert(date.getTime() == 372027319171986);
}
// Date#setUTCHours ////////////////////////////////////////////////////////////////////////////////
{
let date = new Date(372027318331986);
assert(date.getUTCHours() == 17);
date.setUTCHours(12);
assert(date.getUTCHours() == 12);
date.setUTCHours(2);
assert(date.getUTCHours() == 2);
// test boundaries
date.setUTCHours(0);
assert(date.getTime() == 372027257131986);
date.setUTCHours(23);
assert(date.getTime() == 372027339931986);
}
// Date#setUTCDate /////////////////////////////////////////////////////////////////////////////////
{
let date = new Date(123814991274);
assert(date.getUTCFullYear() == 1973);
assert(date.getUTCMonth() == 11);
// test a few values
date.setUTCDate(12);
assert(date.getUTCDate() == 12);
date.setUTCDate(2);
assert(date.getUTCDate() == 2);
// test boundaries
// nov has 30 days
date.setUTCDate(1);
date.setUTCDate(30);
// jan has 31 days
date.setUTCMonth(1);
date.setUTCDate(1);
date.setUTCDate(31);
// feb on leap year
date.setUTCFullYear(2024);
date.setUTCMonth(2);
date.setUTCDate(1);
date.setUTCDate(29);
assert(date.getTime() == 1711674191274);
assert(date.getUTCDate() == 29);
assert(date.getUTCMinutes() == 3);
assert(date.getUTCSeconds() == 11);
assert(date.getUTCMilliseconds() == 274);
date = new Date(1362106799999);
date.setUTCDate(20);
assert(date.getTime() == 1363748399999);
date.setUTCDate(1);
assert(date.getTime() == 1362106799999);
date.setUTCMilliseconds(1000);
assert(date.getTime() == 1362106800000);
date.setUTCMilliseconds(60 * 60 * 1000);
assert(date.getTime() == 1362110400000);
date.setUTCMilliseconds(60 * 60 * 1000 + 1);
assert(date.getTime() == 1362114000001);
date.setUTCMilliseconds(60 * 60 * 1000 + 1);
assert(date.getTime() == 1362117600001);
date = new Date(123814991274);
date.setUTCDate(-2208);
assert(date.getTime() == -67301808726);
date = new Date(123814991274);
date.setUTCDate(2208);
assert(date.getTime() == 314240591274);
}
// Date#setUTCDay //////////////////////////////////////////////////////////////////////////////////
{
// tests from test262
const july6: i64 = 1467763200000;
const july9: i64 = 1468022400000;
const dayMs: i64 = 24 * 60 * 60 * 1000;
assert(new Date(july6 ).getUTCDay() == 3);
assert(new Date(july6 - 1).getUTCDay() == 2);
assert(new Date(july6 + dayMs - 1).getUTCDay() == 3);
assert(new Date(july6 + dayMs ).getUTCDay() == 4);
assert(new Date(july9 ).getUTCDay() == 6);
assert(new Date(july9 - 1).getUTCDay() == 5);
assert(new Date(july9 + dayMs - 1).getUTCDay() == 6);
assert(new Date(july9 + dayMs ).getUTCDay() == 0);
}
// Date#setUTCMonth ////////////////////////////////////////////////////////////////////////////////
{
let date = new Date(7899943856218720);
assert(date.getUTCMonth() == 3);
date.setUTCMonth(10);
assert(date.getUTCMonth() == 10);
date.setUTCMonth(2);
assert(date.getUTCMonth() == 2);
assert(date.getTime() == 7899941177818720);
// test boundaries
date.setUTCMonth(1);
date.setUTCMonth(12);
assert(date.getTime() == 7899967616218720);
// test out of boundaries
date.setUTCMonth(0);
assert(date.getTime() == 7899967616218720);
date.setUTCMonth(13);
assert(date.getTime() == 7900001830618720);
}
// Date#setUTCFullYear /////////////////////////////////////////////////////////////////////////////
{
let date = new Date(7941202527925698);
assert(date.getUTCFullYear() == 253616);
date.setUTCFullYear(1976);
assert(date.getUTCFullYear() == 1976);
date.setUTCFullYear(20212);
assert(date.getUTCFullYear() == 20212);
date.setUTCFullYear(71);
assert(date.getUTCFullYear() == 71);
}
// Date#toISOString ////////////////////////////////////////////////////////////////////////////////
{
let date = new Date(-62167219200000);
assert(date.toISOString() == "0000-01-01T00:00:00.000Z");
date = new Date(-62167219200000 - 1);
assert(date.toISOString() == "-000001-12-31T23:59:59.999Z");
date = new Date(-62127219200000);
assert(date.toISOString() == "0001-04-07T23:06:40.000Z");
date = new Date(1231231231020);
assert(date.toISOString() == "2009-01-06T08:40:31.020Z");
date = new Date(1231231231456);
assert(date.toISOString() == "2009-01-06T08:40:31.456Z");
date = new Date(322331231231020);
assert(date.toISOString() == "+012184-04-08T13:07:11.020Z");
date = new Date(253402300799999);
assert(date.toISOString() == "9999-12-31T23:59:59.999Z");
date = new Date(253402300800000);
assert(date.toISOString() == "+010000-01-01T00:00:00.000Z");
date = new Date(-62847038769226);
assert(date.toISOString() == "-000022-06-16T17:13:50.774Z");
}
// Date#toDateString ///////////////////////////////////////////////////////////////////////////////
{
let date = new Date(-61536067200000);
assert(date.toDateString() == "Wed Jan 01 0020");
date = new Date(1580601600000);
assert(date.toDateString() == "Sun Feb 02 2020");
// negative year
date = new Date(-62183116800000); // '-000001-07-01T00:00Z'
assert(date.toDateString() == "Thu Jul 01 -0001");
}
// Date#toTimeString ///////////////////////////////////////////////////////////////////////////////
{
let date = new Date(-61536067200000);
assert(date.toTimeString() == "00:00:00"); // use UTC time instead local
date = new Date(253402300799999);
assert(date.toTimeString() == "23:59:59"); // use UTC time instead local
}
// Date#toUTCString ///////////////////////////////////////////////////////////////////////////////
{
let date = new Date(-61536067200000);
assert(date.toUTCString() == "Wed, 01 Jan 0020 00:00:00 GMT");
date = new Date(1580741613467);
assert(date.toUTCString() == "Mon, 03 Feb 2020 14:53:33 GMT");
// negative year
date = new Date(-62183116800000); // '-000001-07-01T00:00Z'
assert(date.toUTCString() == "Thu, 01 Jul -0001 00:00:00 GMT");
}
// Date#fromString /////////////////////////////////////////////////////////////////////////////////
{
// supports year / month / day
let date = Date.fromString("1976-02-02");
assert(date.getTime() == 192067200000);
date = Date.fromString("1976-2-2");
assert(date.getTime() == 192067200000);
date = Date.fromString("2345-11-04");
assert(date.getTime() == 11860387200000);
// supports year / month / day / hour / minute / second
date = Date.fromString("1976-02-02T12:34:56"); // still use Z suffix
assert(date.getTime() == 192112496000);
// supports milliseconds
date = Date.fromString("1976-02-02T12:34:56.456"); // still use Z suffix
assert(date.getTime() == 192112496456);
// supports 'Z' suffix
date = Date.fromString("1976-02-02T12:34:56.456Z");
assert(date.getTime() == 192112496456);
date = Date.fromString("0000");
assert(date.getTime() == -62167219200000);
date = Date.fromString("0001");
assert(date.getTime() == -62135596800000);
date = Date.fromString("1976");
assert(date.getTime() == 189302400000);
date = Date.fromString("1976-02");
assert(date.getTime() == 191980800000);
date = Date.fromString("1976-02-02");
assert(date.getTime() == 192067200000);
date = Date.fromString("1976-02-02T12:34"); // still use Z suffix
assert(date.getTime() == 192112440000);
date = Date.fromString("1976-02-02T12:34:56"); // still use Z suffix
assert(date.getTime() == 192112496000);
// date = Date.fromString('0Z');
// assert(date.getTime() == 946684800000); // FIXME: fail
// date = Date.fromString('000Z');
// assert(date.getTime() == 946684800000); // FIXME: fail
// Date.fromString(""); // Invalid Date
// Date.fromString("1000000"); // Invalid Date
// Date.fromString("1976-02-02T12"); // Invalid Date
}
// Minimum / Maximum dates ////////////////////////////////////////////////////////////////////////
{
let minDate = new Date(-8640000000000000);
let maxDate = new Date( 8640000000000000);
assert(minDate.getTime() == -8640000000000000);
assert(maxDate.getTime() == 8640000000000000);
assert(minDate.getUTCFullYear() == -271821);
assert(maxDate.getUTCFullYear() == 275760);
assert(minDate.getUTCMonth() == 3);
assert(maxDate.getUTCMonth() == 8);
assert(minDate.getUTCDate() == 20);
assert(maxDate.getUTCDate() == 13);
assert(minDate.toISOString() == "-271821-04-20T00:00:00.000Z");
assert(maxDate.toISOString() == "+275760-09-13T00:00:00.000Z");
let maxDateDec = new Date( 8640000000000000 - 1);
let minDateInc = new Date(-8640000000000000 + 1);
assert(minDateInc.getUTCFullYear() == -271821);
assert(minDateInc.getUTCMonth() == 3);
assert(minDateInc.getUTCDate() == 20);
assert(minDateInc.getUTCHours() == 0);
assert(minDateInc.getUTCMinutes() == 0);
assert(minDateInc.getUTCSeconds() == 0);
assert(minDateInc.getUTCMilliseconds() == 1);
assert(maxDateDec.toISOString() == "+275760-09-12T23:59:59.999Z");
assert(minDateInc.toISOString() == "-271821-04-20T00:00:00.001Z");
// new Date(maxDate.getTime() + 1); // Invalid Date
// new Date(minDate.getTime() - 1); // Invalid Date
} | the_stack |
import Integer, { int, isInt } from '../integer'
import { newError } from '../error'
import { assertNumberOrInteger } from './util'
import { NumberOrInteger } from '../graph-types'
/*
Code in this util should be compatible with code in the database that uses JSR-310 java.time APIs.
It is based on a library called ThreeTen (https://github.com/ThreeTen/threetenbp) which was derived
from JSR-310 reference implementation previously hosted on GitHub. Code uses `Integer` type everywhere
to correctly handle large integer values that are greater than `Number.MAX_SAFE_INTEGER`.
Please consult either ThreeTen or js-joda (https://github.com/js-joda/js-joda) when working with the
conversion functions.
*/
class ValueRange {
_minNumber: number
_maxNumber: number
_minInteger: Integer
_maxInteger: Integer
constructor (min: number, max: number) {
this._minNumber = min
this._maxNumber = max
this._minInteger = int(min)
this._maxInteger = int(max)
}
contains (value: number | Integer | bigint) {
if (isInt(value) && value instanceof Integer) {
return (
value.greaterThanOrEqual(this._minInteger) &&
value.lessThanOrEqual(this._maxInteger)
)
} else if (typeof value === 'bigint') {
const intValue = int(value)
return (
intValue.greaterThanOrEqual(this._minInteger) &&
intValue.lessThanOrEqual(this._maxInteger)
)
} else {
return value >= this._minNumber && value <= this._maxNumber
}
}
toString () {
return `[${this._minNumber}, ${this._maxNumber}]`
}
}
export const YEAR_RANGE = new ValueRange(-999999999, 999999999)
export const MONTH_OF_YEAR_RANGE = new ValueRange(1, 12)
export const DAY_OF_MONTH_RANGE = new ValueRange(1, 31)
export const HOUR_OF_DAY_RANGE = new ValueRange(0, 23)
export const MINUTE_OF_HOUR_RANGE = new ValueRange(0, 59)
export const SECOND_OF_MINUTE_RANGE = new ValueRange(0, 59)
export const NANOSECOND_OF_SECOND_RANGE = new ValueRange(0, 999999999)
export const MINUTES_PER_HOUR = 60
export const SECONDS_PER_MINUTE = 60
export const SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR
export const NANOS_PER_SECOND = 1000000000
export const NANOS_PER_MILLISECOND = 1000000
export const NANOS_PER_MINUTE = NANOS_PER_SECOND * SECONDS_PER_MINUTE
export const NANOS_PER_HOUR = NANOS_PER_MINUTE * MINUTES_PER_HOUR
export const DAYS_0000_TO_1970 = 719528
export const DAYS_PER_400_YEAR_CYCLE = 146097
export const SECONDS_PER_DAY = 86400
export function normalizeSecondsForDuration (
seconds: number | Integer | bigint,
nanoseconds: number | Integer | bigint
): Integer {
return int(seconds).add(floorDiv(nanoseconds, NANOS_PER_SECOND))
}
export function normalizeNanosecondsForDuration (
nanoseconds: number | Integer | bigint
): Integer {
return floorMod(nanoseconds, NANOS_PER_SECOND)
}
/**
* Converts given local time into a single integer representing this same time in nanoseconds of the day.
* @param {Integer|number|string} hour the hour of the local time to convert.
* @param {Integer|number|string} minute the minute of the local time to convert.
* @param {Integer|number|string} second the second of the local time to convert.
* @param {Integer|number|string} nanosecond the nanosecond of the local time to convert.
* @return {Integer} nanoseconds representing the given local time.
*/
export function localTimeToNanoOfDay (
hour: NumberOrInteger | string,
minute: NumberOrInteger | string,
second: NumberOrInteger | string,
nanosecond: NumberOrInteger | string
): Integer {
hour = int(hour)
minute = int(minute)
second = int(second)
nanosecond = int(nanosecond)
let totalNanos = hour.multiply(NANOS_PER_HOUR)
totalNanos = totalNanos.add(minute.multiply(NANOS_PER_MINUTE))
totalNanos = totalNanos.add(second.multiply(NANOS_PER_SECOND))
return totalNanos.add(nanosecond)
}
/**
* Converts given local date time into a single integer representing this same time in epoch seconds UTC.
* @param {Integer|number|string} year the year of the local date-time to convert.
* @param {Integer|number|string} month the month of the local date-time to convert.
* @param {Integer|number|string} day the day of the local date-time to convert.
* @param {Integer|number|string} hour the hour of the local date-time to convert.
* @param {Integer|number|string} minute the minute of the local date-time to convert.
* @param {Integer|number|string} second the second of the local date-time to convert.
* @param {Integer|number|string} nanosecond the nanosecond of the local date-time to convert.
* @return {Integer} epoch second in UTC representing the given local date time.
*/
export function localDateTimeToEpochSecond (
year: NumberOrInteger | string,
month: NumberOrInteger | string,
day: NumberOrInteger | string,
hour: NumberOrInteger | string,
minute: NumberOrInteger | string,
second: NumberOrInteger | string,
nanosecond: NumberOrInteger | string
): Integer {
const epochDay = dateToEpochDay(year, month, day)
const localTimeSeconds = localTimeToSecondOfDay(hour, minute, second)
return epochDay.multiply(SECONDS_PER_DAY).add(localTimeSeconds)
}
/**
* Converts given local date into a single integer representing it's epoch day.
* @param {Integer|number|string} year the year of the local date to convert.
* @param {Integer|number|string} month the month of the local date to convert.
* @param {Integer|number|string} day the day of the local date to convert.
* @return {Integer} epoch day representing the given date.
*/
export function dateToEpochDay (
year: NumberOrInteger | string,
month: NumberOrInteger | string,
day: NumberOrInteger | string
): Integer {
year = int(year)
month = int(month)
day = int(day)
let epochDay = year.multiply(365)
if (year.greaterThanOrEqual(0)) {
epochDay = epochDay.add(
year
.add(3)
.div(4)
.subtract(year.add(99).div(100))
.add(year.add(399).div(400))
)
} else {
epochDay = epochDay.subtract(
year
.div(-4)
.subtract(year.div(-100))
.add(year.div(-400))
)
}
epochDay = epochDay.add(
month
.multiply(367)
.subtract(362)
.div(12)
)
epochDay = epochDay.add(day.subtract(1))
if (month.greaterThan(2)) {
epochDay = epochDay.subtract(1)
if (!isLeapYear(year)) {
epochDay = epochDay.subtract(1)
}
}
return epochDay.subtract(DAYS_0000_TO_1970)
}
/**
* Format given duration to an ISO 8601 string.
* @param {Integer|number|string} months the number of months.
* @param {Integer|number|string} days the number of days.
* @param {Integer|number|string} seconds the number of seconds.
* @param {Integer|number|string} nanoseconds the number of nanoseconds.
* @return {string} ISO string that represents given duration.
*/
export function durationToIsoString (
months: NumberOrInteger | string,
days: NumberOrInteger | string,
seconds: NumberOrInteger | string,
nanoseconds: NumberOrInteger | string
): string {
const monthsString = formatNumber(months)
const daysString = formatNumber(days)
const secondsAndNanosecondsString = formatSecondsAndNanosecondsForDuration(
seconds,
nanoseconds
)
return `P${monthsString}M${daysString}DT${secondsAndNanosecondsString}S`
}
/**
* Formats given time to an ISO 8601 string.
* @param {Integer|number|string} hour the hour value.
* @param {Integer|number|string} minute the minute value.
* @param {Integer|number|string} second the second value.
* @param {Integer|number|string} nanosecond the nanosecond value.
* @return {string} ISO string that represents given time.
*/
export function timeToIsoString (
hour: NumberOrInteger | string,
minute: NumberOrInteger | string,
second: NumberOrInteger | string,
nanosecond: NumberOrInteger | string
): string {
const hourString = formatNumber(hour, 2)
const minuteString = formatNumber(minute, 2)
const secondString = formatNumber(second, 2)
const nanosecondString = formatNanosecond(nanosecond)
return `${hourString}:${minuteString}:${secondString}${nanosecondString}`
}
/**
* Formats given time zone offset in seconds to string representation like '±HH:MM', '±HH:MM:SS' or 'Z' for UTC.
* @param {Integer|number|string} offsetSeconds the offset in seconds.
* @return {string} ISO string that represents given offset.
*/
export function timeZoneOffsetToIsoString (
offsetSeconds: NumberOrInteger | string
): string {
offsetSeconds = int(offsetSeconds)
if (offsetSeconds.equals(0)) {
return 'Z'
}
const isNegative = offsetSeconds.isNegative()
if (isNegative) {
offsetSeconds = offsetSeconds.multiply(-1)
}
const signPrefix = isNegative ? '-' : '+'
const hours = formatNumber(offsetSeconds.div(SECONDS_PER_HOUR), 2)
const minutes = formatNumber(
offsetSeconds.div(SECONDS_PER_MINUTE).modulo(MINUTES_PER_HOUR),
2
)
const secondsValue = offsetSeconds.modulo(SECONDS_PER_MINUTE)
const seconds = secondsValue.equals(0) ? null : formatNumber(secondsValue, 2)
return seconds
? `${signPrefix}${hours}:${minutes}:${seconds}`
: `${signPrefix}${hours}:${minutes}`
}
/**
* Formats given date to an ISO 8601 string.
* @param {Integer|number|string} year the date year.
* @param {Integer|number|string} month the date month.
* @param {Integer|number|string} day the date day.
* @return {string} ISO string that represents given date.
*/
export function dateToIsoString (
year: NumberOrInteger | string,
month: NumberOrInteger | string,
day: NumberOrInteger | string
): string {
year = int(year)
const isNegative = year.isNegative()
if (isNegative) {
year = year.multiply(-1)
}
let yearString = formatNumber(year, 4)
if (isNegative) {
yearString = '-' + yearString
}
const monthString = formatNumber(month, 2)
const dayString = formatNumber(day, 2)
return `${yearString}-${monthString}-${dayString}`
}
/**
* Get the total number of nanoseconds from the milliseconds of the given standard JavaScript date and optional nanosecond part.
* @param {global.Date} standardDate the standard JavaScript date.
* @param {Integer|number|bigint|undefined} nanoseconds the optional number of nanoseconds.
* @return {Integer|number|bigint} the total amount of nanoseconds.
*/
export function totalNanoseconds (
standardDate: Date,
nanoseconds?: NumberOrInteger
): NumberOrInteger {
nanoseconds = nanoseconds || 0
const nanosFromMillis = standardDate.getMilliseconds() * NANOS_PER_MILLISECOND
return add(nanoseconds, nanosFromMillis)
}
/**
* Get the time zone offset in seconds from the given standard JavaScript date.
*
* <b>Implementation note:</b>
* Time zone offset returned by the standard JavaScript date is the difference, in minutes, from local time to UTC.
* So positive value means offset is behind UTC and negative value means it is ahead.
* For Neo4j temporal types, like `Time` or `DateTime` offset is in seconds and represents difference from UTC to local time.
* This is different from standard JavaScript dates and that's why implementation negates the returned value.
*
* @param {global.Date} standardDate the standard JavaScript date.
* @return {number} the time zone offset in seconds.
*/
export function timeZoneOffsetInSeconds (standardDate: Date): number {
const offsetInMinutes = standardDate.getTimezoneOffset()
if (offsetInMinutes === 0) {
return 0
}
return -1 * offsetInMinutes * SECONDS_PER_MINUTE
}
/**
* Assert that the year value is valid.
* @param {Integer|number} year the value to check.
* @return {Integer|number} the value of the year if it is valid. Exception is thrown otherwise.
*/
export function assertValidYear (year: NumberOrInteger): NumberOrInteger {
return assertValidTemporalValue(year, YEAR_RANGE, 'Year')
}
/**
* Assert that the month value is valid.
* @param {Integer|number} month the value to check.
* @return {Integer|number} the value of the month if it is valid. Exception is thrown otherwise.
*/
export function assertValidMonth (month: NumberOrInteger): NumberOrInteger {
return assertValidTemporalValue(month, MONTH_OF_YEAR_RANGE, 'Month')
}
/**
* Assert that the day value is valid.
* @param {Integer|number} day the value to check.
* @return {Integer|number} the value of the day if it is valid. Exception is thrown otherwise.
*/
export function assertValidDay (day: NumberOrInteger): NumberOrInteger {
return assertValidTemporalValue(day, DAY_OF_MONTH_RANGE, 'Day')
}
/**
* Assert that the hour value is valid.
* @param {Integer|number} hour the value to check.
* @return {Integer|number} the value of the hour if it is valid. Exception is thrown otherwise.
*/
export function assertValidHour (hour: NumberOrInteger): NumberOrInteger {
return assertValidTemporalValue(hour, HOUR_OF_DAY_RANGE, 'Hour')
}
/**
* Assert that the minute value is valid.
* @param {Integer|number} minute the value to check.
* @return {Integer|number} the value of the minute if it is valid. Exception is thrown otherwise.
*/
export function assertValidMinute (minute: NumberOrInteger): NumberOrInteger {
return assertValidTemporalValue(minute, MINUTE_OF_HOUR_RANGE, 'Minute')
}
/**
* Assert that the second value is valid.
* @param {Integer|number} second the value to check.
* @return {Integer|number} the value of the second if it is valid. Exception is thrown otherwise.
*/
export function assertValidSecond (second: NumberOrInteger): NumberOrInteger {
return assertValidTemporalValue(second, SECOND_OF_MINUTE_RANGE, 'Second')
}
/**
* Assert that the nanosecond value is valid.
* @param {Integer|number} nanosecond the value to check.
* @return {Integer|number} the value of the nanosecond if it is valid. Exception is thrown otherwise.
*/
export function assertValidNanosecond (
nanosecond: NumberOrInteger
): NumberOrInteger {
return assertValidTemporalValue(
nanosecond,
NANOSECOND_OF_SECOND_RANGE,
'Nanosecond'
)
}
/**
* Check if the given value is of expected type and is in the expected range.
* @param {Integer|number} value the value to check.
* @param {ValueRange} range the range.
* @param {string} name the name of the value.
* @return {Integer|number} the value if valid. Exception is thrown otherwise.
*/
function assertValidTemporalValue (
value: NumberOrInteger,
range: ValueRange,
name: string
): NumberOrInteger {
assertNumberOrInteger(value, name)
if (!range.contains(value)) {
throw newError(
`${name} is expected to be in range ${range} but was: ${value}`
)
}
return value
}
/**
* Converts given local time into a single integer representing this same time in seconds of the day. Nanoseconds are skipped.
* @param {Integer|number|string} hour the hour of the local time.
* @param {Integer|number|string} minute the minute of the local time.
* @param {Integer|number|string} second the second of the local time.
* @return {Integer} seconds representing the given local time.
*/
function localTimeToSecondOfDay (
hour: NumberOrInteger | string,
minute: NumberOrInteger | string,
second: NumberOrInteger | string
): Integer {
hour = int(hour)
minute = int(minute)
second = int(second)
let totalSeconds = hour.multiply(SECONDS_PER_HOUR)
totalSeconds = totalSeconds.add(minute.multiply(SECONDS_PER_MINUTE))
return totalSeconds.add(second)
}
/**
* Check if given year is a leap year. Uses algorithm described here {@link https://en.wikipedia.org/wiki/Leap_year#Algorithm}.
* @param {Integer|number|string} year the year to check. Will be converted to {@link Integer} for all calculations.
* @return {boolean} `true` if given year is a leap year, `false` otherwise.
*/
function isLeapYear (year: NumberOrInteger | string): boolean {
year = int(year)
if (!year.modulo(4).equals(0)) {
return false
} else if (!year.modulo(100).equals(0)) {
return true
} else if (!year.modulo(400).equals(0)) {
return false
} else {
return true
}
}
/**
* @param {Integer|number|string} x the divident.
* @param {Integer|number|string} y the divisor.
* @return {Integer} the result.
*/
export function floorDiv (
x: NumberOrInteger | string,
y: NumberOrInteger | string
): Integer {
x = int(x)
y = int(y)
let result = x.div(y)
if (x.isPositive() !== y.isPositive() && result.multiply(y).notEquals(x)) {
result = result.subtract(1)
}
return result
}
/**
* @param {Integer|number|string} x the divident.
* @param {Integer|number|string} y the divisor.
* @return {Integer} the result.
*/
export function floorMod (
x: NumberOrInteger | string,
y: NumberOrInteger | string
): Integer {
x = int(x)
y = int(y)
return x.subtract(floorDiv(x, y).multiply(y))
}
/**
* @param {Integer|number|string} seconds the number of seconds to format.
* @param {Integer|number|string} nanoseconds the number of nanoseconds to format.
* @return {string} formatted value.
*/
function formatSecondsAndNanosecondsForDuration (
seconds: NumberOrInteger | string,
nanoseconds: NumberOrInteger | string
): string {
seconds = int(seconds)
nanoseconds = int(nanoseconds)
let secondsString
let nanosecondsString
const secondsNegative = seconds.isNegative()
const nanosecondsGreaterThanZero = nanoseconds.greaterThan(0)
if (secondsNegative && nanosecondsGreaterThanZero) {
if (seconds.equals(-1)) {
secondsString = '-0'
} else {
secondsString = seconds.add(1).toString()
}
} else {
secondsString = seconds.toString()
}
if (nanosecondsGreaterThanZero) {
if (secondsNegative) {
nanosecondsString = formatNanosecond(
nanoseconds
.negate()
.add(2 * NANOS_PER_SECOND)
.modulo(NANOS_PER_SECOND)
)
} else {
nanosecondsString = formatNanosecond(
nanoseconds.add(NANOS_PER_SECOND).modulo(NANOS_PER_SECOND)
)
}
}
return nanosecondsString ? secondsString + nanosecondsString : secondsString
}
/**
* @param {Integer|number|string} value the number of nanoseconds to format.
* @return {string} formatted and possibly left-padded nanoseconds part as string.
*/
function formatNanosecond (value: NumberOrInteger | string): string {
value = int(value)
return value.equals(0) ? '' : '.' + formatNumber(value, 9)
}
/**
* @param {Integer|number|string} num the number to format.
* @param {number} [stringLength=undefined] the string length to left-pad to.
* @return {string} formatted and possibly left-padded number as string.
*/
function formatNumber (
num: NumberOrInteger | string,
stringLength?: number
): string {
num = int(num)
const isNegative = num.isNegative()
if (isNegative) {
num = num.negate()
}
let numString = num.toString()
if (stringLength) {
// left pad the string with zeroes
while (numString.length < stringLength) {
numString = '0' + numString
}
}
return isNegative ? '-' + numString : numString
}
function add (x: NumberOrInteger, y: number): NumberOrInteger {
if (x instanceof Integer) {
return x.add(y)
} else if (typeof x === 'bigint') {
return x + BigInt(y)
}
return x + y
} | the_stack |
import {
HeadQueueEntry,
LiveAtlasMarkerSet,
LiveAtlasPlayer,
LiveAtlasServerDefinition,
LiveAtlasWorldDefinition
} from "@/index";
import ChatError from "@/errors/ChatError";
import {MutationTypes} from "@/store/mutation-types";
import MapProvider from "@/providers/MapProvider";
import {ActionTypes} from "@/store/action-types";
import {
buildAreas,
buildCircles, buildComponents,
buildLines,
buildMarkers,
buildMarkerSet,
buildMessagesConfig,
buildServerConfig, buildUpdates, buildWorlds
} from "@/util/dynmap";
import {getImagePixelSize} from "@/util";
export default class DynmapMapProvider extends MapProvider {
private configurationAbort?: AbortController = undefined;
private markersAbort?: AbortController = undefined;
private updateAbort?: AbortController = undefined;
private updatesEnabled = false;
private updateTimeout: null | ReturnType<typeof setTimeout> = null;
private updateTimestamp: Date = new Date();
private updateInterval: number = 3000;
constructor(config: LiveAtlasServerDefinition) {
super(config);
}
private async getMarkerSets(world: LiveAtlasWorldDefinition): Promise<Map<string, LiveAtlasMarkerSet>> {
const url = `${this.config.dynmap!.markers}_markers_/marker_${world.name}.json`;
if(this.markersAbort) {
this.markersAbort.abort();
}
this.markersAbort = new AbortController();
const response = await this.getJSON(url, this.markersAbort.signal);
const sets: Map<string, LiveAtlasMarkerSet> = new Map();
response.sets = response.sets || {};
for (const key in response.sets) {
if (!Object.prototype.hasOwnProperty.call(response.sets, key)) {
continue;
}
const set = response.sets[key],
markers = buildMarkers(set.markers || {}),
circles = buildCircles(set.circles || {}),
areas = buildAreas(set.areas || {}),
lines = buildLines(set.lines || {});
sets.set(key, {
...buildMarkerSet(key, set),
markers,
circles,
areas,
lines,
});
}
return sets;
}
async loadServerConfiguration(): Promise<void> {
if(this.configurationAbort) {
this.configurationAbort.abort();
}
this.configurationAbort = new AbortController();
const response = await this.getJSON(this.config.dynmap!.configuration, this.configurationAbort.signal);
if (response.error) {
throw new Error(response.error);
}
const config = buildServerConfig(response);
this.updateInterval = response.updaterate || 3000;
this.store.commit(MutationTypes.SET_SERVER_CONFIGURATION, config);
this.store.commit(MutationTypes.SET_SERVER_CONFIGURATION_HASH, response.confighash || 0);
this.store.commit(MutationTypes.SET_MAX_PLAYERS, response.maxcount || 0);
this.store.commit(MutationTypes.SET_SERVER_MESSAGES, buildMessagesConfig(response));
this.store.commit(MutationTypes.SET_WORLDS, buildWorlds(response));
this.store.commit(MutationTypes.SET_COMPONENTS, buildComponents(response));
this.store.commit(MutationTypes.SET_LOGGED_IN, response.loggedin || false);
}
async populateWorld(world: LiveAtlasWorldDefinition): Promise<void> {
const markerSets = await this.getMarkerSets(world);
this.store.commit(MutationTypes.SET_MARKER_SETS, markerSets);
}
private async getUpdate(): Promise<void> {
let url = this.config.dynmap!.update;
url = url.replace('{world}', this.store.state.currentWorld!.name);
url = url.replace('{timestamp}', this.updateTimestamp.getTime().toString());
if(this.updateAbort) {
this.updateAbort.abort();
}
this.updateAbort = new AbortController();
const response = await this.getJSON(url, this.updateAbort.signal);
const players: Set<LiveAtlasPlayer> = new Set(),
updates = buildUpdates(response.updates || [], this.updateTimestamp),
worldState = {
timeOfDay: response.servertime || 0,
thundering: response.isThundering || false,
raining: response.hasStorm || false,
};
(response.players || []).forEach((player: any) => {
const world = player.world && player.world !== '-some-other-bogus-world-' ? player.world : undefined;
players.add({
name: player.account || "",
displayName: player.name || "",
health: player.health || 0,
armor: player.armor || 0,
sort: player.sort || 0,
hidden: !world,
location: {
//Add 0.5 to position in the middle of a block
x: !isNaN(player.x) ? player.x + 0.5 : 0,
y: !isNaN(player.y) ? player.y : 0,
z: !isNaN(player.z) ? player.z + 0.5 : 0,
world: world,
}
});
});
//Extra fake players for testing
// for(let i = 0; i < 450; i++) {
// players.add({
// account: "VIDEO GAMES " + i,
// health: Math.round(Math.random() * 10),
// armor: Math.round(Math.random() * 10),
// name: "VIDEO GAMES " + i,
// sort: Math.round(Math.random() * 10),
// hidden: false,
// location: {
// x: Math.round(Math.random() * 1000) - 500,
// y: 64,
// z: Math.round(Math.random() * 1000) - 500,
// world: "world",
// }
// });
// }
this.updateTimestamp = new Date(response.timestamp || 0);
this.store.commit(MutationTypes.SET_WORLD_STATE, worldState);
this.store.commit(MutationTypes.ADD_MARKER_SET_UPDATES, updates.markerSets);
this.store.commit(MutationTypes.ADD_TILE_UPDATES, updates.tiles);
this.store.commit(MutationTypes.ADD_CHAT, updates.chat);
if(response.configHash) {
this.store.commit(MutationTypes.SET_SERVER_CONFIGURATION_HASH, response.confighash || 0);
}
await this.store.dispatch(ActionTypes.SET_PLAYERS, players);
}
sendChatMessage(message: string) {
if (!this.store.state.components.chatSending) {
return Promise.reject(this.store.state.messages.chatErrorDisabled);
}
return fetch(this.config.dynmap!.sendmessage, {
method: 'POST',
credentials: 'include',
body: JSON.stringify({
name: null,
message: message,
})
}).then((response) => {
if (response.status === 403) { //Rate limited
throw new ChatError(this.store.state.messages.chatErrorCooldown
.replace('%interval%', this.store.state.components.chatSending!.cooldown.toString()));
}
if (!response.ok) {
throw new Error('Network request failed');
}
return response.json();
}).then(response => {
if (response.error !== 'none') {
throw new ChatError(this.store.state.messages.chatErrorNotAllowed);
}
}).catch(e => {
if (!(e instanceof ChatError)) {
console.error(this.store.state.messages.chatErrorUnknown);
console.trace(e);
}
throw e;
});
}
startUpdates() {
this.updatesEnabled = true;
this.update();
}
private async update() {
try {
await this.getUpdate();
} finally {
if(this.updatesEnabled) {
if(this.updateTimeout) {
clearTimeout(this.updateTimeout);
}
this.updateTimeout = setTimeout(() => this.update(), this.updateInterval);
}
}
}
stopUpdates() {
this.updatesEnabled = false;
if (this.updateTimeout) {
clearTimeout(this.updateTimeout);
}
this.updateTimeout = null;
}
getTilesUrl(): string {
return this.config.dynmap!.tiles;
}
getPlayerHeadUrl(head: HeadQueueEntry): string {
const baseUrl = `${this.config.dynmap!.markers}faces/`;
if(head.size === 'body') {
return `${baseUrl}body/${head.name}.png`;
}
const pixels = getImagePixelSize(head.size);
return `${baseUrl}${pixels}x${pixels}/${head.name}.png`;
}
getMarkerIconUrl(icon: string): string {
return `${this.config.dynmap!.markers}_markers_/${icon}.png`;
}
async login(data: any) {
if (!this.store.getters.loginEnabled) {
return Promise.reject(this.store.state.messages.loginErrorDisabled);
}
this.store.commit(MutationTypes.SET_LOGGED_IN, false);
try {
const body = new URLSearchParams();
body.append('j_username', data.username || '');
body.append('j_password', data.password || '');
const response = await DynmapMapProvider.fetchJSON(this.config.dynmap!.login, {
method: 'POST',
body,
});
switch(response.result) {
case 'success':
this.store.commit(MutationTypes.SET_LOGGED_IN, true);
return;
case 'loginfailed':
return Promise.reject(this.store.state.messages.loginErrorIncorrect);
default:
return Promise.reject(this.store.state.messages.loginErrorUnknown);
}
} catch(e) {
console.error(this.store.state.messages.loginErrorUnknown);
console.trace(e);
return Promise.reject(this.store.state.messages.loginErrorUnknown);
}
}
async logout() {
if (!this.store.getters.loginEnabled) {
return Promise.reject(this.store.state.messages.loginErrorDisabled);
}
try {
await DynmapMapProvider.fetchJSON(this.config.dynmap!.login, {
method: 'POST',
});
this.store.commit(MutationTypes.SET_LOGGED_IN, false);
} catch(e) {
return Promise.reject(this.store.state.messages.logoutErrorUnknown);
}
}
async register(data: any) {
if (!this.store.getters.loginEnabled) {
return Promise.reject(this.store.state.messages.loginErrorDisabled);
}
this.store.commit(MutationTypes.SET_LOGGED_IN, false);
try {
const body = new URLSearchParams();
body.append('j_username', data.username || '');
body.append('j_password', data.password || '');
body.append('j_verify_password', data.password || '');
body.append('j_passcode', data.code || '');
const response = await DynmapMapProvider.fetchJSON(this.config.dynmap!.register, {
method: 'POST',
body,
});
switch(response.result) {
case 'success':
this.store.commit(MutationTypes.SET_LOGGED_IN, true);
return;
case 'verifyfailed':
return Promise.reject(this.store.state.messages.registerErrorVerifyFailed);
case 'registerfailed':
return Promise.reject(this.store.state.messages.registerErrorIncorrect);
default:
return Promise.reject(this.store.state.messages.registerErrorUnknown);
}
} catch(e) {
console.error(this.store.state.messages.registerErrorUnknown);
console.trace(e);
return Promise.reject(this.store.state.messages.registerErrorUnknown);
}
}
destroy() {
super.destroy();
if(this.configurationAbort) {
this.configurationAbort.abort();
}
if(this.updateAbort) {
this.updateAbort.abort();
}
if(this.markersAbort) {
this.markersAbort.abort();
}
}
protected async getJSON(url: string, signal: AbortSignal) {
return MapProvider.fetchJSON(url, {signal, credentials: 'include'}).then(response => {
if(response.error === 'login-required') {
this.store.commit(MutationTypes.SET_LOGIN_REQUIRED, true);
throw new Error("Login required");
}
return response;
});
}
} | the_stack |
import { Injectable } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { BehaviorSubject } from 'rxjs';
import { filter } from 'rxjs/operators';
import { Breadcrumb } from './types/breadcrumb';
import {
BreadcrumbObject,
BreadcrumbFunction,
} from './types/breadcrumb.config';
type BreadcrumbConfig = BreadcrumbObject | BreadcrumbFunction | string;
type StoreMatcherKey = 'routeLink' | 'routeRegex' | 'alias';
export type BreadcrumbDefinition = Breadcrumb & BreadcrumbObject;
const PATH_PARAM = {
PREFIX: ':',
REGEX_IDENTIFIER: '/:[^/]+',
REGEX_REPLACER: '/[^/]+',
};
const ALIAS_PREFIX = '@';
const isNonEmpty = (obj: unknown): boolean => {
return obj && Object.keys(obj).length > 0;
};
@Injectable({
providedIn: 'root',
})
export class BreadcrumbService {
private baseHref = '/';
/**
* dynamicBreadcrumbStore holds information about dynamically updated breadcrumbs.
* Breadcrumbs can be set from anywhere (component, service) in the app.
* On every breadcrumb update check this store and use the info if available.
*/
private dynamicBreadcrumbStore: BreadcrumbDefinition[] = [];
/**
* breadcrumbList for the current route
* When breadcrumb info is changed dynamically, check if the currentBreadcrumbs is effected
* If effected, update the change and emit a new stream
*/
private currentBreadcrumbs: BreadcrumbDefinition[] = [];
private previousBreadcrumbs: BreadcrumbDefinition[] = [];
/**
* Breadcrumbs observable to be subscribed by BreadcrumbComponent
* Emits on every route change OR dynamic update of breadcrumb
*/
private breadcrumbs = new BehaviorSubject<BreadcrumbDefinition[]>([]);
public breadcrumbs$ = this.breadcrumbs.asObservable();
constructor(private activatedRoute: ActivatedRoute, private router: Router) {
this.detectRouteChanges();
}
/**
* Whenever route changes build breadcrumb list again
*/
private detectRouteChanges() {
this.router.events
.pipe(filter((event) => event instanceof NavigationEnd))
.subscribe(() => {
this.previousBreadcrumbs = this.currentBreadcrumbs;
// breadcrumb label for base OR root path. Usually, this can be set as 'Home'
const rootBreadcrumb = this.getRootBreadcrumb();
this.currentBreadcrumbs = rootBreadcrumb ? [rootBreadcrumb] : [];
this.prepareBreadcrumbList(this.activatedRoute.root, this.baseHref);
});
}
private getRootBreadcrumb() {
const rootConfig = this.router.config.find((config) => config.path === '');
const rootBreadcrumb = this.extractObject(rootConfig?.data?.breadcrumb);
const storeItem = this.getFromStore(rootBreadcrumb.alias, '/');
if (isNonEmpty(rootBreadcrumb) || isNonEmpty(storeItem)) {
return {
...storeItem,
...rootBreadcrumb,
routeLink: this.baseHref,
...this.getQueryParamsFromPreviousList('/'),
};
}
}
private prepareBreadcrumbItem(
activatedRoute: ActivatedRoute,
routeLinkPrefix: string
): BreadcrumbDefinition {
const { path, breadcrumb } = this.parseRouteData(
activatedRoute.routeConfig
);
const resolvedSegment = this.resolvePathSegment(path, activatedRoute);
const routeLink = `${routeLinkPrefix}${resolvedSegment}`;
const storeItem = this.getFromStore(breadcrumb.alias, routeLink);
const label = this.extractLabel(
storeItem?.label || breadcrumb?.label,
resolvedSegment
);
let isAutoGeneratedLabel = false;
let autoGeneratedLabel = '';
if (!label) {
isAutoGeneratedLabel = true;
autoGeneratedLabel = resolvedSegment;
}
return {
...storeItem,
...breadcrumb,
label: isAutoGeneratedLabel ? autoGeneratedLabel : label,
routeLink,
isAutoGeneratedLabel,
...this.getQueryParamsFromPreviousList(routeLink),
};
}
private prepareBreadcrumbList(
activatedRoute: ActivatedRoute,
routeLinkPrefix: string
): Breadcrumb[] {
if (activatedRoute.routeConfig && activatedRoute.routeConfig.path) {
const breadcrumbItem = this.prepareBreadcrumbItem(
activatedRoute,
routeLinkPrefix
);
this.currentBreadcrumbs.push(breadcrumbItem);
if (activatedRoute.firstChild) {
return this.prepareBreadcrumbList(
activatedRoute.firstChild,
breadcrumbItem.routeLink + '/'
);
}
} else if (activatedRoute.firstChild) {
return this.prepareBreadcrumbList(
activatedRoute.firstChild,
routeLinkPrefix
);
}
const lastCrumb = this.currentBreadcrumbs[
this.currentBreadcrumbs.length - 1
];
this.setQueryParamsForActiveBreadcrumb(lastCrumb, activatedRoute);
// remove breadcrumb items that needs to be hidden
const breadcrumbsToShow = this.currentBreadcrumbs.filter(
(item) => !item.skip
);
this.breadcrumbs.next(breadcrumbsToShow);
}
private getFromStore(alias: string, routeLink: string): BreadcrumbDefinition {
return this.dynamicBreadcrumbStore.find((item) => {
return (
(alias && alias === item.alias) ||
(routeLink && routeLink === item.routeLink) ||
this.matchRegex(routeLink, item.routeRegex)
);
});
}
/**
* use exact match instead of regexp.test
* for /mentor/[^/]+ we should match '/mentor/12' but not '/mentor/12/abc'
*/
private matchRegex(routeLink: string, routeRegex: string) {
const match = routeLink.match(new RegExp(routeRegex));
return match && match[0] === routeLink;
}
/**
* if the path segment has route params, read the param value from url
* for each segment of route this gets called
*
* for mentor/:id/view - it gets called with mentor, :id, view 3 times
*/
private resolvePathSegment(segment: string, activatedRoute: ActivatedRoute) {
//quirk -segment can be defined as view/:id in route config in which case you need to make it view/<resolved-param>
if (segment.includes(PATH_PARAM.PREFIX)) {
Object.entries(activatedRoute.snapshot.params).forEach(([key, value]) => {
segment = segment.replace(`:${key}`, `${value}`);
});
}
return segment;
}
/**
* queryParams & fragments for previous breadcrumb path are copied over to new list
*/
private getQueryParamsFromPreviousList(routeLink: string): Breadcrumb {
const { queryParams, fragment } =
this.previousBreadcrumbs.find((item) => item.routeLink === routeLink) ||
{};
return { queryParams, fragment };
}
/**
* set current activated route query params to the last breadcrumb item
*/
private setQueryParamsForActiveBreadcrumb(
lastItem: Breadcrumb,
activatedRoute: ActivatedRoute
) {
if (lastItem) {
const { queryParams, fragment } = activatedRoute.snapshot;
lastItem.queryParams = queryParams ? { ...queryParams } : undefined;
lastItem.fragment = fragment;
}
}
/**
* For a specific route, breadcrumb can be defined either on parent OR it's child(which has empty path)
* When both are defined, child takes precedence
*
* Ex: Below we are setting breadcrumb on both parent and child.
* So, child takes precedence and "Defined On Child" is displayed for the route 'home'
* { path: 'home', loadChildren: './home/home.module#HomeModule' , data: {breadcrumb: "Defined On Module"}}
* AND
* children: [
* { path: '', component: ShowUserComponent, data: {breadcrumb: "Defined On Child" }
* ]
*/
private parseRouteData(routeConfig) {
const { path, data } = routeConfig;
const breadcrumb = this.mergeWithBaseChildData(
routeConfig,
data?.breadcrumb
);
return { path, breadcrumb };
}
/**
* get empty children of a module or Component. Empty child is the one with path: ''
* When parent and it's children (that has empty route path) define data merge them both with child taking precedence
*/
private mergeWithBaseChildData(
routeConfig,
config: BreadcrumbConfig
): BreadcrumbObject {
if (!routeConfig) {
return this.extractObject(config);
}
let baseChild;
if (routeConfig.loadChildren) {
// To handle a module with empty child route
baseChild = routeConfig._loadedConfig.routes.find(
(route) => route.path === ''
);
} else if (routeConfig.children) {
// To handle a component with empty child route
baseChild = routeConfig.children.find((route) => route.path === '');
}
const childConfig = baseChild?.data?.breadcrumb;
return childConfig
? this.mergeWithBaseChildData(baseChild, {
...this.extractObject(config),
...this.extractObject(childConfig),
})
: this.extractObject(config);
}
/**
* Update breadcrumb dynamically
*
* key can be a path | alias
*
* 1) Using complete route path. route can be passed the same way you define angular routes
* - path can be passed as 'exact path(routeLink)' or 'path with params(routeRegex)'
* - update label Ex: set('/mentor', 'Mentor'), set('/mentor/:id', 'Mentor Details')
* - change visibility Ex: set('/mentor/:id/edit', { skip: true })
* ------------------------------------------ OR ------------------------------------------
* 2) Using route alias (prefixed with '@'). alias should be unique for a route
* - update label Ex: set('@mentor', 'Enabler')
* - change visibility Ex: set('@mentorEdit', { skip: true })
*
*
* value can be string | BreadcrumbObject | BreadcrumbFunction
*/
set(key: string, breadcrumb: string | BreadcrumbObject) {
const breadcrumbObject = this.extractObject(breadcrumb);
let updateArgs: [StoreMatcherKey, BreadcrumbDefinition];
if (key.startsWith(ALIAS_PREFIX)) {
updateArgs = ['alias', { ...breadcrumbObject, alias: key.slice(1) }];
} else if (key.includes(PATH_PARAM.PREFIX)) {
updateArgs = [
'routeRegex',
{ ...breadcrumbObject, routeRegex: this.buildRegex(key) },
];
} else {
updateArgs = [
'routeLink',
{ ...breadcrumbObject, routeLink: this.ensureLeadingSlash(key) },
];
}
this.updateStore(...updateArgs);
this.updateCurrentBreadcrumbs(...updateArgs);
}
/**
* Update the store to reuse for dynamic declarations
* If the store already has this route definition update it, else add
*/
private updateStore(key: string, breadcrumb: BreadcrumbDefinition) {
const storeItemIndex = this.dynamicBreadcrumbStore.findIndex((item) => {
return breadcrumb[key] === item[key];
});
if (storeItemIndex > -1) {
this.dynamicBreadcrumbStore[storeItemIndex] = {
...this.dynamicBreadcrumbStore[storeItemIndex],
...breadcrumb,
};
} else {
this.dynamicBreadcrumbStore.push({ ...breadcrumb });
}
}
/**
* If breadcrumb is present in current breadcrumbs update it and emit new stream
*/
private updateCurrentBreadcrumbs(
key: string,
breadcrumb: BreadcrumbDefinition
) {
const itemIndex = this.currentBreadcrumbs.findIndex((item) => {
return key === 'routeRegex'
? this.matchRegex(item.routeLink, breadcrumb[key])
: breadcrumb[key] === item[key];
});
if (itemIndex > -1) {
this.currentBreadcrumbs[itemIndex] = {
...this.currentBreadcrumbs[itemIndex],
...breadcrumb,
};
const breadcrumbsToShow = this.currentBreadcrumbs.filter(
(item) => !item.skip
);
this.breadcrumbs.next([...breadcrumbsToShow]);
}
}
/**
* For a route with path param, we create regex dynamically from angular route syntax
* '/mentor/:id' becomes '/mentor/[^/]',
* breadcrumbService.set('/mentor/:id', 'Uday') should update 'Uday' as label for '/mentor/2' OR 'mentor/ada'
*/
private buildRegex(path: string) {
return this.ensureLeadingSlash(path).replace(
new RegExp(PATH_PARAM.REGEX_IDENTIFIER, 'g'),
PATH_PARAM.REGEX_REPLACER
);
}
private ensureLeadingSlash(path: string) {
return path.startsWith('/') ? path : `/${path}`;
}
/**
* In App's RouteConfig, breadcrumb can be defined as a string OR a function OR an object
*
* string: simple static breadcrumb label for a path
* function: callback that gets invoked with resolved path param
* object: additional data defined along with breadcrumb label that gets passed to *xngBreadcrumbItem directive
*/
private extractLabel(config: BreadcrumbConfig, resolvedParam?: string) {
const label = typeof config === 'object' ? config.label : config;
if (typeof label === 'function') {
return label(resolvedParam);
}
return label;
}
private extractObject(config: BreadcrumbConfig): BreadcrumbObject {
// don't include {label} if config is undefined. This is important since we merge the configs
if (
config &&
(typeof config === 'string' || typeof config === 'function')
) {
return { label: config };
}
return (config as BreadcrumbObject) || {};
}
} | the_stack |
import { LrosaDs } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { LROClient } from "../lROClient";
import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro";
import { LroImpl } from "../lroImpl";
import {
LrosaDsPutNonRetry400OptionalParams,
LrosaDsPutNonRetry400Response,
LrosaDsPutNonRetry201Creating400OptionalParams,
LrosaDsPutNonRetry201Creating400Response,
LrosaDsPutNonRetry201Creating400InvalidJsonOptionalParams,
LrosaDsPutNonRetry201Creating400InvalidJsonResponse,
LrosaDsPutAsyncRelativeRetry400OptionalParams,
LrosaDsPutAsyncRelativeRetry400Response,
LrosaDsDeleteNonRetry400OptionalParams,
LrosaDsDeleteNonRetry400Response,
LrosaDsDelete202NonRetry400OptionalParams,
LrosaDsDelete202NonRetry400Response,
LrosaDsDeleteAsyncRelativeRetry400OptionalParams,
LrosaDsDeleteAsyncRelativeRetry400Response,
LrosaDsPostNonRetry400OptionalParams,
LrosaDsPostNonRetry400Response,
LrosaDsPost202NonRetry400OptionalParams,
LrosaDsPost202NonRetry400Response,
LrosaDsPostAsyncRelativeRetry400OptionalParams,
LrosaDsPostAsyncRelativeRetry400Response,
LrosaDsPutError201NoProvisioningStatePayloadOptionalParams,
LrosaDsPutError201NoProvisioningStatePayloadResponse,
LrosaDsPutAsyncRelativeRetryNoStatusOptionalParams,
LrosaDsPutAsyncRelativeRetryNoStatusResponse,
LrosaDsPutAsyncRelativeRetryNoStatusPayloadOptionalParams,
LrosaDsPutAsyncRelativeRetryNoStatusPayloadResponse,
LrosaDsDelete204SucceededOptionalParams,
LrosaDsDeleteAsyncRelativeRetryNoStatusOptionalParams,
LrosaDsDeleteAsyncRelativeRetryNoStatusResponse,
LrosaDsPost202NoLocationOptionalParams,
LrosaDsPost202NoLocationResponse,
LrosaDsPostAsyncRelativeRetryNoPayloadOptionalParams,
LrosaDsPostAsyncRelativeRetryNoPayloadResponse,
LrosaDsPut200InvalidJsonOptionalParams,
LrosaDsPut200InvalidJsonResponse,
LrosaDsPutAsyncRelativeRetryInvalidHeaderOptionalParams,
LrosaDsPutAsyncRelativeRetryInvalidHeaderResponse,
LrosaDsPutAsyncRelativeRetryInvalidJsonPollingOptionalParams,
LrosaDsPutAsyncRelativeRetryInvalidJsonPollingResponse,
LrosaDsDelete202RetryInvalidHeaderOptionalParams,
LrosaDsDelete202RetryInvalidHeaderResponse,
LrosaDsDeleteAsyncRelativeRetryInvalidHeaderOptionalParams,
LrosaDsDeleteAsyncRelativeRetryInvalidHeaderResponse,
LrosaDsDeleteAsyncRelativeRetryInvalidJsonPollingOptionalParams,
LrosaDsDeleteAsyncRelativeRetryInvalidJsonPollingResponse,
LrosaDsPost202RetryInvalidHeaderOptionalParams,
LrosaDsPost202RetryInvalidHeaderResponse,
LrosaDsPostAsyncRelativeRetryInvalidHeaderOptionalParams,
LrosaDsPostAsyncRelativeRetryInvalidHeaderResponse,
LrosaDsPostAsyncRelativeRetryInvalidJsonPollingOptionalParams,
LrosaDsPostAsyncRelativeRetryInvalidJsonPollingResponse
} from "../models";
/** Class containing LrosaDs operations. */
export class LrosaDsImpl implements LrosaDs {
private readonly client: LROClient;
/**
* Initialize a new instance of the class LrosaDs class.
* @param client Reference to the service client
*/
constructor(client: LROClient) {
this.client = client;
}
/**
* Long running put request, service returns a 400 to the initial request
* @param options The options parameters.
*/
async beginPutNonRetry400(
options?: LrosaDsPutNonRetry400OptionalParams
): Promise<
PollerLike<
PollOperationState<LrosaDsPutNonRetry400Response>,
LrosaDsPutNonRetry400Response
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LrosaDsPutNonRetry400Response> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
putNonRetry400OperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running put request, service returns a 400 to the initial request
* @param options The options parameters.
*/
async beginPutNonRetry400AndWait(
options?: LrosaDsPutNonRetry400OptionalParams
): Promise<LrosaDsPutNonRetry400Response> {
const poller = await this.beginPutNonRetry400(options);
return poller.pollUntilDone();
}
/**
* Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201
* response code
* @param options The options parameters.
*/
async beginPutNonRetry201Creating400(
options?: LrosaDsPutNonRetry201Creating400OptionalParams
): Promise<
PollerLike<
PollOperationState<LrosaDsPutNonRetry201Creating400Response>,
LrosaDsPutNonRetry201Creating400Response
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LrosaDsPutNonRetry201Creating400Response> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
putNonRetry201Creating400OperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201
* response code
* @param options The options parameters.
*/
async beginPutNonRetry201Creating400AndWait(
options?: LrosaDsPutNonRetry201Creating400OptionalParams
): Promise<LrosaDsPutNonRetry201Creating400Response> {
const poller = await this.beginPutNonRetry201Creating400(options);
return poller.pollUntilDone();
}
/**
* Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201
* response code
* @param options The options parameters.
*/
async beginPutNonRetry201Creating400InvalidJson(
options?: LrosaDsPutNonRetry201Creating400InvalidJsonOptionalParams
): Promise<
PollerLike<
PollOperationState<LrosaDsPutNonRetry201Creating400InvalidJsonResponse>,
LrosaDsPutNonRetry201Creating400InvalidJsonResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LrosaDsPutNonRetry201Creating400InvalidJsonResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
putNonRetry201Creating400InvalidJsonOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201
* response code
* @param options The options parameters.
*/
async beginPutNonRetry201Creating400InvalidJsonAndWait(
options?: LrosaDsPutNonRetry201Creating400InvalidJsonOptionalParams
): Promise<LrosaDsPutNonRetry201Creating400InvalidJsonResponse> {
const poller = await this.beginPutNonRetry201Creating400InvalidJson(
options
);
return poller.pollUntilDone();
}
/**
* Long running put request, service returns a 200 with ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
* @param options The options parameters.
*/
async beginPutAsyncRelativeRetry400(
options?: LrosaDsPutAsyncRelativeRetry400OptionalParams
): Promise<
PollerLike<
PollOperationState<LrosaDsPutAsyncRelativeRetry400Response>,
LrosaDsPutAsyncRelativeRetry400Response
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LrosaDsPutAsyncRelativeRetry400Response> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
putAsyncRelativeRetry400OperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running put request, service returns a 200 with ProvisioningState=’Creating’. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
* @param options The options parameters.
*/
async beginPutAsyncRelativeRetry400AndWait(
options?: LrosaDsPutAsyncRelativeRetry400OptionalParams
): Promise<LrosaDsPutAsyncRelativeRetry400Response> {
const poller = await this.beginPutAsyncRelativeRetry400(options);
return poller.pollUntilDone();
}
/**
* Long running delete request, service returns a 400 with an error body
* @param options The options parameters.
*/
async beginDeleteNonRetry400(
options?: LrosaDsDeleteNonRetry400OptionalParams
): Promise<
PollerLike<
PollOperationState<LrosaDsDeleteNonRetry400Response>,
LrosaDsDeleteNonRetry400Response
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LrosaDsDeleteNonRetry400Response> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
deleteNonRetry400OperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running delete request, service returns a 400 with an error body
* @param options The options parameters.
*/
async beginDeleteNonRetry400AndWait(
options?: LrosaDsDeleteNonRetry400OptionalParams
): Promise<LrosaDsDeleteNonRetry400Response> {
const poller = await this.beginDeleteNonRetry400(options);
return poller.pollUntilDone();
}
/**
* Long running delete request, service returns a 202 with a location header
* @param options The options parameters.
*/
async beginDelete202NonRetry400(
options?: LrosaDsDelete202NonRetry400OptionalParams
): Promise<
PollerLike<
PollOperationState<LrosaDsDelete202NonRetry400Response>,
LrosaDsDelete202NonRetry400Response
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LrosaDsDelete202NonRetry400Response> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
delete202NonRetry400OperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running delete request, service returns a 202 with a location header
* @param options The options parameters.
*/
async beginDelete202NonRetry400AndWait(
options?: LrosaDsDelete202NonRetry400OptionalParams
): Promise<LrosaDsDelete202NonRetry400Response> {
const poller = await this.beginDelete202NonRetry400(options);
return poller.pollUntilDone();
}
/**
* Long running delete request, service returns a 202 to the initial request. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
* @param options The options parameters.
*/
async beginDeleteAsyncRelativeRetry400(
options?: LrosaDsDeleteAsyncRelativeRetry400OptionalParams
): Promise<
PollerLike<
PollOperationState<LrosaDsDeleteAsyncRelativeRetry400Response>,
LrosaDsDeleteAsyncRelativeRetry400Response
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LrosaDsDeleteAsyncRelativeRetry400Response> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
deleteAsyncRelativeRetry400OperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running delete request, service returns a 202 to the initial request. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
* @param options The options parameters.
*/
async beginDeleteAsyncRelativeRetry400AndWait(
options?: LrosaDsDeleteAsyncRelativeRetry400OptionalParams
): Promise<LrosaDsDeleteAsyncRelativeRetry400Response> {
const poller = await this.beginDeleteAsyncRelativeRetry400(options);
return poller.pollUntilDone();
}
/**
* Long running post request, service returns a 400 with no error body
* @param options The options parameters.
*/
async beginPostNonRetry400(
options?: LrosaDsPostNonRetry400OptionalParams
): Promise<
PollerLike<
PollOperationState<LrosaDsPostNonRetry400Response>,
LrosaDsPostNonRetry400Response
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LrosaDsPostNonRetry400Response> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
postNonRetry400OperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running post request, service returns a 400 with no error body
* @param options The options parameters.
*/
async beginPostNonRetry400AndWait(
options?: LrosaDsPostNonRetry400OptionalParams
): Promise<LrosaDsPostNonRetry400Response> {
const poller = await this.beginPostNonRetry400(options);
return poller.pollUntilDone();
}
/**
* Long running post request, service returns a 202 with a location header
* @param options The options parameters.
*/
async beginPost202NonRetry400(
options?: LrosaDsPost202NonRetry400OptionalParams
): Promise<
PollerLike<
PollOperationState<LrosaDsPost202NonRetry400Response>,
LrosaDsPost202NonRetry400Response
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LrosaDsPost202NonRetry400Response> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
post202NonRetry400OperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running post request, service returns a 202 with a location header
* @param options The options parameters.
*/
async beginPost202NonRetry400AndWait(
options?: LrosaDsPost202NonRetry400OptionalParams
): Promise<LrosaDsPost202NonRetry400Response> {
const poller = await this.beginPost202NonRetry400(options);
return poller.pollUntilDone();
}
/**
* Long running post request, service returns a 202 to the initial request Poll the endpoint indicated
* in the Azure-AsyncOperation header for operation status
* @param options The options parameters.
*/
async beginPostAsyncRelativeRetry400(
options?: LrosaDsPostAsyncRelativeRetry400OptionalParams
): Promise<
PollerLike<
PollOperationState<LrosaDsPostAsyncRelativeRetry400Response>,
LrosaDsPostAsyncRelativeRetry400Response
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LrosaDsPostAsyncRelativeRetry400Response> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
postAsyncRelativeRetry400OperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running post request, service returns a 202 to the initial request Poll the endpoint indicated
* in the Azure-AsyncOperation header for operation status
* @param options The options parameters.
*/
async beginPostAsyncRelativeRetry400AndWait(
options?: LrosaDsPostAsyncRelativeRetry400OptionalParams
): Promise<LrosaDsPostAsyncRelativeRetry400Response> {
const poller = await this.beginPostAsyncRelativeRetry400(options);
return poller.pollUntilDone();
}
/**
* Long running put request, service returns a 201 to the initial request with no payload
* @param options The options parameters.
*/
async beginPutError201NoProvisioningStatePayload(
options?: LrosaDsPutError201NoProvisioningStatePayloadOptionalParams
): Promise<
PollerLike<
PollOperationState<LrosaDsPutError201NoProvisioningStatePayloadResponse>,
LrosaDsPutError201NoProvisioningStatePayloadResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LrosaDsPutError201NoProvisioningStatePayloadResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
putError201NoProvisioningStatePayloadOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running put request, service returns a 201 to the initial request with no payload
* @param options The options parameters.
*/
async beginPutError201NoProvisioningStatePayloadAndWait(
options?: LrosaDsPutError201NoProvisioningStatePayloadOptionalParams
): Promise<LrosaDsPutError201NoProvisioningStatePayloadResponse> {
const poller = await this.beginPutError201NoProvisioningStatePayload(
options
);
return poller.pollUntilDone();
}
/**
* Long running put request, service returns a 200 to the initial request, with an entity that contains
* ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for
* operation status
* @param options The options parameters.
*/
async beginPutAsyncRelativeRetryNoStatus(
options?: LrosaDsPutAsyncRelativeRetryNoStatusOptionalParams
): Promise<
PollerLike<
PollOperationState<LrosaDsPutAsyncRelativeRetryNoStatusResponse>,
LrosaDsPutAsyncRelativeRetryNoStatusResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LrosaDsPutAsyncRelativeRetryNoStatusResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
putAsyncRelativeRetryNoStatusOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running put request, service returns a 200 to the initial request, with an entity that contains
* ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for
* operation status
* @param options The options parameters.
*/
async beginPutAsyncRelativeRetryNoStatusAndWait(
options?: LrosaDsPutAsyncRelativeRetryNoStatusOptionalParams
): Promise<LrosaDsPutAsyncRelativeRetryNoStatusResponse> {
const poller = await this.beginPutAsyncRelativeRetryNoStatus(options);
return poller.pollUntilDone();
}
/**
* Long running put request, service returns a 200 to the initial request, with an entity that contains
* ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for
* operation status
* @param options The options parameters.
*/
async beginPutAsyncRelativeRetryNoStatusPayload(
options?: LrosaDsPutAsyncRelativeRetryNoStatusPayloadOptionalParams
): Promise<
PollerLike<
PollOperationState<LrosaDsPutAsyncRelativeRetryNoStatusPayloadResponse>,
LrosaDsPutAsyncRelativeRetryNoStatusPayloadResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LrosaDsPutAsyncRelativeRetryNoStatusPayloadResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
putAsyncRelativeRetryNoStatusPayloadOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running put request, service returns a 200 to the initial request, with an entity that contains
* ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for
* operation status
* @param options The options parameters.
*/
async beginPutAsyncRelativeRetryNoStatusPayloadAndWait(
options?: LrosaDsPutAsyncRelativeRetryNoStatusPayloadOptionalParams
): Promise<LrosaDsPutAsyncRelativeRetryNoStatusPayloadResponse> {
const poller = await this.beginPutAsyncRelativeRetryNoStatusPayload(
options
);
return poller.pollUntilDone();
}
/**
* Long running delete request, service returns a 204 to the initial request, indicating success.
* @param options The options parameters.
*/
async beginDelete204Succeeded(
options?: LrosaDsDelete204SucceededOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<void> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
delete204SucceededOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running delete request, service returns a 204 to the initial request, indicating success.
* @param options The options parameters.
*/
async beginDelete204SucceededAndWait(
options?: LrosaDsDelete204SucceededOptionalParams
): Promise<void> {
const poller = await this.beginDelete204Succeeded(options);
return poller.pollUntilDone();
}
/**
* Long running delete request, service returns a 202 to the initial request. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
* @param options The options parameters.
*/
async beginDeleteAsyncRelativeRetryNoStatus(
options?: LrosaDsDeleteAsyncRelativeRetryNoStatusOptionalParams
): Promise<
PollerLike<
PollOperationState<LrosaDsDeleteAsyncRelativeRetryNoStatusResponse>,
LrosaDsDeleteAsyncRelativeRetryNoStatusResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LrosaDsDeleteAsyncRelativeRetryNoStatusResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
deleteAsyncRelativeRetryNoStatusOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running delete request, service returns a 202 to the initial request. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
* @param options The options parameters.
*/
async beginDeleteAsyncRelativeRetryNoStatusAndWait(
options?: LrosaDsDeleteAsyncRelativeRetryNoStatusOptionalParams
): Promise<LrosaDsDeleteAsyncRelativeRetryNoStatusResponse> {
const poller = await this.beginDeleteAsyncRelativeRetryNoStatus(options);
return poller.pollUntilDone();
}
/**
* Long running post request, service returns a 202 to the initial request, without a location header.
* @param options The options parameters.
*/
async beginPost202NoLocation(
options?: LrosaDsPost202NoLocationOptionalParams
): Promise<
PollerLike<
PollOperationState<LrosaDsPost202NoLocationResponse>,
LrosaDsPost202NoLocationResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LrosaDsPost202NoLocationResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
post202NoLocationOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running post request, service returns a 202 to the initial request, without a location header.
* @param options The options parameters.
*/
async beginPost202NoLocationAndWait(
options?: LrosaDsPost202NoLocationOptionalParams
): Promise<LrosaDsPost202NoLocationResponse> {
const poller = await this.beginPost202NoLocation(options);
return poller.pollUntilDone();
}
/**
* Long running post request, service returns a 202 to the initial request, with an entity that
* contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation
* header for operation status
* @param options The options parameters.
*/
async beginPostAsyncRelativeRetryNoPayload(
options?: LrosaDsPostAsyncRelativeRetryNoPayloadOptionalParams
): Promise<
PollerLike<
PollOperationState<LrosaDsPostAsyncRelativeRetryNoPayloadResponse>,
LrosaDsPostAsyncRelativeRetryNoPayloadResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LrosaDsPostAsyncRelativeRetryNoPayloadResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
postAsyncRelativeRetryNoPayloadOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running post request, service returns a 202 to the initial request, with an entity that
* contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation
* header for operation status
* @param options The options parameters.
*/
async beginPostAsyncRelativeRetryNoPayloadAndWait(
options?: LrosaDsPostAsyncRelativeRetryNoPayloadOptionalParams
): Promise<LrosaDsPostAsyncRelativeRetryNoPayloadResponse> {
const poller = await this.beginPostAsyncRelativeRetryNoPayload(options);
return poller.pollUntilDone();
}
/**
* Long running put request, service returns a 200 to the initial request, with an entity that is not a
* valid json
* @param options The options parameters.
*/
async beginPut200InvalidJson(
options?: LrosaDsPut200InvalidJsonOptionalParams
): Promise<
PollerLike<
PollOperationState<LrosaDsPut200InvalidJsonResponse>,
LrosaDsPut200InvalidJsonResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LrosaDsPut200InvalidJsonResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
put200InvalidJsonOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running put request, service returns a 200 to the initial request, with an entity that is not a
* valid json
* @param options The options parameters.
*/
async beginPut200InvalidJsonAndWait(
options?: LrosaDsPut200InvalidJsonOptionalParams
): Promise<LrosaDsPut200InvalidJsonResponse> {
const poller = await this.beginPut200InvalidJson(options);
return poller.pollUntilDone();
}
/**
* Long running put request, service returns a 200 to the initial request, with an entity that contains
* ProvisioningState=’Creating’. The endpoint indicated in the Azure-AsyncOperation header is invalid.
* @param options The options parameters.
*/
async beginPutAsyncRelativeRetryInvalidHeader(
options?: LrosaDsPutAsyncRelativeRetryInvalidHeaderOptionalParams
): Promise<
PollerLike<
PollOperationState<LrosaDsPutAsyncRelativeRetryInvalidHeaderResponse>,
LrosaDsPutAsyncRelativeRetryInvalidHeaderResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LrosaDsPutAsyncRelativeRetryInvalidHeaderResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
putAsyncRelativeRetryInvalidHeaderOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running put request, service returns a 200 to the initial request, with an entity that contains
* ProvisioningState=’Creating’. The endpoint indicated in the Azure-AsyncOperation header is invalid.
* @param options The options parameters.
*/
async beginPutAsyncRelativeRetryInvalidHeaderAndWait(
options?: LrosaDsPutAsyncRelativeRetryInvalidHeaderOptionalParams
): Promise<LrosaDsPutAsyncRelativeRetryInvalidHeaderResponse> {
const poller = await this.beginPutAsyncRelativeRetryInvalidHeader(options);
return poller.pollUntilDone();
}
/**
* Long running put request, service returns a 200 to the initial request, with an entity that contains
* ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for
* operation status
* @param options The options parameters.
*/
async beginPutAsyncRelativeRetryInvalidJsonPolling(
options?: LrosaDsPutAsyncRelativeRetryInvalidJsonPollingOptionalParams
): Promise<
PollerLike<
PollOperationState<
LrosaDsPutAsyncRelativeRetryInvalidJsonPollingResponse
>,
LrosaDsPutAsyncRelativeRetryInvalidJsonPollingResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LrosaDsPutAsyncRelativeRetryInvalidJsonPollingResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
putAsyncRelativeRetryInvalidJsonPollingOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running put request, service returns a 200 to the initial request, with an entity that contains
* ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for
* operation status
* @param options The options parameters.
*/
async beginPutAsyncRelativeRetryInvalidJsonPollingAndWait(
options?: LrosaDsPutAsyncRelativeRetryInvalidJsonPollingOptionalParams
): Promise<LrosaDsPutAsyncRelativeRetryInvalidJsonPollingResponse> {
const poller = await this.beginPutAsyncRelativeRetryInvalidJsonPolling(
options
);
return poller.pollUntilDone();
}
/**
* Long running delete request, service returns a 202 to the initial request receing a reponse with an
* invalid 'Location' and 'Retry-After' headers
* @param options The options parameters.
*/
async beginDelete202RetryInvalidHeader(
options?: LrosaDsDelete202RetryInvalidHeaderOptionalParams
): Promise<
PollerLike<
PollOperationState<LrosaDsDelete202RetryInvalidHeaderResponse>,
LrosaDsDelete202RetryInvalidHeaderResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LrosaDsDelete202RetryInvalidHeaderResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
delete202RetryInvalidHeaderOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running delete request, service returns a 202 to the initial request receing a reponse with an
* invalid 'Location' and 'Retry-After' headers
* @param options The options parameters.
*/
async beginDelete202RetryInvalidHeaderAndWait(
options?: LrosaDsDelete202RetryInvalidHeaderOptionalParams
): Promise<LrosaDsDelete202RetryInvalidHeaderResponse> {
const poller = await this.beginDelete202RetryInvalidHeader(options);
return poller.pollUntilDone();
}
/**
* Long running delete request, service returns a 202 to the initial request. The endpoint indicated in
* the Azure-AsyncOperation header is invalid
* @param options The options parameters.
*/
async beginDeleteAsyncRelativeRetryInvalidHeader(
options?: LrosaDsDeleteAsyncRelativeRetryInvalidHeaderOptionalParams
): Promise<
PollerLike<
PollOperationState<LrosaDsDeleteAsyncRelativeRetryInvalidHeaderResponse>,
LrosaDsDeleteAsyncRelativeRetryInvalidHeaderResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LrosaDsDeleteAsyncRelativeRetryInvalidHeaderResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
deleteAsyncRelativeRetryInvalidHeaderOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running delete request, service returns a 202 to the initial request. The endpoint indicated in
* the Azure-AsyncOperation header is invalid
* @param options The options parameters.
*/
async beginDeleteAsyncRelativeRetryInvalidHeaderAndWait(
options?: LrosaDsDeleteAsyncRelativeRetryInvalidHeaderOptionalParams
): Promise<LrosaDsDeleteAsyncRelativeRetryInvalidHeaderResponse> {
const poller = await this.beginDeleteAsyncRelativeRetryInvalidHeader(
options
);
return poller.pollUntilDone();
}
/**
* Long running delete request, service returns a 202 to the initial request. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
* @param options The options parameters.
*/
async beginDeleteAsyncRelativeRetryInvalidJsonPolling(
options?: LrosaDsDeleteAsyncRelativeRetryInvalidJsonPollingOptionalParams
): Promise<
PollerLike<
PollOperationState<
LrosaDsDeleteAsyncRelativeRetryInvalidJsonPollingResponse
>,
LrosaDsDeleteAsyncRelativeRetryInvalidJsonPollingResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LrosaDsDeleteAsyncRelativeRetryInvalidJsonPollingResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
deleteAsyncRelativeRetryInvalidJsonPollingOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running delete request, service returns a 202 to the initial request. Poll the endpoint
* indicated in the Azure-AsyncOperation header for operation status
* @param options The options parameters.
*/
async beginDeleteAsyncRelativeRetryInvalidJsonPollingAndWait(
options?: LrosaDsDeleteAsyncRelativeRetryInvalidJsonPollingOptionalParams
): Promise<LrosaDsDeleteAsyncRelativeRetryInvalidJsonPollingResponse> {
const poller = await this.beginDeleteAsyncRelativeRetryInvalidJsonPolling(
options
);
return poller.pollUntilDone();
}
/**
* Long running post request, service returns a 202 to the initial request, with invalid 'Location' and
* 'Retry-After' headers.
* @param options The options parameters.
*/
async beginPost202RetryInvalidHeader(
options?: LrosaDsPost202RetryInvalidHeaderOptionalParams
): Promise<
PollerLike<
PollOperationState<LrosaDsPost202RetryInvalidHeaderResponse>,
LrosaDsPost202RetryInvalidHeaderResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LrosaDsPost202RetryInvalidHeaderResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
post202RetryInvalidHeaderOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running post request, service returns a 202 to the initial request, with invalid 'Location' and
* 'Retry-After' headers.
* @param options The options parameters.
*/
async beginPost202RetryInvalidHeaderAndWait(
options?: LrosaDsPost202RetryInvalidHeaderOptionalParams
): Promise<LrosaDsPost202RetryInvalidHeaderResponse> {
const poller = await this.beginPost202RetryInvalidHeader(options);
return poller.pollUntilDone();
}
/**
* Long running post request, service returns a 202 to the initial request, with an entity that
* contains ProvisioningState=’Creating’. The endpoint indicated in the Azure-AsyncOperation header is
* invalid.
* @param options The options parameters.
*/
async beginPostAsyncRelativeRetryInvalidHeader(
options?: LrosaDsPostAsyncRelativeRetryInvalidHeaderOptionalParams
): Promise<
PollerLike<
PollOperationState<LrosaDsPostAsyncRelativeRetryInvalidHeaderResponse>,
LrosaDsPostAsyncRelativeRetryInvalidHeaderResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LrosaDsPostAsyncRelativeRetryInvalidHeaderResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
postAsyncRelativeRetryInvalidHeaderOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running post request, service returns a 202 to the initial request, with an entity that
* contains ProvisioningState=’Creating’. The endpoint indicated in the Azure-AsyncOperation header is
* invalid.
* @param options The options parameters.
*/
async beginPostAsyncRelativeRetryInvalidHeaderAndWait(
options?: LrosaDsPostAsyncRelativeRetryInvalidHeaderOptionalParams
): Promise<LrosaDsPostAsyncRelativeRetryInvalidHeaderResponse> {
const poller = await this.beginPostAsyncRelativeRetryInvalidHeader(options);
return poller.pollUntilDone();
}
/**
* Long running post request, service returns a 202 to the initial request, with an entity that
* contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation
* header for operation status
* @param options The options parameters.
*/
async beginPostAsyncRelativeRetryInvalidJsonPolling(
options?: LrosaDsPostAsyncRelativeRetryInvalidJsonPollingOptionalParams
): Promise<
PollerLike<
PollOperationState<
LrosaDsPostAsyncRelativeRetryInvalidJsonPollingResponse
>,
LrosaDsPostAsyncRelativeRetryInvalidJsonPollingResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<LrosaDsPostAsyncRelativeRetryInvalidJsonPollingResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ options },
postAsyncRelativeRetryInvalidJsonPollingOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Long running post request, service returns a 202 to the initial request, with an entity that
* contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation
* header for operation status
* @param options The options parameters.
*/
async beginPostAsyncRelativeRetryInvalidJsonPollingAndWait(
options?: LrosaDsPostAsyncRelativeRetryInvalidJsonPollingOptionalParams
): Promise<LrosaDsPostAsyncRelativeRetryInvalidJsonPollingResponse> {
const poller = await this.beginPostAsyncRelativeRetryInvalidJsonPolling(
options
);
return poller.pollUntilDone();
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const putNonRetry400OperationSpec: coreClient.OperationSpec = {
path: "/lro/nonretryerror/put/400",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.Product
},
201: {
bodyMapper: Mappers.Product
},
202: {
bodyMapper: Mappers.Product
},
204: {
bodyMapper: Mappers.Product
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.product,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const putNonRetry201Creating400OperationSpec: coreClient.OperationSpec = {
path: "/lro/nonretryerror/put/201/creating/400",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.Product
},
201: {
bodyMapper: Mappers.Product
},
202: {
bodyMapper: Mappers.Product
},
204: {
bodyMapper: Mappers.Product
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.product,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const putNonRetry201Creating400InvalidJsonOperationSpec: coreClient.OperationSpec = {
path: "/lro/nonretryerror/put/201/creating/400/invalidjson",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.Product
},
201: {
bodyMapper: Mappers.Product
},
202: {
bodyMapper: Mappers.Product
},
204: {
bodyMapper: Mappers.Product
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.product,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const putAsyncRelativeRetry400OperationSpec: coreClient.OperationSpec = {
path: "/lro/nonretryerror/putasync/retry/400",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.Product,
headersMapper: Mappers.LrosaDsPutAsyncRelativeRetry400Headers
},
201: {
bodyMapper: Mappers.Product,
headersMapper: Mappers.LrosaDsPutAsyncRelativeRetry400Headers
},
202: {
bodyMapper: Mappers.Product,
headersMapper: Mappers.LrosaDsPutAsyncRelativeRetry400Headers
},
204: {
bodyMapper: Mappers.Product,
headersMapper: Mappers.LrosaDsPutAsyncRelativeRetry400Headers
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.product,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const deleteNonRetry400OperationSpec: coreClient.OperationSpec = {
path: "/lro/nonretryerror/delete/400",
httpMethod: "DELETE",
responses: {
200: {
headersMapper: Mappers.LrosaDsDeleteNonRetry400Headers
},
201: {
headersMapper: Mappers.LrosaDsDeleteNonRetry400Headers
},
202: {
headersMapper: Mappers.LrosaDsDeleteNonRetry400Headers
},
204: {
headersMapper: Mappers.LrosaDsDeleteNonRetry400Headers
},
default: {
bodyMapper: Mappers.CloudError
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const delete202NonRetry400OperationSpec: coreClient.OperationSpec = {
path: "/lro/nonretryerror/delete/202/retry/400",
httpMethod: "DELETE",
responses: {
200: {
headersMapper: Mappers.LrosaDsDelete202NonRetry400Headers
},
201: {
headersMapper: Mappers.LrosaDsDelete202NonRetry400Headers
},
202: {
headersMapper: Mappers.LrosaDsDelete202NonRetry400Headers
},
204: {
headersMapper: Mappers.LrosaDsDelete202NonRetry400Headers
},
default: {
bodyMapper: Mappers.CloudError
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const deleteAsyncRelativeRetry400OperationSpec: coreClient.OperationSpec = {
path: "/lro/nonretryerror/deleteasync/retry/400",
httpMethod: "DELETE",
responses: {
200: {
headersMapper: Mappers.LrosaDsDeleteAsyncRelativeRetry400Headers
},
201: {
headersMapper: Mappers.LrosaDsDeleteAsyncRelativeRetry400Headers
},
202: {
headersMapper: Mappers.LrosaDsDeleteAsyncRelativeRetry400Headers
},
204: {
headersMapper: Mappers.LrosaDsDeleteAsyncRelativeRetry400Headers
},
default: {
bodyMapper: Mappers.CloudError
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const postNonRetry400OperationSpec: coreClient.OperationSpec = {
path: "/lro/nonretryerror/post/400",
httpMethod: "POST",
responses: {
200: {
headersMapper: Mappers.LrosaDsPostNonRetry400Headers
},
201: {
headersMapper: Mappers.LrosaDsPostNonRetry400Headers
},
202: {
headersMapper: Mappers.LrosaDsPostNonRetry400Headers
},
204: {
headersMapper: Mappers.LrosaDsPostNonRetry400Headers
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.product,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const post202NonRetry400OperationSpec: coreClient.OperationSpec = {
path: "/lro/nonretryerror/post/202/retry/400",
httpMethod: "POST",
responses: {
200: {
headersMapper: Mappers.LrosaDsPost202NonRetry400Headers
},
201: {
headersMapper: Mappers.LrosaDsPost202NonRetry400Headers
},
202: {
headersMapper: Mappers.LrosaDsPost202NonRetry400Headers
},
204: {
headersMapper: Mappers.LrosaDsPost202NonRetry400Headers
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.product,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const postAsyncRelativeRetry400OperationSpec: coreClient.OperationSpec = {
path: "/lro/nonretryerror/postasync/retry/400",
httpMethod: "POST",
responses: {
200: {
headersMapper: Mappers.LrosaDsPostAsyncRelativeRetry400Headers
},
201: {
headersMapper: Mappers.LrosaDsPostAsyncRelativeRetry400Headers
},
202: {
headersMapper: Mappers.LrosaDsPostAsyncRelativeRetry400Headers
},
204: {
headersMapper: Mappers.LrosaDsPostAsyncRelativeRetry400Headers
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.product,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const putError201NoProvisioningStatePayloadOperationSpec: coreClient.OperationSpec = {
path: "/lro/error/put/201/noprovisioningstatepayload",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.Product
},
201: {
bodyMapper: Mappers.Product
},
202: {
bodyMapper: Mappers.Product
},
204: {
bodyMapper: Mappers.Product
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.product,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const putAsyncRelativeRetryNoStatusOperationSpec: coreClient.OperationSpec = {
path: "/lro/error/putasync/retry/nostatus",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.Product,
headersMapper: Mappers.LrosaDsPutAsyncRelativeRetryNoStatusHeaders
},
201: {
bodyMapper: Mappers.Product,
headersMapper: Mappers.LrosaDsPutAsyncRelativeRetryNoStatusHeaders
},
202: {
bodyMapper: Mappers.Product,
headersMapper: Mappers.LrosaDsPutAsyncRelativeRetryNoStatusHeaders
},
204: {
bodyMapper: Mappers.Product,
headersMapper: Mappers.LrosaDsPutAsyncRelativeRetryNoStatusHeaders
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.product,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const putAsyncRelativeRetryNoStatusPayloadOperationSpec: coreClient.OperationSpec = {
path: "/lro/error/putasync/retry/nostatuspayload",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.Product,
headersMapper: Mappers.LrosaDsPutAsyncRelativeRetryNoStatusPayloadHeaders
},
201: {
bodyMapper: Mappers.Product,
headersMapper: Mappers.LrosaDsPutAsyncRelativeRetryNoStatusPayloadHeaders
},
202: {
bodyMapper: Mappers.Product,
headersMapper: Mappers.LrosaDsPutAsyncRelativeRetryNoStatusPayloadHeaders
},
204: {
bodyMapper: Mappers.Product,
headersMapper: Mappers.LrosaDsPutAsyncRelativeRetryNoStatusPayloadHeaders
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.product,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const delete204SucceededOperationSpec: coreClient.OperationSpec = {
path: "/lro/error/delete/204/nolocation",
httpMethod: "DELETE",
responses: {
200: {},
201: {},
202: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const deleteAsyncRelativeRetryNoStatusOperationSpec: coreClient.OperationSpec = {
path: "/lro/error/deleteasync/retry/nostatus",
httpMethod: "DELETE",
responses: {
200: {
headersMapper: Mappers.LrosaDsDeleteAsyncRelativeRetryNoStatusHeaders
},
201: {
headersMapper: Mappers.LrosaDsDeleteAsyncRelativeRetryNoStatusHeaders
},
202: {
headersMapper: Mappers.LrosaDsDeleteAsyncRelativeRetryNoStatusHeaders
},
204: {
headersMapper: Mappers.LrosaDsDeleteAsyncRelativeRetryNoStatusHeaders
},
default: {
bodyMapper: Mappers.CloudError
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const post202NoLocationOperationSpec: coreClient.OperationSpec = {
path: "/lro/error/post/202/nolocation",
httpMethod: "POST",
responses: {
200: {
headersMapper: Mappers.LrosaDsPost202NoLocationHeaders
},
201: {
headersMapper: Mappers.LrosaDsPost202NoLocationHeaders
},
202: {
headersMapper: Mappers.LrosaDsPost202NoLocationHeaders
},
204: {
headersMapper: Mappers.LrosaDsPost202NoLocationHeaders
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.product,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const postAsyncRelativeRetryNoPayloadOperationSpec: coreClient.OperationSpec = {
path: "/lro/error/postasync/retry/nopayload",
httpMethod: "POST",
responses: {
200: {
headersMapper: Mappers.LrosaDsPostAsyncRelativeRetryNoPayloadHeaders
},
201: {
headersMapper: Mappers.LrosaDsPostAsyncRelativeRetryNoPayloadHeaders
},
202: {
headersMapper: Mappers.LrosaDsPostAsyncRelativeRetryNoPayloadHeaders
},
204: {
headersMapper: Mappers.LrosaDsPostAsyncRelativeRetryNoPayloadHeaders
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.product,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const put200InvalidJsonOperationSpec: coreClient.OperationSpec = {
path: "/lro/error/put/200/invalidjson",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.Product
},
201: {
bodyMapper: Mappers.Product
},
202: {
bodyMapper: Mappers.Product
},
204: {
bodyMapper: Mappers.Product
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.product,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const putAsyncRelativeRetryInvalidHeaderOperationSpec: coreClient.OperationSpec = {
path: "/lro/error/putasync/retry/invalidheader",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.Product,
headersMapper: Mappers.LrosaDsPutAsyncRelativeRetryInvalidHeaderHeaders
},
201: {
bodyMapper: Mappers.Product,
headersMapper: Mappers.LrosaDsPutAsyncRelativeRetryInvalidHeaderHeaders
},
202: {
bodyMapper: Mappers.Product,
headersMapper: Mappers.LrosaDsPutAsyncRelativeRetryInvalidHeaderHeaders
},
204: {
bodyMapper: Mappers.Product,
headersMapper: Mappers.LrosaDsPutAsyncRelativeRetryInvalidHeaderHeaders
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.product,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const putAsyncRelativeRetryInvalidJsonPollingOperationSpec: coreClient.OperationSpec = {
path: "/lro/error/putasync/retry/invalidjsonpolling",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.Product,
headersMapper:
Mappers.LrosaDsPutAsyncRelativeRetryInvalidJsonPollingHeaders
},
201: {
bodyMapper: Mappers.Product,
headersMapper:
Mappers.LrosaDsPutAsyncRelativeRetryInvalidJsonPollingHeaders
},
202: {
bodyMapper: Mappers.Product,
headersMapper:
Mappers.LrosaDsPutAsyncRelativeRetryInvalidJsonPollingHeaders
},
204: {
bodyMapper: Mappers.Product,
headersMapper:
Mappers.LrosaDsPutAsyncRelativeRetryInvalidJsonPollingHeaders
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.product,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const delete202RetryInvalidHeaderOperationSpec: coreClient.OperationSpec = {
path: "/lro/error/delete/202/retry/invalidheader",
httpMethod: "DELETE",
responses: {
200: {
headersMapper: Mappers.LrosaDsDelete202RetryInvalidHeaderHeaders
},
201: {
headersMapper: Mappers.LrosaDsDelete202RetryInvalidHeaderHeaders
},
202: {
headersMapper: Mappers.LrosaDsDelete202RetryInvalidHeaderHeaders
},
204: {
headersMapper: Mappers.LrosaDsDelete202RetryInvalidHeaderHeaders
},
default: {
bodyMapper: Mappers.CloudError
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const deleteAsyncRelativeRetryInvalidHeaderOperationSpec: coreClient.OperationSpec = {
path: "/lro/error/deleteasync/retry/invalidheader",
httpMethod: "DELETE",
responses: {
200: {
headersMapper: Mappers.LrosaDsDeleteAsyncRelativeRetryInvalidHeaderHeaders
},
201: {
headersMapper: Mappers.LrosaDsDeleteAsyncRelativeRetryInvalidHeaderHeaders
},
202: {
headersMapper: Mappers.LrosaDsDeleteAsyncRelativeRetryInvalidHeaderHeaders
},
204: {
headersMapper: Mappers.LrosaDsDeleteAsyncRelativeRetryInvalidHeaderHeaders
},
default: {
bodyMapper: Mappers.CloudError
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const deleteAsyncRelativeRetryInvalidJsonPollingOperationSpec: coreClient.OperationSpec = {
path: "/lro/error/deleteasync/retry/invalidjsonpolling",
httpMethod: "DELETE",
responses: {
200: {
headersMapper:
Mappers.LrosaDsDeleteAsyncRelativeRetryInvalidJsonPollingHeaders
},
201: {
headersMapper:
Mappers.LrosaDsDeleteAsyncRelativeRetryInvalidJsonPollingHeaders
},
202: {
headersMapper:
Mappers.LrosaDsDeleteAsyncRelativeRetryInvalidJsonPollingHeaders
},
204: {
headersMapper:
Mappers.LrosaDsDeleteAsyncRelativeRetryInvalidJsonPollingHeaders
},
default: {
bodyMapper: Mappers.CloudError
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const post202RetryInvalidHeaderOperationSpec: coreClient.OperationSpec = {
path: "/lro/error/post/202/retry/invalidheader",
httpMethod: "POST",
responses: {
200: {
headersMapper: Mappers.LrosaDsPost202RetryInvalidHeaderHeaders
},
201: {
headersMapper: Mappers.LrosaDsPost202RetryInvalidHeaderHeaders
},
202: {
headersMapper: Mappers.LrosaDsPost202RetryInvalidHeaderHeaders
},
204: {
headersMapper: Mappers.LrosaDsPost202RetryInvalidHeaderHeaders
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.product,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const postAsyncRelativeRetryInvalidHeaderOperationSpec: coreClient.OperationSpec = {
path: "/lro/error/postasync/retry/invalidheader",
httpMethod: "POST",
responses: {
200: {
headersMapper: Mappers.LrosaDsPostAsyncRelativeRetryInvalidHeaderHeaders
},
201: {
headersMapper: Mappers.LrosaDsPostAsyncRelativeRetryInvalidHeaderHeaders
},
202: {
headersMapper: Mappers.LrosaDsPostAsyncRelativeRetryInvalidHeaderHeaders
},
204: {
headersMapper: Mappers.LrosaDsPostAsyncRelativeRetryInvalidHeaderHeaders
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.product,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const postAsyncRelativeRetryInvalidJsonPollingOperationSpec: coreClient.OperationSpec = {
path: "/lro/error/postasync/retry/invalidjsonpolling",
httpMethod: "POST",
responses: {
200: {
headersMapper:
Mappers.LrosaDsPostAsyncRelativeRetryInvalidJsonPollingHeaders
},
201: {
headersMapper:
Mappers.LrosaDsPostAsyncRelativeRetryInvalidJsonPollingHeaders
},
202: {
headersMapper:
Mappers.LrosaDsPostAsyncRelativeRetryInvalidJsonPollingHeaders
},
204: {
headersMapper:
Mappers.LrosaDsPostAsyncRelativeRetryInvalidJsonPollingHeaders
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.product,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
}; | the_stack |
import { extensionValidityTest, renderEditor } from 'jest-remirror';
import type { AnnotationOptions } from '../';
import { Annotation, AnnotationExtension } from '../';
extensionValidityTest(AnnotationExtension);
function create(options?: AnnotationOptions) {
return renderEditor([new AnnotationExtension(options)]);
}
describe('commands', () => {
it('#addAnnotation', () => {
const {
add,
view,
nodes: { p, doc },
commands,
} = create();
add(doc(p('An <start>important<end> note')));
commands.addAnnotation({ id: '1' });
expect(view.dom.innerHTML).toMatchInlineSnapshot(`
<p>
An
<span class="selection"
style="background: rgb(215, 215, 255);"
>
important
</span>
note
</p>
`);
});
it('#updateAnnotation', () => {
const {
add,
view,
nodes: { p, doc },
commands,
} = create();
const id = '1';
add(doc(p('An <start>important<end> note')));
commands.addAnnotation({ id });
// Pre-condition
expect(view.dom.innerHTML).toMatchInlineSnapshot(`
<p>
An
<span class="selection"
style="background: rgb(215, 215, 255);"
>
important
</span>
note
</p>
`);
commands.updateAnnotation(id, {
className: 'updated',
});
expect(view.dom.innerHTML).toMatchInlineSnapshot(`
<p>
An
<span class="selection updated"
style="background: rgb(215, 215, 255);"
>
important
</span>
note
</p>
`);
});
it('#setAnnotations', () => {
const {
add,
view,
nodes: { p, doc },
commands,
} = create();
add(doc(p('An important note')));
commands.setAnnotations([
{
id: '1',
from: 3,
to: 13,
},
]);
expect(view.dom.innerHTML).toMatchInlineSnapshot(`
<p>
An
<span style="background: rgb(215, 215, 255);">
important
</span>
note
</p>
`);
});
it('#removeAnnotation', () => {
const {
add,
view,
nodes: { p, doc },
commands,
} = create();
const id = '1';
add(doc(p('An <start>important<end> note')));
commands.addAnnotation({ id });
// Pre-condition
expect(view.dom.innerHTML).toMatchInlineSnapshot(`
<p>
An
<span class="selection"
style="background: rgb(215, 215, 255);"
>
important
</span>
note
</p>
`);
commands.removeAnnotations([id]);
expect(view.dom.innerHTML).toMatchInlineSnapshot(`
<p>
An
<span class="selection"
style
>
important
</span>
note
</p>
`);
});
it('#redrawAnnotations', () => {
let color = 'red';
const getStyle = () => `background: ${color};`;
const {
add,
view,
nodes: { p, doc },
commands,
} = create({ getStyle });
const id = '1';
add(doc(p('<start>Hello<end>')));
commands.addAnnotation({ id });
// Pre-condition
expect(view.dom.innerHTML).toMatchInlineSnapshot(`
<p>
<span class="selection"
style="background: red;"
>
Hello
</span>
</p>
`);
color = 'green';
commands.redrawAnnotations();
expect(view.dom.innerHTML).toMatchInlineSnapshot(`
<p>
<span class="selection"
style="background: green;"
>
Hello
</span>
</p>
`);
});
it('supports chaining commands', () => {
const {
manager,
add,
view,
nodes: { p, doc },
chain,
} = create();
const id = '1';
add(doc(p('An <start>important<end> note')));
chain.addAnnotation({ id }).selectText('end').insertText(' awesome!').tr();
expect(manager.tr.getMeta(AnnotationExtension.name)).toMatchInlineSnapshot(`
Object {
"annotationData": Object {
"id": "1",
},
"from": 4,
"to": 13,
"type": 0,
}
`);
expect(manager.tr.steps).toHaveLength(1);
chain.run();
expect(view.dom.innerHTML).toMatchInlineSnapshot(`
<p>
An
<span class
style="background: rgb(215, 215, 255);"
>
important
</span>
note awesome!
</p>
`);
});
});
describe('plugin#apply', () => {
it('removes annotations when content is deleted', () => {
const {
add,
helpers,
nodes: { p, doc },
commands,
} = create();
add(doc(p('<start>Hello<end>')));
commands.addAnnotation({ id: '1' });
// Pre-condition
expect(helpers.getAnnotations()).toHaveLength(1);
// Delete all annotated content
commands.delete();
expect(helpers.getAnnotations()).toHaveLength(0);
});
it('updates annotation when content is added within an annotation', () => {
const {
add,
helpers,
nodes: { p, doc },
commands,
} = create();
add(doc(p('<start>Hello<end>')));
commands.addAnnotation({ id: '1' });
// Pre-condition
expect(helpers.getAnnotations()[0]?.text).toEqual('Hello');
commands.insertText('ADDED', { from: 3 });
expect(helpers.getAnnotations()[0]?.text).toEqual('HeADDEDllo');
});
it("doesn't extend annotation when content is added at the end of an annotation", () => {
const {
add,
helpers,
nodes: { p, doc },
commands,
} = create();
add(doc(p('<start>Hello<end>')));
commands.addAnnotation({ id: '1' });
// Pre-condition
expect(helpers.getAnnotations()[0]?.text).toEqual('Hello');
commands.insertText('ADDED', { from: 6 });
expect(helpers.getAnnotations()[0]?.text).toEqual('Hello');
});
});
describe('styling', () => {
it('annotation-specific classname', () => {
const {
add,
view: { dom },
nodes: { p, doc },
commands,
} = create();
add(doc(p('<start>Hello<end>')));
commands.addAnnotation({ id: '1', className: 'custom-annotation' });
expect(dom.innerHTML).toMatchInlineSnapshot(`
<p>
<span class="selection custom-annotation"
style="background: rgb(215, 215, 255);"
>
Hello
</span>
</p>
`);
});
});
describe('helpers', () => {
describe('#getAnnotations', () => {
it('default', () => {
const {
add,
helpers,
nodes: { p, doc },
commands,
} = create();
add(doc(p('<start>Hello<end>')));
commands.addAnnotation({ id: '1' });
expect(helpers.getAnnotations()).toEqual([
{
id: '1',
from: 1,
to: 6,
text: 'Hello',
},
]);
});
it('gracefully handles misplaced annotations', () => {
const {
add,
helpers,
nodes: { p, doc },
commands,
} = create();
add(doc(p('Hello')));
commands.setAnnotations([
{
id: '1',
from: 100,
to: 110,
},
]);
expect(helpers.getAnnotations()[0]?.text).toBeUndefined();
});
it('concats multi-block content with configured blockseparator', () => {
const {
add,
helpers,
nodes: { p, doc },
commands,
} = create({
blockSeparator: '<NEWLINE>',
});
add(doc(p('Hello'), p('World')));
commands.setAnnotations([
{
id: '1',
from: 1,
to: 13,
},
]);
expect(helpers.getAnnotations()[0]?.text).toEqual('Hello<NEWLINE>World');
});
});
describe('#getAnnotationsAt', () => {
let {
add,
helpers,
nodes: { p, doc },
commands,
} = create();
beforeEach(() => {
({
add,
helpers,
nodes: { p, doc },
commands,
} = create());
add(doc(p('An <start>important<end> note')));
commands.addAnnotation({ id: '1' });
});
it('default', () => {
expect(helpers.getAnnotationsAt()).toEqual([
{
id: '1',
from: 4,
to: 13,
text: 'important',
},
]);
});
it('pos', () => {
expect(helpers.getAnnotationsAt(5)).toEqual([
{
id: '1',
from: 4,
to: 13,
text: 'important',
},
]);
});
it('edge pos', () => {
expect(helpers.getAnnotationsAt(13)).toEqual([
{
id: '1',
from: 4,
to: 13,
text: 'important',
},
]);
});
it('no annotation', () => {
expect(helpers.getAnnotationsAt(2)).toEqual([]);
});
it('default, includeEdges = false', () => {
expect(helpers.getAnnotationsAt(undefined, false)).toEqual([]);
});
it('pos, includeEdges = false', () => {
expect(helpers.getAnnotationsAt(5, false)).toEqual([
{
id: '1',
from: 4,
to: 13,
text: 'important',
},
]);
});
it('edge pos, includeEdges = false', () => {
expect(helpers.getAnnotationsAt(13, false)).toEqual([]);
});
it('no annotation, includeEdges = false', () => {
expect(helpers.getAnnotationsAt(2, false)).toEqual([]);
});
});
});
describe('custom annotations', () => {
interface MyAnnotation extends Annotation {
tag: string;
}
it('should support custom annotations', () => {
const {
add,
helpers,
nodes: { p, doc },
commands,
} = renderEditor([new AnnotationExtension<MyAnnotation>()]);
add(doc(p('<start>Hello<end>')));
commands.addAnnotation({ id: '1', tag: 'tag' });
expect(helpers.getAnnotations()).toEqual([
{
id: '1',
from: 1,
to: 6,
tag: 'tag',
text: 'Hello',
},
]);
});
it('should support overlapping custom annotations', () => {
const {
dom,
selectText,
add,
nodes: { p, doc },
commands,
} = renderEditor([new AnnotationExtension<MyAnnotation>()]);
add(doc(p('<start>Hello<end> my friend')));
commands.addAnnotation({ id: '1', tag: 'tag' });
selectText({ from: 5, to: 14 });
commands.addAnnotation({ id: '2', tag: 'awesome', className: 'custom' });
expect(dom.innerHTML).toMatchInlineSnapshot(`
<p>
<span class
style="background: rgb(215, 215, 255);"
>
Hell
</span>
<span class="selection custom"
style="background: rgb(175, 175, 255);"
>
o
</span>
<span class="selection custom"
style="background: rgb(215, 215, 255);"
>
my frie
</span>
nd
</p>
`);
});
});
describe('custom styling', () => {
interface ColoredAnnotation extends Annotation {
color: string;
}
it('should use custom styling', () => {
const getStyle = (annotations: Array<Omit<ColoredAnnotation, 'text'>>) => {
return `background: ${annotations[0]?.color}`;
};
const {
dom,
add,
nodes: { p, doc },
commands,
} = renderEditor([new AnnotationExtension<ColoredAnnotation>({ getStyle })]);
add(doc(p('<start>Hello<end> my friend')));
commands.addAnnotation({ id: '1', color: 'red' });
expect(dom.innerHTML).toMatchInlineSnapshot(`
<p>
<span class="selection"
style="background: red;"
>
Hello
</span>
my friend
</p>
`);
});
});
describe('custom map like via getMap', () => {
it('should use the provided map like object passed via `getMap`', () => {
const myMap = new Map();
const options = {
getMap: () => myMap,
};
const {
add,
nodes: { p, doc },
commands,
helpers,
} = create(options);
add(doc(p('Hello <start>again<end> my friend')));
commands.addAnnotation({ id: 'an-id' });
expect(myMap.size).toBe(1);
expect(myMap.get('an-id')).toEqual({
id: 'an-id',
from: 7,
to: 12,
});
expect(helpers.getAnnotations()).toEqual([
{
id: 'an-id',
from: 7,
to: 12,
text: 'again',
},
]);
});
});
describe('custom positions', () => {
it('should use the provided map like object passed via `getMap`', () => {
const myMap = new Map();
const options = {
getMap: () => myMap,
transformPosition: (pos: number) => ({ pos, meta: { mock: 'data' } }),
transformPositionBeforeRender: (obj: any) => obj.pos,
};
const {
add,
nodes: { p, doc },
commands,
helpers,
} = create(options);
add(doc(p('Hello <start>transforms<end> my old friend')));
commands.addAnnotation({ id: 'some-id' });
expect(myMap.size).toBe(1);
expect(myMap.get('some-id')).toStrictEqual({
id: 'some-id',
from: { pos: 7, meta: { mock: 'data' } },
to: { pos: 17, meta: { mock: 'data' } },
});
expect(helpers.getAnnotations()).toEqual([
{
id: 'some-id',
from: 7,
to: 17,
text: 'transforms',
},
]);
});
}); | the_stack |
import table from "text-table";
import { fetchCommandFromWAPM } from "./query";
import { extractContents } from "../wasmfs/tar";
import { lowerI64Imports } from "@wasmer/wasm-transformer";
import WasmTerminal from "@runno/terminal";
import { WasmFs } from "../wasmfs";
var COMPILED_MODULES: { [name: string]: WebAssembly.Module } = {};
const WAPM_PACKAGE_QUERY = `query shellGetPackageQuery($name: String!, $version: String) {
packageVersion: getPackageVersion(name: $name, version: $version) {
version
package {
name
displayName
}
filesystem {
wasm
host
}
distribution {
downloadUrl
}
modules {
name
publicUrl
abi
}
commands {
command
module {
name
abi
source
publicUrl
}
}
}
}
`;
type PackageVersion = {
version: string;
package: {
name: string;
displayName: string;
};
filesystem: Array<{
wasm: string;
host: string;
}>;
distribution: {
downloadUrl: string;
};
modules: Array<{
name: string;
publicUrl: string;
abi: string;
}>;
commands: Array<{
command: string;
module: {
name: string;
abi: string;
source: string;
publicUrl: string;
};
}>;
};
type PackageQueryData = {
packageVersion: PackageVersion;
};
async function execWapmQuery(query: string, variables: any) {
const fetchResponse = await fetch("https://registry.wapm.io/graphql", {
method: "POST",
mode: "cors",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
// operationName: "shellGetCommandQuery",
query,
variables,
}),
});
const response = await fetchResponse.json();
if (response && response.data) {
return response.data;
}
}
const getBinaryFromUrl = async (url: string) => {
const fetched = await fetch(url);
const buffer = await fetched.arrayBuffer();
return new Uint8Array(buffer);
};
const getWAPMPackageFromPackageName = async (packageName: string) => {
let version;
if (packageName.indexOf("@") > -1) {
const splitted = packageName.split("@");
packageName = splitted[0];
version = splitted[1];
}
let data: PackageQueryData = (await execWapmQuery(WAPM_PACKAGE_QUERY, {
name: packageName,
version: version,
})) as PackageQueryData;
if (data && data.packageVersion) {
return data.packageVersion;
} else {
throw new Error(`Package not found in the registry ${packageName}`);
}
};
const getWasmBinaryFromUrl = async (url: string) => {
const fetched = await fetch(url);
const buffer = await fetched.arrayBuffer();
return new Uint8Array(buffer);
};
export default class WAPM {
wasmTerminal: WasmTerminal | undefined;
wapmInstalledPackages: PackageVersion[];
wapmCommands: { [name: string]: Uint8Array };
uploadedCommands: { [name: string]: Uint8Array };
cachedModules: { [name: string]: Uint8Array };
wasmFs: WasmFs;
callbackCommands: { [name: string]: Function };
_hiddenInput: HTMLInputElement;
currentInstallResolver: Function | undefined;
constructor(wasmFs: WasmFs, wasmTerminal?: WasmTerminal) {
// Clear the cache. Can be very big.
this.wasmTerminal = wasmTerminal;
this.wapmInstalledPackages = [];
this.wapmCommands = {};
this.uploadedCommands = {};
this.cachedModules = {};
this.wasmFs = wasmFs;
// Launch off an update request to our storage
this.callbackCommands = {
wapm: this._wapmCallbackCommand.bind(this),
};
// Create a hidden input on the page for opening files
const hiddenInput = document.createElement("input");
hiddenInput.id = "hidden-file-input";
hiddenInput.classList.add("hidden-file-input");
hiddenInput.setAttribute("type", "file");
hiddenInput.setAttribute("accept", ".wasm");
hiddenInput.setAttribute("hidden", "true");
hiddenInput.addEventListener(
"change",
this._onHiddenInputChange.bind(this)
);
document.body.appendChild(hiddenInput);
this._hiddenInput = hiddenInput;
// A variable for resolving file input
this.currentInstallResolver = undefined;
}
async regenerateWAPMCommands() {
this.wapmCommands = {};
for (let packageVersion of this.wapmInstalledPackages) {
for (let command of packageVersion.commands) {
if (command.module.abi === "wasi") {
let commandUrl = command.module.publicUrl;
this.wapmCommands[command.command] = await this.fetchBinary(
commandUrl
);
}
}
}
}
async fetchBinary(binaryUrl: string) {
if (!(binaryUrl in this.cachedModules)) {
this.cachedModules[binaryUrl] = await getWasmBinaryFromUrl(binaryUrl);
}
return this.cachedModules[binaryUrl];
}
// Check if a command is cached
isCommandCached(commandName: string) {
const cachedCommand = this._getCachedCommand(commandName);
return cachedCommand !== undefined;
}
// Get a command from the wapm manager
async runCommand(options: {
args: string[];
env: { [name: string]: string };
}) {
let commandName = options.args[0];
// We convert the `wasmer run thecommand ...` to `thecommand ...`
if (commandName == "wasmer") {
if (options.args[1] == "run") {
options.args = options.args.slice(2);
} else {
options.args = options.args.slice(1);
}
commandName = options.args[0];
// This fixes the issue when doing `wasmer abc.wasm`, so it converts
// it to `wasmer ./abc.wasm`.
if (commandName.indexOf("/") == -1) {
commandName = `./${commandName}`;
}
} else if (commandName == "wapm" && options.args[1] == "run") {
options.args = options.args.slice(2);
commandName = options.args[0];
} else if (commandName == "wax") {
options.args = options.args.slice(1);
commandName = options.args[0];
}
// We are executing a WebAssembly file
if (commandName.indexOf("/") > -1) {
let modulePath = commandName;
if (!this.wasmFs.fs.existsSync(modulePath)) {
throw new Error(`No such file or directory: ${modulePath}`);
}
let wasmBinary = this.wasmFs.fs.readFileSync(modulePath) as Uint8Array;
let loweredBinary = await lowerI64Imports(wasmBinary);
COMPILED_MODULES[modulePath] = await WebAssembly.compile(loweredBinary);
return {
args: options.args,
module: COMPILED_MODULES[modulePath],
};
}
// Check if the command was cached
const cachedCommand = this._getCachedCommand(commandName);
if (cachedCommand) {
return cachedCommand;
}
// Try to install from WAPM
return await this._installFromWapmCommand(options, this.wasmFs);
}
async installWasmBinary(commandName: string, wasmBinary: Uint8Array) {
this.uploadedCommands[commandName] = wasmBinary;
}
_getCachedCommand(commandName: string) {
if (this.callbackCommands[commandName]) {
return this.callbackCommands[commandName];
}
if (this.uploadedCommands[commandName]) {
return this.uploadedCommands[commandName];
}
return undefined;
}
async _wapmCallbackCommand(options: { args: string[] }, wasmFs: WasmFs) {
const args = options.args;
if (args.length === 1) {
return this._help();
}
if (args[1] === "upload") {
const commandName = await this._installFromFile();
const uploadMessage = `Module ${commandName}.wasm installed successfully!
→ Installed commands: ${commandName}`;
return uploadMessage.replace(/\n\n/g, "\n \n");
}
if (args[1] === "install" && args.length === 3) {
return await this._install(args[2], wasmFs);
}
if (args[1] === "uninstall" && args.length === 3) {
return await this._uninstall(args[2]);
}
if (args[1] === "list") {
return this._list();
}
return this._help();
}
_help() {
const helpMessage = `wapm-cli lite (adapted for WebAssembly.sh)
The Wasmer Engineering Team <engineering@wasmer.io>
WebAssembly Package Manager CLI
USAGE:
wapm <SUBCOMMAND>
SUBCOMMANDS:
list List the currently installed packages and their commands
install Install a package from Wapm
upload Install a local Wasm module
uninstall Uninstall a package`;
return helpMessage.replace(/\n\n/g, "\n \n");
}
_list() {
let packageModules: Array<string[]> = [];
for (const _package of this.wapmInstalledPackages) {
for (const mod of _package.modules) {
packageModules.push([
_package.package.displayName,
_package.version,
mod.name,
mod.abi,
]);
}
}
let packages = [["COMMAND", "VERSION", "MODULE", "ABI"]].concat(
packageModules
);
let commands = [["COMMAND", "TYPE"]]
.concat(
Object.keys(this.wapmCommands).map((key) => {
return [`${key}`, "WAPM"];
})
)
.concat(
Object.keys(this.uploadedCommands).map((key) => {
return [`${key}`, "uploaded by user"];
})
)
.concat(
Object.keys(this.callbackCommands).map((key) => {
return [`${key}`, "builtin"];
})
);
let message = `LOCAL PACKAGES:
${table(packages, { align: ["l"], hsep: " | " }).replace(/\n/g, "\n ")}
LOCAL COMMANDS:
${table(commands, { align: ["l"], hsep: " | " }).replace(/\n/g, "\n ")}
Additional commands can be installed by:
• Running a command from any WASI package in https://wapm.io
• Uploading a file with \`wapm upload\``;
return message.replace(/\n\n/g, "\n \n");
}
async _install(packageName: string, wasmFs: WasmFs) {
let packageVersion = await getWAPMPackageFromPackageName(packageName);
if (!packageVersion) {
throw new Error(`Package not found in the registry: ${packageName}`);
}
// console.log(`Running wapm install ${packageName}`);
let installed = await this._installWapmPackage(packageVersion, wasmFs);
if (!installed) {
return `Package ${packageName} already installed.`;
}
this.wapmInstalledPackages = this.wapmInstalledPackages.filter(
(installedPackage) =>
installedPackage.package.displayName !==
packageVersion.package.displayName
);
this.wapmInstalledPackages.push(packageVersion);
await this.regenerateWAPMCommands();
return `Package ${packageVersion.package.displayName}@${
packageVersion.version
} installed successfully!
→ Installed commands: ${packageVersion.commands
.map((command) => command.command)
.join(", ")}`;
}
async _uninstall(packageOrCommandName: string) {
// Uninstalling a callback (should error)
if (this.callbackCommands[packageOrCommandName]) {
return `Cannot remove the built-in command: \`${packageOrCommandName}\`.`;
}
// Uninstalling an uploaded command
if (this.uploadedCommands[packageOrCommandName]) {
delete this.uploadedCommands[packageOrCommandName];
return `Uploaded command "${packageOrCommandName}" uninstalled successfully.`;
}
// Uninstalling a wapm package
const packages = this.wapmInstalledPackages.filter(
(installedPackage) =>
installedPackage.package.displayName === packageOrCommandName
);
if (packages.length > 0) {
const removePackage = packages[0];
this.wapmInstalledPackages = this.wapmInstalledPackages.filter(
(installedPackage) => installedPackage !== removePackage
);
await this.regenerateWAPMCommands();
return `Package "${removePackage.package.displayName}" uninstalled successfully.`;
}
return `Package "${packageOrCommandName}" is not installed.`;
}
async _installWapmPackage(packageVersion: PackageVersion, wasmFs: WasmFs) {
// console.log("Install package", packageVersion)
const packageUrl = packageVersion.distribution.downloadUrl;
let binary = await getBinaryFromUrl(packageUrl);
const installedPath = `/_wasmer/wapm_packages/${packageVersion.package.name}@${packageVersion.version}`;
if (wasmFs.fs.existsSync(installedPath)) {
// console.log("package already installed");
// The package is already installed.
// Do nothing.
return false;
}
wasmFs.fs.mkdirpSync(installedPath);
// We extract the contents on the desired directory
await extractContents(wasmFs, binary, installedPath);
// console.log("CONTENTS extracted");
wasmFs.fs.mkdirpSync("/bin");
for (let command of packageVersion.commands) {
const binaryName = `/bin/${command.command}`;
const wasmFullPath = `${installedPath}/${command.module.source}`;
const filesystem = packageVersion.filesystem;
let preopens: { [name: string]: string } = {};
filesystem.forEach(({ wasm, host }) => {
preopens[wasm] = `${installedPath}/${host}`;
});
const mainFunction = new Function(`// wasi
return function main(options) {
var preopens = ${JSON.stringify(preopens)};
return {
"args": options.args,
"env": options.env,
// We use the path for the lowered Wasm
"modulePath": ${JSON.stringify(wasmFullPath)},
"preopens": preopens,
};
}
`)();
wasmFs.fs.writeFileSync(binaryName, mainFunction.toString());
}
return true;
}
async _installFromWapmCommand(
{ args, env }: { args: string[]; env: { [name: string]: string } },
wasmFs: WasmFs
) {
let commandName = args[0];
// const wasmPackage = await getWAPMPackageFromCommandName(commandName);
// await this.regenerateWAPMCommands();
// return this.wapmCommands[commandName];
const binaryName = `/bin/${commandName}`;
if (!wasmFs.fs.existsSync(binaryName)) {
let command = await fetchCommandFromWAPM({ args });
await this._installWapmPackage(command.packageVersion, wasmFs);
}
// let time1 = performance.now();
let fileContents = wasmFs.fs.readFileSync(binaryName, "utf8");
let mainProgram = new Function(`return ${fileContents}`)();
let program = mainProgram({ args, env });
// let time2 = performance.now();
if (!(program.modulePath in COMPILED_MODULES)) {
let wasmBinary: any; // TODO: Unclear what type this is but it seems to work
try {
wasmBinary = wasmFs.fs.readFileSync(program.modulePath);
} catch {
throw new Error(`The module ${program.modulePath} doesn't exist`);
}
if (this.wasmTerminal) {
this.wasmTerminal.wasmTty.clearStatus(true);
this.wasmTerminal.wasmTty.printStatus("[INFO] Compiling module", true);
}
let loweredBinary = await lowerI64Imports(wasmBinary);
COMPILED_MODULES[program.modulePath] = await WebAssembly.compile(
loweredBinary
);
if (this.wasmTerminal) {
this.wasmTerminal.wasmTty.clearStatus(true);
}
}
program.module = COMPILED_MODULES[program.modulePath];
// let time3 = performance.now();
// console.log(`Miliseconds to run: ${time2-time1} (lowering) ${time3-time2} (compiling)`);
return program;
}
async _installFromFile() {
const gotInputPromise: Promise<File> = new Promise((resolve) => {
this.currentInstallResolver = resolve;
});
this._hiddenInput.click();
const file = await gotInputPromise;
if (!file) {
return "Cancelled opening wasm file.";
}
const buffer = await file.arrayBuffer();
const wasmBinary = new Uint8Array(buffer);
const commandName = file.name.replace(".wasm", "");
this.installWasmBinary(commandName, wasmBinary);
return commandName;
}
_onHiddenInputChange(event: Event) {
if (this.currentInstallResolver) {
this.currentInstallResolver(
(event.target! as HTMLInputElement).files![0]
);
}
}
} | the_stack |
import type { ExecutionResult, GraphQLError } from 'graphql';
import { CacheInstance, createCache } from '../Cache';
import { GQtyError } from '../Error';
import { doRetry } from '../Error/retry';
import { createQueryBuilder } from '../QueryBuilder';
import {
createSelectionManager,
SelectionManager,
separateSelectionTypes,
} from '../Selection/SelectionManager';
import {
createDeferredPromise,
DeferredPromise,
get,
LazyPromise,
} from '../Utils';
import type { FetchEventData } from '../Events';
import type { NormalizationHandler } from '../Normalization';
import type { SchedulerPromiseValue } from '../Scheduler';
import type { Selection } from '../Selection/selection';
import type {
InnerClientState,
SubscribeEvents,
SubscriptionsClient,
} from './client';
export interface ResolveOptions<TData> {
/**
* Set to `true` to refetch the data requirements
*/
refetch?: boolean;
/**
* Ignore the client cache
*/
noCache?: boolean;
/**
* Activate special handling of non-serializable variables,
* for example, files uploading
*
* @default false
*/
nonSerializableVariables?: boolean;
/**
* Middleware function that is called if valid cache is found
* for all the data requirements, it should return `true` if the
* the resolution and fetch should continue, and `false`
* if you wish to stop the resolution, resolving the promise
* with the existing cache data.
*/
onCacheData?: (data: TData) => boolean;
/**
* On No Cache found
*/
onNoCacheFound?: () => void;
/**
* Get every selection intercepted in the specified function
*/
onSelection?: (selection: Selection) => void;
/**
* On subscription event listener
*/
onSubscription?: (
event:
| {
type: 'data';
unsubscribe: () => Promise<void>;
data: TData;
error?: undefined;
}
| {
type: 'with-errors';
unsubscribe: () => Promise<void>;
data?: TData;
error: GQtyError;
}
| {
type: 'start' | 'complete';
unsubscribe: () => Promise<void>;
data?: undefined;
error?: undefined;
}
) => void;
/**
* Function called on empty resolution
*/
onEmptyResolve?: () => void;
/**
* Retry strategy
*/
retry?: RetryOptions;
}
export type RetryOptions =
| {
/**
* Amount of retries to be made
* @default 3
*/
maxRetries?: number;
/**
* Amount of milliseconds between each attempt, it can be a static number,
* or a function based on the attempt number
*
* @default attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000)
*/
retryDelay?: number | ((attemptIndex: number) => number);
}
/** If retries should be enabled
* @default true
*/
| boolean
/** Amount of retries to be made
* @default 3
*/
| number;
export interface FetchResolveOptions {
retry?: RetryOptions;
scheduler?: boolean;
ignoreResolveCache?: boolean;
onSubscription?: ResolveOptions<any>['onSubscription'];
}
function filterSelectionsWithErrors(
graphQLErrors: readonly GraphQLError[] | undefined,
executionData: Record<string, unknown> | null | undefined,
selections: Selection[]
) {
if (!executionData) return selections;
const gqlErrorsPaths = graphQLErrors
?.map((err) =>
err.path
?.filter(
(pathValue): pathValue is string => typeof pathValue === 'string'
)
.join('.')
)
.filter(
(possiblePath): possiblePath is NonNullable<typeof possiblePath> => {
return !!possiblePath;
}
);
const selectionsWithErrors = !gqlErrorsPaths?.length
? selections
: selections.filter((selection) => {
const selectionPathNoIndex = selection.noIndexSelections
.slice(1)
.map((selection) => selection.alias || selection.key)
.join('.');
const selectionData = get(executionData, selectionPathNoIndex);
switch (selectionData) {
case undefined: {
return true;
}
case null: {
return gqlErrorsPaths.includes(selectionPathNoIndex);
}
default:
return false;
}
});
return selectionsWithErrors;
}
export interface Resolved {
<T = unknown>(dataFn: () => T, opts?: ResolveOptions<T>): Promise<T>;
}
export interface BuildAndFetchSelections {
<TData = unknown>(
selections: Selection[] | undefined,
type: 'query' | 'mutation',
cache?: CacheInstance,
options?: FetchResolveOptions,
lastTryParam?: boolean | undefined
): Promise<TData | null | undefined>;
}
export interface ResolveSelections {
(
selections: Selection[] | Set<Selection>,
cache?: CacheInstance,
options?: FetchResolveOptions
): Promise<void>;
}
export interface Resolvers {
resolveSelections: ResolveSelections;
buildAndFetchSelections: BuildAndFetchSelections;
resolved: Resolved;
inlineResolved: InlineResolved;
}
export interface InlineResolved {
<TData = unknown>(fn: () => TData, options?: InlineResolveOptions<TData>):
| TData
| Promise<TData>;
}
export interface InlineResolveOptions<TData> {
refetch?: boolean;
onEmptyResolve?: () => void;
/**
* Get every selection intercepted in the specified function
*/
onSelection?: (selection: Selection) => void;
/**
* On valid cache data found callback
*/
onCacheData?: (data: TData) => void;
}
export function createResolvers(
innerState: InnerClientState,
catchSelectionsTimeMS: number,
subscriptions?: SubscriptionsClient
): Resolvers {
const {
interceptorManager,
eventHandler,
queryFetcher,
scheduler,
clientCache: globalCache,
selectionManager: globalSelectionManager,
defaults: { resolved: resolvedDefaults = {} },
} = innerState;
const { globalInterceptor } = interceptorManager;
const buildQuery = createQueryBuilder();
const inlineResolved: InlineResolved = function inlineResolved<
TData = unknown
>(
fn: () => TData,
{
refetch,
onEmptyResolve,
onSelection,
onCacheData,
}: InlineResolveOptions<TData> = {}
) {
const prevFoundValidCache = innerState.foundValidCache;
innerState.foundValidCache = true;
const interceptor = interceptorManager.createInterceptor();
let noSelection = true;
function onScalarSelection() {
noSelection = false;
}
interceptor.selectionAddListeners.add(onScalarSelection);
interceptor.selectionCacheRefetchListeners.add(onScalarSelection);
if (onSelection) {
interceptor.selectionAddListeners.add(onSelection);
interceptor.selectionCacheListeners.add(onSelection);
interceptor.selectionCacheRefetchListeners.add(onSelection);
}
const prevAllowCache = innerState.allowCache;
try {
if (refetch) innerState.allowCache = false;
const data = fn();
const foundValidCache = innerState.foundValidCache;
innerState.foundValidCache = prevFoundValidCache;
interceptorManager.removeInterceptor(interceptor);
innerState.allowCache = prevAllowCache;
if (noSelection) {
if (process.env.NODE_ENV !== 'production') {
console.warn('[gqty] Warning! No data requested.');
}
if (onEmptyResolve) onEmptyResolve();
return data;
}
const promises: Promise<SchedulerPromiseValue>[] = [];
groups: for (const [
selectionSet,
promise,
] of scheduler.pendingSelectionsGroupsPromises) {
for (const selection of interceptor.fetchSelections) {
if (selectionSet.has(selection)) {
promises.push(promise);
continue groups;
}
}
}
if (promises.length) {
if (foundValidCache) {
if (onCacheData) {
onCacheData(data);
}
}
return Promise.all(promises).then((value) => {
for (const v of value) if (v.error) throw v.error;
innerState.allowCache = true;
return fn();
});
}
return data;
} finally {
innerState.foundValidCache = prevFoundValidCache;
interceptorManager.removeInterceptor(interceptor);
innerState.allowCache = prevAllowCache;
}
};
const {
noCache: noCacheDefault = false,
refetch: refetchDefault = false,
retry: retryDefault = false,
} = resolvedDefaults;
const resolved: Resolved = async function resolved<T = unknown>(
dataFn: () => T,
{
refetch = refetchDefault,
noCache = noCacheDefault,
onCacheData,
onSelection,
onSubscription,
retry = retryDefault,
nonSerializableVariables,
onNoCacheFound,
onEmptyResolve,
}: ResolveOptions<T> = {}
): Promise<T> {
const prevFoundValidCache = innerState.foundValidCache;
innerState.foundValidCache = true;
let prevAllowCache = innerState.allowCache;
if (refetch) {
innerState.allowCache = false;
}
let tempCache: typeof innerState.clientCache | undefined;
let tempSelectionManager: SelectionManager | undefined;
if (noCache) {
innerState.clientCache = tempCache = createCache();
}
if (nonSerializableVariables) {
innerState.selectionManager = tempSelectionManager =
createSelectionManager();
}
let prevGlobalInterceptorListening = globalInterceptor.listening;
globalInterceptor.listening = false;
const interceptor = interceptorManager.createInterceptor();
let noSelection = true;
function onScalarSelection() {
noSelection = false;
}
interceptor.selectionAddListeners.add(onScalarSelection);
interceptor.selectionCacheRefetchListeners.add(onScalarSelection);
if (onSelection) {
interceptor.selectionAddListeners.add(onSelection);
interceptor.selectionCacheListeners.add(onSelection);
interceptor.selectionCacheRefetchListeners.add(onSelection);
}
try {
const data = dataFn();
if (noSelection) {
if (process.env.NODE_ENV !== 'production') {
console.warn('[gqty] Warning! No data requested.');
}
if (onEmptyResolve) onEmptyResolve();
return data;
}
interceptorManager.removeInterceptor(interceptor);
if (innerState.foundValidCache) {
if (onCacheData) {
const shouldContinue = onCacheData(data);
if (!shouldContinue) return data;
}
} else if (onNoCacheFound) {
onNoCacheFound();
}
innerState.foundValidCache = prevFoundValidCache;
innerState.allowCache = prevAllowCache;
innerState.clientCache = globalCache;
innerState.selectionManager = globalSelectionManager;
globalInterceptor.listening = prevGlobalInterceptorListening;
await resolveSelections(
interceptor.fetchSelections,
tempCache || innerState.clientCache,
{
ignoreResolveCache: refetch || noCache,
onSubscription: onSubscription
? (event) => {
switch (event.type) {
case 'data':
case 'with-errors':
if (event.data) {
const prevAllowCache = innerState.allowCache;
try {
innerState.allowCache = true;
globalInterceptor.listening = false;
if (tempCache) {
innerState.clientCache = tempCache;
}
onSubscription({
...event,
data: dataFn(),
});
} finally {
innerState.allowCache = prevAllowCache;
globalInterceptor.listening = true;
innerState.clientCache = globalCache;
}
} else {
onSubscription(event);
}
return;
default:
onSubscription(event);
}
}
: undefined,
retry,
}
);
prevAllowCache = innerState.allowCache;
innerState.allowCache = true;
prevGlobalInterceptorListening = globalInterceptor.listening;
globalInterceptor.listening = false;
if (tempCache) {
innerState.clientCache = tempCache;
}
if (tempSelectionManager) {
innerState.selectionManager = tempSelectionManager;
}
return dataFn();
} catch (err) {
throw GQtyError.create(err, resolved);
} finally {
interceptorManager.removeInterceptor(interceptor);
innerState.allowCache = prevAllowCache;
innerState.clientCache = globalCache;
innerState.selectionManager = globalSelectionManager;
innerState.foundValidCache = prevFoundValidCache;
globalInterceptor.listening = prevGlobalInterceptorListening;
}
};
const resolutionTempCache = new Map<string, unknown>();
const resolutionTempCacheTimeout = catchSelectionsTimeMS * 5;
function buildQueryAndCheckTempCache<TData>(
selections: Selection[],
type: 'query' | 'mutation' | 'subscription',
normalizationHandler: NormalizationHandler | undefined,
ignoreResolveCache: boolean | undefined,
isGlobalCache: boolean
) {
const { query, variables, cacheKey } = buildQuery(
selections,
{
type,
},
normalizationHandler != null,
isGlobalCache
);
const cachedData = ignoreResolveCache
? undefined
: (resolutionTempCache.get(cacheKey) as TData | undefined);
return {
query,
variables,
cacheKey,
cachedData,
};
}
const resolveQueryPromisesMap: Record<string, Promise<any>> = {};
async function buildAndFetchSelections<TData = unknown>(
selections: Selection[] | undefined,
type: 'query' | 'mutation',
cache: CacheInstance = innerState.clientCache,
options: FetchResolveOptions = {},
lastTryParam?: boolean
): Promise<TData | null | undefined> {
if (!selections) return;
const isLastTry =
lastTryParam === undefined
? options.retry
? false
: true
: lastTryParam;
const { query, variables, cachedData, cacheKey } =
buildQueryAndCheckTempCache<TData>(
selections,
type,
innerState.normalizationHandler,
options.ignoreResolveCache,
cache === globalCache
);
if (!options.scheduler) return resolve();
let promise: Promise<TData | undefined> | undefined =
resolveQueryPromisesMap[cacheKey];
if (promise) return promise;
promise = LazyPromise(() => {
return resolve();
});
resolveQueryPromisesMap[cacheKey] = promise;
try {
return await promise;
} finally {
delete resolveQueryPromisesMap[cacheKey];
}
async function resolve() {
if (!selections) return;
let executionData: ExecutionResult['data'];
let loggingPromise: DeferredPromise<FetchEventData> | undefined;
try {
if (cachedData != null) return cachedData;
if (eventHandler.hasFetchSubscribers) {
loggingPromise = createDeferredPromise<FetchEventData>();
eventHandler.sendFetchPromise(loggingPromise.promise, selections);
}
const executionResult = await queryFetcher(query, variables);
const { data, errors } = executionResult;
if (data) {
if (!errors && cacheKey) {
resolutionTempCache.set(cacheKey, data);
setTimeout(
() => resolutionTempCache.delete(cacheKey),
resolutionTempCacheTimeout
);
}
cache.mergeCache(data, type);
executionData = data;
}
if (errors?.length) {
throw GQtyError.fromGraphQLErrors(errors);
} else if (options.scheduler) {
innerState.scheduler.errors.removeErrors(selections);
}
loggingPromise?.resolve({
executionResult,
query,
variables,
cacheSnapshot: cache.cache,
selections,
type,
});
return data as unknown as TData;
} catch (err) {
const error = GQtyError.create(err, () => {});
loggingPromise?.resolve({
error,
query,
variables,
cacheSnapshot: cache.cache,
selections,
type,
});
if (options.scheduler) {
const selectionsWithErrors = filterSelectionsWithErrors(
error.graphQLErrors,
executionData,
selections
);
innerState.scheduler.errors.triggerError(
error,
selectionsWithErrors,
isLastTry
);
}
if (options.retry) {
async function retryFn(lastTry: boolean) {
const retryPromise: Promise<SchedulerPromiseValue> =
buildAndFetchSelections(
selections,
type,
cache,
Object.assign({}, options, {
retry: false,
ignoreResolveCache: true,
} as FetchResolveOptions),
lastTry
).then(
(data) => ({ data, selections: new Set(selections) }),
(err) => {
console.error(err);
return {
error: GQtyError.create(err),
selections: new Set(selections),
};
}
);
if (options.scheduler) {
const setSelections = new Set(selections);
scheduler.pendingSelectionsGroups.add(setSelections);
scheduler.errors.retryPromise(retryPromise, setSelections);
retryPromise.finally(() => {
scheduler.pendingSelectionsGroups.delete(setSelections);
});
}
const { error } = await retryPromise;
if (error) throw error;
}
doRetry(options.retry, {
onLastTry() {
return retryFn(true);
},
onRetry() {
return retryFn(false);
},
});
}
throw error;
} finally {
interceptorManager.removeSelections(selections);
}
}
}
function subscriptionSchedulerEvents(ctx: {
selections: Selection[];
query: string;
variables: Record<string, unknown> | undefined;
operationId: string;
}): SubscribeEvents {
return {
onData(data) {
const { selections, query, operationId, variables } = ctx;
globalCache.mergeCache(data, 'subscription');
scheduler.errors.removeErrors(selections);
for (const selection of selections) {
eventHandler.sendCacheChange({
data,
selection,
});
}
if (eventHandler.hasFetchSubscribers) {
eventHandler.sendFetchPromise(
Promise.resolve({
executionResult: {
data,
},
cacheSnapshot: globalCache.cache,
query,
variables,
selections,
type: 'subscription',
label: `[id=${operationId}] [data]`,
}),
selections
);
}
},
onError({ data, error }) {
const { query, variables, selections, operationId } = ctx;
if (data) globalCache.mergeCache(data, 'subscription');
scheduler.errors.triggerError(
error,
filterSelectionsWithErrors(error.graphQLErrors, data, selections),
true
);
if (eventHandler.hasFetchSubscribers) {
eventHandler.sendFetchPromise(
Promise.resolve({
executionResult: {
data,
},
error,
cacheSnapshot: globalCache.cache,
query,
variables,
selections,
type: 'subscription',
label: `[id=${operationId}] [error]`,
}),
selections
);
}
},
};
}
async function buildAndSubscribeSelections<TData = unknown>(
selections: Selection[] | undefined,
cache: CacheInstance = innerState.clientCache,
options: FetchResolveOptions
) {
if (!selections) return;
if (!subscriptions) {
if (typeof window !== 'undefined') {
console.error('ERROR: No subscriptions client specified!');
}
return;
}
const selectionsByRoot = new Map<Selection, Array<Selection>>();
for (const selection of selections) {
const root = selection.selectionsList[1];
// This case realistically should never happen
/* istanbul ignore next */
if (!root) continue;
let selectionSet = selectionsByRoot.get(root);
if (selectionSet) {
selectionSet.push(selection);
} else {
selectionSet = [selection];
selectionsByRoot.set(root, selectionSet);
}
}
const unsubscribeCallbacks = new Set<() => Promise<void>>();
const unsubscribe = async () => {
await Promise.all(Array.from(unsubscribeCallbacks).map((cb) => cb()));
};
for (const selections of selectionsByRoot.values()) {
const { query, variables, cacheKey } = buildQueryAndCheckTempCache<TData>(
selections,
'subscription',
innerState.normalizationHandler,
true,
cache === globalCache
);
let operationId: string;
const subResult = subscriptions.subscribe({
query,
variables,
selections,
cacheKey,
events: options.scheduler
? subscriptionSchedulerEvents
: {
onData(data) {
cache.mergeCache(data, 'subscription');
options.onSubscription?.({
type: 'data',
unsubscribe,
data,
});
if (eventHandler.hasFetchSubscribers) {
eventHandler.sendFetchPromise(
Promise.resolve({
executionResult: {
data,
},
cacheSnapshot: globalCache.cache,
query,
variables,
selections,
type: 'subscription',
label: `[id=${operationId}] [data]`,
}),
selections
);
}
},
onError({ data, error }) {
if (data) cache.mergeCache(data, 'subscription');
options.onSubscription?.({
type: 'with-errors',
unsubscribe,
data,
error,
});
if (eventHandler.hasFetchSubscribers) {
eventHandler.sendFetchPromise(
Promise.resolve({
executionResult: {
data,
},
error,
cacheSnapshot: globalCache.cache,
query,
variables,
selections,
type: 'subscription',
label: `[id=${operationId}] [error]`,
}),
selections
);
}
},
onStart: options.onSubscription
? () => {
options.onSubscription?.({
type: 'start',
unsubscribe,
});
}
: undefined,
onComplete: options.onSubscription
? () => {
options.onSubscription?.({
type: 'complete',
unsubscribe,
});
}
: undefined,
},
});
if (subResult instanceof Promise) {
let loggingPromise: DeferredPromise<FetchEventData> | undefined;
if (eventHandler.hasFetchSubscribers) {
loggingPromise = createDeferredPromise();
eventHandler.sendFetchPromise(loggingPromise.promise, selections);
}
const { unsubscribe, operationId } = await subResult;
unsubscribeCallbacks.add(unsubscribe);
loggingPromise?.resolve({
cacheSnapshot: cache.cache,
query,
variables,
selections,
type: 'subscription',
label: `[id=${operationId}] [created]`,
});
} else {
unsubscribeCallbacks.add(subResult.unsubscribe);
}
}
}
async function resolveSelections<
TQuery = unknown,
TMutation = unknown,
TSubscription = unknown
>(
selections: Selection[] | Set<Selection>,
cache: CacheInstance = innerState.clientCache,
options: FetchResolveOptions = {}
) {
const { querySelections, mutationSelections, subscriptionSelections } =
separateSelectionTypes(selections);
try {
await Promise.all([
buildAndFetchSelections<TQuery>(
querySelections,
'query',
cache,
options
),
buildAndFetchSelections<TMutation>(
mutationSelections,
'mutation',
cache,
options
),
buildAndSubscribeSelections<TSubscription>(
subscriptionSelections,
cache,
options
),
]);
} catch (err) {
throw GQtyError.create(err);
}
}
return {
resolveSelections,
buildAndFetchSelections,
resolved,
inlineResolved,
};
} | the_stack |
import { File, Project, Directory, FileType, Problem, isBinaryFileType, fileTypeFromFileName, IStatusProvider } from "./models";
import { padLeft, padRight, isBranch, toAddress, decodeRestrictedBase64ToBytes, base64EncodeBytes } from "./util";
import { assert } from "./util";
import { gaEvent } from "./utils/ga";
import { WorkerCommand, IWorkerResponse } from "./message";
import { processJSFile, RewriteSourcesContext } from "./utils/rewriteSources";
import { getCurrentRunnerInfo } from "./utils/taskRunner";
import { createCompilerService, Language } from "./compilerServices";
declare var capstone: {
ARCH_X86: any;
MODE_64: any;
Cs: any;
};
declare var Module: ({ }) => any;
declare var showdown: {
Converter: any;
setFlavor: Function;
};
export interface IFiddleFile {
name: string;
data?: string;
type?: "binary" | "text";
}
export interface ICreateFiddleRequest {
files: IFiddleFile [];
}
export interface ILoadFiddleResponse {
files: IFiddleFile [];
id: string;
message: string;
success: boolean;
}
export { Language } from "./compilerServices";
function getProjectFilePath(file: File): string {
const project = file.getProject();
return file.getPath(project);
}
export class ServiceWorker {
worker: Worker;
workerCallbacks: Array<{fn: (data: any) => void, ex: (err: Error) => void}> = [];
nextId = 0;
private getNextId() {
return String(this.nextId++);
}
constructor() {
this.worker = new Worker("dist/worker.bundle.js");
this.worker.addEventListener("message", (e: {data: IWorkerResponse}) => {
if (!e.data.id) {
return;
}
const cb = this.workerCallbacks[e.data.id];
if (e.data.success) {
cb.fn(e.data.payload);
} else {
const error = Object.assign(
Object.create(Error.prototype),
e.data.payload,
);
cb.ex(error);
}
this.workerCallbacks[e.data.id] = null;
});
}
setWorkerCallback(id: string, fn: (e: any) => void, ex?: (e: any) => void) {
assert(!this.workerCallbacks[id as any]);
this.workerCallbacks[id as any] = {fn, ex};
}
async postMessage(command: WorkerCommand, payload: any): Promise<any> {
return new Promise((resolve, reject) => {
const id = this.getNextId();
this.setWorkerCallback(id, (data: any) => {
resolve(data);
}, (err: Error) => {
reject(err);
});
this.worker.postMessage({
id, command, payload
}, undefined);
});
}
async optimizeWasmWithBinaryen(data: ArrayBuffer): Promise<ArrayBuffer> {
return await this.postMessage(WorkerCommand.OptimizeWasmWithBinaryen, data);
}
async validateWasmWithBinaryen(data: ArrayBuffer): Promise<number> {
return await this.postMessage(WorkerCommand.ValidateWasmWithBinaryen, data);
}
async createWasmCallGraphWithBinaryen(data: ArrayBuffer): Promise<string> {
return await this.postMessage(WorkerCommand.CreateWasmCallGraphWithBinaryen, data);
}
async convertWasmToAsmWithBinaryen(data: ArrayBuffer): Promise<string> {
return await this.postMessage(WorkerCommand.ConvertWasmToAsmWithBinaryen, data);
}
async disassembleWasmWithBinaryen(data: ArrayBuffer): Promise<string> {
return await this.postMessage(WorkerCommand.DisassembleWasmWithBinaryen, data);
}
async assembleWatWithBinaryen(data: string): Promise<ArrayBuffer> {
return await this.postMessage(WorkerCommand.AssembleWatWithBinaryen, data);
}
async disassembleWasmWithWabt(data: ArrayBuffer): Promise<string> {
return await this.postMessage(WorkerCommand.DisassembleWasmWithWabt, data);
}
async assembleWatWithWabt(data: string): Promise<ArrayBuffer> {
return await this.postMessage(WorkerCommand.AssembleWatWithWabt, data);
}
async twiggyWasm(data: ArrayBuffer): Promise<string> {
return await this.postMessage(WorkerCommand.TwiggyWasm, data);
}
}
export class Service {
private static worker = new ServiceWorker();
static getMarkers(response: string): monaco.editor.IMarkerData[] {
// Parse and annotate errors if compilation fails.
const annotations: monaco.editor.IMarkerData[] = [];
if (response.indexOf("(module") !== 0) {
const re1 = /^.*?:(\d+?):(\d+?):\s(.*)$/gm;
let m: any;
// Single position.
while ((m = re1.exec(response)) !== null) {
if (m.index === re1.lastIndex) {
re1.lastIndex++;
}
const startLineNumber = parseInt(m[1], 10);
const startColumn = parseInt(m[2], 10);
const message = m[3];
let severity = monaco.MarkerSeverity.Info;
if (message.indexOf("error") >= 0) {
severity = monaco.MarkerSeverity.Error;
} else if (message.indexOf("warning") >= 0) {
severity = monaco.MarkerSeverity.Warning;
}
annotations.push({
severity, message,
startLineNumber: startLineNumber,
startColumn: startColumn,
endLineNumber: startLineNumber, endColumn: startColumn
});
}
// Range. This is generated via the -diagnostics-print-source-range-info
// clang flag.
const re2 = /^.*?:\d+?:\d+?:\{(\d+?):(\d+?)-(\d+?):(\d+?)\}:\s(.*)$/gm;
while ((m = re2.exec(response)) !== null) {
if (m.index === re2.lastIndex) {
re2.lastIndex++;
}
const message = m[5];
let severity = monaco.MarkerSeverity.Info;
if (message.indexOf("error") >= 0) {
severity = monaco.MarkerSeverity.Error;
} else if (message.indexOf("warning") >= 0) {
severity = monaco.MarkerSeverity.Warning;
}
annotations.push({
severity, message,
startLineNumber: parseInt(m[1], 10), startColumn: parseInt(m[2], 10),
endLineNumber: parseInt(m[3], 10), endColumn: parseInt(m[4], 10)
});
}
}
return annotations;
}
static async compileFiles(files: File[], from: Language, to: Language, options = ""): Promise<{ [name: string]: (string|ArrayBuffer); }> {
gaEvent("compile", "Service", `${from}->${to}`);
const service = await createCompilerService(from, to);
const fileNameMap: {[name: string]: File} = files.reduce((acc: any, f: File) => {
acc[getProjectFilePath(f)] = f;
return acc;
}, {} as any);
const input = {
files: files.reduce((acc: any, f: File) => {
acc[getProjectFilePath(f)] = {
content: f.getData(),
};
return acc;
}, {} as any),
options,
};
const result = await service.compile(input);
for (const file of files) {
file.setProblems([]);
}
for (const [ name, item ] of Object.entries(result.items)) {
const { fileRef, console } = item;
if (!fileRef || !console) {
continue;
}
const file = fileNameMap[fileRef];
if (!file) {
continue;
}
const markers = Service.getMarkers(console);
if (markers.length > 0) {
monaco.editor.setModelMarkers(file.buffer, "compiler", markers);
file.setProblems(markers.map(marker => {
return Problem.fromMarker(file, marker);
}));
}
}
if (!result.success) {
throw new Error(result.console);
}
const outputFiles: any = {};
for (const [ name, item ] of Object.entries(result.items)) {
const { content } = item;
if (content) {
outputFiles[name] = content;
}
}
return outputFiles;
}
static async compileFile(file: File, from: Language, to: Language, options = ""): Promise<any> {
const result = await Service.compileFileWithBindings(file, from, to, options);
return result.wasm;
}
static async compileFileWithBindings(file: File, from: Language, to: Language, options = ""): Promise<any> {
if (to !== Language.Wasm) {
throw new Error(`Only wasm target is supported, but "${to}" was found`);
}
const result = await Service.compileFiles([file], from, to, options);
const expectedOutputFilename = "a.wasm";
let output: any = {
wasm: result[expectedOutputFilename],
};
const expectedWasmBindgenJsFilename = "wasm_bindgen.js";
if (result[expectedWasmBindgenJsFilename]) {
output = {
...output,
wasmBindgenJs: result[expectedWasmBindgenJsFilename],
};
}
return output;
}
static async disassembleWasm(buffer: ArrayBuffer, status: IStatusProvider): Promise<string> {
gaEvent("disassemble", "Service", "wabt");
status && status.push("Disassembling with Wabt");
const result = await this.worker.disassembleWasmWithWabt(buffer);
status && status.pop();
return result;
}
static async disassembleWasmWithWabt(file: File, status?: IStatusProvider) {
const result = await Service.disassembleWasm(file.getData() as ArrayBuffer, status);
const output = file.parent.newFile(file.name + ".wat", FileType.Wat);
output.description = "Disassembled from " + file.name + " using Wabt.";
output.setData(result);
}
static async assembleWat(wat: string, status?: IStatusProvider): Promise<ArrayBuffer> {
gaEvent("assemble", "Service", "wabt");
status && status.push("Assembling Wat with Wabt");
let result = null;
try {
result = await this.worker.assembleWatWithWabt(wat);
} catch (e) {
throw e;
} finally {
status && status.pop();
}
return result;
}
static async assembleWatWithWabt(file: File, status?: IStatusProvider) {
const result = await Service.assembleWat(file.getData() as string, status);
const output = file.parent.newFile(file.name + ".wasm", FileType.Wasm);
output.description = "Assembled from " + file.name + " using Wabt.";
output.setData(result);
}
static async createGist(json: object): Promise<string> {
const url = "https://api.github.com/gists";
const response = await fetch(url, {
method: "POST",
body: JSON.stringify(json),
headers: new Headers({ "Content-type": "application/json; charset=utf-8" })
});
return JSON.parse(await response.text()).html_url;
}
static async loadJSON(uri: string): Promise<ILoadFiddleResponse> {
const url = "https://webassembly-studio-fiddles.herokuapp.com/fiddle/" + uri;
const response = await fetch(url, {
headers: new Headers({ "Content-type": "application/json; charset=utf-8" })
});
return await response.json();
}
static async saveJSON(json: ICreateFiddleRequest, uri: string): Promise<string> {
const update = !!uri;
if (update) {
throw new Error("NYI");
} else {
const response = await fetch("https://webassembly-studio-fiddles.herokuapp.com/set-fiddle", {
method: "POST",
headers: new Headers({ "Content-type": "application/json; charset=utf-8" }),
body: JSON.stringify(json)
});
let jsonURI = (await response.json()).id;
jsonURI = jsonURI.substring(jsonURI.lastIndexOf("/") + 1);
return jsonURI;
}
}
static parseFiddleURI(): string {
let uri = window.location.search.substring(1);
if (uri) {
const i = uri.indexOf("/");
if (i > 0) {
uri = uri.substring(0, i);
}
}
return uri;
}
static async exportToGist(content: File, uri?: string): Promise<string> {
gaEvent("export", "Service", "gist");
const files: any = {};
function serialize(file: File) {
if (file instanceof Directory) {
file.mapEachFile((file: File) => serialize(file), true);
} else {
files[file.name] = {content: file.data};
}
}
serialize(content);
const json: any = { description: "source: https://webassembly.studio", public: true, files};
if (uri !== undefined) {
json["description"] = json["description"] + `/?f=${uri}`;
}
return await this.createGist(json);
}
static async saveProject(project: Project, openedFiles: string[][], uri?: string): Promise<string> {
const files: IFiddleFile [] = [];
project.forEachFile((f: File) => {
let data: string;
let type: "binary" | "text";
if (isBinaryFileType(f.type)) {
data = base64EncodeBytes(new Uint8Array(f.data as ArrayBuffer));
type = "binary";
} else {
data = f.data as string;
type = "text";
}
const file = {
name: f.getPath(project),
data,
type
};
files.push(file);
}, true, true);
return await this.saveJSON({
files
}, uri);
}
static async loadFilesIntoProject(files: IFiddleFile[], project: Project, base: URL = null): Promise<any> {
for (const f of files) {
const type = fileTypeFromFileName(f.name);
const file = project.newFile(f.name, type, false);
let data: string | ArrayBuffer;
if (f.data) {
if (f.type === "binary") {
data = decodeRestrictedBase64ToBytes(f.data).buffer as ArrayBuffer;
} else {
data = f.data;
}
} else {
const request = await fetch(new URL(f.name, base).toString());
if (f.type === "binary") {
data = await request.arrayBuffer();
} else {
data = await request.text();
}
}
file.setData(data);
}
}
static lazyLoad(uri: string, status?: IStatusProvider): Promise<any> {
return new Promise((resolve, reject) => {
status && status.push("Loading " + uri);
const self = this;
const d = window.document;
const b = d.body;
const e = d.createElement("script");
e.async = true;
e.src = uri;
b.appendChild(e);
e.onload = function() {
status && status.pop();
resolve(this);
};
// TODO: What about fail?
});
}
static async optimizeWasmWithBinaryen(file: File, status?: IStatusProvider) {
assert(this.worker);
gaEvent("optimize", "Service", "binaryen");
let data = file.getData() as ArrayBuffer;
status && status.push("Optimizing with Binaryen");
data = await this.worker.optimizeWasmWithBinaryen(data);
status && status.pop();
file.setData(data);
file.buffer.setValue(await Service.disassembleWasm(data, status));
}
static async validateWasmWithBinaryen(file: File, status?: IStatusProvider): Promise<boolean> {
gaEvent("validate", "Service", "binaryen");
const data = file.getData() as ArrayBuffer;
status && status.push("Validating with Binaryen");
const result = await this.worker.validateWasmWithBinaryen(data);
status && status.pop();
return !!result;
}
static async getWasmCallGraphWithBinaryen(file: File, status?: IStatusProvider) {
gaEvent("call-graph", "Service", "binaryen");
const data = file.getData() as ArrayBuffer;
status && status.push("Creating Call Graph with Binaryen");
const result = await this.worker.createWasmCallGraphWithBinaryen(data);
status && status.pop();
const output = file.parent.newFile(file.name + ".dot", FileType.DOT);
output.description = "Call graph created from " + file.name + " using Binaryen's print-call-graph pass.";
output.setData(result);
}
static async disassembleWasmWithBinaryen(file: File, status?: IStatusProvider) {
gaEvent("disassemble", "Service", "binaryen");
const data = file.getData() as ArrayBuffer;
status && status.push("Disassembling with Binaryen");
const result = await this.worker.disassembleWasmWithBinaryen(data);
status && status.pop();
const output = file.parent.newFile(file.name + ".wat", FileType.Wat);
output.description = "Disassembled from " + file.name + " using Binaryen.";
output.setData(result);
}
static async convertWasmToAsmWithBinaryen(file: File, status?: IStatusProvider) {
gaEvent("asm.js", "Service", "binaryen");
const data = file.getData() as ArrayBuffer;
status && status.push("Converting to asm.js with Binaryen");
const result = await this.worker.convertWasmToAsmWithBinaryen(data);
status && status.pop();
const output = file.parent.newFile(file.name + ".asm.js", FileType.JavaScript);
output.description = "Converted from " + file.name + " using Binaryen.";
output.setData(result);
}
static async assembleWatWithBinaryen(file: File, status?: IStatusProvider) {
gaEvent("assemble", "Service", "binaryen");
const data = file.getData() as string;
status && status.push("Assembling with Binaryen");
const result = await this.worker.assembleWatWithBinaryen(data);
status && status.pop();
const output = file.parent.newFile(file.name + ".wasm", FileType.Wasm);
output.description = "Converted from " + file.name + " using Binaryen.";
output.setData(result);
}
static downloadLink: HTMLAnchorElement = null;
static download(file: File) {
if (!Service.downloadLink) {
Service.downloadLink = document.createElement("a");
Service.downloadLink.style.display = "none";
document.body.appendChild(Service.downloadLink);
}
const url = URL.createObjectURL(new Blob([file.getData()], { type: "application/octet-stream" }));
Service.downloadLink.href = url;
Service.downloadLink.download = file.name;
if (Service.downloadLink.href as any !== document.location) {
Service.downloadLink.click();
}
}
static clangFormatModule: any = null;
// Kudos to https://github.com/tbfleming/cib
static async clangFormat(file: File, status?: IStatusProvider) {
gaEvent("format", "Service", "clang-format");
function format() {
const result = Service.clangFormatModule.ccall("formatCode", "string", ["string"], [file.buffer.getValue()]);
file.buffer.setValue(result);
}
if (Service.clangFormatModule) {
format();
} else {
await Service.lazyLoad("lib/clang-format.js", status);
const response = await fetch("lib/clang-format.wasm");
const wasmBinary = await response.arrayBuffer();
const module: any = {
postRun() {
format();
},
wasmBinary
};
Service.clangFormatModule = Module(module);
}
}
static async disassembleX86(file: File, status?: IStatusProvider, options = "") {
gaEvent("disassemble", "Service", "capstone.x86");
if (typeof capstone === "undefined") {
await Service.lazyLoad("lib/capstone.x86.min.js", status);
}
const output = file.parent.newFile(file.name + ".x86", FileType.x86);
function toBytes(a: any) {
return a.map(function(x: any) { return padLeft(Number(x).toString(16), 2, "0"); }).join(" ");
}
const service = await createCompilerService(Language.Wasm, Language.x86);
const input = {
files: {
"in.wasm": {
content: file.getData(),
},
},
options,
};
const result = await service.compile(input);
const json: any = result.items["a.json"].content;
let s = "";
const cs = new capstone.Cs(capstone.ARCH_X86, capstone.MODE_64);
const annotations: any[] = [];
const assemblyInstructionsByAddress = Object.create(null);
for (let i = 0; i < json.regions.length; i++) {
const region = json.regions[i];
s += region.name + ":\n";
const csBuffer = decodeRestrictedBase64ToBytes(region.bytes);
const instructions = cs.disasm(csBuffer, region.entry);
const basicBlocks: any = {};
instructions.forEach(function(instr: any, i: any) {
assemblyInstructionsByAddress[instr.address] = instr;
if (isBranch(instr)) {
const targetAddress = parseInt(instr.op_str, 10);
if (!basicBlocks[targetAddress]) {
basicBlocks[targetAddress] = [];
}
basicBlocks[targetAddress].push(instr.address);
if (i + 1 < instructions.length) {
basicBlocks[instructions[i + 1].address] = [];
}
}
});
instructions.forEach(function(instr: any) {
if (basicBlocks[instr.address]) {
s += " " + padRight(toAddress(instr.address) + ":", 39, " ");
if (basicBlocks[instr.address].length > 0) {
s += "; " + toAddress(instr.address) + " from: [" + basicBlocks[instr.address].map(toAddress).join(", ") + "]";
}
s += "\n";
}
s += " " + padRight(instr.mnemonic + " " + instr.op_str, 38, " ");
s += "; " + toAddress(instr.address) + " " + toBytes(instr.bytes) + "\n";
});
s += "\n";
}
output.setData(s);
}
private static binaryExplorerMessageListener: (e: any) => void;
static openBinaryExplorer(file: File) {
window.open(
"//wasdk.github.io/wasmcodeexplorer/?api=postmessage",
"",
"toolbar=no,ocation=no,directories=no,status=no,menubar=no,location=no,scrollbars=yes,resizable=yes,width=1024,height=568"
);
if (Service.binaryExplorerMessageListener) {
window.removeEventListener("message", Service.binaryExplorerMessageListener, false);
}
Service.binaryExplorerMessageListener = (e: any) => {
if (e.data.type === "wasmexplorer-ready") {
window.removeEventListener("message", Service.binaryExplorerMessageListener, false);
Service.binaryExplorerMessageListener = null;
const dataToSend = new Uint8Array((file.data as any).slice(0));
e.source.postMessage({
type: "wasmexplorer-load",
data: dataToSend
}, "*", [dataToSend.buffer]);
}
};
window.addEventListener("message", Service.binaryExplorerMessageListener, false);
}
static async import(path: string): Promise<any> {
const { project, global } = getCurrentRunnerInfo();
const context = new RewriteSourcesContext(project);
context.logLn = console.log;
context.createFile = (src: ArrayBuffer|string, type: string) => {
const blob = new global.Blob([src], { type, });
return global.URL.createObjectURL(blob);
};
const url = processJSFile(context, path);
// Create script tag to load ES module.
const script = global.document.createElement("script");
script.setAttribute("type", "module");
script.setAttribute("async", "async");
const id = `__import__${Math.random().toString(36).substr(2)}`;
const scriptReady = new Promise((resolve, reject) => {
global[id] = resolve;
});
script.textContent = `import * as i from '${url}'; ${id}(i);`;
global.document.head.appendChild(script);
const module = await scriptReady;
// Module loaded -- cleaning up
script.remove();
delete global[id];
return module;
}
static async compileMarkdownToHtml(src: string): Promise<string> {
if (typeof showdown === "undefined") {
await Service.lazyLoad("lib/showdown.min.js");
}
const converter = new showdown.Converter({ tables: true, ghCodeBlocks: true });
showdown.setFlavor("github");
return converter.makeHtml(src);
}
static async twiggyWasm(file: File, status: IStatusProvider): Promise<string> {
const buffer = file.getData() as ArrayBuffer;
gaEvent("disassemble", "Service", "twiggy");
status && status.push("Analyze with Twiggy");
const result = await this.worker.twiggyWasm(buffer);
const output = file.parent.newFile(file.name + ".md", FileType.Markdown);
output.description = "Analyzed " + file.name + " using Twiggy.";
output.setData(result);
status && status.pop();
return result;
}
} | the_stack |
import { deref, isDeref } from "@thi.ng/api/deref";
import { implementsFunction } from "@thi.ng/checks/implements-function";
import { isArray } from "@thi.ng/checks/is-array";
import { isFunction } from "@thi.ng/checks/is-function";
import { isNotStringAndIterable } from "@thi.ng/checks/is-not-string-iterable";
import { isPlainObject } from "@thi.ng/checks/is-plain-object";
import { isString } from "@thi.ng/checks/is-string";
import { illegalArgs } from "@thi.ng/errors/illegal-arguments";
import { escapeEntities } from "@thi.ng/strings/entities";
import {
ATTRIB_JOIN_DELIMS,
CDATA,
COMMENT,
NO_CLOSE_EMPTY,
NO_SPANS,
PROC_TAGS,
VOID_TAGS,
} from "./api.js";
import { css } from "./css.js";
import { normalize } from "./normalize.js";
import { formatPrefixes } from "./prefix.js";
/**
* Recursively normalizes and serializes given tree as HTML/SVG/XML
* string. Expands any embedded component functions with their results.
*
* @remarks
* Each node of the input tree can have one of the following input
* forms:
*
* ```js
* ["tag", ...]
* ["tag#id.class1.class2", ...]
* ["tag", {other: "attrib"}, ...]
* ["tag", {...}, "body", function, ...]
* [function, arg1, arg2, ...]
* [{render: (ctx,...) => [...]}, args...]
* iterable
* ```
*
* Tags can be defined in "Zencoding" convention, e.g.
*
* ```js
* ["div#foo.bar.baz", "hi"] // <div id="foo" class="bar baz">hi</div>
* ```
*
* The presence of the attributes object (2nd array index) is optional.
* Any attribute values, incl. functions are allowed. If the latter, the
* function is called with the full attribs object as argument and the
* return value is used for the attribute. This allows for the dynamic
* creation of attrib values based on other attribs. The only exception
* to this are event attributes, i.e. attribute names starting with
* "on". Function values assigned to event attributes will be omitted
* from the output.
*
* ```js
* ["div#foo", { bar: (attribs) => attribs.id + "-bar" }]
* // <div id="foo" bar="foo-bar"></div>
* ```
*
* The `style` attribute can ONLY be defined as string or object.
*
* ```js
* ["div", {style: {color: "red", background: "#000"}}]
* // <div style="color:red;background:#000;"></div>
* ```
*
* Boolean attribs are serialized in HTML5 syntax (present or not).
* `null`, `undefined` or empty string attrib values are ignored.
*
* Any `null` or `undefined` array values (other than in head position)
* will also be removed, unless a function is in head position.
*
* A function in head position of a node acts as a mechanism for
* component composition & delayed execution. The function will only be
* executed at serialization time. In this case the optional global
* context object and all other elements of that node / array are passed
* as arguments when that function is called. The return value the
* function MUST be a valid new tree (or `undefined`).
*
* If the `ctx` object it'll be passed to each embedded component fns.
* Optionally call {@link derefContext} prior to {@link serialize} to
* auto-deref context keys with values implementing the
* {@link @thi.ng/api#IDeref} interface.
*
* ```js
* const foo = (ctx, a, b) => ["div#" + a, ctx.foo, b];
*
* serialize([foo, "id", "body"], { foo: { class: "black" } })
* // <div id="id" class="black">body</div>
* ```
*
* Functions located in other positions are called ONLY with the global
* context arg and can return any (serializable) value (i.e. new trees,
* strings, numbers, iterables or any type with a suitable
* `.toString()`, `.toHiccup()` or `.deref()` implementation).
*
* If the optional `span` flag is true (default: false), all text
* content will be wrapped in <span> elements (this is to ensure DOM
* compatibility with hdom). The only elements for spans are never
* created are listed in `NO_SPANS` in `api.ts`.
*
* If the optional `keys` flag is true (default: false), all elements
* will have an autogenerated `key` attribute injected. If `span` is
* enabled, `keys` will be enabled by default too (since in this case we
* assume the output is meant to be compatible with
* {@link @thi.ng/hdom# | @thi.ng/hdom}).
*
* hiccup & hdom control attributes (i.e. attrib names prefixed with
* `__`) will be omitted from the output. The only control attrib
* supported by this package is `__serialize`. If set to `false`, the
* entire tree branch will be excluded from the output.
*
* Single or multiline comments can be included using the special
* `COMMENT` tag (`__COMMENT__`) (always WITHOUT attributes!).
*
* ```
* [COMMENT, "Hello world"]
* // <!-- Hello world -->
*
* [COMMENT, "Hello", "world"]
* <!--
* Hello
* world
* -->
* ```
*
* Currently, the only processing / DTD instructions supported are:
*
* - `?xml`
* - `!DOCTYTPE`
* - `!ELEMENT`
* - `!ENTITY`
* - `!ATTLIST`
*
* These are used as follows (attribs are only allowed for `?xml`, all
* others only accept a body string which is taken as is):
*
* ```
* ["?xml", { version: "1.0", standalone: "yes" }]
* // <?xml version="1.0" standalone="yes"?>
*
* ["!DOCTYPE", "html"]
* // <!DOCTYPE html>
* ```
*
* @param tree - hiccup elements / component tree
* @param ctx - arbitrary user context object
* @param escape - auto-escape entities
* @param span - use spans for text content
* @param keys - attach key attribs
*/
export const serialize = (
tree: any,
ctx?: any,
escape = false,
span = false,
keys = span,
path = [0]
) => _serialize(tree, ctx, escape, span, keys, path);
const _serialize = (
tree: any,
ctx: any,
esc: boolean,
span: boolean,
keys: boolean,
path: any[]
): string =>
tree == null
? ""
: Array.isArray(tree)
? serializeElement(tree, ctx, esc, span, keys, path)
: isFunction(tree)
? _serialize(tree(ctx), ctx, esc, span, keys, path)
: implementsFunction(tree, "toHiccup")
? _serialize(tree.toHiccup(ctx), ctx, esc, span, keys, path)
: isDeref(tree)
? _serialize(tree.deref(), ctx, esc, span, keys, path)
: isNotStringAndIterable(tree)
? serializeIter(tree, ctx, esc, span, keys, path)
: ((tree = esc ? escapeEntities(String(tree)) : String(tree)), span)
? `<span${keys ? ` key="${path.join("-")}"` : ""}>${tree}</span>`
: tree;
const serializeElement = (
tree: any[],
ctx: any,
esc: boolean,
span: boolean,
keys: boolean,
path: any[]
) => {
let tag = tree[0];
return !tree.length
? ""
: isFunction(tag)
? _serialize(
tag.apply(null, [ctx, ...tree.slice(1)]),
ctx,
esc,
span,
keys,
path
)
: implementsFunction(tag, "render")
? _serialize(
tag.render.apply(null, [ctx, ...tree.slice(1)]),
ctx,
esc,
span,
keys,
path
)
: tag === COMMENT
? serializeComment(tree)
: tag == CDATA
? serializeCData(tree)
: isString(tag)
? serializeTag(tree, ctx, esc, span, keys, path)
: isNotStringAndIterable(tree)
? serializeIter(tree, ctx, esc, span, keys, path)
: illegalArgs(`invalid tree node: ${tree}`);
};
const serializeTag = (
tree: any[],
ctx: any,
esc: boolean,
span: boolean,
keys: boolean,
path: any[]
) => {
tree = normalize(tree);
const attribs = tree[1];
if (attribs.__skip || attribs.__serialize === false) return "";
keys && attribs.key === undefined && (attribs.key = path.join("-"));
const tag = tree[0];
const body = tree[2]
? serializeBody(tag, tree[2], ctx, esc, span, keys, path)
: !VOID_TAGS[tag] && !NO_CLOSE_EMPTY[tag]
? `></${tag}>`
: PROC_TAGS[tag] || "/>";
return `<${tag}${serializeAttribs(attribs, esc)}${body}`;
};
const serializeAttribs = (attribs: any, esc: boolean) => {
let res = "";
for (let a in attribs) {
if (a.startsWith("__")) continue;
const v = serializeAttrib(attribs, a, deref(attribs[a]), esc);
v != null && (res += v);
}
return res;
};
const serializeAttrib = (attribs: any, a: string, v: any, esc: boolean) => {
return v == null
? null
: isFunction(v) && (/^on\w+/.test(a) || (v = v(attribs)) == null)
? null
: v === true
? " " + a
: v === false
? null
: a === "data"
? serializeDataAttribs(v, esc)
: attribPair(a, v, esc);
};
const attribPair = (a: string, v: any, esc: boolean) => {
v =
a === "style" && isPlainObject(v)
? css(v)
: a === "prefix" && isPlainObject(v)
? formatPrefixes(v)
: isArray(v)
? v.join(ATTRIB_JOIN_DELIMS[a] || " ")
: v.toString();
return v.length ? ` ${a}="${esc ? escapeEntities(v) : v}"` : null;
};
const serializeDataAttribs = (data: any, esc: boolean) => {
let res = "";
for (let id in data) {
let v = deref(data[id]);
isFunction(v) && (v = v(data));
v != null && (res += ` data-${id}="${esc ? escapeEntities(v) : v}"`);
}
return res;
};
const serializeBody = (
tag: string,
body: any[],
ctx: any,
esc: boolean,
span: boolean,
keys: boolean,
path: any[]
) => {
if (VOID_TAGS[tag]) {
illegalArgs(`No body allowed in tag: ${tag}`);
}
const proc = PROC_TAGS[tag];
let res = proc ? " " : ">";
span = span && !proc && !NO_SPANS[tag];
for (let i = 0, n = body.length; i < n; i++) {
res += _serialize(body[i], ctx, esc, span, keys, [...path, i]);
}
return res + (proc || `</${tag}>`);
};
const serializeComment = (tree: any[]) =>
tree.length > 2
? `\n<!--\n${tree
.slice(1)
.map((x) => " " + x)
.join("\n")}\n-->\n`
: `\n<!-- ${tree[1]} -->\n`;
const serializeCData = (tree: any[]) =>
`<![CDATA[\n${tree.slice(1).join("\n")}\n]]>`;
const serializeIter = (
iter: Iterable<any>,
ctx: any,
esc: boolean,
span: boolean,
keys: boolean,
path: any[]
) => {
const res = [];
const p = path.slice(0, path.length - 1);
let k = 0;
for (let i of iter) {
res.push(_serialize(i, ctx, esc, span, keys, [...p, k++]));
}
return res.join("");
}; | the_stack |
import testMobx from './mobx';
import { Collection, Model, View, Attribute } from '../src';
import { updateModelId } from '../src/helpers/model/fields';
import { ViewAttribute } from '../src/Attribute';
import { mobx } from '@datx/utils';
// @ts-ignore
testMobx.configure({ enforceActions: 'observed' });
describe('View', () => {
it('should init a view', () => {
const collection = new Collection();
const viewInstance = new View('foo', collection);
expect(viewInstance).toBeInstanceOf(View);
});
it('should be able to get initial models', () => {
class Foo extends Model {
public static type = 'foo';
}
class AppCollection extends Collection {
public static types = [Foo];
}
const collection = new AppCollection();
const foos = collection.add([{}, {}], Foo);
const viewInstance = new View(Foo, collection, undefined, [-1, -2]);
expect(viewInstance).toHaveLength(2);
expect(viewInstance.list[0]).toBeInstanceOf(Foo);
expect(viewInstance.list[1]).toBeInstanceOf(Foo);
expect(viewInstance.list[0]).toBe(foos[0]);
expect(viewInstance.hasItem(foos[1])).toBe(true);
});
it('should be able to receive models', () => {
class Foo extends Model {
public static type = 'foo';
}
class AppCollection extends Collection {
public static types = [Foo];
}
const collection = new AppCollection();
const foos = collection.add([{}, {}], Foo);
const viewInstance = new View(Foo, collection);
viewInstance.add(foos);
expect(viewInstance).toHaveLength(2);
expect(viewInstance.list[0]).toBeInstanceOf(Foo);
expect(viewInstance.list[1]).toBeInstanceOf(Foo);
expect(viewInstance.list[0]).toBe(foos[0]);
});
it('should be a dynamic list', () => {
class Foo extends Model {
public static type = 'foo';
}
class AppCollection extends Collection {
public static types = [Foo];
}
const collection = new AppCollection();
const foos = collection.add([{}, {}], Foo);
const viewInstance = new View(Foo, collection);
let expectedLength = 0;
let lengthAutorunCount = 0;
let listAutorunCount = 0;
testMobx.autorun(() => {
expect(viewInstance).toHaveLength(expectedLength);
lengthAutorunCount++;
});
testMobx.autorun(() => {
expect(viewInstance.list).toHaveLength(expectedLength);
listAutorunCount++;
});
expectedLength = foos.length;
viewInstance.add(foos);
expect(viewInstance).toHaveLength(2);
expect(viewInstance.list[0]).toBeInstanceOf(Foo);
expect(viewInstance.list[1]).toBeInstanceOf(Foo);
expect(viewInstance.list[0]).toBe(foos[0]);
expect(listAutorunCount).toBe(mobx.useRealMobX ? 2 : 1);
expect(lengthAutorunCount).toBe(mobx.useRealMobX ? 2 : 1);
});
it('should be able to sort models', () => {
class Foo extends Model {
public static type = 'foo';
@Attribute()
public key!: number;
}
class AppCollection extends Collection {
public static types = [Foo];
}
const collection = new AppCollection();
const foos = collection.add([{ key: 2 }, { key: 3 }, { key: 1 }], Foo);
const viewInstance = new View(Foo, collection, (item: Foo) => item.key, foos);
expect(viewInstance).toHaveLength(3);
const item0a = viewInstance.list[0];
const item2a = viewInstance.list[2];
expect(item0a && item0a.key).toBe(1);
expect(item2a && item2a.key).toBe(3);
const foo0 = collection.add({ key: 0 }, Foo);
expect(viewInstance).toHaveLength(3);
viewInstance.add(foo0);
const item0b = viewInstance.list[0];
const item2b = viewInstance.list[2];
expect(item0b && item0b.key).toBe(0);
expect(item2b && item2b.key).toBe(2);
});
it('should be able to sort models by non-numerical prop', () => {
class Foo extends Model {
public static type = 'foo';
@Attribute()
public key!: string;
}
class AppCollection extends Collection {
public static types = [Foo];
}
const collection = new AppCollection();
const foos = collection.add([{ key: 'abd' }, { key: 'bbf' }, { key: 'ecf' }], Foo);
const viewInstance = new View(Foo, collection, (item: Foo) => item.key, foos);
expect(viewInstance).toHaveLength(3);
const item0a = viewInstance.list[0];
const item2a = viewInstance.list[2];
expect(item0a && item0a.key).toBe('abd');
expect(item2a && item2a.key).toBe('ecf');
const foo0 = collection.add({ key: 'ccc' }, Foo);
expect(viewInstance).toHaveLength(3);
viewInstance.add(foo0);
const item0b = viewInstance.list[0];
const item2b = viewInstance.list[2];
expect(item0b && item0b.key).toBe('abd');
expect(item2b && item2b.key).toBe('ccc');
});
it('should be able to update sort method', () => {
class Foo extends Model {
public static type = 'foo';
@Attribute()
public key!: number;
}
class AppCollection extends Collection {
public static types = [Foo];
}
const collection = new AppCollection();
const foos = collection.add([{ key: 2 }, { key: 3 }, { key: 1 }], Foo);
const viewInstance = new View(Foo, collection, (item: Foo) => item.key, foos);
expect(viewInstance).toHaveLength(3);
const item0a = viewInstance.list[0];
const item2a = viewInstance.list[2];
expect(item0a && item0a.key).toBe(1);
expect(item2a && item2a.key).toBe(3);
let keyList: Array<number | null> = [];
let autorunCount = 0;
testMobx.autorun(() => {
keyList = viewInstance.list.map((item) => item && item.key);
autorunCount++;
});
expect(keyList[2]).toBe(3);
testMobx.runInAction(() => {
viewInstance.sortMethod = 'id';
});
const item0b = viewInstance.list[0];
const item2b = viewInstance.list[2];
expect(item0b && item0b.key).toBe(2);
expect(item2b && item2b.key).toBe(1);
if (mobx.useRealMobX) {
expect(keyList[2]).toBe(1);
expect(autorunCount).toBe(2);
}
});
it('should be able to sort models by prop', () => {
class Foo extends Model {
public static type = 'foo';
@Attribute()
public key!: number;
}
class AppCollection extends Collection {
public static types = [Foo];
}
const collection = new AppCollection();
const foos = collection.add([{ key: 2 }, { key: 3 }, { key: 1 }], Foo);
const viewInstance = new View(Foo, collection, 'key', foos);
expect(viewInstance).toHaveLength(3);
const item0a = viewInstance.list[0];
const item2a = viewInstance.list[2];
expect(item0a && item0a.key).toBe(1);
expect(item2a && item2a.key).toBe(3);
const foo0 = collection.add({ key: 0 }, Foo);
expect(viewInstance).toHaveLength(3);
viewInstance.add(foo0);
const item0b = viewInstance.list[0];
const item2b = viewInstance.list[2];
expect(item0b && item0b.key).toBe(0);
expect(item2b && item2b.key).toBe(2);
});
it('should be able to remove models', () => {
class Foo extends Model {
public static type = 'foo';
}
class AppCollection extends Collection {
public static types = [Foo];
}
const collection = new AppCollection();
const foos = collection.add([{}, {}, {}], Foo);
const viewInstance = new View(Foo, collection, undefined, foos);
expect(viewInstance).toHaveLength(3);
viewInstance.remove(foos[2]);
expect(viewInstance).toHaveLength(2);
viewInstance.removeAll();
expect(viewInstance).toHaveLength(0);
});
it('should work with updating the list', () => {
class Foo extends Model {
public static type = 'foo';
}
class AppCollection extends Collection {
public static types = [Foo];
}
const collection = new AppCollection();
const foos = collection.add([{}, {}, {}], Foo);
const viewInstance = new View(Foo, collection, undefined, foos);
const [foo1, foo2] = collection.add([{}, {}, {}], Foo);
expect(viewInstance).toHaveLength(3);
if (mobx.useRealMobX) {
viewInstance.list.push(foo1);
expect(viewInstance).toHaveLength(4);
viewInstance.list.unshift(foo2);
expect(viewInstance).toHaveLength(5);
viewInstance.list.splice(2, 2);
expect(viewInstance).toHaveLength(3);
} else {
viewInstance.list = [...viewInstance.list, foo1];
expect(viewInstance).toHaveLength(4);
viewInstance.list = [foo2, ...viewInstance.list];
expect(viewInstance).toHaveLength(5);
viewInstance.list = [...viewInstance.list.slice(0, 2), ...viewInstance.list.slice(4)];
expect(viewInstance).toHaveLength(3);
}
});
it('should work with sorted list', () => {
class Foo extends Model {
public static type = 'foo';
@Attribute({ isIdentifier: true })
public id!: number;
}
class AppCollection extends Collection {
public static types = [Foo];
}
const collection = new AppCollection();
const foos = collection.add([{}, {}, {}], Foo);
const viewInstance = new View(Foo, collection, (item) => item.id, foos);
const [foo1, foo2] = collection.add([{}, {}, {}], Foo);
expect(viewInstance).toHaveLength(3);
expect(() => {
if (mobx.useRealMobX) {
viewInstance.list.push(foo1);
} else {
viewInstance.list = [...viewInstance.list, foo1];
}
}).toThrowError(
"New models can't be added directly to a sorted view list",
);
expect(() => {
if (mobx.useRealMobX) {
viewInstance.list.push(foo2);
} else {
viewInstance.list = [foo2, ...viewInstance.list];
}
}).toThrowError(
"New models can't be added directly to a sorted view list",
);
expect(() => {
if (mobx.useRealMobX) {
viewInstance.list[1] = foo1;
} else {
viewInstance.list = [
...viewInstance.list.slice(0, 1),
foo1,
...viewInstance.list.slice(2),
];
}
}).toThrowError("New models can't be added directly to a sorted view list");
expect(() => {
if (mobx.useRealMobX) {
viewInstance.list[3] = foo1;
} else {
viewInstance.list = [
...viewInstance.list.slice(0, 3),
foo1,
...viewInstance.list.slice(4),
];
}
}).toThrowError("New models can't be added directly to a sorted view list");
if (mobx.useRealMobX) {
viewInstance.list.splice(1, 2);
expect(viewInstance).toHaveLength(1);
}
});
it('should work with unique list', () => {
class Foo extends Model {
public static type = 'foo';
@Attribute({ isIdentifier: true })
public id!: number;
}
class AppCollection extends Collection {
public static types = [Foo];
}
const collection = new AppCollection();
const foos = collection.add([{}, {}, {}], Foo);
const viewInstance = new View(Foo, collection, undefined, foos, true);
const [foo1] = foos;
if (mobx.useRealMobX) {
viewInstance.list[0] = foo1;
} else {
viewInstance.list = [foo1, ...viewInstance.list.slice(1)];
}
expect(() => {
if (mobx.useRealMobX) {
viewInstance.list[1] = foo1;
} else {
viewInstance.list = [viewInstance.list[0], foo1, ...viewInstance.list.slice(2)];
}
}).toThrowError('The models in this view need to be unique');
expect(() => {
if (mobx.useRealMobX) {
viewInstance.list.push(foo1);
} else {
viewInstance.list = [...viewInstance.list, foo1];
}
}).toThrowError(
'The models in this view need to be unique',
);
expect(() => {
if (mobx.useRealMobX) {
viewInstance.list.splice(0, 0, foo1);
} else {
viewInstance.list = [foo1, ...viewInstance.list];
}
}).toThrowError(
'The models in this view need to be unique',
);
});
it('should be able to deserialize the view', () => {
class Foo extends Model {
public static type = 'foo';
}
class AppCollection extends Collection {
public static types = [Foo];
}
const collection = new AppCollection();
const foos = collection.add([{}, {}], Foo);
const viewInstance = new View(Foo, collection);
viewInstance.add(foos);
const { snapshot } = viewInstance;
const view2 = new View(
snapshot.modelType,
collection,
undefined,
snapshot.models,
snapshot.unique,
);
expect(view2).toHaveLength(2);
expect(view2.value[0]).toBeInstanceOf(Foo);
expect(view2.value[1]).toBeInstanceOf(Foo);
expect(view2.value[0]).toBe(foos[0]);
});
describe('Collections', () => {
it('should be possible to add a view', () => {
class Foo extends Model {
public static type = 'foo';
}
class AppCollection extends Collection {
public static types = [Foo];
public test!: View<Foo>;
}
const collection = new AppCollection();
const foos = collection.add([{}, {}], Foo);
collection.addView('test', Foo, { models: foos });
expect(collection.test).toHaveLength(2);
expect(collection.test.value[0]).toBeInstanceOf(Foo);
expect(collection.test.value[1]).toBeInstanceOf(Foo);
expect(collection.test.value[0]).toBe(foos[0]);
});
it('should be possible to define views upfront', () => {
class Foo extends Model {
public static type = 'foo';
}
class AppCollection extends Collection {
public static types = [Foo];
public static views = {
test: { modelType: Foo },
};
public test!: View<Foo>;
}
const collection = new AppCollection();
expect(collection.test.modelType).toBe('foo');
const foos = collection.test.add([{}, {}]);
expect(collection.test).toHaveLength(2);
expect(collection.test.value[0]).toBeInstanceOf(Foo);
expect(collection.test.value[1]).toBeInstanceOf(Foo);
expect(collection.test.value[0]).toBe(foos[0]);
const { snapshot } = collection;
const collection2 = new AppCollection(snapshot);
expect(collection2.test).toHaveLength(2);
});
it('should be possible to define views upfront with a decorator', () => {
class Foo extends Model {
public static type = 'foo';
}
class AppCollection extends Collection {
public static types = [Foo];
@ViewAttribute(Foo)
public test!: View<Foo>;
}
const collection = new AppCollection();
expect(collection.test.modelType).toBe('foo');
const foos = collection.test.add([{}, {}]);
expect(collection.test).toHaveLength(2);
expect(collection.test.value[0]).toBeInstanceOf(Foo);
expect(collection.test.value[1]).toBeInstanceOf(Foo);
expect(collection.test.value[0]).toBe(foos[0]);
const { snapshot } = collection;
const collection2 = new AppCollection(snapshot);
expect(collection2.test).toHaveLength(2);
});
});
it('should support changing ids', () => {
class Foo extends Model {
public static type = 'foo';
}
class AppCollection extends Collection {
public static types = [Foo];
}
const collection = new AppCollection();
const foos = collection.add([{}, {}], Foo);
const viewInstance = new View(
Foo,
collection,
undefined,
foos.map((foo) => foo.meta.id),
);
expect(viewInstance).toHaveLength(2);
expect(viewInstance.list[0]).toBeInstanceOf(Foo);
expect(viewInstance.list[1]).toBeInstanceOf(Foo);
expect(viewInstance.list[0]).toBe(foos[0]);
expect(viewInstance.hasItem(foos[1])).toBe(true);
const foo1 = foos[1];
updateModelId(foo1, 123);
expect(viewInstance.list[1]).toBe(foo1);
expect(viewInstance.hasItem(foo1)).toBe(true);
expect(foo1.meta.id).toBe(123);
});
it('should support ids before models', () => {
class Foo extends Model {
public static type = 'foo';
@Attribute({ isIdentifier: true })
public id!: number;
}
class AppCollection extends Collection {
public static types = [Foo];
}
const collection = new AppCollection();
const viewInstance = new View(Foo, collection, undefined, [987, 123, 234]);
// const foos = collection.add([{ id: 123 }, { id: 234 }], Foo);
const lengths: Array<number> = [];
testMobx.autorun(() => {
lengths.push(viewInstance.length);
});
testMobx.runInAction(() => {
if (mobx.useRealMobX) {
// @ts-expect-error
viewInstance.list.push(876);
} else {
// @ts-expect-error
viewInstance.list = [...viewInstance.list, 876];
}
});
// expect(collection).toHaveLength(2);
// expect(viewInstance).toHaveLength(2);
// expect(viewInstance.snapshot.models).toHaveLength(4);
// expect(viewInstance.list[0]).toBeInstanceOf(Foo);
// expect(viewInstance.list[1]).toBeInstanceOf(Foo);
// expect(viewInstance.list[0]).toBe(foos[0]);
// expect(viewInstance.hasItem(foos[1])).toBe(true);
// const foo987 = collection.add({ id: 987 }, Foo);
// expect(collection).toHaveLength(3);
// expect(viewInstance).toHaveLength(3);
// expect(viewInstance.hasItem(foo987)).toBe(true);
// // viewInstance.add({ id: 876 });
// const foo876 = collection.add({ id: 876 }, Foo);
// collection.add({ id: 765 }, Foo);
// expect(collection).toHaveLength(5);
// expect(viewInstance).toHaveLength(4);
// expect(viewInstance.hasItem(foo876)).toBe(true);
});
}); | the_stack |
import { Buffer } from 'buffer';
import {
DOMWidgetModel, DOMWidgetView, WidgetModel, ISerializers, Dict, unpack_models
} from '@jupyter-widgets/base';
import {
RoughCanvas
} from 'roughjs/bin/canvas';
import {
MODULE_NAME, MODULE_VERSION
} from './version';
import {
getArg, toBytes, fromBytes, getTypedArray
} from './utils';
function getContext(canvas: HTMLCanvasElement) {
const context = canvas.getContext("2d");
if (context === null) {
throw 'Could not create 2d context.';
}
return context;
}
function serializeImageData(array: Uint8ClampedArray) {
return new DataView(array.buffer.slice(0));
}
function deserializeImageData(dataview: DataView | null) {
if (dataview === null) {
return null;
}
return new Uint8ClampedArray(dataview.buffer);
}
async function createImageFromWidget(image: DOMWidgetModel): Promise<HTMLImageElement> {
// Create the image manually instead of creating an ImageView
let url: string;
const format = image.get('format');
const value = image.get('value');
if (format !== 'url') {
const blob = new Blob([value], {type: `image/${format}`});
url = URL.createObjectURL(blob);
} else {
url = (new TextDecoder('utf-8')).decode(value.buffer);
}
const img = new Image();
return new Promise((resolve) => {
img.onload = () => {
resolve(img);
};
img.src = url;
});
}
const COMMANDS = [
'fillRect', 'strokeRect', 'fillRects', 'strokeRects', 'clearRect', 'fillArc',
'fillCircle', 'strokeArc', 'strokeCircle', 'fillArcs', 'strokeArcs',
'fillCircles', 'strokeCircles', 'strokeLine', 'beginPath', 'closePath',
'stroke', 'fillPath', 'fill', 'moveTo', 'lineTo',
'rect', 'arc', 'ellipse', 'arcTo', 'quadraticCurveTo',
'bezierCurveTo', 'fillText', 'strokeText', 'setLineDash', 'drawImage',
'putImageData', 'clip', 'save', 'restore', 'translate',
'rotate', 'scale', 'transform', 'setTransform', 'resetTransform',
'set', 'clear', 'sleep', 'fillPolygon', 'strokePolygon',
'strokeLines',
];
export
class Path2DModel extends WidgetModel {
defaults() {
return {...super.defaults(),
_model_name: Path2DModel.model_name,
_model_module: Path2DModel.model_module,
_model_module_version: Path2DModel.model_module_version,
value: '',
};
}
initialize(attributes: any, options: any) {
super.initialize(attributes, options);
this.value = new Path2D(this.get('value'));
}
value: Path2D;
static model_name = 'Path2DModel';
static model_module = MODULE_NAME;
static model_module_version = MODULE_VERSION;
}
export
class PatternModel extends WidgetModel {
defaults() {
return {...super.defaults(),
_model_name: PatternModel.model_name,
_model_module: PatternModel.model_module,
_model_module_version: PatternModel.model_module_version,
image: '',
repetition: 'repeat',
};
}
async initialize(attributes: any, options: any) {
super.initialize(attributes, options);
const image = this.get('image');
let patternSource: HTMLCanvasElement | HTMLImageElement | undefined = undefined;
if (image instanceof CanvasModel || image instanceof MultiCanvasModel) {
patternSource = image.canvas;
}
if (image.get('_model_name') == 'ImageModel') {
const img = await createImageFromWidget(image);
patternSource = img;
}
if (patternSource == undefined) {
throw "Could not understand the souce for the pattern";
}
const pattern = PatternModel.ctx.createPattern(patternSource, this.get('repetition'));
if (pattern == null) {
throw "Could not initialize pattern object";
}
this.value = pattern;
}
static serializers: ISerializers = {
...WidgetModel.serializers,
image: { deserialize: (unpack_models as any) },
}
value: CanvasPattern;
static model_name = 'PatternModel';
static model_module = MODULE_NAME;
static model_module_version = MODULE_VERSION;
// Global context for creating the gradients
static ctx: CanvasRenderingContext2D = getContext(document.createElement('canvas'));
}
class GradientModel extends WidgetModel {
defaults() {
return {...super.defaults(),
_model_module: GradientModel.model_module,
_model_module_version: GradientModel.model_module_version,
x0: 0.,
y0: 0.,
x1: 0.,
y1: 0.,
color_stops: [],
};
}
initialize(attributes: any, options: any) {
super.initialize(attributes, options);
this.createGradient();
for (const colorStop of this.get('color_stops')) {
this.value.addColorStop(colorStop[0], colorStop[1]);
}
}
protected createGradient() {
this.value = GradientModel.ctx.createLinearGradient(
this.get('x0'), this.get('y0'),
this.get('x1'), this.get('y1')
);
}
value: CanvasGradient;
static model_module = MODULE_NAME;
static model_module_version = MODULE_VERSION;
// Global context for creating the gradients
static ctx: CanvasRenderingContext2D = getContext(document.createElement('canvas'));
}
export
class LinearGradientModel extends GradientModel {
defaults() {
return {...super.defaults(),
_model_name: LinearGradientModel.model_name,
};
}
static model_name = 'LinearGradientModel';
}
export
class RadialGradientModel extends GradientModel {
defaults() {
return {...super.defaults(),
_model_name: RadialGradientModel.model_name,
r0: 0.,
r1: 0.,
};
}
protected createGradient() {
this.value = GradientModel.ctx.createRadialGradient(
this.get('x0'), this.get('y0'), this.get('r0'),
this.get('x1'), this.get('y1'), this.get('r1')
);
}
static model_name = 'RadialGradientModel';
}
export
class CanvasModel extends DOMWidgetModel {
defaults() {
return {...super.defaults(),
_model_name: CanvasModel.model_name,
_model_module: CanvasModel.model_module,
_model_module_version: CanvasModel.model_module_version,
_view_name: CanvasModel.view_name,
_view_module: CanvasModel.view_module,
_view_module_version: CanvasModel.view_module_version,
width: 700,
height: 500,
sync_image_data: false,
image_data: null,
};
}
static serializers: ISerializers = {
...DOMWidgetModel.serializers,
image_data: {
serialize: serializeImageData,
deserialize: deserializeImageData
}
}
static ATTRS = [
'fillStyle', 'strokeStyle', 'globalAlpha', 'font', 'textAlign',
'textBaseline', 'direction', 'globalCompositeOperation',
'lineWidth', 'lineCap', 'lineJoin', 'miterLimit', 'lineDashOffset',
'shadowOffsetX', 'shadowOffsetY', 'shadowBlur', 'shadowColor',
];
initialize(attributes: any, options: any) {
super.initialize(attributes, options);
this.canvas = document.createElement('canvas');
this.ctx = getContext(this.canvas);
this.resizeCanvas();
this.drawImageData();
this.on_some_change(['width', 'height'], this.resizeCanvas, this);
this.on('change:sync_image_data', this.syncImageData.bind(this));
this.on('msg:custom', this.onCommand.bind(this));
this.send({ event: 'client_ready' }, {});
}
private async drawImageData() {
if (this.get('image_data') !== null) {
const img = await fromBytes(this.get('image_data'));
this.ctx.drawImage(img, 0, 0);
this.trigger('new-frame');
}
}
private async onCommand(command: any, buffers: any) {
// Retrieve the commands buffer as an object (list of commands)
const commands = JSON.parse(Buffer.from(getTypedArray(buffers[0], command)).toString('utf-8'));
await this.processCommand(commands, buffers.slice(1, buffers.length));
this.forEachView((view: CanvasView) => {
view.updateCanvas();
});
this.trigger('new-frame');
this.syncImageData();
}
private async processCommand(command: any, buffers: any) {
// If it's a list of commands
if (command instanceof Array && command[0] instanceof Array) {
let remainingBuffers = buffers;
for (const subcommand of command) {
let subbuffers = [];
const nBuffers: Number = subcommand[2];
if (nBuffers) {
subbuffers = remainingBuffers.slice(0, nBuffers);
remainingBuffers = remainingBuffers.slice(nBuffers)
}
await this.processCommand(subcommand, subbuffers);
}
return;
}
const name: string = COMMANDS[command[0]];
const args: any[] = command[1];
switch (name) {
case 'sleep':
await this.sleep(args[0]);
break;
case 'fillRect':
this.fillRect(args[0], args[1], args[2], args[3]);
break;
case 'strokeRect':
this.strokeRect(args[0], args[1], args[2], args[3]);
break;
case 'fillRects':
this.drawRects(args, buffers, this.fillRect.bind(this));
break;
case 'strokeRects':
this.drawRects(args, buffers, this.strokeRect.bind(this));
break;
case 'fillArc':
this.fillArc(args[0], args[1], args[2], args[3], args[4], args[5]);
break;
case 'strokeArc':
this.strokeArc(args[0], args[1], args[2], args[3], args[4], args[5]);
break;
case 'fillArcs':
this.drawArcs(args, buffers, this.fillArc.bind(this));
break;
case 'strokeArcs':
this.drawArcs(args, buffers, this.strokeArc.bind(this));
break;
case 'fillCircle':
this.fillCircle(args[0], args[1], args[2]);
break;
case 'strokeCircle':
this.strokeCircle(args[0], args[1], args[2]);
break;
case 'fillCircles':
this.drawCircles(args, buffers, this.fillCircle.bind(this));
break;
case 'strokeCircles':
this.drawCircles(args, buffers, this.strokeCircle.bind(this));
break;
case 'strokeLine':
this.strokeLine(args, buffers);
break;
case 'strokeLines':
this.strokeLines(args, buffers);
break;
case 'fillPolygon':
this.fillPolygon(args, buffers);
break;
case 'strokePolygon':
this.strokePolygon(args, buffers);
break;
case 'fillPath':
await this.fillPath(args, buffers);
break;
case 'drawImage':
await this.drawImage(args, buffers);
break;
case 'putImageData':
this.putImageData(args, buffers);
break;
case 'set':
await this.setAttr(args[0], args[1]);
break;
case 'clear':
this.clearCanvas();
break;
default:
this.executeCommand(name, args);
break;
}
}
private async sleep(time: number) {
this.forEachView((view: CanvasView) => {
view.updateCanvas();
});
this.trigger('new-frame');
this.syncImageData();
await new Promise(resolve => setTimeout(resolve, time));
}
protected fillRect(x: number, y: number, width: number, height: number) {
this.ctx.fillRect(x, y, width, height);
}
protected strokeRect(x: number, y: number, width: number, height: number) {
this.ctx.strokeRect(x, y, width, height);
}
private drawRects(args: any[], buffers: any, callback: (x: number, y: number, width: number, height: number) => void) {
const x = getArg(args[0], buffers);
const y = getArg(args[1], buffers);
const width = getArg(args[2], buffers);
const height = getArg(args[3], buffers);
const numberRects = Math.min(x.length, y.length, width.length, height.length);
for (let idx = 0; idx < numberRects; ++idx) {
callback(x.getItem(idx), y.getItem(idx), width.getItem(idx), height.getItem(idx));
}
}
protected fillArc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise: boolean) {
this.ctx.beginPath();
this.ctx.moveTo(x, y); // Move to center
this.ctx.lineTo(x + radius * Math.cos(startAngle), y + radius * Math.sin(startAngle)); // Line to beginning of the arc
this.ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
this.ctx.lineTo(x, y); // Line to center
this.ctx.fill();
this.ctx.closePath();
}
protected strokeArc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise: boolean) {
this.ctx.beginPath();
this.ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
this.ctx.stroke();
this.ctx.closePath();
}
private drawArcs(args: any[], buffers: any, callback: (x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise: boolean) => void) {
const x = getArg(args[0], buffers);
const y = getArg(args[1], buffers);
const radius = getArg(args[2], buffers);
const startAngle = getArg(args[3], buffers);
const endAngle = getArg(args[4], buffers);
const anticlockwise = getArg(args[5], buffers);
const numberArcs = Math.min(
x.length, y.length, radius.length,
startAngle.length, endAngle.length
);
for (let idx = 0; idx < numberArcs; ++idx) {
callback(
x.getItem(idx), y.getItem(idx), radius.getItem(idx),
startAngle.getItem(idx), endAngle.getItem(idx),
anticlockwise.getItem(idx)
)
}
}
protected fillCircle(x: number, y: number, radius: number) {
this.ctx.beginPath();
this.ctx.arc(x, y, radius, 0, 2 * Math.PI);
this.ctx.fill();
this.ctx.closePath();
}
protected strokeCircle(x: number, y: number, radius: number) {
this.ctx.beginPath();
this.ctx.arc(x, y, radius, 0, 2 * Math.PI);
this.ctx.stroke();
this.ctx.closePath();
}
private drawCircles(args: any[], buffers: any, callback: (x: number, y: number, radius: number) => void) {
const x = getArg(args[0], buffers);
const y = getArg(args[1], buffers);
const radius = getArg(args[2], buffers);
const numberCircles = Math.min(x.length, y.length, radius.length);
for (let idx = 0; idx < numberCircles; ++idx) {
callback(x.getItem(idx), y.getItem(idx), radius.getItem(idx))
}
}
protected strokeLine(args: any[], buffers: any) {
this.ctx.beginPath();
this.ctx.moveTo(args[0], args[1]);
this.ctx.lineTo(args[2], args[3]);
this.ctx.stroke();
this.ctx.closePath();
}
protected strokeLines(args: any[], buffers: any) {
this.ctx.beginPath();
const points = getArg(args[0], buffers);
// Move to the first point, then create lines between points
this.ctx.moveTo(points.getItem(0), points.getItem(1));
for (let idx = 2; idx < points.length; idx += 2) {
this.ctx.lineTo(points.getItem(idx), points.getItem(idx + 1));
}
this.ctx.stroke();
this.ctx.closePath();
}
protected fillPolygon(args: any[], buffers: any) {
this.ctx.beginPath();
const points = getArg(args[0], buffers);
// Move to the first point, then create lines between points
this.ctx.moveTo(points.getItem(0), points.getItem(1));
for (let idx = 2; idx < points.length; idx += 2) {
this.ctx.lineTo(points.getItem(idx), points.getItem(idx + 1));
}
this.ctx.closePath();
this.ctx.fill();
}
protected strokePolygon(args: any[], buffers: any) {
this.ctx.beginPath();
const points = getArg(args[0], buffers);
// Move to the first point, then create lines between points
this.ctx.moveTo(points.getItem(0), points.getItem(1));
for (let idx = 2; idx < points.length; idx += 2) {
this.ctx.lineTo(points.getItem(idx), points.getItem(idx + 1));
}
this.ctx.closePath();
this.ctx.stroke();
}
protected async fillPath(args: any[], buffers: any) {
const [serializedPath] = args;
const path = await unpack_models(serializedPath, this.widget_manager);
this.ctx.fill(path.value);
}
private async drawImage(args: any[], buffers: any) {
const [serializedImage, x, y, width, height] = args;
const image = await unpack_models(serializedImage, this.widget_manager);
if (image instanceof CanvasModel || image instanceof MultiCanvasModel) {
this._drawImage(image.canvas, x, y, width, height);
return;
}
if (image.get('_model_name') == 'ImageModel') {
const img = await createImageFromWidget(image);
this._drawImage(img, x, y, width, height);
}
}
private _drawImage(image: HTMLCanvasElement | HTMLImageElement,
x: number, y: number,
width: number | undefined, height: number | undefined) {
if (width === undefined || height === undefined) {
this.ctx.drawImage(image, x, y);
} else {
this.ctx.drawImage(image, x, y, width, height);
}
}
private putImageData(args: any[], buffers: any) {
const [bufferMetadata, dx, dy] = args;
const width = bufferMetadata.shape[1];
const height = bufferMetadata.shape[0];
const data = new Uint8ClampedArray(buffers[0].buffer);
const imageData = new ImageData(data, width, height);
// Draw on a temporary off-screen canvas. This is a workaround for `putImageData` to support transparency.
const offscreenCanvas = document.createElement('canvas');
offscreenCanvas.width = width;
offscreenCanvas.height = height;
getContext(offscreenCanvas).putImageData(imageData, 0, 0);
this.ctx.drawImage(offscreenCanvas, dx, dy);
}
protected async setAttr(attr: number, value: any) {
if (typeof value === 'string' && value.startsWith('IPY')) {
const widgetModel: GradientModel = await unpack_models(value, this.widget_manager);
value = widgetModel.value;
}
(this.ctx as any)[CanvasModel.ATTRS[attr]] = value;
}
private clearCanvas() {
this.forEachView((view: CanvasView) => {
view.clear();
});
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
protected executeCommand(name: string, args: any[] = []) {
(this.ctx as any)[name](...args);
}
private forEachView(callback: (view: CanvasView) => void) {
for (const view_id in this.views) {
this.views[view_id].then((view: CanvasView) => {
callback(view);
});
}
}
private resizeCanvas() {
this.canvas.setAttribute('width', this.get('width'));
this.canvas.setAttribute('height', this.get('height'));
}
private async syncImageData() {
if (!this.get('sync_image_data')) {
return;
}
const bytes = await toBytes(this.canvas);
this.set('image_data', bytes);
this.save_changes();
}
static model_name = 'CanvasModel';
static model_module = MODULE_NAME;
static model_module_version = MODULE_VERSION;
static view_name = 'CanvasView';
static view_module = MODULE_NAME;
static view_module_version = MODULE_VERSION;
canvas: HTMLCanvasElement;
ctx: CanvasRenderingContext2D;
views: Dict<Promise<CanvasView>>;
}
export
class RoughCanvasModel extends CanvasModel {
static ROUGH_ATTRS: string[] = new Array(100).concat(['roughFillStyle', 'roughness', 'bowing']);
defaults() {
return {...super.defaults(),
_model_name: RoughCanvasModel.model_name,
};
}
initialize(attributes: any, options: any) {
super.initialize(attributes, options);
this.roughCanvas = new RoughCanvas(this.canvas);
}
protected fillRect(x: number, y: number, width: number, height: number) {
this.roughCanvas.rectangle(x, y, width, height, this.getRoughFillStyle());
}
protected strokeRect(x: number, y: number, width: number, height: number) {
this.roughCanvas.rectangle(x, y, width, height, this.getRoughStrokeStyle());
}
protected fillCircle(x: number, y: number, radius: number) {
this.roughCanvas.circle(x, y, 2. * radius, this.getRoughFillStyle());
}
protected strokeCircle(x: number, y: number, radius: number) {
this.roughCanvas.circle(x, y, 2. * radius, this.getRoughStrokeStyle());
}
protected strokeLine(args: any[], buffers: any) {
this.roughCanvas.line(args[0], args[1], args[2], args[3], this.getRoughStrokeStyle());
}
protected strokeLines(args: any[], buffers: any) {
const points = getArg(args[0], buffers);
const polygon: [number, number][] = [];
for (let idx = 0; idx < points.length; idx += 2) {
polygon.push([points.getItem(idx), points.getItem(idx + 1)]);
}
this.roughCanvas.linearPath(polygon, this.getRoughStrokeStyle());
}
protected async fillPath(args: any[], buffers: any) {
const [serializedPath] = args;
const path = await unpack_models(serializedPath, this.widget_manager);
this.roughCanvas.path(path.get('value'), this.getRoughFillStyle());
}
protected fillArc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise: boolean) {
const ellipseSize = 2. * radius;
// The following is needed because roughjs does not allow a clockwise draw
const start = anticlockwise ? endAngle : startAngle;
const end = anticlockwise ? startAngle + 2. * Math.PI : endAngle;
this.roughCanvas.arc(x, y, ellipseSize, ellipseSize, start, end, true, this.getRoughFillStyle());
}
protected strokeArc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise: boolean) {
const ellipseSize = 2. * radius;
// The following is needed because roughjs does not allow a clockwise draw
const start = anticlockwise ? endAngle : startAngle;
const end = anticlockwise ? startAngle + 2. * Math.PI : endAngle;
this.roughCanvas.arc(x, y, ellipseSize, ellipseSize, start, end, false, this.getRoughStrokeStyle());
}
protected fillPolygon(args: any[], buffers: any) {
const points = getArg(args[0], buffers);
const polygon: [number, number][] = [];
for (let idx = 0; idx < points.length; idx += 2) {
polygon.push([points.getItem(idx), points.getItem(idx + 1)]);
}
this.roughCanvas.polygon(polygon, this.getRoughFillStyle());
}
protected strokePolygon(args: any[], buffers: any) {
const points = getArg(args[0], buffers);
const polygon: [number, number][] = [];
for (let idx = 0; idx < points.length; idx += 2) {
polygon.push([points.getItem(idx), points.getItem(idx + 1)]);
}
this.roughCanvas.polygon(polygon, this.getRoughStrokeStyle());
}
protected async setAttr(attr: number, value: any) {
if (RoughCanvasModel.ROUGH_ATTRS[attr]) {
(this as any)[RoughCanvasModel.ROUGH_ATTRS[attr]] = value;
return;
}
await super.setAttr(attr, value);
}
private getRoughFillStyle() {
const fill = this.ctx.fillStyle as string;
const lineWidth = this.ctx.lineWidth;
return {
fill,
fillStyle: this.roughFillStyle,
fillWeight: lineWidth / 2.,
hachureGap: lineWidth * 4.,
curveStepCount: 18,
strokeWidth: 0.001, // This is to ensure there is no stroke,
roughness: this.roughness,
bowing: this.bowing,
};
}
private getRoughStrokeStyle() {
const stroke = this.ctx.strokeStyle as string;
const lineWidth = this.ctx.lineWidth;
return {
stroke,
strokeWidth: lineWidth,
roughness: this.roughness,
bowing: this.bowing,
curveStepCount: 18,
};
}
static model_name = 'RoughCanvasModel';
roughCanvas: RoughCanvas;
roughFillStyle: string = 'hachure';
roughness: number = 1.;
bowing: number = 1.;
}
export
class CanvasView extends DOMWidgetView {
render() {
this.ctx = getContext(this.el);
this.resizeCanvas();
this.model.on_some_change(['width', 'height'], this.resizeCanvas, this);
this.el.addEventListener('mousemove', { handleEvent: this.onMouseMove.bind(this) });
this.el.addEventListener('mousedown', { handleEvent: this.onMouseDown.bind(this) });
this.el.addEventListener('mouseup', { handleEvent: this.onMouseUp.bind(this) });
this.el.addEventListener('mouseout', { handleEvent: this.onMouseOut.bind(this) });
this.el.addEventListener('touchstart', { handleEvent: this.onTouchStart.bind(this) });
this.el.addEventListener('touchend', { handleEvent: this.onTouchEnd.bind(this) });
this.el.addEventListener('touchmove', { handleEvent: this.onTouchMove.bind(this) });
this.el.addEventListener('touchcancel', { handleEvent: this.onTouchCancel.bind(this) });
this.updateCanvas();
}
clear() {
this.ctx.clearRect(0, 0, this.el.width, this.el.height);
}
updateCanvas() {
this.clear();
this.ctx.drawImage(this.model.canvas, 0, 0);
}
protected resizeCanvas() {
this.el.setAttribute('width', this.model.get('width'));
this.el.setAttribute('height', this.model.get('height'));
}
private onMouseMove(event: MouseEvent) {
this.model.send({ event: 'mouse_move', ...this.getCoordinates(event) }, {});
}
private onMouseDown(event: MouseEvent) {
this.model.send({ event: 'mouse_down', ...this.getCoordinates(event) }, {});
}
private onMouseUp(event: MouseEvent) {
this.model.send({ event: 'mouse_up', ...this.getCoordinates(event) }, {});
}
private onMouseOut(event: MouseEvent) {
this.model.send({ event: 'mouse_out', ...this.getCoordinates(event) }, {});
}
private onTouchStart(event: TouchEvent) {
const touches: Touch[] = Array.from(event.touches);
this.model.send({ event: 'touch_start', touches: touches.map(this.getCoordinates.bind(this)) }, {});
}
private onTouchEnd(event: TouchEvent) {
const touches: Touch[] = Array.from(event.touches);
this.model.send({ event: 'touch_end', touches: touches.map(this.getCoordinates.bind(this)) }, {});
}
private onTouchMove(event: TouchEvent) {
const touches: Touch[] = Array.from(event.touches);
this.model.send({ event: 'touch_move', touches: touches.map(this.getCoordinates.bind(this)) }, {});
}
private onTouchCancel(event: TouchEvent) {
const touches: Touch[] = Array.from(event.touches);
this.model.send({ event: 'touch_cancel', touches: touches.map(this.getCoordinates.bind(this)) }, {});
}
protected getCoordinates(event: MouseEvent | Touch) {
const rect = this.el.getBoundingClientRect();
const x = this.el.width * (event.clientX - rect.left) / rect.width;
const y = this.el.height * (event.clientY - rect.top) / rect.height;
return { x, y };
}
get tagName(): string {
return 'canvas';
}
el: HTMLCanvasElement;
ctx: CanvasRenderingContext2D;
model: CanvasModel | MultiCanvasModel;
}
export
class MultiCanvasModel extends DOMWidgetModel {
defaults() {
return {...super.defaults(),
_model_name: MultiCanvasModel.model_name,
_model_module: MultiCanvasModel.model_module,
_model_module_version: MultiCanvasModel.model_module_version,
_view_name: MultiCanvasModel.view_name,
_view_module: MultiCanvasModel.view_module,
_view_module_version: MultiCanvasModel.view_module_version,
_canvases: [],
sync_image_data: false,
image_data: null,
width: 700,
height: 500,
};
}
static serializers: ISerializers = {
...DOMWidgetModel.serializers,
_canvases: { deserialize: (unpack_models as any) },
image_data: { serialize: (bytes: Uint8ClampedArray) => {
return new DataView(bytes.buffer.slice(0));
}}
}
initialize(attributes: any, options: any) {
super.initialize(attributes, options);
this.canvas = document.createElement('canvas');
this.ctx = getContext(this.canvas);
this.resizeCanvas();
this.on_some_change(['width', 'height'], this.resizeCanvas, this);
this.on('change:_canvases', this.updateCanvasModels.bind(this));
this.on('change:sync_image_data', this.syncImageData.bind(this));
this.updateCanvasModels();
}
get canvasModels(): CanvasModel[] {
return this.get('_canvases');
}
private updateCanvasModels() {
// TODO: Remove old listeners
for (const canvasModel of this.canvasModels) {
canvasModel.on('new-frame', this.updateCanvas, this);
}
this.updateCanvas();
}
private updateCanvas() {
this.ctx.clearRect(0, 0, this.get('width'), this.get('height'));
for (const canvasModel of this.canvasModels) {
this.ctx.drawImage(canvasModel.canvas, 0, 0);
}
this.forEachView((view: MultiCanvasView) => {
view.updateCanvas();
});
this.syncImageData();
}
private resizeCanvas() {
this.canvas.setAttribute('width', this.get('width'));
this.canvas.setAttribute('height', this.get('height'));
}
private async syncImageData() {
if (!this.get('sync_image_data')) {
return;
}
const bytes = await toBytes(this.canvas);
this.set('image_data', bytes);
this.save_changes();
}
private forEachView(callback: (view: MultiCanvasView) => void) {
for (const view_id in this.views) {
this.views[view_id].then((view: MultiCanvasView) => {
callback(view);
});
}
}
canvas: HTMLCanvasElement;
ctx: CanvasRenderingContext2D;
views: Dict<Promise<MultiCanvasView>>;
static model_name = 'MultiCanvasModel';
static model_module = MODULE_NAME;
static model_module_version = MODULE_VERSION;
static view_name = 'MultiCanvasView';
static view_module = MODULE_NAME;
static view_module_version = MODULE_VERSION;
}
export
class MultiCanvasView extends CanvasView {
model: MultiCanvasModel;
} | the_stack |
import * as program from 'commander';
/* tslint:disable */
import request = require('request');
import * as fs from 'fs';
import { logger } from './logger';
import { AlfrescoApi } from '@alfresco/js-api';
const ACTIVITI_CLOUD_APPS = require('./resources').ACTIVITI_CLOUD_APPS;
/* tslint:enable */
let alfrescoJsApiModeler: any;
let alfrescoJsApiDevops: any;
let args: ConfigArgs;
let isValid = true;
const absentApps: any [] = [];
const failingApps: any [] = [];
export interface ConfigArgs {
modelerUsername: string;
modelerPassword: string;
devopsUsername: string;
devopsPassword: string;
clientId: string;
host: string;
identityHost: boolean;
}
export const AAE_MICROSERVICES = [
'deployment-service',
'modeling-service',
'dmn-service'
];
async function healthCheck(nameService: string) {
const url = `${args.host}/${nameService}/actuator/health`;
const pathParams = {}, queryParams = {},
headerParams = {}, formParams = {}, bodyParam = {},
contentTypes = ['application/json'], accepts = ['application/json'];
try {
const health = await alfrescoJsApiModeler.oauth2Auth.callCustomApi(url, 'GET', pathParams, queryParams, headerParams, formParams, bodyParam,
contentTypes, accepts);
if (health.status !== 'UP') {
logger.error(`${nameService} is DOWN `);
isValid = false;
} else {
const reset = '\x1b[0m', green = '\x1b[32m';
logger.info(`${green}${nameService} is UP!${reset}`);
}
} catch (error) {
logger.error(`${nameService} is not reachable error: `, error);
isValid = false;
}
}
async function getApplicationByStatus(status: string) {
const url = `${args.host}/deployment-service/v1/applications/`;
const pathParams = {}, queryParams = { status: status },
headerParams = {}, formParams = {}, bodyParam = {},
contentTypes = ['application/json'], accepts = ['application/json'];
try {
await alfrescoJsApiDevops.login(args.devopsUsername, args.devopsPassword);
return alfrescoJsApiDevops.oauth2Auth.callCustomApi(url, 'GET', pathParams, queryParams, headerParams, formParams, bodyParam,
contentTypes, accepts).on('error', (error) => {
logger.error(`Get application by status ${error} `);
});
} catch (error) {
logger.error(`Get application by status ${error.status} `);
isValid = false;
}
}
function getDescriptors() {
const url = `${args.host}/deployment-service/v1/descriptors`;
const pathParams = {}, queryParams = {},
headerParams = {}, formParams = {}, bodyParam = {},
contentTypes = ['application/json'], accepts = ['application/json'];
try {
return alfrescoJsApiDevops.oauth2Auth.callCustomApi(url, 'GET', pathParams, queryParams, headerParams, formParams, bodyParam,
contentTypes, accepts);
} catch (error) {
logger.error(`Get Descriptors ${error.status} `);
isValid = false;
}
}
function getProjects() {
const url = `${args.host}/modeling-service/v1/projects`;
const pathParams = {}, queryParams = { maxItems: 1000 },
headerParams = {}, formParams = {}, bodyParam = {},
contentTypes = ['application/json'], accepts = ['application/json'];
try {
return alfrescoJsApiModeler.oauth2Auth.callCustomApi(url, 'GET', pathParams, queryParams, headerParams, formParams, bodyParam,
contentTypes, accepts);
} catch (error) {
logger.error('Get Projects' + error.status);
isValid = false;
}
}
function getProjectRelease(projectId: string) {
const url = `${args.host}/modeling-service/v1/projects/${projectId}/releases`;
const pathParams = {}, queryParams = {},
headerParams = {}, formParams = {}, bodyParam = {},
contentTypes = ['application/json'], accepts = ['application/json'];
try {
return alfrescoJsApiModeler.oauth2Auth.callCustomApi(url, 'GET', pathParams, queryParams, headerParams, formParams, bodyParam,
contentTypes, accepts);
} catch (error) {
logger.error('Get Projects Release' + error.status);
isValid = false;
}
}
async function releaseProject(projectId: string) {
const url = `${args.host}/modeling-service/v1/projects/${projectId}/releases`;
const pathParams = {}, queryParams = {},
headerParams = {}, formParams = {}, bodyParam = {},
contentTypes = ['application/json'], accepts = ['application/json'];
try {
return alfrescoJsApiModeler.oauth2Auth.callCustomApi(url, 'POST', pathParams, queryParams, headerParams, formParams, bodyParam,
contentTypes, accepts);
} catch (error) {
await deleteProject(projectId);
logger.error('Post Projects Release' + error.status);
isValid = false;
}
}
function deleteProject(projectId: string) {
const url = `${args.host}/modeling-service/v1/projects/${projectId}`;
const pathParams = {}, queryParams = {},
headerParams = {}, formParams = {}, bodyParam = {},
contentTypes = ['application/json'], accepts = ['application/json'];
try {
return alfrescoJsApiModeler.oauth2Auth.callCustomApi(url, 'DELETE', pathParams, queryParams, headerParams, formParams, bodyParam,
contentTypes, accepts);
} catch (error) {
logger.error('Delete project error' + error.status);
isValid = false;
}
}
async function importAndReleaseProject(absoluteFilePath: string) {
const fileContent = await fs.createReadStream(absoluteFilePath);
try {
const project = await alfrescoJsApiModeler.oauth2Auth.callCustomApi(`${args.host}/modeling-service/v1/projects/import`, 'POST', {}, {}, {}, { file: fileContent }, {}, ['multipart/form-data'], ['application/json']);
logger.info(`Project imported`);
logger.info(`Create release`);
const release = await alfrescoJsApiModeler.oauth2Auth.callCustomApi(`${args.host}/modeling-service/v1/projects/${project.entry.id}/releases`, 'POST', {}, {}, {}, {}, {},
['application/json'], ['application/json']);
return release;
} catch (error) {
logger.error(`Not able to import the project/create the release ${absoluteFilePath} with status: ${error}`);
isValid = false;
throw(error);
}
}
function deleteDescriptor(name: string) {
const url = `${args.host}/deployment-service/v1/descriptors/${name}`;
const pathParams = {}, queryParams = {},
headerParams = {}, formParams = {}, bodyParam = {},
contentTypes = ['application/json'], accepts = ['application/json'];
try {
return alfrescoJsApiDevops.oauth2Auth.callCustomApi(url, 'DELETE', pathParams, queryParams, headerParams, formParams, bodyParam,
contentTypes, accepts);
} catch (error) {
logger.error('Delete descriptor' + error.status);
isValid = false;
}
}
function deploy(model: any) {
const url = `${args.host}/deployment-service/v1/applications/`;
const pathParams = {}, queryParams = {},
headerParams = {}, formParams = {}, bodyParam = model,
contentTypes = ['application/json'], accepts = ['application/json'];
try {
return alfrescoJsApiDevops.oauth2Auth.callCustomApi(url, 'POST', pathParams, queryParams, headerParams, formParams, bodyParam,
contentTypes, accepts);
} catch (error) {
logger.error('Deploy post' + error.status);
isValid = false;
}
}
function getAlfrescoJsApiInstance(configArgs: ConfigArgs) {
const config = {
provider: 'BPM',
hostBpm: `${configArgs.host}`,
authType: 'OAUTH',
oauth2: {
host: `${configArgs.host}/auth/realms/alfresco`,
clientId: `${configArgs.clientId}`,
scope: 'openid',
secret: '',
implicitFlow: false,
silentLogin: false,
redirectUri: '/'
}
};
return new AlfrescoApi(config);
}
async function deployMissingApps() {
const deployedApps = await getApplicationByStatus('');
findMissingApps(deployedApps.list.entries);
findFailingApps(deployedApps.list.entries);
if (failingApps.length > 0) {
failingApps.forEach( app => {
const reset = '\x1b[0m', bright = '\x1b[1m', red = '\x1b[31m';
logger.error(`${red}${bright}ERROR: App ${app.entry.name} down or inaccessible ${reset}${red} with status ${app.entry.status}${reset}`);
});
process.exit(1);
} else if (absentApps.length > 0) {
logger.warn(`Missing apps: ${JSON.stringify(absentApps)}`);
await checkIfAppIsReleased(absentApps);
} else {
const reset = '\x1b[0m', green = '\x1b[32m';
logger.info(`${green}All the apps are correctly deployed${reset}`);
}
}
async function checkIfAppIsReleased(missingApps: any []) {
const projectList = await getProjects();
let TIME = 5000;
let noError = true;
for (let i = 0; i < missingApps.length; i++) {
noError = true;
const currentAbsentApp = missingApps[i];
const project = projectList.list.entries.find((currentApp: any) => {
return currentAbsentApp.name === currentApp.entry.name;
});
let projectRelease: any;
if (project === undefined) {
logger.warn('Missing project: Create the project for ' + currentAbsentApp.name);
try {
projectRelease = await importProjectAndRelease(currentAbsentApp);
} catch (error) {
logger.info(`error status ${error.status}`);
if (error.status !== 409) {
logger.info(`Not possible to upload the project ${currentAbsentApp.name} status : ${JSON.stringify(error)}`);
process.exit(1);
} else {
logger.error(`Not possible to upload the project because inconsistency CS - Modelling try to delete manually the node`);
process.exit(1);
}
}
} else {
TIME += 5000;
logger.info('Project ' + project.entry.name + ' found');
const projectReleaseList = await getProjectRelease(project.entry.id);
if (projectReleaseList.list.entries.length === 0) {
logger.warn('Project needs release');
projectRelease = await releaseProject(project);
logger.warn(`Project released: ${projectRelease.id}`);
} else {
logger.info('Project already has release');
// getting the latest project release
let currentReleaseVersion = -1;
projectReleaseList.list.entries.forEach((currentRelease: any) => {
if (currentRelease.entry.version > currentReleaseVersion) {
currentReleaseVersion = currentRelease.entry.version;
projectRelease = currentRelease;
}
});
}
}
if (noError) {
await checkDescriptorExist(currentAbsentApp.name);
await sleep(TIME);
const deployPayload = {
'name': currentAbsentApp.name,
'releaseId': projectRelease.entry.id,
'security': currentAbsentApp.security,
'infrastructure': currentAbsentApp.infrastructure,
'variables': currentAbsentApp.variables
};
await deploy(deployPayload);
}
}
}
async function checkDescriptorExist(name: string) {
logger.info(`Check descriptor ${name} exist in the list `);
const descriptorList = await getDescriptors();
if (descriptorList && descriptorList.list && descriptorList.entries) {
for (const descriptor of descriptorList.list.entries) {
if (descriptor.entry.name === name) {
if (descriptor.entry.deployed === false) {
await deleteDescriptor(descriptor.entry.name);
}
}
}
}
return false;
}
async function importProjectAndRelease(app: any) {
await getFileFromRemote(app.file_location, app.name);
logger.warn('Project imported ' + app.name);
const projectRelease = await importAndReleaseProject(`${app.name}.zip`);
await deleteLocalFile(`${app.name}`);
return projectRelease;
}
function findMissingApps(deployedApps: any []) {
Object.keys(ACTIVITI_CLOUD_APPS).forEach((key) => {
const isPresent = deployedApps.find((currentApp: any) => {
return ACTIVITI_CLOUD_APPS[key].name === currentApp.entry.name;
});
if (!isPresent) {
absentApps.push(ACTIVITI_CLOUD_APPS[key]);
}
});
}
function findFailingApps(deployedApps: any []) {
Object.keys(ACTIVITI_CLOUD_APPS).forEach((key) => {
const failingApp = deployedApps.filter((currentApp: any) => {
return ACTIVITI_CLOUD_APPS[key].name === currentApp.entry.name && 'Running' !== currentApp.entry.status;
});
if (failingApp?.length > 0) {
failingApps.push(...failingApp);
}
});
}
async function getFileFromRemote(url: string, name: string) {
return new Promise((resolve, reject) => {
request(url)
.pipe(fs.createWriteStream(`${name}.zip`))
.on('finish', () => {
logger.info(`The file is finished downloading.`);
resolve();
})
.on('error', (error: any) => {
logger.error(`Not possible to download the project form remote`);
reject(error);
});
});
}
async function deleteLocalFile(name: string) {
logger.info(`Deleting local file ${name}.zip`);
fs.unlinkSync(`${name}.zip`);
}
async function sleep(time: number) {
logger.info(`Waiting for ${time} sec...`);
await new Promise(done => setTimeout(done, time));
logger.info(`Done...`);
return;
}
export default async function (configArgs: ConfigArgs) {
await main(configArgs);
}
async function main(configArgs: ConfigArgs) {
args = configArgs;
program
.version('0.1.0')
.description('The following command is in charge of Initializing the activiti cloud env with the default apps' +
'adf-cli init-aae-env --host "gateway_env" --modelerUsername "modelerusername" --modelerPassword "modelerpassword" --devopsUsername "devevopsusername" --devopsPassword "devopspassword"')
.option('-h, --host [type]', 'Host gateway')
.option('--clientId [type]', 'sso client')
.option('--modelerUsername [type]', 'username of a user with role ACTIVIT_MODELER')
.option('--modelerPassword [type]', 'modeler password')
.option('--devopsUsername [type]', 'username of a user with role ACTIVIT_DEVOPS')
.option('--devopsPassword [type]', 'devops password')
.parse(process.argv);
if (process.argv.includes('-h') || process.argv.includes('--help')) {
program.outputHelp();
return;
}
alfrescoJsApiModeler = getAlfrescoJsApiInstance(args);
AAE_MICROSERVICES.map(async (serviceName) => {
await healthCheck(serviceName);
});
await alfrescoJsApiModeler.login(args.modelerUsername, args.modelerPassword).then(() => {
const reset = '\x1b[0m', green = '\x1b[32m';
logger.info(`${green}login SSO ok${reset}`);
}, (error) => {
logger.error(`login SSO error ${JSON.stringify(error)} ${args.modelerUsername}`);
process.exit(1);
});
if (isValid) {
const reset = '\x1b[0m', green = '\x1b[32m';
logger.info(`${green}The environment is up and running ${reset}`);
alfrescoJsApiDevops = getAlfrescoJsApiInstance(args);
await alfrescoJsApiDevops.login(args.devopsUsername, args.devopsPassword).then(() => {
logger.info('login SSO ok devopsUsername');
}, (error) => {
logger.error(`login SSO error ${JSON.stringify(error)} ${args.devopsUsername}`);
process.exit(1);
});
await deployMissingApps();
} else {
logger.error('The environment is not up');
process.exit(1);
}
} | the_stack |
import { Event } from 'vs/base/common/event';
import { IHostService } from 'vs/workbench/services/host/browser/host';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { ILayoutService } from 'vs/platform/layout/browser/layoutService';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IWindowSettings, IWindowOpenable, IOpenWindowOptions, isFolderToOpen, isWorkspaceToOpen, isFileToOpen, IOpenEmptyWindowOptions, IPathData, IFileToOpen, IWorkspaceToOpen, IFolderToOpen } from 'vs/platform/window/common/window';
import { pathsToEditors } from 'vs/workbench/common/editor';
import { whenEditorClosed } from 'vs/workbench/browser/editor';
import { IFileService } from 'vs/platform/files/common/files';
import { ILabelService } from 'vs/platform/label/common/label';
import { ModifierKeyEmitter, trackFocus } from 'vs/base/browser/dom';
import { Disposable } from 'vs/base/common/lifecycle';
import { IBrowserWorkbenchEnvironmentService } from 'vs/workbench/services/environment/browser/environmentService';
import { memoize } from 'vs/base/common/decorators';
import { parseLineAndColumnAware } from 'vs/base/common/extpath';
import { IWorkspaceFolderCreationData } from 'vs/platform/workspaces/common/workspaces';
import { IWorkspaceEditingService } from 'vs/workbench/services/workspaces/common/workspaceEditing';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ILifecycleService, BeforeShutdownEvent, ShutdownReason } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { BrowserLifecycleService } from 'vs/workbench/services/lifecycle/browser/lifecycleService';
import { ILogService } from 'vs/platform/log/common/log';
import { getWorkspaceIdentifier } from 'vs/workbench/services/workspaces/browser/workspaces';
import { localize } from 'vs/nls';
import Severity from 'vs/base/common/severity';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { DomEmitter } from 'vs/base/browser/event';
import { isUndefined } from 'vs/base/common/types';
import { isTemporaryWorkspace, IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { ServicesAccessor } from 'vs/editor/browser/editorExtensions';
import { Schemas } from 'vs/base/common/network';
import { ITextEditorOptions } from 'vs/platform/editor/common/editor';
/**
* A workspace to open in the workbench can either be:
* - a workspace file with 0-N folders (via `workspaceUri`)
* - a single folder (via `folderUri`)
* - empty (via `undefined`)
*/
export type IWorkspace = IWorkspaceToOpen | IFolderToOpen | undefined;
export interface IWorkspaceProvider {
/**
* The initial workspace to open.
*/
readonly workspace: IWorkspace;
/**
* Arbitrary payload from the `IWorkspaceProvider.open` call.
*/
readonly payload?: object;
/**
* Return `true` if the provided [workspace](#IWorkspaceProvider.workspace) is trusted, `false` if not trusted, `undefined` if unknown.
*/
readonly trusted: boolean | undefined;
/**
* Asks to open a workspace in the current or a new window.
*
* @param workspace the workspace to open.
* @param options optional options for the workspace to open.
* - `reuse`: whether to open inside the current window or a new window
* - `payload`: arbitrary payload that should be made available
* to the opening window via the `IWorkspaceProvider.payload` property.
* @param payload optional payload to send to the workspace to open.
*
* @returns true if successfully opened, false otherwise.
*/
open(workspace: IWorkspace, options?: { reuse?: boolean; payload?: object }): Promise<boolean>;
}
enum HostShutdownReason {
/**
* An unknown shutdown reason.
*/
Unknown = 1,
/**
* A shutdown that was potentially triggered by keyboard use.
*/
Keyboard = 2,
/**
* An explicit shutdown via code.
*/
Api = 3
}
export class BrowserHostService extends Disposable implements IHostService {
declare readonly _serviceBrand: undefined;
private workspaceProvider: IWorkspaceProvider;
private shutdownReason = HostShutdownReason.Unknown;
constructor(
@ILayoutService private readonly layoutService: ILayoutService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IFileService private readonly fileService: IFileService,
@ILabelService private readonly labelService: ILabelService,
@IBrowserWorkbenchEnvironmentService private readonly environmentService: IBrowserWorkbenchEnvironmentService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@ILifecycleService private readonly lifecycleService: BrowserLifecycleService,
@ILogService private readonly logService: ILogService,
@IDialogService private readonly dialogService: IDialogService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService
) {
super();
if (environmentService.options?.workspaceProvider) {
this.workspaceProvider = environmentService.options.workspaceProvider;
} else {
this.workspaceProvider = new class implements IWorkspaceProvider {
readonly workspace = undefined;
readonly trusted = undefined;
async open() { return true; }
};
}
this.registerListeners();
}
private registerListeners(): void {
// Veto shutdown depending on `window.confirmBeforeClose` setting
this._register(this.lifecycleService.onBeforeShutdown(e => this.onBeforeShutdown(e)));
// Track modifier keys to detect keybinding usage
this._register(ModifierKeyEmitter.getInstance().event(() => this.updateShutdownReasonFromEvent()));
}
private onBeforeShutdown(e: BeforeShutdownEvent): void {
switch (this.shutdownReason) {
// Unknown / Keyboard shows veto depending on setting
case HostShutdownReason.Unknown:
case HostShutdownReason.Keyboard: {
const confirmBeforeClose = this.configurationService.getValue('window.confirmBeforeClose');
if (confirmBeforeClose === 'always' || (confirmBeforeClose === 'keyboardOnly' && this.shutdownReason === HostShutdownReason.Keyboard)) {
e.veto(true, 'veto.confirmBeforeClose');
}
break;
}
// Api never shows veto
case HostShutdownReason.Api:
break;
}
// Unset for next shutdown
this.shutdownReason = HostShutdownReason.Unknown;
}
private updateShutdownReasonFromEvent(): void {
if (this.shutdownReason === HostShutdownReason.Api) {
return; // do not overwrite any explicitly set shutdown reason
}
if (ModifierKeyEmitter.getInstance().isModifierPressed) {
this.shutdownReason = HostShutdownReason.Keyboard;
} else {
this.shutdownReason = HostShutdownReason.Unknown;
}
}
//#region Focus
@memoize
get onDidChangeFocus(): Event<boolean> {
const focusTracker = this._register(trackFocus(window));
const onVisibilityChange = this._register(new DomEmitter(window.document, 'visibilitychange'));
return Event.latch(Event.any(
Event.map(focusTracker.onDidFocus, () => this.hasFocus),
Event.map(focusTracker.onDidBlur, () => this.hasFocus),
Event.map(onVisibilityChange.event, () => this.hasFocus)
));
}
get hasFocus(): boolean {
return document.hasFocus();
}
async hadLastFocus(): Promise<boolean> {
return true;
}
async focus(): Promise<void> {
window.focus();
}
//#endregion
//#region Window
openWindow(options?: IOpenEmptyWindowOptions): Promise<void>;
openWindow(toOpen: IWindowOpenable[], options?: IOpenWindowOptions): Promise<void>;
openWindow(arg1?: IOpenEmptyWindowOptions | IWindowOpenable[], arg2?: IOpenWindowOptions): Promise<void> {
if (Array.isArray(arg1)) {
return this.doOpenWindow(arg1, arg2);
}
return this.doOpenEmptyWindow(arg1);
}
private async doOpenWindow(toOpen: IWindowOpenable[], options?: IOpenWindowOptions): Promise<void> {
const payload = this.preservePayload();
const fileOpenables: IFileToOpen[] = [];
const foldersToAdd: IWorkspaceFolderCreationData[] = [];
for (const openable of toOpen) {
openable.label = openable.label || this.getRecentLabel(openable);
// Folder
if (isFolderToOpen(openable)) {
if (options?.addMode) {
foldersToAdd.push(({ uri: openable.folderUri }));
} else {
this.doOpen({ folderUri: openable.folderUri }, { reuse: this.shouldReuse(options, false /* no file */), payload });
}
}
// Workspace
else if (isWorkspaceToOpen(openable)) {
this.doOpen({ workspaceUri: openable.workspaceUri }, { reuse: this.shouldReuse(options, false /* no file */), payload });
}
// File (handled later in bulk)
else if (isFileToOpen(openable)) {
fileOpenables.push(openable);
}
}
// Handle Folders to Add
if (foldersToAdd.length > 0) {
this.withServices(accessor => {
const workspaceEditingService: IWorkspaceEditingService = accessor.get(IWorkspaceEditingService);
workspaceEditingService.addFolders(foldersToAdd);
});
}
// Handle Files
if (fileOpenables.length > 0) {
this.withServices(async accessor => {
const editorService = accessor.get(IEditorService);
// Support diffMode
if (options?.diffMode && fileOpenables.length === 2) {
const editors = await pathsToEditors(fileOpenables, this.fileService);
if (editors.length !== 2 || !editors[0].resource || !editors[1].resource) {
return; // invalid resources
}
// Same Window: open via editor service in current window
if (this.shouldReuse(options, true /* file */)) {
editorService.openEditor({
original: { resource: editors[0].resource },
modified: { resource: editors[1].resource },
options: { pinned: true }
});
}
// New Window: open into empty window
else {
const environment = new Map<string, string>();
environment.set('diffFileSecondary', editors[0].resource.toString());
environment.set('diffFilePrimary', editors[1].resource.toString());
this.doOpen(undefined, { payload: Array.from(environment.entries()) });
}
}
// Just open normally
else {
for (const openable of fileOpenables) {
// Same Window: open via editor service in current window
if (this.shouldReuse(options, true /* file */)) {
let openables: IPathData<ITextEditorOptions>[] = [];
// Support: --goto parameter to open on line/col
if (options?.gotoLineMode) {
const pathColumnAware = parseLineAndColumnAware(openable.fileUri.path);
openables = [{
fileUri: openable.fileUri.with({ path: pathColumnAware.path }),
options: {
selection: !isUndefined(pathColumnAware.line) ? { startLineNumber: pathColumnAware.line, startColumn: pathColumnAware.column || 1 } : undefined
}
}];
} else {
openables = [openable];
}
editorService.openEditors(await pathsToEditors(openables, this.fileService), undefined, { validateTrust: true });
}
// New Window: open into empty window
else {
const environment = new Map<string, string>();
environment.set('openFile', openable.fileUri.toString());
if (options?.gotoLineMode) {
environment.set('gotoLineMode', 'true');
}
this.doOpen(undefined, { payload: Array.from(environment.entries()) });
}
}
}
// Support wait mode
const waitMarkerFileURI = options?.waitMarkerFileURI;
if (waitMarkerFileURI) {
(async () => {
// Wait for the resources to be closed in the text editor...
await this.instantiationService.invokeFunction(accessor => whenEditorClosed(accessor, fileOpenables.map(fileOpenable => fileOpenable.fileUri)));
// ...before deleting the wait marker file
await this.fileService.del(waitMarkerFileURI);
})();
}
});
}
}
private withServices(fn: (accessor: ServicesAccessor) => unknown): void {
// Host service is used in a lot of contexts and some services
// need to be resolved dynamically to avoid cyclic dependencies
// (https://github.com/microsoft/vscode/issues/108522)
this.instantiationService.invokeFunction(accessor => fn(accessor));
}
private preservePayload(): Array<unknown> | undefined {
// Selectively copy payload: for now only extension debugging properties are considered
let newPayload: Array<unknown> | undefined = undefined;
if (this.environmentService.extensionDevelopmentLocationURI) {
newPayload = new Array();
newPayload.push(['extensionDevelopmentPath', this.environmentService.extensionDevelopmentLocationURI.toString()]);
if (this.environmentService.debugExtensionHost.debugId) {
newPayload.push(['debugId', this.environmentService.debugExtensionHost.debugId]);
}
if (this.environmentService.debugExtensionHost.port) {
newPayload.push(['inspect-brk-extensions', String(this.environmentService.debugExtensionHost.port)]);
}
}
return newPayload;
}
private getRecentLabel(openable: IWindowOpenable): string {
if (isFolderToOpen(openable)) {
return this.labelService.getWorkspaceLabel(openable.folderUri, { verbose: true });
}
if (isWorkspaceToOpen(openable)) {
return this.labelService.getWorkspaceLabel(getWorkspaceIdentifier(openable.workspaceUri), { verbose: true });
}
return this.labelService.getUriLabel(openable.fileUri);
}
private shouldReuse(options: IOpenWindowOptions = Object.create(null), isFile: boolean): boolean {
if (options.waitMarkerFileURI) {
return true; // always handle --wait in same window
}
const windowConfig = this.configurationService.getValue<IWindowSettings | undefined>('window');
const openInNewWindowConfig = isFile ? (windowConfig?.openFilesInNewWindow || 'off' /* default */) : (windowConfig?.openFoldersInNewWindow || 'default' /* default */);
let openInNewWindow = (options.preferNewWindow || !!options.forceNewWindow) && !options.forceReuseWindow;
if (!options.forceNewWindow && !options.forceReuseWindow && (openInNewWindowConfig === 'on' || openInNewWindowConfig === 'off')) {
openInNewWindow = (openInNewWindowConfig === 'on');
}
return !openInNewWindow;
}
private async doOpenEmptyWindow(options?: IOpenEmptyWindowOptions): Promise<void> {
return this.doOpen(undefined, { reuse: options?.forceReuseWindow });
}
private async doOpen(workspace: IWorkspace, options?: { reuse?: boolean; payload?: object }): Promise<void> {
// When we are in a temporary workspace and are asked to open a local folder
// we swap that folder into the workspace to avoid a window reload. Access
// to local resources is only possible without a window reload because it
// needs user activation.
if (workspace && isFolderToOpen(workspace) && workspace.folderUri.scheme === Schemas.file && isTemporaryWorkspace(this.contextService.getWorkspace())) {
this.withServices(async accessor => {
const workspaceEditingService: IWorkspaceEditingService = accessor.get(IWorkspaceEditingService);
await workspaceEditingService.updateFolders(0, this.contextService.getWorkspace().folders.length, [{ uri: workspace.folderUri }]);
});
return;
}
// We know that `workspaceProvider.open` will trigger a shutdown
// with `options.reuse` so we handle this expected shutdown
if (options?.reuse) {
await this.handleExpectedShutdown(ShutdownReason.LOAD);
}
const opened = await this.workspaceProvider.open(workspace, options);
if (!opened) {
const showResult = await this.dialogService.show(Severity.Warning, localize('unableToOpenExternal', "The browser interrupted the opening of a new tab or window. Press 'Open' to open it anyway."), [localize('open', "Open"), localize('cancel', "Cancel")], { cancelId: 1 });
if (showResult.choice === 0) {
await this.workspaceProvider.open(workspace, options);
}
}
}
async toggleFullScreen(): Promise<void> {
const target = this.layoutService.container;
// Chromium
if (document.fullscreen !== undefined) {
if (!document.fullscreen) {
try {
return await target.requestFullscreen();
} catch (error) {
this.logService.warn('toggleFullScreen(): requestFullscreen failed'); // https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen
}
} else {
try {
return await document.exitFullscreen();
} catch (error) {
this.logService.warn('toggleFullScreen(): exitFullscreen failed');
}
}
}
// Safari and Edge 14 are all using webkit prefix
if ((<any>document).webkitIsFullScreen !== undefined) {
try {
if (!(<any>document).webkitIsFullScreen) {
(<any>target).webkitRequestFullscreen(); // it's async, but doesn't return a real promise.
} else {
(<any>document).webkitExitFullscreen(); // it's async, but doesn't return a real promise.
}
} catch {
this.logService.warn('toggleFullScreen(): requestFullscreen/exitFullscreen failed');
}
}
}
//#endregion
//#region Lifecycle
async restart(): Promise<void> {
this.reload();
}
async reload(): Promise<void> {
await this.handleExpectedShutdown(ShutdownReason.RELOAD);
window.location.reload();
}
async close(): Promise<void> {
await this.handleExpectedShutdown(ShutdownReason.CLOSE);
window.close();
}
private async handleExpectedShutdown(reason: ShutdownReason): Promise<void> {
// Update shutdown reason in a way that we do
// not show a dialog because this is a expected
// shutdown.
this.shutdownReason = HostShutdownReason.Api;
// Signal shutdown reason to lifecycle
return this.lifecycleService.withExpectedShutdown(reason);
}
//#endregion
}
registerSingleton(IHostService, BrowserHostService, true); | the_stack |
import { Constants, PersistentCacheKeys, StringUtils, CommonAuthorizationCodeRequest, ICrypto, AccountEntity, IdTokenEntity, AccessTokenEntity, RefreshTokenEntity, AppMetadataEntity, CacheManager, ServerTelemetryEntity, ThrottlingEntity, ProtocolUtils, Logger, AuthorityMetadataEntity, DEFAULT_CRYPTO_IMPLEMENTATION, AccountInfo, CcsCredential, CcsCredentialType, IdToken } from "@azure/msal-common";
import { CacheOptions } from "../config/Configuration";
import { BrowserAuthError } from "../error/BrowserAuthError";
import { BrowserCacheLocation, InteractionType, TemporaryCacheKeys, InMemoryCacheKeys } from "../utils/BrowserConstants";
import { BrowserStorage } from "./BrowserStorage";
import { MemoryStorage } from "./MemoryStorage";
import { IWindowStorage } from "./IWindowStorage";
import { BrowserProtocolUtils } from "../utils/BrowserProtocolUtils";
/**
* This class implements the cache storage interface for MSAL through browser local or session storage.
* Cookies are only used if storeAuthStateInCookie is true, and are only used for
* parameters such as state and nonce, generally.
*/
export class BrowserCacheManager extends CacheManager {
// Cache configuration, either set by user or default values.
private cacheConfig: Required<CacheOptions>;
// Window storage object (either local or sessionStorage)
private browserStorage: IWindowStorage;
// Internal in-memory storage object used for data used by msal that does not need to persist across page loads
private internalStorage: MemoryStorage;
// Temporary cache
private temporaryCacheStorage: IWindowStorage;
// Client id of application. Used in cache keys to partition cache correctly in the case of multiple instances of MSAL.
private logger: Logger;
// Cookie life calculation (hours * minutes * seconds * ms)
private readonly COOKIE_LIFE_MULTIPLIER = 24 * 60 * 60 * 1000;
constructor(clientId: string, cacheConfig: Required<CacheOptions>, cryptoImpl: ICrypto, logger: Logger) {
super(clientId, cryptoImpl);
this.cacheConfig = cacheConfig;
this.logger = logger;
this.internalStorage = new MemoryStorage();
this.browserStorage = this.setupBrowserStorage(this.cacheConfig.cacheLocation);
this.temporaryCacheStorage = this.setupTemporaryCacheStorage(this.cacheConfig.cacheLocation);
// Migrate any cache entries from older versions of MSAL.
this.migrateCacheEntries();
}
/**
* Returns a window storage class implementing the IWindowStorage interface that corresponds to the configured cacheLocation.
* @param cacheLocation
*/
private setupBrowserStorage(cacheLocation: BrowserCacheLocation | string): IWindowStorage {
switch (cacheLocation) {
case BrowserCacheLocation.LocalStorage:
case BrowserCacheLocation.SessionStorage:
try {
// Temporary cache items will always be stored in session storage to mitigate problems caused by multiple tabs
return new BrowserStorage(cacheLocation);
} catch (e) {
this.logger.verbose(e);
break;
}
case BrowserCacheLocation.MemoryStorage:
default:
break;
}
this.cacheConfig.cacheLocation = BrowserCacheLocation.MemoryStorage;
return new MemoryStorage();
}
/**
*
* @param cacheLocation
*/
private setupTemporaryCacheStorage(cacheLocation: BrowserCacheLocation | string): IWindowStorage {
switch (cacheLocation) {
case BrowserCacheLocation.LocalStorage:
case BrowserCacheLocation.SessionStorage:
try {
// Temporary cache items will always be stored in session storage to mitigate problems caused by multiple tabs
return new BrowserStorage(BrowserCacheLocation.SessionStorage);
} catch (e) {
this.logger.verbose(e);
return this.internalStorage;
}
case BrowserCacheLocation.MemoryStorage:
default:
return this.internalStorage;
}
}
/**
* Migrate all old cache entries to new schema. No rollback supported.
* @param storeAuthStateInCookie
*/
private migrateCacheEntries(): void {
const idTokenKey = `${Constants.CACHE_PREFIX}.${PersistentCacheKeys.ID_TOKEN}`;
const clientInfoKey = `${Constants.CACHE_PREFIX}.${PersistentCacheKeys.CLIENT_INFO}`;
const errorKey = `${Constants.CACHE_PREFIX}.${PersistentCacheKeys.ERROR}`;
const errorDescKey = `${Constants.CACHE_PREFIX}.${PersistentCacheKeys.ERROR_DESC}`;
const idTokenValue = this.browserStorage.getItem(idTokenKey);
const clientInfoValue = this.browserStorage.getItem(clientInfoKey);
const errorValue = this.browserStorage.getItem(errorKey);
const errorDescValue = this.browserStorage.getItem(errorDescKey);
const values = [idTokenValue, clientInfoValue, errorValue, errorDescValue];
const keysToMigrate = [PersistentCacheKeys.ID_TOKEN, PersistentCacheKeys.CLIENT_INFO, PersistentCacheKeys.ERROR, PersistentCacheKeys.ERROR_DESC];
keysToMigrate.forEach((cacheKey:string, index: number) => this.migrateCacheEntry(cacheKey, values[index]));
}
/**
* Utility function to help with migration.
* @param newKey
* @param value
* @param storeAuthStateInCookie
*/
private migrateCacheEntry(newKey: string, value: string|null): void {
if (value) {
this.setTemporaryCache(newKey, value, true);
}
}
/**
* Parses passed value as JSON object, JSON.parse() will throw an error.
* @param input
*/
private validateAndParseJson(jsonValue: string): object | null {
try {
const parsedJson = JSON.parse(jsonValue);
/**
* There are edge cases in which JSON.parse will successfully parse a non-valid JSON object
* (e.g. JSON.parse will parse an escaped string into an unescaped string), so adding a type check
* of the parsed value is necessary in order to be certain that the string represents a valid JSON object.
*
*/
return (parsedJson && typeof parsedJson === "object") ? parsedJson : null;
} catch (error) {
return null;
}
}
/**
* fetches the entry from the browser storage based off the key
* @param key
*/
getItem(key: string): string | null {
return this.browserStorage.getItem(key);
}
/**
* sets the entry in the browser storage
* @param key
* @param value
*/
setItem(key: string, value: string): void {
this.browserStorage.setItem(key, value);
}
/**
* fetch the account entity from the platform cache
* @param accountKey
*/
getAccount(accountKey: string): AccountEntity | null {
const account = this.getItem(accountKey);
if (!account) {
return null;
}
const parsedAccount = this.validateAndParseJson(account);
if (!parsedAccount || !AccountEntity.isAccountEntity(parsedAccount)) {
return null;
}
return CacheManager.toObject<AccountEntity>(new AccountEntity(), parsedAccount);
}
/**
* set account entity in the platform cache
* @param key
* @param value
*/
setAccount(account: AccountEntity): void {
this.logger.trace("BrowserCacheManager.setAccount called");
const key = account.generateAccountKey();
this.setItem(key, JSON.stringify(account));
}
/**
* generates idToken entity from a string
* @param idTokenKey
*/
getIdTokenCredential(idTokenKey: string): IdTokenEntity | null {
const value = this.getItem(idTokenKey);
if (!value) {
this.logger.trace("BrowserCacheManager.getIdTokenCredential: called, no cache hit");
return null;
}
const parsedIdToken = this.validateAndParseJson(value);
if (!parsedIdToken || !IdTokenEntity.isIdTokenEntity(parsedIdToken)) {
this.logger.trace("BrowserCacheManager.getIdTokenCredential: called, no cache hit");
return null;
}
this.logger.trace("BrowserCacheManager.getIdTokenCredential: cache hit");
return CacheManager.toObject(new IdTokenEntity(), parsedIdToken);
}
/**
* set IdToken credential to the platform cache
* @param idToken
*/
setIdTokenCredential(idToken: IdTokenEntity): void {
this.logger.trace("BrowserCacheManager.setIdTokenCredential called");
const idTokenKey = idToken.generateCredentialKey();
this.setItem(idTokenKey, JSON.stringify(idToken));
}
/**
* generates accessToken entity from a string
* @param key
*/
getAccessTokenCredential(accessTokenKey: string): AccessTokenEntity | null {
const value = this.getItem(accessTokenKey);
if (!value) {
this.logger.trace("BrowserCacheManager.getAccessTokenCredential: called, no cache hit");
return null;
}
const parsedAccessToken = this.validateAndParseJson(value);
if (!parsedAccessToken || !AccessTokenEntity.isAccessTokenEntity(parsedAccessToken)) {
this.logger.trace("BrowserCacheManager.getAccessTokenCredential: called, no cache hit");
return null;
}
this.logger.trace("BrowserCacheManager.getAccessTokenCredential: cache hit");
return CacheManager.toObject(new AccessTokenEntity(), parsedAccessToken);
}
/**
* set accessToken credential to the platform cache
* @param accessToken
*/
setAccessTokenCredential(accessToken: AccessTokenEntity): void {
this.logger.trace("BrowserCacheManager.setAccessTokenCredential called");
const accessTokenKey = accessToken.generateCredentialKey();
this.setItem(accessTokenKey, JSON.stringify(accessToken));
}
/**
* generates refreshToken entity from a string
* @param refreshTokenKey
*/
getRefreshTokenCredential(refreshTokenKey: string): RefreshTokenEntity | null {
const value = this.getItem(refreshTokenKey);
if (!value) {
this.logger.trace("BrowserCacheManager.getRefreshTokenCredential: called, no cache hit");
return null;
}
const parsedRefreshToken = this.validateAndParseJson(value);
if (!parsedRefreshToken || !RefreshTokenEntity.isRefreshTokenEntity(parsedRefreshToken)) {
this.logger.trace("BrowserCacheManager.getRefreshTokenCredential: called, no cache hit");
return null;
}
this.logger.trace("BrowserCacheManager.getRefreshTokenCredential: cache hit");
return CacheManager.toObject(new RefreshTokenEntity(), parsedRefreshToken);
}
/**
* set refreshToken credential to the platform cache
* @param refreshToken
*/
setRefreshTokenCredential(refreshToken: RefreshTokenEntity): void {
this.logger.trace("BrowserCacheManager.setRefreshTokenCredential called");
const refreshTokenKey = refreshToken.generateCredentialKey();
this.setItem(refreshTokenKey, JSON.stringify(refreshToken));
}
/**
* fetch appMetadata entity from the platform cache
* @param appMetadataKey
*/
getAppMetadata(appMetadataKey: string): AppMetadataEntity | null {
const value = this.getItem(appMetadataKey);
if (!value) {
this.logger.trace("BrowserCacheManager.getAppMetadata: called, no cache hit");
return null;
}
const parsedMetadata = this.validateAndParseJson(value);
if (!parsedMetadata || !AppMetadataEntity.isAppMetadataEntity(appMetadataKey, parsedMetadata)) {
this.logger.trace("BrowserCacheManager.getAppMetadata: called, no cache hit");
return null;
}
this.logger.trace("BrowserCacheManager.getAppMetadata: cache hit");
return CacheManager.toObject(new AppMetadataEntity(), parsedMetadata);
}
/**
* set appMetadata entity to the platform cache
* @param appMetadata
*/
setAppMetadata(appMetadata: AppMetadataEntity): void {
this.logger.trace("BrowserCacheManager.setAppMetadata called");
const appMetadataKey = appMetadata.generateAppMetadataKey();
this.setItem(appMetadataKey, JSON.stringify(appMetadata));
}
/**
* fetch server telemetry entity from the platform cache
* @param serverTelemetryKey
*/
getServerTelemetry(serverTelemetryKey: string): ServerTelemetryEntity | null {
const value = this.getItem(serverTelemetryKey);
if (!value) {
this.logger.trace("BrowserCacheManager.getServerTelemetry: called, no cache hit");
return null;
}
const parsedMetadata = this.validateAndParseJson(value);
if (!parsedMetadata || !ServerTelemetryEntity.isServerTelemetryEntity(serverTelemetryKey, parsedMetadata)) {
this.logger.trace("BrowserCacheManager.getServerTelemetry: called, no cache hit");
return null;
}
this.logger.trace("BrowserCacheManager.getServerTelemetry: cache hit");
return CacheManager.toObject(new ServerTelemetryEntity(), parsedMetadata);
}
/**
* set server telemetry entity to the platform cache
* @param serverTelemetryKey
* @param serverTelemetry
*/
setServerTelemetry(serverTelemetryKey: string, serverTelemetry: ServerTelemetryEntity): void {
this.logger.trace("BrowserCacheManager.setServerTelemetry called");
this.setItem(serverTelemetryKey, JSON.stringify(serverTelemetry));
}
/**
*
*/
getAuthorityMetadata(key: string) : AuthorityMetadataEntity | null {
const value = this.internalStorage.getItem(key);
if (!value) {
this.logger.trace("BrowserCacheManager.getAuthorityMetadata: called, no cache hit");
return null;
}
const parsedMetadata = this.validateAndParseJson(value);
if (parsedMetadata && AuthorityMetadataEntity.isAuthorityMetadataEntity(key, parsedMetadata)) {
this.logger.trace("BrowserCacheManager.getAuthorityMetadata: cache hit");
return CacheManager.toObject(new AuthorityMetadataEntity(), parsedMetadata);
}
return null;
}
/**
*
*/
getAuthorityMetadataKeys(): Array<string> {
const allKeys = this.internalStorage.getKeys();
return allKeys.filter((key) => {
return this.isAuthorityMetadata(key);
});
}
/**
* Sets wrapper metadata in memory
* @param wrapperSKU
* @param wrapperVersion
*/
setWrapperMetadata(wrapperSKU: string, wrapperVersion: string): void {
this.internalStorage.setItem(InMemoryCacheKeys.WRAPPER_SKU, wrapperSKU);
this.internalStorage.setItem(InMemoryCacheKeys.WRAPPER_VER, wrapperVersion);
}
/**
* Returns wrapper metadata from in-memory storage
*/
getWrapperMetadata(): [string, string] {
const sku = this.internalStorage.getItem(InMemoryCacheKeys.WRAPPER_SKU) || "";
const version = this.internalStorage.getItem(InMemoryCacheKeys.WRAPPER_VER) || "";
return [sku, version];
}
/**
*
* @param entity
*/
setAuthorityMetadata(key: string, entity: AuthorityMetadataEntity): void {
this.logger.trace("BrowserCacheManager.setAuthorityMetadata called");
this.internalStorage.setItem(key, JSON.stringify(entity));
}
/**
* Gets the active account
*/
getActiveAccount(): AccountInfo | null {
const activeAccountIdKey = this.generateCacheKey(PersistentCacheKeys.ACTIVE_ACCOUNT);
const activeAccountId = this.browserStorage.getItem(activeAccountIdKey);
if (!activeAccountId) {
return null;
}
return this.getAccountInfoByFilter({localAccountId: activeAccountId})[0] || null;
}
/**
* Sets the active account's localAccountId in cache
* @param account
*/
setActiveAccount(account: AccountInfo | null): void {
const activeAccountIdKey = this.generateCacheKey(PersistentCacheKeys.ACTIVE_ACCOUNT);
if (account) {
this.logger.verbose("setActiveAccount: Active account set");
this.browserStorage.setItem(activeAccountIdKey, account.localAccountId);
} else {
this.logger.verbose("setActiveAccount: No account passed, active account not set");
this.browserStorage.removeItem(activeAccountIdKey);
}
}
/**
* Gets a list of accounts that match all of the filters provided
* @param account
*/
getAccountInfoByFilter(accountFilter: Partial<Omit<AccountInfo, "idTokenClaims"|"name">>): AccountInfo[] {
const allAccounts = this.getAllAccounts();
return allAccounts.filter((accountObj) => {
if (accountFilter.username && accountFilter.username.toLowerCase() !== accountObj.username.toLowerCase()) {
return false;
}
if (accountFilter.homeAccountId && accountFilter.homeAccountId !== accountObj.homeAccountId) {
return false;
}
if (accountFilter.localAccountId && accountFilter.localAccountId !== accountObj.localAccountId) {
return false;
}
if (accountFilter.tenantId && accountFilter.tenantId !== accountObj.tenantId) {
return false;
}
if (accountFilter.environment && accountFilter.environment !== accountObj.environment) {
return false;
}
return true;
});
}
/**
* fetch throttling entity from the platform cache
* @param throttlingCacheKey
*/
getThrottlingCache(throttlingCacheKey: string): ThrottlingEntity | null {
const value = this.getItem(throttlingCacheKey);
if (!value) {
this.logger.trace("BrowserCacheManager.getThrottlingCache: called, no cache hit");
return null;
}
const parsedThrottlingCache = this.validateAndParseJson(value);
if (!parsedThrottlingCache || !ThrottlingEntity.isThrottlingEntity(throttlingCacheKey, parsedThrottlingCache)) {
this.logger.trace("BrowserCacheManager.getThrottlingCache: called, no cache hit");
return null;
}
this.logger.trace("BrowserCacheManager.getThrottlingCache: cache hit");
return CacheManager.toObject(new ThrottlingEntity(), parsedThrottlingCache);
}
/**
* set throttling entity to the platform cache
* @param throttlingCacheKey
* @param throttlingCache
*/
setThrottlingCache(throttlingCacheKey: string, throttlingCache: ThrottlingEntity): void {
this.logger.trace("BrowserCacheManager.setThrottlingCache called");
this.setItem(throttlingCacheKey, JSON.stringify(throttlingCache));
}
/**
* Gets cache item with given key.
* Will retrieve from cookies if storeAuthStateInCookie is set to true.
* @param key
*/
getTemporaryCache(cacheKey: string, generateKey?: boolean): string | null {
const key = generateKey ? this.generateCacheKey(cacheKey) : cacheKey;
if (this.cacheConfig.storeAuthStateInCookie) {
const itemCookie = this.getItemCookie(key);
if (itemCookie) {
this.logger.trace("BrowserCacheManager.getTemporaryCache: storeAuthStateInCookies set to true, retrieving from cookies");
return itemCookie;
}
}
const value = this.temporaryCacheStorage.getItem(key);
if (!value) {
// If temp cache item not found in session/memory, check local storage for items set by old versions
if (this.cacheConfig.cacheLocation === BrowserCacheLocation.LocalStorage) {
const item = this.browserStorage.getItem(key);
if (item) {
this.logger.trace("BrowserCacheManager.getTemporaryCache: Temporary cache item found in local storage");
return item;
}
}
this.logger.trace("BrowserCacheManager.getTemporaryCache: No cache item found in local storage");
return null;
}
this.logger.trace("BrowserCacheManager.getTemporaryCache: Temporary cache item returned");
return value;
}
/**
* Sets the cache item with the key and value given.
* Stores in cookie if storeAuthStateInCookie is set to true.
* This can cause cookie overflow if used incorrectly.
* @param key
* @param value
*/
setTemporaryCache(cacheKey: string, value: string, generateKey?: boolean): void {
const key = generateKey ? this.generateCacheKey(cacheKey) : cacheKey;
this.temporaryCacheStorage.setItem(key, value);
if (this.cacheConfig.storeAuthStateInCookie) {
this.logger.trace("BrowserCacheManager.setTemporaryCache: storeAuthStateInCookie set to true, setting item cookie");
this.setItemCookie(key, value);
}
}
/**
* Removes the cache item with the given key.
* Will also clear the cookie item if storeAuthStateInCookie is set to true.
* @param key
*/
removeItem(key: string): boolean {
this.browserStorage.removeItem(key);
this.temporaryCacheStorage.removeItem(key);
if (this.cacheConfig.storeAuthStateInCookie) {
this.logger.trace("BrowserCacheManager.removeItem: storeAuthStateInCookie is true, clearing item cookie");
this.clearItemCookie(key);
}
return true;
}
/**
* Checks whether key is in cache.
* @param key
*/
containsKey(key: string): boolean {
return this.browserStorage.containsKey(key) || this.temporaryCacheStorage.containsKey(key);
}
/**
* Gets all keys in window.
*/
getKeys(): string[] {
return [
...this.browserStorage.getKeys(),
...this.temporaryCacheStorage.getKeys()
];
}
/**
* Clears all cache entries created by MSAL.
*/
async clear(): Promise<void> {
// Removes all accounts and their credentials
await this.removeAllAccounts();
this.removeAppMetadata();
// Removes all remaining MSAL cache items
this.getKeys().forEach((cacheKey: string) => {
// Check if key contains msal prefix; For now, we are clearing all the cache items created by MSAL.js
if ((this.browserStorage.containsKey(cacheKey) || this.temporaryCacheStorage.containsKey(cacheKey)) && ((cacheKey.indexOf(Constants.CACHE_PREFIX) !== -1) || (cacheKey.indexOf(this.clientId) !== -1))) {
this.removeItem(cacheKey);
}
});
this.internalStorage.clear();
}
/**
* Add value to cookies
* @param cookieName
* @param cookieValue
* @param expires
*/
setItemCookie(cookieName: string, cookieValue: string, expires?: number): void {
let cookieStr = `${encodeURIComponent(cookieName)}=${encodeURIComponent(cookieValue)};path=/;`;
if (expires) {
const expireTime = this.getCookieExpirationTime(expires);
cookieStr += `expires=${expireTime};`;
}
if (this.cacheConfig.secureCookies) {
cookieStr += "Secure;";
}
document.cookie = cookieStr;
}
/**
* Get one item by key from cookies
* @param cookieName
*/
getItemCookie(cookieName: string): string {
const name = `${encodeURIComponent(cookieName)}=`;
const cookieList = document.cookie.split(";");
for (let i: number = 0; i < cookieList.length; i++) {
let cookie = cookieList[i];
while (cookie.charAt(0) === " ") {
cookie = cookie.substring(1);
}
if (cookie.indexOf(name) === 0) {
return decodeURIComponent(cookie.substring(name.length, cookie.length));
}
}
return "";
}
/**
* Clear all msal-related cookies currently set in the browser. Should only be used to clear temporary cache items.
*/
clearMsalCookies(): void {
const cookiePrefix = `${Constants.CACHE_PREFIX}.${this.clientId}`;
const cookieList = document.cookie.split(";");
cookieList.forEach((cookie: string): void => {
while (cookie.charAt(0) === " ") {
// eslint-disable-next-line no-param-reassign
cookie = cookie.substring(1);
}
if (cookie.indexOf(cookiePrefix) === 0) {
const cookieKey = cookie.split("=")[0];
this.clearItemCookie(cookieKey);
}
});
}
/**
* Clear an item in the cookies by key
* @param cookieName
*/
clearItemCookie(cookieName: string): void {
this.setItemCookie(cookieName, "", -1);
}
/**
* Get cookie expiration time
* @param cookieLifeDays
*/
getCookieExpirationTime(cookieLifeDays: number): string {
const today = new Date();
const expr = new Date(today.getTime() + cookieLifeDays * this.COOKIE_LIFE_MULTIPLIER);
return expr.toUTCString();
}
/**
* Gets the cache object referenced by the browser
*/
getCache(): object {
return this.browserStorage;
}
/**
* interface compat, we cannot overwrite browser cache; Functionality is supported by individual entities in browser
*/
setCache(): void {
// sets nothing
}
/**
* Prepend msal.<client-id> to each key; Skip for any JSON object as Key (defined schemas do not need the key appended: AccessToken Keys or the upcoming schema)
* @param key
* @param addInstanceId
*/
generateCacheKey(key: string): string {
const generatedKey = this.validateAndParseJson(key);
if (!generatedKey) {
if (StringUtils.startsWith(key, Constants.CACHE_PREFIX) || StringUtils.startsWith(key, PersistentCacheKeys.ADAL_ID_TOKEN)) {
return key;
}
return `${Constants.CACHE_PREFIX}.${this.clientId}.${key}`;
}
return JSON.stringify(key);
}
/**
* Create authorityKey to cache authority
* @param state
*/
generateAuthorityKey(stateString: string): string {
const {
libraryState: {
id: stateId
}
} = ProtocolUtils.parseRequestState(this.cryptoImpl, stateString);
return this.generateCacheKey(`${TemporaryCacheKeys.AUTHORITY}.${stateId}`);
}
/**
* Create Nonce key to cache nonce
* @param state
*/
generateNonceKey(stateString: string): string {
const {
libraryState: {
id: stateId
}
} = ProtocolUtils.parseRequestState(this.cryptoImpl, stateString);
return this.generateCacheKey(`${TemporaryCacheKeys.NONCE_IDTOKEN}.${stateId}`);
}
/**
* Creates full cache key for the request state
* @param stateString State string for the request
*/
generateStateKey(stateString: string): string {
// Use the library state id to key temp storage for uniqueness for multiple concurrent requests
const {
libraryState: {
id: stateId
}
} = ProtocolUtils.parseRequestState(this.cryptoImpl, stateString);
return this.generateCacheKey(`${TemporaryCacheKeys.REQUEST_STATE}.${stateId}`);
}
/**
* Gets the cached authority based on the cached state. Returns empty if no cached state found.
*/
getCachedAuthority(cachedState: string): string | null {
const stateCacheKey = this.generateStateKey(cachedState);
const state = this.getTemporaryCache(stateCacheKey);
if (!state) {
return null;
}
const authorityCacheKey = this.generateAuthorityKey(state);
return this.getTemporaryCache(authorityCacheKey);
}
/**
* Updates account, authority, and state in cache
* @param serverAuthenticationRequest
* @param account
*/
updateCacheEntries(state: string, nonce: string, authorityInstance: string, loginHint: string, account: AccountInfo|null): void {
this.logger.trace("BrowserCacheManager.updateCacheEntries called");
// Cache the request state
const stateCacheKey = this.generateStateKey(state);
this.setTemporaryCache(stateCacheKey, state, false);
// Cache the nonce
const nonceCacheKey = this.generateNonceKey(state);
this.setTemporaryCache(nonceCacheKey, nonce, false);
// Cache authorityKey
const authorityCacheKey = this.generateAuthorityKey(state);
this.setTemporaryCache(authorityCacheKey, authorityInstance, false);
if (account) {
const ccsCredential: CcsCredential = {
credential: account.homeAccountId,
type: CcsCredentialType.HOME_ACCOUNT_ID
};
this.setTemporaryCache(TemporaryCacheKeys.CCS_CREDENTIAL, JSON.stringify(ccsCredential), true);
} else if (!StringUtils.isEmpty(loginHint)) {
const ccsCredential: CcsCredential = {
credential: loginHint,
type: CcsCredentialType.UPN
};
this.setTemporaryCache(TemporaryCacheKeys.CCS_CREDENTIAL, JSON.stringify(ccsCredential), true);
}
}
/**
* Reset all temporary cache items
* @param state
*/
resetRequestCache(state: string): void {
this.logger.trace("BrowserCacheManager.resetRequestCache called");
// check state and remove associated cache items
if (!StringUtils.isEmpty(state)) {
this.getKeys().forEach(key => {
if (key.indexOf(state) !== -1) {
this.removeItem(key);
}
});
}
// delete generic interactive request parameters
if (state) {
this.removeItem(this.generateStateKey(state));
this.removeItem(this.generateNonceKey(state));
this.removeItem(this.generateAuthorityKey(state));
}
this.removeItem(this.generateCacheKey(TemporaryCacheKeys.REQUEST_PARAMS));
this.removeItem(this.generateCacheKey(TemporaryCacheKeys.ORIGIN_URI));
this.removeItem(this.generateCacheKey(TemporaryCacheKeys.URL_HASH));
this.removeItem(this.generateCacheKey(TemporaryCacheKeys.CORRELATION_ID));
this.removeItem(this.generateCacheKey(TemporaryCacheKeys.CCS_CREDENTIAL));
this.setInteractionInProgress(false);
}
/**
* Removes temporary cache for the provided state
* @param stateString
*/
cleanRequestByState(stateString: string): void {
this.logger.trace("BrowserCacheManager.cleanRequestByState called");
// Interaction is completed - remove interaction status.
if (stateString) {
const stateKey = this.generateStateKey(stateString);
const cachedState = this.temporaryCacheStorage.getItem(stateKey);
this.logger.infoPii(`BrowserCacheManager.cleanRequestByState: Removing temporary cache items for state: ${cachedState}`);
this.resetRequestCache(cachedState || "");
}
this.clearMsalCookies();
}
/**
* Looks in temporary cache for any state values with the provided interactionType and removes all temporary cache items for that state
* Used in scenarios where temp cache needs to be cleaned but state is not known, such as clicking browser back button.
* @param interactionType
*/
cleanRequestByInteractionType(interactionType: InteractionType): void {
this.logger.trace("BrowserCacheManager.cleanRequestByInteractionType called");
// Loop through all keys to find state key
this.getKeys().forEach((key) => {
// If this key is not the state key, move on
if (key.indexOf(TemporaryCacheKeys.REQUEST_STATE) === -1) {
return;
}
// Retrieve state value, return if not a valid value
const stateValue = this.temporaryCacheStorage.getItem(key);
if (!stateValue) {
return;
}
// Extract state and ensure it matches given InteractionType, then clean request cache
const parsedState = BrowserProtocolUtils.extractBrowserRequestState(this.cryptoImpl, stateValue);
if (parsedState && parsedState.interactionType === interactionType) {
this.logger.infoPii(`BrowserCacheManager.cleanRequestByInteractionType: Removing temporary cache items for state: ${stateValue}`);
this.resetRequestCache(stateValue);
}
});
this.clearMsalCookies();
}
cacheCodeRequest(authCodeRequest: CommonAuthorizationCodeRequest, browserCrypto: ICrypto): void {
this.logger.trace("BrowserCacheManager.cacheCodeRequest called");
const encodedValue = browserCrypto.base64Encode(JSON.stringify(authCodeRequest));
this.setTemporaryCache(TemporaryCacheKeys.REQUEST_PARAMS, encodedValue, true);
}
/**
* Gets the token exchange parameters from the cache. Throws an error if nothing is found.
*/
getCachedRequest(state: string, browserCrypto: ICrypto): CommonAuthorizationCodeRequest {
this.logger.trace("BrowserCacheManager.getCachedRequest called");
// Get token request from cache and parse as TokenExchangeParameters.
const encodedTokenRequest = this.getTemporaryCache(TemporaryCacheKeys.REQUEST_PARAMS, true);
if (!encodedTokenRequest) {
throw BrowserAuthError.createNoTokenRequestCacheError();
}
const parsedRequest = this.validateAndParseJson(browserCrypto.base64Decode(encodedTokenRequest)) as CommonAuthorizationCodeRequest;
if (!parsedRequest) {
throw BrowserAuthError.createUnableToParseTokenRequestCacheError();
}
this.removeItem(this.generateCacheKey(TemporaryCacheKeys.REQUEST_PARAMS));
// Get cached authority and use if no authority is cached with request.
if (StringUtils.isEmpty(parsedRequest.authority)) {
const authorityCacheKey: string = this.generateAuthorityKey(state);
const cachedAuthority = this.getTemporaryCache(authorityCacheKey);
if (!cachedAuthority) {
throw BrowserAuthError.createNoCachedAuthorityError();
}
parsedRequest.authority = cachedAuthority;
}
return parsedRequest;
}
isInteractionInProgress(matchClientId?: boolean): boolean {
const clientId = this.getInteractionInProgress();
if (matchClientId) {
return clientId === this.clientId;
} else {
return !!clientId;
}
}
getInteractionInProgress(): string | null {
const key = `${Constants.CACHE_PREFIX}.${TemporaryCacheKeys.INTERACTION_STATUS_KEY}`;
return this.getTemporaryCache(key, false);
}
setInteractionInProgress(inProgress: boolean): void {
const clientId = this.getInteractionInProgress();
// Ensure we don't overwrite interaction in progress for a different clientId
const key = `${Constants.CACHE_PREFIX}.${TemporaryCacheKeys.INTERACTION_STATUS_KEY}`;
if (inProgress && !clientId) {
// No interaction is in progress
this.setTemporaryCache(key, this.clientId, false);
} else if (!inProgress && clientId === this.clientId) {
this.removeItem(key);
}
}
/**
* Returns username retrieved from ADAL or MSAL v1 idToken
*/
getLegacyLoginHint(): string | null {
// Only check for adal/msal token if no SSO params are being used
const adalIdTokenString = this.getTemporaryCache(PersistentCacheKeys.ADAL_ID_TOKEN);
if (adalIdTokenString) {
this.browserStorage.removeItem(PersistentCacheKeys.ADAL_ID_TOKEN);
this.logger.verbose("Cached ADAL id token retrieved.");
}
// Check for cached MSAL v1 id token
const msalIdTokenString = this.getTemporaryCache(PersistentCacheKeys.ID_TOKEN, true);
if (msalIdTokenString) {
this.removeItem(this.generateCacheKey(PersistentCacheKeys.ID_TOKEN));
this.logger.verbose("Cached MSAL.js v1 id token retrieved");
}
const cachedIdTokenString = msalIdTokenString || adalIdTokenString;
if (cachedIdTokenString) {
const cachedIdToken = new IdToken(cachedIdTokenString, this.cryptoImpl);
if (cachedIdToken.claims && cachedIdToken.claims.preferred_username) {
this.logger.verbose("No SSO params used and ADAL/MSAL v1 token retrieved, setting ADAL/MSAL v1 preferred_username as loginHint");
return cachedIdToken.claims.preferred_username;
}
else if (cachedIdToken.claims && cachedIdToken.claims.upn) {
this.logger.verbose("No SSO params used and ADAL/MSAL v1 token retrieved, setting ADAL/MSAL v1 upn as loginHint");
return cachedIdToken.claims.upn;
}
else {
this.logger.verbose("No SSO params used and ADAL/MSAL v1 token retrieved, however, no account hint claim found. Enable preferred_username or upn id token claim to get SSO.");
}
}
return null;
}
}
export const DEFAULT_BROWSER_CACHE_MANAGER = (clientId: string, logger: Logger): BrowserCacheManager => {
const cacheOptions = {
cacheLocation: BrowserCacheLocation.MemoryStorage,
storeAuthStateInCookie: false,
secureCookies: false
};
return new BrowserCacheManager(clientId, cacheOptions, DEFAULT_CRYPTO_IMPLEMENTATION, logger);
}; | the_stack |
import { ID, GraphSelection, SyrupOperation, copyWithTypeCondition } from "../GraphApi"
import {
CurrencyCode,
WeightUnit,
OrderDisplayFulfillmentStatus,
FulfillmentDisplayStatus,
FulfillmentEventStatus,
} from "../Enums"
export namespace TestQuery7QueryData {
export interface Variables {
first?: number | null;
}
export interface ShopBillingAddress {
__typename: 'MailingAddress';
/**
* The name of the city, district, village, or town.
*/
city?: string | null;
/**
* The name of the customer's company or organization.
*/
company?: string | null;
/**
* The latitude coordinate of the customer address.
*/
latitude?: number | null;
/**
* The longitude coordinate of the customer address.
*/
longitude?: number | null;
}
export interface ShopServices {
__typename: 'FulfillmentService';
/**
* The name of the fulfillment service as seen by merchants.
*/
serviceName: string;
/**
* Human-readable unique identifier for this fulfillment service.
*/
handle: string;
}
export interface ShopOrdersEdgesNodeFulfillmentsEventsEdgesNode {
__typename: 'FulfillmentEvent';
/**
* The status of this fulfillment event.
*/
status: FulfillmentEventStatus;
}
export interface ShopOrdersEdgesNodeFulfillmentsEventsEdges {
__typename: 'FulfillmentEventEdge';
/**
* The item at the end of FulfillmentEventEdge.
*/
node: ShopOrdersEdgesNodeFulfillmentsEventsEdgesNode;
}
export interface ShopOrdersEdgesNodeFulfillmentsEvents {
__typename: 'FulfillmentEventConnection';
/**
* A list of edges.
*/
edges: ShopOrdersEdgesNodeFulfillmentsEventsEdges[];
}
export interface ShopOrdersEdgesNodeFulfillments {
__typename: 'Fulfillment';
/**
* Human readable reference identifier for this fulfillment.
*/
name: string;
/**
* The date and time when the fulfillment was created.
*/
createdAt: string;
/**
* The date and time when the fulfillment went into transit.
*/
inTransitAt?: string | null;
/**
* The date that this fulfillment was delivered.
*/
deliveredAt?: string | null;
/**
* Human readable display status for this fulfillment.
*/
displayStatus?: FulfillmentDisplayStatus | null;
/**
* The history of events associated with this fulfillment.
*/
events: ShopOrdersEdgesNodeFulfillmentsEvents;
}
export interface ShopOrdersEdgesNode {
__typename: 'Order';
/**
* Unique identifier for the order that appears on the order.
* For example, _#1000_ or _Store1001.
* This value is not unique across multiple stores.
*/
name: string;
/**
* Fulfillment status for the order that can be shown to the merchant.
* This field does not capture all the possible details of an order's fulfillment state. It should only be used for display summary purposes.
*/
displayFulfillmentStatus: OrderDisplayFulfillmentStatus;
/**
* List of shipments for the order.
*/
fulfillments: ShopOrdersEdgesNodeFulfillments[];
}
export interface ShopOrdersEdges {
__typename: 'OrderEdge';
/**
* The item at the end of OrderEdge.
*/
node: ShopOrdersEdgesNode;
}
export interface ShopOrders {
__typename: 'OrderConnection';
/**
* A list of edges.
*/
edges: ShopOrdersEdges[];
}
export interface Shop {
__typename: 'Shop';
/**
* The shop's name.
*/
name: string;
/**
* The three letter code for the shop's currency.
*/
currencyCode: CurrencyCode;
/**
* The shop's primary unit of weight for products and shipping.
*/
weightUnit: WeightUnit;
/**
* The shop's billing address information.
*/
billingAddress: ShopBillingAddress;
/**
* List of the shop's installed fulfillment services.
*/
services: ShopServices[];
/**
* List of orders placed on the shop.
*
* @deprecated Use `QueryRoot.orders` instead.
*/
orders: ShopOrders;
}
}
export interface TestQuery7QueryData {
/**
* Returns a Shop resource corresponding to access token used in request.
*/
shop: TestQuery7QueryData.Shop;
}
const document: SyrupOperation<TestQuery7QueryData, TestQuery7QueryData.Variables> = {
id: "fea84634662eff752b6ddb956e3f566e4862ee3a26b0b01dab1ff8872be27700",
name: "TestQuery7",
source: "query TestQuery7(\$first: Int) { __typename shop { __typename name currencyCode weightUnit billingAddress { __typename city company latitude longitude } services: fulfillmentServices { __typename serviceName handle } orders(first: \$first) { __typename edges { __typename node { __typename name displayFulfillmentStatus fulfillments { __typename name createdAt inTransitAt deliveredAt displayStatus events(first: 10) { __typename edges { __typename node { __typename status } } } } } } } } }",
operationType: 'query',
selections: ([
{
name: "__typename",
type: { name: "String", definedType: "Scalar" },
typeCondition: { name: "QueryRoot", definedType: "Object" },
},
{
name: "shop",
type: { name: "Shop", definedType: "Object" },
typeCondition: { name: "QueryRoot", definedType: "Object" },
selections: ([
{
name: "__typename",
type: { name: "String", definedType: "Scalar" },
typeCondition: { name: "Shop", definedType: "Object" },
},
{
name: "name",
type: { name: "String", definedType: "Scalar" },
typeCondition: { name: "Shop", definedType: "Object" },
},
{
name: "currencyCode",
type: { name: "CurrencyCode", definedType: "Scalar" },
typeCondition: { name: "Shop", definedType: "Object" },
},
{
name: "weightUnit",
type: { name: "WeightUnit", definedType: "Scalar" },
typeCondition: { name: "Shop", definedType: "Object" },
},
{
name: "billingAddress",
type: { name: "MailingAddress", definedType: "Object" },
typeCondition: { name: "Shop", definedType: "Object" },
selections: ([
{
name: "__typename",
type: { name: "String", definedType: "Scalar" },
typeCondition: { name: "MailingAddress", definedType: "Object" },
},
{
name: "city",
type: { name: "String", definedType: "Scalar" },
typeCondition: { name: "MailingAddress", definedType: "Object" },
},
{
name: "company",
type: { name: "String", definedType: "Scalar" },
typeCondition: { name: "MailingAddress", definedType: "Object" },
},
{
name: "latitude",
type: { name: "Float", definedType: "Scalar" },
typeCondition: { name: "MailingAddress", definedType: "Object" },
},
{
name: "longitude",
type: { name: "Float", definedType: "Scalar" },
typeCondition: { name: "MailingAddress", definedType: "Object" },
}
] as GraphSelection[])
},
{
name: "fulfillmentServices",
type: { name: "FulfillmentService", definedType: "Object" },
typeCondition: { name: "Shop", definedType: "Object" },
alias: "services",
selections: ([
{
name: "__typename",
type: { name: "String", definedType: "Scalar" },
typeCondition: { name: "FulfillmentService", definedType: "Object" },
},
{
name: "serviceName",
type: { name: "String", definedType: "Scalar" },
typeCondition: { name: "FulfillmentService", definedType: "Object" },
},
{
name: "handle",
type: { name: "String", definedType: "Scalar" },
typeCondition: { name: "FulfillmentService", definedType: "Object" },
}
] as GraphSelection[])
},
{
name: "orders",
type: { name: "OrderConnection", definedType: "Object" },
typeCondition: { name: "Shop", definedType: "Object" },
arguments: { first: { type: "OperationVariableKey", value: "first" } },
selections: ([
{
name: "__typename",
type: { name: "String", definedType: "Scalar" },
typeCondition: { name: "OrderConnection", definedType: "Object" },
},
{
name: "edges",
type: { name: "OrderEdge", definedType: "Object" },
typeCondition: { name: "OrderConnection", definedType: "Object" },
selections: ([
{
name: "__typename",
type: { name: "String", definedType: "Scalar" },
typeCondition: { name: "OrderEdge", definedType: "Object" },
},
{
name: "node",
type: { name: "Order", definedType: "Object" },
typeCondition: { name: "OrderEdge", definedType: "Object" },
selections: ([
{
name: "__typename",
type: { name: "String", definedType: "Scalar" },
typeCondition: { name: "Order", definedType: "Object" },
},
{
name: "name",
type: { name: "String", definedType: "Scalar" },
typeCondition: { name: "Order", definedType: "Object" },
},
{
name: "displayFulfillmentStatus",
type: { name: "OrderDisplayFulfillmentStatus", definedType: "Scalar" },
typeCondition: { name: "Order", definedType: "Object" },
},
{
name: "fulfillments",
type: { name: "Fulfillment", definedType: "Object" },
typeCondition: { name: "Order", definedType: "Object" },
selections: ([
{
name: "__typename",
type: { name: "String", definedType: "Scalar" },
typeCondition: { name: "Fulfillment", definedType: "Object" },
},
{
name: "name",
type: { name: "String", definedType: "Scalar" },
typeCondition: { name: "Fulfillment", definedType: "Object" },
},
{
name: "createdAt",
type: { name: "DateTime", definedType: "Scalar" },
typeCondition: { name: "Fulfillment", definedType: "Object" },
},
{
name: "inTransitAt",
type: { name: "DateTime", definedType: "Scalar" },
typeCondition: { name: "Fulfillment", definedType: "Object" },
},
{
name: "deliveredAt",
type: { name: "DateTime", definedType: "Scalar" },
typeCondition: { name: "Fulfillment", definedType: "Object" },
},
{
name: "displayStatus",
type: { name: "FulfillmentDisplayStatus", definedType: "Scalar" },
typeCondition: { name: "Fulfillment", definedType: "Object" },
},
{
name: "events",
type: { name: "FulfillmentEventConnection", definedType: "Object" },
typeCondition: { name: "Fulfillment", definedType: "Object" },
arguments: { first: { type: "IntValue", value: 10 } },
selections: ([
{
name: "__typename",
type: { name: "String", definedType: "Scalar" },
typeCondition: { name: "FulfillmentEventConnection", definedType: "Object" },
},
{
name: "edges",
type: { name: "FulfillmentEventEdge", definedType: "Object" },
typeCondition: { name: "FulfillmentEventConnection", definedType: "Object" },
selections: ([
{
name: "__typename",
type: { name: "String", definedType: "Scalar" },
typeCondition: { name: "FulfillmentEventEdge", definedType: "Object" },
},
{
name: "node",
type: { name: "FulfillmentEvent", definedType: "Object" },
typeCondition: { name: "FulfillmentEventEdge", definedType: "Object" },
selections: ([
{
name: "__typename",
type: { name: "String", definedType: "Scalar" },
typeCondition: { name: "FulfillmentEvent", definedType: "Object" },
},
{
name: "status",
type: { name: "FulfillmentEventStatus", definedType: "Scalar" },
typeCondition: { name: "FulfillmentEvent", definedType: "Object" },
}
] as GraphSelection[])
}
] as GraphSelection[])
}
] as GraphSelection[])
}
] as GraphSelection[])
}
] as GraphSelection[])
}
] as GraphSelection[])
}
] as GraphSelection[])
}
] as GraphSelection[])
}
] as GraphSelection[])
}
export default document | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* Allows you to manage an Azure SQL Elastic Pool via the `v3.0` API which allows for `vCore` and `DTU` based configurations.
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as azure from "@pulumi/azure";
*
* const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"});
* const exampleSqlServer = new azure.sql.SqlServer("exampleSqlServer", {
* resourceGroupName: exampleResourceGroup.name,
* location: exampleResourceGroup.location,
* version: "12.0",
* administratorLogin: "4dm1n157r470r",
* administratorLoginPassword: "4-v3ry-53cr37-p455w0rd",
* });
* const exampleElasticPool = new azure.mssql.ElasticPool("exampleElasticPool", {
* resourceGroupName: exampleResourceGroup.name,
* location: exampleResourceGroup.location,
* serverName: exampleSqlServer.name,
* licenseType: "LicenseIncluded",
* maxSizeGb: 756,
* sku: {
* name: "GP_Gen5",
* tier: "GeneralPurpose",
* family: "Gen5",
* capacity: 4,
* },
* perDatabaseSettings: {
* minCapacity: 0.25,
* maxCapacity: 4,
* },
* });
* ```
*
* ## Import
*
* SQL Elastic Pool can be imported using the `resource id`, e.g.
*
* ```sh
* $ pulumi import azure:mssql/elasticPool:ElasticPool example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Sql/servers/myserver/elasticPools/myelasticpoolname
* ```
*/
export class ElasticPool extends pulumi.CustomResource {
/**
* Get an existing ElasticPool resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: ElasticPoolState, opts?: pulumi.CustomResourceOptions): ElasticPool {
return new ElasticPool(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'azure:mssql/elasticPool:ElasticPool';
/**
* Returns true if the given object is an instance of ElasticPool. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is ElasticPool {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === ElasticPool.__pulumiType;
}
/**
* Specifies the license type applied to this database. Possible values are `LicenseIncluded` and `BasePrice`.
*/
public readonly licenseType!: pulumi.Output<string>;
/**
* Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.
*/
public readonly location!: pulumi.Output<string>;
/**
* The max data size of the elastic pool in bytes. Conflicts with `maxSizeGb`.
*/
public readonly maxSizeBytes!: pulumi.Output<number>;
/**
* The max data size of the elastic pool in gigabytes. Conflicts with `maxSizeBytes`.
*/
public readonly maxSizeGb!: pulumi.Output<number>;
/**
* The name of the elastic pool. This needs to be globally unique. Changing this forces a new resource to be created.
*/
public readonly name!: pulumi.Output<string>;
/**
* A `perDatabaseSettings` block as defined below.
*/
public readonly perDatabaseSettings!: pulumi.Output<outputs.mssql.ElasticPoolPerDatabaseSettings>;
/**
* The name of the resource group in which to create the elastic pool. This must be the same as the resource group of the underlying SQL server.
*/
public readonly resourceGroupName!: pulumi.Output<string>;
/**
* The name of the SQL Server on which to create the elastic pool. Changing this forces a new resource to be created.
*/
public readonly serverName!: pulumi.Output<string>;
/**
* A `sku` block as defined below.
*/
public readonly sku!: pulumi.Output<outputs.mssql.ElasticPoolSku>;
/**
* A mapping of tags to assign to the resource.
*/
public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* Whether or not this elastic pool is zone redundant. `tier` needs to be `Premium` for `DTU` based or `BusinessCritical` for `vCore` based `sku`. Defaults to `false`.
*/
public readonly zoneRedundant!: pulumi.Output<boolean | undefined>;
/**
* Create a ElasticPool resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args: ElasticPoolArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: ElasticPoolArgs | ElasticPoolState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as ElasticPoolState | undefined;
inputs["licenseType"] = state ? state.licenseType : undefined;
inputs["location"] = state ? state.location : undefined;
inputs["maxSizeBytes"] = state ? state.maxSizeBytes : undefined;
inputs["maxSizeGb"] = state ? state.maxSizeGb : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["perDatabaseSettings"] = state ? state.perDatabaseSettings : undefined;
inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined;
inputs["serverName"] = state ? state.serverName : undefined;
inputs["sku"] = state ? state.sku : undefined;
inputs["tags"] = state ? state.tags : undefined;
inputs["zoneRedundant"] = state ? state.zoneRedundant : undefined;
} else {
const args = argsOrState as ElasticPoolArgs | undefined;
if ((!args || args.perDatabaseSettings === undefined) && !opts.urn) {
throw new Error("Missing required property 'perDatabaseSettings'");
}
if ((!args || args.resourceGroupName === undefined) && !opts.urn) {
throw new Error("Missing required property 'resourceGroupName'");
}
if ((!args || args.serverName === undefined) && !opts.urn) {
throw new Error("Missing required property 'serverName'");
}
if ((!args || args.sku === undefined) && !opts.urn) {
throw new Error("Missing required property 'sku'");
}
inputs["licenseType"] = args ? args.licenseType : undefined;
inputs["location"] = args ? args.location : undefined;
inputs["maxSizeBytes"] = args ? args.maxSizeBytes : undefined;
inputs["maxSizeGb"] = args ? args.maxSizeGb : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["perDatabaseSettings"] = args ? args.perDatabaseSettings : undefined;
inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined;
inputs["serverName"] = args ? args.serverName : undefined;
inputs["sku"] = args ? args.sku : undefined;
inputs["tags"] = args ? args.tags : undefined;
inputs["zoneRedundant"] = args ? args.zoneRedundant : undefined;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(ElasticPool.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering ElasticPool resources.
*/
export interface ElasticPoolState {
/**
* Specifies the license type applied to this database. Possible values are `LicenseIncluded` and `BasePrice`.
*/
licenseType?: pulumi.Input<string>;
/**
* Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.
*/
location?: pulumi.Input<string>;
/**
* The max data size of the elastic pool in bytes. Conflicts with `maxSizeGb`.
*/
maxSizeBytes?: pulumi.Input<number>;
/**
* The max data size of the elastic pool in gigabytes. Conflicts with `maxSizeBytes`.
*/
maxSizeGb?: pulumi.Input<number>;
/**
* The name of the elastic pool. This needs to be globally unique. Changing this forces a new resource to be created.
*/
name?: pulumi.Input<string>;
/**
* A `perDatabaseSettings` block as defined below.
*/
perDatabaseSettings?: pulumi.Input<inputs.mssql.ElasticPoolPerDatabaseSettings>;
/**
* The name of the resource group in which to create the elastic pool. This must be the same as the resource group of the underlying SQL server.
*/
resourceGroupName?: pulumi.Input<string>;
/**
* The name of the SQL Server on which to create the elastic pool. Changing this forces a new resource to be created.
*/
serverName?: pulumi.Input<string>;
/**
* A `sku` block as defined below.
*/
sku?: pulumi.Input<inputs.mssql.ElasticPoolSku>;
/**
* A mapping of tags to assign to the resource.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* Whether or not this elastic pool is zone redundant. `tier` needs to be `Premium` for `DTU` based or `BusinessCritical` for `vCore` based `sku`. Defaults to `false`.
*/
zoneRedundant?: pulumi.Input<boolean>;
}
/**
* The set of arguments for constructing a ElasticPool resource.
*/
export interface ElasticPoolArgs {
/**
* Specifies the license type applied to this database. Possible values are `LicenseIncluded` and `BasePrice`.
*/
licenseType?: pulumi.Input<string>;
/**
* Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.
*/
location?: pulumi.Input<string>;
/**
* The max data size of the elastic pool in bytes. Conflicts with `maxSizeGb`.
*/
maxSizeBytes?: pulumi.Input<number>;
/**
* The max data size of the elastic pool in gigabytes. Conflicts with `maxSizeBytes`.
*/
maxSizeGb?: pulumi.Input<number>;
/**
* The name of the elastic pool. This needs to be globally unique. Changing this forces a new resource to be created.
*/
name?: pulumi.Input<string>;
/**
* A `perDatabaseSettings` block as defined below.
*/
perDatabaseSettings: pulumi.Input<inputs.mssql.ElasticPoolPerDatabaseSettings>;
/**
* The name of the resource group in which to create the elastic pool. This must be the same as the resource group of the underlying SQL server.
*/
resourceGroupName: pulumi.Input<string>;
/**
* The name of the SQL Server on which to create the elastic pool. Changing this forces a new resource to be created.
*/
serverName: pulumi.Input<string>;
/**
* A `sku` block as defined below.
*/
sku: pulumi.Input<inputs.mssql.ElasticPoolSku>;
/**
* A mapping of tags to assign to the resource.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* Whether or not this elastic pool is zone redundant. `tier` needs to be `Premium` for `DTU` based or `BusinessCritical` for `vCore` based `sku`. Defaults to `false`.
*/
zoneRedundant?: pulumi.Input<boolean>;
} | the_stack |
import type {
AnyObject,
PropsOfType,
StringKeyof,
Dictionary,
ExactlyExtends,
NoInfer,
} from './utils';
export interface WithId {
id: number;
}
export interface PineDeferred {
__id: number;
}
/**
* When not selected-out holds a deferred.
* When expanded hold an array with a single element.
*/
export type NavigationResource<T = WithId> = [T] | PineDeferred;
export type OptionalNavigationResource<T = WithId> =
| []
| [T]
| PineDeferred
| null;
/**
* When expanded holds an array, otherwise the property is not present.
* Selecting is not suggested,
* in that case it holds a deferred to the original resource.
*/
export type ReverseNavigationResource<T = WithId> = T[] | undefined;
export type AssociatedResource<T = WithId> =
| NavigationResource<T>
| OptionalNavigationResource<T>
| ReverseNavigationResource<T>;
export type InferAssociatedResourceType<T> = T extends AssociatedResource &
any[]
? T[number]
: never;
export type SelectableProps<T> =
// This allows us to get proper results when T is any/AnyObject, otherwise this returned never
PropsOfType<T, ReverseNavigationResource> extends StringKeyof<T>
? StringKeyof<T>
: Exclude<StringKeyof<T>, PropsOfType<T, ReverseNavigationResource>>; // This is the normal typed case
export type ExpandableProps<T> = PropsOfType<T, AssociatedResource> & string;
type SelectedProperty<
T,
K extends keyof T,
> = T[K] extends NavigationResource<any>
? PineDeferred
: T[K] extends OptionalNavigationResource<any>
? PineDeferred | null
: T[K];
type SelectResultObject<T, Props extends keyof T> = {
[P in Props]: SelectedProperty<T, P>;
};
export type TypedSelectResult<
T,
TParams extends ODataOptions<T>,
> = TParams['$select'] extends keyof T
? SelectResultObject<T, TParams['$select']>
: TParams['$select'] extends Array<keyof T>
? SelectResultObject<T, TParams['$select'][number]>
: TParams['$select'] extends '*'
? SelectResultObject<T, SelectableProps<T>>
: undefined extends TParams['$select']
? SelectResultObject<T, SelectableProps<T>>
: never;
type ExpandedProperty<
T,
K extends keyof T,
KOpts extends ODataOptions<InferAssociatedResourceType<T[K]>>,
> = KOpts extends ODataOptionsWithCount<any>
? number
: T[K] extends NavigationResource<any>
? [TypedResult<InferAssociatedResourceType<T[K]>, KOpts>]
: T[K] extends OptionalNavigationResource<any>
? [TypedResult<InferAssociatedResourceType<T[K]>, KOpts>] | []
: T[K] extends ReverseNavigationResource<any>
? Array<TypedResult<InferAssociatedResourceType<T[K]>, KOpts>>
: never;
export type ExpandResultObject<T, Props extends keyof T> = {
[P in Props]: ExpandedProperty<T, P, {}>;
};
type ExpandResourceExpandObject<
T,
TResourceExpand extends ResourceExpand<T>,
> = {
[P in keyof TResourceExpand]: ExpandedProperty<
T,
P extends keyof T ? P : never,
Exclude<TResourceExpand[P], undefined>
>;
};
export type TypedExpandResult<
T,
TParams extends ODataOptions<T>,
> = TParams['$expand'] extends ExpandableProps<T>
? ExpandResultObject<T, TParams['$expand']>
: TParams['$expand'] extends ResourceExpand<T>
? keyof TParams['$expand'] extends ExpandableProps<T>
? ExpandResourceExpandObject<T, TParams['$expand']>
: never
: {};
export type TypedResult<
T,
TParams extends ODataOptions<T> | undefined,
> = TParams extends ODataOptionsWithCount<T>
? number
: TParams extends ODataOptions<T>
? Omit<TypedSelectResult<T, TParams>, keyof TypedExpandResult<T, TParams>> &
TypedExpandResult<T, TParams>
: undefined extends TParams
? TypedSelectResult<T, { $select: '*' }>
: never;
// based on https://github.com/balena-io/pinejs-client-js/blob/master/core.d.ts
type RawFilter =
| string
| Array<string | Filter<any>>
| { $string: string; [index: string]: Filter<any> | string };
interface LambdaExpression<T> {
[alias: string]: Filter<T>;
}
interface Lambda<T> {
$alias: string;
$expr:
| LambdaExpression<T>
// It seems that TS atm mixes things up after adding the following UNION rules
// and allows having secondary filter props inside the $expr:LambdaExpression<T>
// that are not props of the T
// See: https://github.com/balena-io/balena-sdk/issues/714
| { 1: number }
| { $and: Array<LambdaExpression<T>> }
| { $or: Array<LambdaExpression<T>> }
| { $not: LambdaExpression<T> };
}
type OrderByValues = 'asc' | 'desc';
type OrderBy = string | OrderBy[] | { [index: string]: OrderByValues };
type AssociatedResourceFilter<T> =
T extends NonNullable<ReverseNavigationResource>
? FilterObj<InferAssociatedResourceType<T>>
: FilterObj<InferAssociatedResourceType<T>> | number | null;
type ResourceObjFilterPropValue<
T,
k extends keyof T,
> = T[k] extends AssociatedResource
? AssociatedResourceFilter<T[k]>
: T[k] | FilterExpressions<T[k]> | null;
type ResourceObjFilter<T> = {
[k in keyof T]?: ResourceObjFilterPropValue<T, k>;
};
type Filter<T> = FilterObj<T>;
type FilterObj<T> = ResourceObjFilter<T> | FilterExpressions<T>;
type FilterBaseType = string | number | null | boolean | Date;
type NestedFilter<T> = FilterObj<T> | FilterArray<T> | FilterBaseType;
interface FilterArray<T> extends Array<NestedFilter<T>> {}
type FilterOperationValue<T> =
| NestedFilter<T>
| FilterFunctionExpressions<NestedFilter<T>>;
type FilterFunctionValue<T> = NestedFilter<T>;
type FilterFunctionExpressions<T> = Pick<
FilterExpressions<T>,
FilterFunctionKey
>;
type FilterOperationKey =
| '$ne'
| '$eq'
| '$gt'
| '$ge'
| '$lt'
| '$le'
| '$add'
| '$sub'
| '$mul'
| '$div'
| '$mod';
type FilterFunctionKey =
| '$contains'
| '$endswith'
| '$startswith'
| '$length'
| '$indexof'
| '$substring'
| '$tolower'
| '$toupper'
| '$trim'
| '$concat'
| '$year'
| '$month'
| '$day'
| '$hour'
| '$minute'
| '$second'
| '$fractionalseconds'
| '$date'
| '$time'
| '$totaloffsetminutes'
| '$now'
| '$maxdatetime'
| '$mindatetime'
| '$totalseconds'
| '$round'
| '$floor'
| '$ceiling'
| '$isof'
| '$cast';
interface FilterExpressions<T> {
'@'?: string;
$raw?: RawFilter;
$?: string | string[];
$count?: Filter<T>;
$and?: NestedFilter<T>;
$or?: NestedFilter<T>;
$in?: NestedFilter<T>;
$not?: NestedFilter<T>;
$any?: Lambda<T>;
$all?: Lambda<T>;
// Filter operations
$ne?: FilterOperationValue<T>;
$eq?: FilterOperationValue<T>;
$gt?: FilterOperationValue<T>;
$ge?: FilterOperationValue<T>;
$lt?: FilterOperationValue<T>;
$le?: FilterOperationValue<T>;
$add?: FilterOperationValue<T>;
$sub?: FilterOperationValue<T>;
$mul?: FilterOperationValue<T>;
$div?: FilterOperationValue<T>;
$mod?: FilterOperationValue<T>;
// Filter functions
$contains?: FilterFunctionValue<T>;
$endswith?: FilterFunctionValue<T>;
$startswith?: FilterFunctionValue<T>;
$length?: FilterFunctionValue<T>;
$indexof?: FilterFunctionValue<T>;
$substring?: FilterFunctionValue<T>;
$tolower?: FilterFunctionValue<T>;
$toupper?: FilterFunctionValue<T>;
$trim?: FilterFunctionValue<T>;
$concat?: FilterFunctionValue<T>;
$year?: FilterFunctionValue<T>;
$month?: FilterFunctionValue<T>;
$day?: FilterFunctionValue<T>;
$hour?: FilterFunctionValue<T>;
$minute?: FilterFunctionValue<T>;
$second?: FilterFunctionValue<T>;
$fractionalseconds?: FilterFunctionValue<T>;
$date?: FilterFunctionValue<T>;
$time?: FilterFunctionValue<T>;
$totaloffsetminutes?: FilterFunctionValue<T>;
$now?: FilterFunctionValue<T>;
$maxdatetime?: FilterFunctionValue<T>;
$mindatetime?: FilterFunctionValue<T>;
$totalseconds?: FilterFunctionValue<T>;
$round?: FilterFunctionValue<T>;
$floor?: FilterFunctionValue<T>;
$ceiling?: FilterFunctionValue<T>;
$isof?: FilterFunctionValue<T>;
$cast?: FilterFunctionValue<T>;
}
export type ResourceExpand<T> = {
[k in ExpandableProps<T>]?: ODataOptions<InferAssociatedResourceType<T[k]>>;
};
type ResourceExpandWithSelect<T> = {
[k in ExpandableProps<T>]?: ODataOptionsWithSelect<
InferAssociatedResourceType<T[k]>
>;
};
type BaseExpand<T> = ResourceExpand<T> | ExpandableProps<T>;
export type Expand<T> = BaseExpand<T> | Array<BaseExpand<T>>;
type ExpandWithSelect<T> =
| ResourceExpandWithSelect<T>
| Array<ResourceExpandWithSelect<T>>;
export type ODataMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
export interface ODataOptionsWithoutCount<T> {
$select?: Array<SelectableProps<T>> | SelectableProps<T> | '*';
$filter?: Filter<T>;
$expand?: Expand<T>;
$orderby?: OrderBy;
$top?: number;
$skip?: number;
}
export interface ODataOptions<T> extends ODataOptionsWithoutCount<T> {
$count?: ODataOptionsWithoutCount<T>;
}
export interface ODataOptionsWithCount<T> extends ODataOptionsWithoutCount<T> {
$count: NonNullable<ODataOptions<T>['$count']>;
}
// TODO: Rename to ODataOptionsStrict on the next major
export type ODataOptionsWithSelect<T> = Omit<
ODataOptions<T>,
'$select' | '$expand' | '$count'
> &
(
| {
$select: ODataOptions<T>['$select'];
$expand?: ExpandWithSelect<T>;
}
| {
$count: ODataOptionsWithoutCount<T>;
}
);
export type ODataOptionsWithFilter<T> = ODataOptions<T> &
Required<Pick<ODataOptions<T>, '$filter'>>;
export type SubmitBody<T> = {
[k in keyof T]?: T[k] extends AssociatedResource ? number | null : T[k];
};
type BaseResourceId =
| string
| number
| Date
| {
'@': string;
};
type ResourceAlternateKey<T> = SubmitBody<T>;
type ResourceId<T> = BaseResourceId | ResourceAlternateKey<T>;
export interface ParamsObj<T> {
resource?: string;
body?: SubmitBody<T>;
id?: ResourceId<T>;
options?: ODataOptions<T>;
apiPrefix?: string;
method?: ODataMethod;
url?: string;
passthrough?: AnyObject;
passthroughByMethod?: { [method in ODataMethod]: AnyObject };
customOptions?: AnyObject;
}
export interface ParamsObjWithId<T> extends ParamsObj<T> {
id: ResourceId<T>;
}
export interface ParamsObjWithCount<T> extends ParamsObj<T> {
options: { $count: NonNullable<ODataOptions<T>['$count']> };
}
// TODO: Rename to ParamsObjStrict on the next major
export type ParamsObjWithSelect<T> = Omit<ParamsObj<T>, 'options'> & {
options: ODataOptionsWithSelect<T>;
};
export interface ParamsObjWithFilter<T> extends ParamsObj<T> {
options: ODataOptionsWithFilter<T>;
}
export interface GetOrCreateParams<T> extends Omit<ParamsObj<T>, 'method'> {
id: ResourceAlternateKey<T>;
resource: string;
body: SubmitBody<T>;
}
export interface UpsertParams<T>
extends Omit<ParamsObj<T>, 'id' | 'method' | 'options'> {
id: ResourceAlternateKey<T>;
resource: string;
body: SubmitBody<T>;
}
export declare type Primitive = null | string | number | boolean | Date;
export declare type ParameterAlias = Primitive;
export declare type PreparedFn<T extends Dictionary<ParameterAlias>, U, R> = (
parameterAliases?: T,
body?: ParamsObj<R>['body'],
passthrough?: ParamsObj<R>['passthrough'],
) => U;
interface PollOnObj {
unsubscribe: () => void;
}
declare class Poll<T> {
private intervalTime;
private subscribers;
private stopped;
private pollInterval?;
private requestFn;
constructor(requestFn: () => Promise<T>, intervalTime?: number);
setPollInterval(intervalTime: number): void;
runRequest(): Promise<void>;
on(name: 'data', fn: (response: Promise<T>) => void): PollOnObj;
on(name: 'error', fn: (err: any) => void): PollOnObj;
start(): void;
stop(): void;
destroy(): void;
private restartTimeout;
}
export interface SubscribeParams<T> extends ParamsObj<T> {
method?: 'GET';
pollInterval?: number;
}
export interface SubscribeParamsWithCount<T> extends ParamsObjWithCount<T> {
method?: 'GET';
pollInterval?: number;
}
export interface SubscribeParamsWithId<T> extends ParamsObjWithId<T> {
method?: 'GET';
pollInterval?: number;
}
export interface Pine<ResourceTypeMap extends {} = {}> {
delete<T>(params: ParamsObjWithId<T> | ParamsObjWithFilter<T>): Promise<'OK'>;
// Fully typed result overloads
get<
R extends keyof ResourceTypeMap,
P extends { resource: R } & ParamsObjWithCount<
ResourceTypeMap[P['resource']]
>,
>(
params: ExactlyExtends<
P,
ParamsObjWithCount<ResourceTypeMap[P['resource']]>
>,
): Promise<number>;
get<
R extends keyof ResourceTypeMap,
P extends { resource: R } & ParamsObjWithId<ResourceTypeMap[P['resource']]>,
>(
params: ExactlyExtends<P, ParamsObjWithId<ResourceTypeMap[P['resource']]>>,
): Promise<
TypedResult<ResourceTypeMap[P['resource']], P['options']> | undefined
>;
get<
R extends keyof ResourceTypeMap,
P extends { resource: R } & ParamsObj<ResourceTypeMap[P['resource']]>,
>(
params: ExactlyExtends<P, ParamsObj<ResourceTypeMap[P['resource']]>>,
): Promise<Array<TypedResult<ResourceTypeMap[P['resource']], P['options']>>>;
// User provided resource type overloads
get<T extends {}>(params: ParamsObjWithCount<T>): Promise<number>;
get<T extends {}>(params: ParamsObjWithId<T>): Promise<T | undefined>;
get<T extends {}>(params: ParamsObj<T>): Promise<T[]>;
get<T extends {}, Result>(params: ParamsObj<T>): Promise<Result>;
post<T>(params: ParamsObj<T>): Promise<T & { id: number }>;
patch<T>(params: ParamsObjWithId<T> | ParamsObjWithFilter<T>): Promise<'OK'>;
upsert<T>(params: UpsertParams<T>): Promise<T | 'OK'>;
getOrCreate<T>(params: GetOrCreateParams<T>): Promise<T>;
prepare<T extends Dictionary<ParameterAlias>, R>(
params: ParamsObjWithCount<R> & {
method?: 'GET';
},
): PreparedFn<T, Promise<number>, R>;
prepare<T extends Dictionary<ParameterAlias>, R>(
params: ParamsObjWithId<R> & {
method?: 'GET';
},
): PreparedFn<T, Promise<R | undefined>, R>;
prepare<T extends Dictionary<ParameterAlias>, R>(
params: ParamsObj<R> & {
method?: 'GET';
},
): PreparedFn<T, Promise<R[]>, R>;
prepare<T extends Dictionary<ParameterAlias>, R>(
params: ParamsObj<R> & {
method: 'POST';
},
): PreparedFn<T, Promise<R & { id: number }>, R>;
prepare<T extends Dictionary<ParameterAlias>, R>(
params: ParamsObj<R> & {
method: 'PATCH' | 'DELETE';
},
): PreparedFn<T, Promise<'OK'>, R>;
subscribe<T>(
params: SubscribeParamsWithCount<T> & {
method?: 'GET';
},
): Poll<number>;
subscribe<T>(
params: SubscribeParamsWithId<T> & {
method?: 'GET';
},
): Poll<T | undefined>;
subscribe<T>(
params: SubscribeParams<T> & {
method?: 'GET';
},
): Poll<T[]>;
subscribe<T>(
params: SubscribeParams<T> & {
method: 'POST';
},
): Poll<T & { id: number }>;
subscribe<T>(
params: SubscribeParams<T> & {
method: 'PATCH' | 'DELETE';
},
): Poll<'OK'>;
}
/**
* A variant that makes $select mandatory, helping to create
* requests that explicitly fetch only what your code needs.
*/
export type PineStrict<ResourceTypeMap extends {} = {}> = Omit<
Pine,
'get' | 'prepare' | 'subscribe'
> & {
// Fully typed result overloads
get<
R extends keyof ResourceTypeMap,
P extends { resource: R } & ParamsObjWithCount<
ResourceTypeMap[P['resource']]
>,
>(
params: ExactlyExtends<
P,
ParamsObjWithCount<ResourceTypeMap[P['resource']]>
>,
): Promise<number>;
get<
R extends keyof ResourceTypeMap,
P extends { resource: R } & ParamsObjWithId<
ResourceTypeMap[P['resource']]
> &
ParamsObjWithSelect<ResourceTypeMap[P['resource']]>,
>(
params: ExactlyExtends<
P,
ParamsObjWithId<ResourceTypeMap[P['resource']]> &
ParamsObjWithSelect<ResourceTypeMap[P['resource']]>
>,
): Promise<
TypedResult<ResourceTypeMap[P['resource']], P['options']> | undefined
>;
get<
R extends keyof ResourceTypeMap,
P extends { resource: R } & ParamsObjWithSelect<
ResourceTypeMap[P['resource']]
>,
>(
params: ExactlyExtends<
P,
ParamsObjWithSelect<ResourceTypeMap[P['resource']]>
>,
): Promise<Array<TypedResult<ResourceTypeMap[P['resource']], P['options']>>>;
// User provided resource type overloads
get<T extends {}>(params: ParamsObjWithCount<NoInfer<T>>): Promise<number>;
get<T extends {}>(
params: ParamsObjWithId<NoInfer<T>> & ParamsObjWithSelect<NoInfer<T>>,
): Promise<T | undefined>;
get<T extends {}>(params: ParamsObjWithSelect<NoInfer<T>>): Promise<T[]>;
get<T extends {}, Result extends number>(
params: ParamsObj<NoInfer<T>>,
): Promise<Result>;
get<T extends {}, Result>(
params: ParamsObjWithSelect<NoInfer<T>>,
): Promise<Result>;
prepare<T extends Dictionary<ParameterAlias>, R>(
params: ParamsObjWithCount<R> & {
method?: 'GET';
},
): PreparedFn<T, Promise<number>, R>;
prepare<T extends Dictionary<ParameterAlias>, R>(
params: ParamsObjWithId<R> &
ParamsObjWithSelect<R> & {
method?: 'GET';
},
): PreparedFn<T, Promise<R | undefined>, R>;
prepare<T extends Dictionary<ParameterAlias>, R>(
params: ParamsObj<R> &
ParamsObjWithSelect<R> & {
method?: 'GET';
},
): PreparedFn<T, Promise<R[]>, R>;
prepare<T extends Dictionary<ParameterAlias>, R>(
params: ParamsObj<R> & {
method: 'POST';
},
): PreparedFn<T, Promise<R & { id: number }>, R>;
prepare<T extends Dictionary<ParameterAlias>, R>(
params: ParamsObj<R> & {
method: 'PATCH' | 'DELETE';
},
): PreparedFn<T, Promise<'OK'>, R>;
subscribe<T>(
params: SubscribeParamsWithCount<T> & {
method?: 'GET';
},
): Poll<number>;
subscribe<T>(
params: SubscribeParamsWithId<T> &
ParamsObjWithSelect<T> & {
method?: 'GET';
},
): Poll<T | undefined>;
subscribe<T>(
params: SubscribeParams<T> &
ParamsObjWithSelect<T> & {
method?: 'GET';
},
): Poll<T[]>;
subscribe<T>(
params: SubscribeParams<T> & {
method: 'POST';
},
): Poll<T & { id: number }>;
subscribe<T>(
params: SubscribeParams<T> & {
method: 'PATCH' | 'DELETE';
},
): Poll<'OK'>;
}; | the_stack |
import React from 'react';
import { Link } from 'react-router-dom';
import { Button, Tooltip } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import { connect } from 'react-redux';
import routes from '../constants/routes.json';
import styles from './Home.css';
import { Layout, Header, Footer, Main, Side } from './Layout';
import GraphDrawer from './Core/GraphDrawer';
import SelectedDocumentDrawer from './Core/SelectedDocument/Drawer';
import OperatorBar from './Core/OperatorBar';
import './Layout/index.css';
import { TreeGraphReact } from './Core/Graph';
import Graphin, { Utils } from '../packages/graphin/src';
import Notes from './Core/Notes';
import Inbox from './Core/Inbox';
import TagManagement from './Core/TagManagement';
const hexColor = {
pink: '#eb2f96',
magenta: '#eb2f96',
red: '#f5222d',
volcano: '#fa541c',
orange: '#fa8c16',
yellow: '#fadb14',
gold: '#faad14',
cyan: '#13c2c2',
lime: '#a0d911',
green: '#52c41a',
blue: '#1890ff',
geekblue: '#2f54eb',
purple: '#722ed1',
};
const mapDispatchToProps = (dispatch) => {
return {
// dispatching plain actions
selectDoc: (payload) => dispatch({ type: 'SELECT_DOCUMENT', payload }),
resetSelectedDoc: () => dispatch({ type: 'RESET_SELECTED_DOC' }),
};
};
const mapStateToProps = (state) => ({ layout: state.layout });
const OnlyGraphinReady = (props) => {
const { children, graphRef } = props;
if (graphRef && graphRef.current && graphRef.current.graph) {
const { graph, apis } = graphRef.current;
const graphProps = {
graph,
apis,
};
return (
<div>
{React.Children.map(children, (child) => {
if (!React.isValidElement(child) || typeof child.type === 'string') {
return child;
}
return React.cloneElement(child, {
...graphProps,
});
})}
</div>
);
}
return null;
};
export class Home extends React.Component {
state = {
data: [],
dependencies: {
nodes: [],
edges: [],
},
};
graphRef = React.createRef();
handlingNodeClick = false;
componentDidMount(): void {
this.getInbox();
this.attachNodeClick();
}
componentWillUnmount(): void {
this.removeNodeClick();
}
componentDidUpdate(prevProps, prevState): void {
const { layout } = this.props;
if (
layout.page === 'graph' &&
prevProps.layout &&
prevProps.layout.page !== layout.page
) {
console.log('page change and attaching nodes');
this.attachNodeClick();
} else {
this.removeNodeClick();
}
}
attachNodeClick() {
if (this.graphRef && this.graphRef.current) {
const { graph } = this.graphRef.current;
graph.on('node:click', this.handleNodeClick.bind(this));
}
}
removeNodeClick() {
if (this.graphRef && this.graphRef.current) {
const { graph } = this.graphRef.current;
graph.off('node:click', this.handleNodeClick.bind(this));
}
}
async handleNodeClick(e) {
// if you click a node, the event fires multiple times
if (!this.handlingNodeClick) {
const { selectDoc } = this.props;
console.log('node:click', e.item.get('model'));
const docId = e.item.get('model').id;
if (!docId || e.item.get('model').type === 'CircleNode') {
return;
}
this.handlingNodeClick = true;
const res = await fetch(`http://localhost:3000/documents/${docId}`);
const json = await res.json();
selectDoc(json);
this.handlingNodeClick = false;
}
}
async getInbox() {
const res = await fetch('http://localhost:3000/documents');
const inboxItems = await res.json();
console.log(inboxItems.rows);
const dependencies = {
nodes: [],
edges: [],
};
const tags = {};
const pushedNodeIds = {};
inboxItems.rows.forEach((row, index1) => {
if (row.doc.committed) {
const { hostname } = new URL(row.doc.url);
let totalClickAndMouseOver = 0;
for (const element in row.doc.behaviour.elements) {
const el = row.doc.behaviour.elements[element];
if (el.stats && el.stats.click) {
totalClickAndMouseOver += el.stats.click;
}
if (el.stats && el.stats.mouseover) {
totalClickAndMouseOver += el.stats.mouseover;
}
}
dependencies.nodes.push({
// id: row.doc._id,
// data: {
// id: row.doc._id,
// label: row.doc.title,
// fullLabel: row.doc.title,
// img: 'https://www.google.com/s2/favicons?sz=64&domain_url=' + hostname,
// textSize: 140,
// }
data: {
id: row.doc._id,
label: row.doc.title,
children: row.doc.children,
properties: [],
},
style: {
nodeSize: 20 + totalClickAndMouseOver / 2,
},
id: row.doc._id,
label: row.doc.title,
shape: 'CustomNode',
img: `https://www.google.com/s2/favicons?sz=64&domain_url=${hostname}`,
});
pushedNodeIds[row.doc._id] = true;
row.doc.tags.forEach((tag) => {
if (!tags[`${tag.label}_${tag.color}`]) {
tags[`${tag.label}_${tag.color}`] = [];
}
tags[`${tag.label}_${tag.color}`].push(row.doc._id);
});
}
});
for (const node of dependencies.nodes) {
// console.log('node', node)
node.data.children.forEach((child, idx) => {
// console.log(pushedNodeIds[node.id], pushedNodeIds['document_' + child.id])
if (pushedNodeIds[node.id] && pushedNodeIds[`document_${child.id}`]) {
// console.log('add edge')
dependencies.edges.push({
source: node.id,
target: `document_${child.id}`,
shape: 'CurveEdge',
style: {
line: {
width: 2,
},
},
data: {
source: node.id,
target: `document_${child.id}`,
},
});
}
});
}
const completedRelationships = {};
for (const tag in tags) {
const label = tag.split('_')[0];
const color = tag.split('_')[1];
console.log('color', color);
dependencies.nodes.push({
data: {
id: tag,
label,
properties: [],
},
style: {
nodeSize: 20 + tags[tag].length * 10,
fontSize: 12 + tags[tag].length * 2,
fontWeight: 'bold',
primaryColor: hexColor[color],
},
id: tag,
label,
shape: 'CircleNode',
});
tags[tag].forEach((tag1, idx1) => {
// tags[tag].forEach((tag2, idx2) => {
// if (tag1 !== tag2 && !completedRelationships[`${tag1}_${tag2}`] && !completedRelationships[`${tag2}_${tag1}`]) {
// dependencies.edges.push({
// source: tag1,
// target: tag2
// })
// completedRelationships[`${tag1}_${tag2}`] = true
// completedRelationships[`${tag2}_${tag1}`] = true
// }
// })
dependencies.edges.push({
source: tag1,
target: tag,
shape: 'CurveEdge',
style: {
line: {
width: 2,
},
},
data: {
source: tag1,
target: tag,
},
});
});
}
this.setState({
data: inboxItems.rows,
dependencies,
});
}
getContext() {
return this;
}
renderPage() {
const { dependencies } = this.state;
const { layout } = this.props;
if (layout.page === 'graph') {
return (
<Graphin
ref={this.graphRef}
data={dependencies}
layout={{
name: 'force',
options: {},
}}
/>
);
}
if (layout.page === 'notes') {
return <Notes />;
}
if (layout.page === 'inbox') {
return <Inbox />;
}
if (layout.page === 'tag_management') {
return <TagManagement />;
}
return null;
}
renderHeader() {
const { dependencies } = this.state;
const { layout } = this.props;
if (layout.page === 'graph') {
return (
<span style={{ fontWeight: 600, fontSize: 18 }}>
<span style={{ marginRight: 16 }}>🗺</span>
<span>Knowledge Map</span>
<Tooltip placement="left" title="Refresh">
<Button
style={{ border: 'none' }}
onClick={() => {
this.getInbox();
}}
shape="circle"
icon={<ReloadOutlined style={{ fontSize: 14 }} />}
/>
</Tooltip>
</span>
);
}
if (layout.page === 'notes') {
return (
<span style={{ fontWeight: 600, fontSize: 18 }}>
<span style={{ marginRight: 16 }}>📓</span>
<span>Notes & Highlights</span>
</span>
);
}
if (layout.page === 'inbox') {
return (
<span style={{ fontWeight: 600, fontSize: 18 }}>
<span style={{ marginRight: 16 }}>📥</span>
<span>Inbox</span>
</span>
);
}
if (layout.page === 'tag_management') {
return (
<span style={{ fontWeight: 600, fontSize: 18 }}>
<span style={{ marginRight: 16 }}>🤖</span>
<span>Tag Management</span>
</span>
);
}
return null;
}
render() {
const { layout } = this.props;
return (
<Layout>
<Header>{this.renderHeader()}</Header>
<Side>
<OperatorBar />
</Side>
<Main>
{/* <Graph data={data} layout={layout} toolbar={toolbar} dispatch={dispatch} store={state} /> */}
{/* <OnlyGraphinReady graphRef={this.graphRef}> */}
{/* <GraphDrawer dispatch={dispatch} state={state} /> */}
{/* <GraphModal dispatch={dispatch} state={state} /> */}
{/* <SearchBar dispatch={dispatch} state={state} /> */}
{/* </OnlyGraphinReady> */}
{/* <TreeGraphReact dependencies={dependencies}/> */}
{this.renderPage()}
<GraphDrawer />
{layout.page !== 'inbox' ? <SelectedDocumentDrawer /> : null}
</Main>
{/* <Footer>Footer</Footer> */}
</Layout>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Home); | the_stack |
import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock';
import { ITerminalConfiguration, ITerminalBackend, ITerminalProfileService } from 'vs/workbench/contrib/terminal/common/terminal';
import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService';
import { TestExtensionService } from 'vs/workbench/test/common/workbenchTestServices';
import { TerminalProfileService } from 'vs/workbench/contrib/terminal/browser/terminalProfileService';
import { ITerminalContributionService } from 'vs/workbench/contrib/terminal/common/terminalExtensionPoints';
import { IExtensionTerminalProfile, ITerminalProfile } from 'vs/platform/terminal/common/terminal';
import { ITerminalInstanceService } from 'vs/workbench/contrib/terminal/browser/terminal';
import { isLinux, isWindows, OperatingSystem } from 'vs/base/common/platform';
import { MockContextKeyService } from 'vs/platform/keybinding/test/common/mockKeybindingService';
import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IRemoteAgentEnvironment } from 'vs/platform/remote/common/remoteAgentEnvironment';
import { IThemeService, ThemeIcon } from 'vs/platform/theme/common/themeService';
import { Codicon } from 'vs/base/common/codicons';
import { deepStrictEqual } from 'assert';
import { Emitter } from 'vs/base/common/event';
import { IProfileQuickPickItem, TerminalProfileQuickpick } from 'vs/workbench/contrib/terminal/browser/terminalProfileQuickpick';
import { TestThemeService } from 'vs/platform/theme/test/common/testThemeService';
import { IPickOptions, IQuickInputService, Omit, QuickPickInput } from 'vs/platform/quickinput/common/quickInput';
import { CancellationToken } from 'vs/base/common/cancellation';
class TestTerminalProfileService extends TerminalProfileService implements Partial<ITerminalProfileService>{
hasRefreshedProfiles: Promise<void> | undefined;
override refreshAvailableProfiles(): void {
this.hasRefreshedProfiles = this._refreshAvailableProfilesNow();
}
refreshAndAwaitAvailableProfiles(): Promise<void> {
this.refreshAvailableProfiles();
if (!this.hasRefreshedProfiles) {
throw new Error('has not refreshed profiles yet');
}
return this.hasRefreshedProfiles;
}
}
class MockTerminalProfileService implements Partial<ITerminalProfileService>{
hasRefreshedProfiles: Promise<void> | undefined;
_defaultProfileName: string | undefined;
availableProfiles?: ITerminalProfile[] | undefined = [];
contributedProfiles?: IExtensionTerminalProfile[] | undefined = [];
async getPlatformKey(): Promise<string> {
return 'linux';
}
getDefaultProfileName(): string | undefined {
return this._defaultProfileName;
}
setProfiles(profiles: ITerminalProfile[], contributed: IExtensionTerminalProfile[]): void {
this.availableProfiles = profiles;
this.contributedProfiles = contributed;
}
setDefaultProfileName(name: string): void {
this._defaultProfileName = name;
}
}
class MockQuickInputService implements Partial<IQuickInputService> {
_pick: IProfileQuickPickItem = powershellPick;
pick(picks: QuickPickInput<IProfileQuickPickItem>[] | Promise<QuickPickInput<IProfileQuickPickItem>[]>, options?: IPickOptions<IProfileQuickPickItem> & { canPickMany: true }, token?: CancellationToken): Promise<IProfileQuickPickItem[] | undefined>;
pick(picks: QuickPickInput<IProfileQuickPickItem>[] | Promise<QuickPickInput<IProfileQuickPickItem>[]>, options?: IPickOptions<IProfileQuickPickItem> & { canPickMany: false }, token?: CancellationToken): Promise<IProfileQuickPickItem | undefined>;
pick(picks: QuickPickInput<IProfileQuickPickItem>[] | Promise<QuickPickInput<IProfileQuickPickItem>[]>, options?: Omit<IPickOptions<IProfileQuickPickItem>, 'canPickMany'>, token?: CancellationToken): Promise<IProfileQuickPickItem | undefined>;
async pick(picks: any, options?: any, token?: any): Promise<IProfileQuickPickItem | IProfileQuickPickItem[] | undefined> {
Promise.resolve(picks);
return this._pick;
}
setPick(pick: IProfileQuickPickItem) {
this._pick = pick;
}
}
class TestTerminalProfileQuickpick extends TerminalProfileQuickpick {
}
class TestTerminalExtensionService extends TestExtensionService {
readonly _onDidChangeExtensions = new Emitter<void>();
}
class TestTerminalContributionService implements ITerminalContributionService {
_serviceBrand: undefined;
terminalProfiles: readonly IExtensionTerminalProfile[] = [];
setProfiles(profiles: IExtensionTerminalProfile[]): void {
this.terminalProfiles = profiles;
}
}
class TestTerminalInstanceService implements Partial<ITerminalInstanceService> {
private _profiles: Map<string, ITerminalProfile[]> = new Map();
private _hasReturnedNone = true;
getBackend(remoteAuthority: string | undefined): ITerminalBackend {
return {
getProfiles: async () => {
if (this._hasReturnedNone) {
return this._profiles.get(remoteAuthority ?? '') || [];
} else {
this._hasReturnedNone = true;
return [];
}
}
} as Partial<ITerminalBackend> as any;
}
setProfiles(remoteAuthority: string | undefined, profiles: ITerminalProfile[]) {
this._profiles.set(remoteAuthority ?? '', profiles);
}
setReturnNone() {
this._hasReturnedNone = false;
}
}
class TestRemoteAgentService implements Partial<IRemoteAgentService> {
private _os: OperatingSystem | undefined;
setEnvironment(os: OperatingSystem) {
this._os = os;
}
async getEnvironment(): Promise<IRemoteAgentEnvironment | null> {
return { os: this._os } as IRemoteAgentEnvironment;
}
}
const defaultTerminalConfig: Partial<ITerminalConfiguration> = { profiles: { windows: {}, linux: {}, osx: {} } };
let powershellProfile = {
profileName: 'PowerShell',
path: 'C:\\Powershell.exe',
isDefault: true,
icon: ThemeIcon.asThemeIcon(Codicon.terminalPowershell)
};
let jsdebugProfile = {
extensionIdentifier: 'ms-vscode.js-debug-nightly',
icon: 'debug',
id: 'extension.js-debug.debugTerminal',
title: 'JavaScript Debug Terminal'
};
const powershellPick = { label: 'Powershell', profile: powershellProfile, profileName: powershellProfile.profileName };
const jsdebugPick = { label: 'Javascript Debug Terminal', profile: jsdebugProfile, profileName: jsdebugProfile.title };
suite('TerminalProfileService', () => {
let configurationService: TestConfigurationService;
let terminalInstanceService: TestTerminalInstanceService;
let terminalProfileService: TestTerminalProfileService;
let remoteAgentService: TestRemoteAgentService;
let extensionService: TestTerminalExtensionService;
let environmentService: IWorkbenchEnvironmentService;
let instantiationService: TestInstantiationService;
setup(async () => {
configurationService = new TestConfigurationService({ terminal: { integrated: defaultTerminalConfig } });
remoteAgentService = new TestRemoteAgentService();
terminalInstanceService = new TestTerminalInstanceService();
extensionService = new TestTerminalExtensionService();
environmentService = { remoteAuthority: undefined } as IWorkbenchEnvironmentService;
instantiationService = new TestInstantiationService();
const themeService = new TestThemeService();
const terminalContributionService = new TestTerminalContributionService();
const contextKeyService = new MockContextKeyService();
instantiationService.stub(IContextKeyService, contextKeyService);
instantiationService.stub(IExtensionService, extensionService);
instantiationService.stub(IConfigurationService, configurationService);
instantiationService.stub(IRemoteAgentService, remoteAgentService);
instantiationService.stub(ITerminalContributionService, terminalContributionService);
instantiationService.stub(ITerminalInstanceService, terminalInstanceService);
instantiationService.stub(IWorkbenchEnvironmentService, environmentService);
instantiationService.stub(IThemeService, themeService);
terminalProfileService = instantiationService.createInstance(TestTerminalProfileService);
//reset as these properties are changed in each test
powershellProfile = {
profileName: 'PowerShell',
path: 'C:\\Powershell.exe',
isDefault: true,
icon: ThemeIcon.asThemeIcon(Codicon.terminalPowershell)
};
jsdebugProfile = {
extensionIdentifier: 'ms-vscode.js-debug-nightly',
icon: 'debug',
id: 'extension.js-debug.debugTerminal',
title: 'JavaScript Debug Terminal'
};
terminalInstanceService.setProfiles(undefined, [powershellProfile]);
terminalInstanceService.setProfiles('fakeremote', []);
terminalContributionService.setProfiles([jsdebugProfile]);
if (isWindows) {
remoteAgentService.setEnvironment(OperatingSystem.Windows);
} else if (isLinux) {
remoteAgentService.setEnvironment(OperatingSystem.Linux);
} else {
remoteAgentService.setEnvironment(OperatingSystem.Macintosh);
}
configurationService.setUserConfiguration('terminal', { integrated: defaultTerminalConfig });
});
suite('Contributed Profiles', () => {
test('should filter out contributed profiles set to null (Linux)', async () => {
remoteAgentService.setEnvironment(OperatingSystem.Linux);
await configurationService.setUserConfiguration('terminal', {
integrated: {
profiles: {
linux: {
'JavaScript Debug Terminal': null
}
}
}
});
configurationService.onDidChangeConfigurationEmitter.fire({ affectsConfiguration: () => true, source: ConfigurationTarget.USER } as any);
await terminalProfileService.refreshAndAwaitAvailableProfiles();
deepStrictEqual(terminalProfileService.availableProfiles, [powershellProfile]);
deepStrictEqual(terminalProfileService.contributedProfiles, []);
});
test('should filter out contributed profiles set to null (Windows)', async () => {
remoteAgentService.setEnvironment(OperatingSystem.Windows);
await configurationService.setUserConfiguration('terminal', {
integrated: {
profiles: {
windows: {
'JavaScript Debug Terminal': null
}
}
}
});
configurationService.onDidChangeConfigurationEmitter.fire({ affectsConfiguration: () => true, source: ConfigurationTarget.USER } as any);
await terminalProfileService.refreshAndAwaitAvailableProfiles();
deepStrictEqual(terminalProfileService.availableProfiles, [powershellProfile]);
deepStrictEqual(terminalProfileService.contributedProfiles, []);
});
test('should filter out contributed profiles set to null (macOS)', async () => {
remoteAgentService.setEnvironment(OperatingSystem.Macintosh);
await configurationService.setUserConfiguration('terminal', {
integrated: {
profiles: {
osx: {
'JavaScript Debug Terminal': null
}
}
}
});
configurationService.onDidChangeConfigurationEmitter.fire({ affectsConfiguration: () => true, source: ConfigurationTarget.USER } as any);
await terminalProfileService.refreshAndAwaitAvailableProfiles();
deepStrictEqual(terminalProfileService.availableProfiles, [powershellProfile]);
deepStrictEqual(terminalProfileService.contributedProfiles, []);
});
test('should include contributed profiles', async () => {
await terminalProfileService.refreshAndAwaitAvailableProfiles();
deepStrictEqual(terminalProfileService.availableProfiles, [powershellProfile]);
deepStrictEqual(terminalProfileService.contributedProfiles, [jsdebugProfile]);
});
});
test('should get profiles from remoteTerminalService when there is a remote authority', async () => {
environmentService = { remoteAuthority: 'fakeremote' } as IWorkbenchEnvironmentService;
instantiationService.stub(IWorkbenchEnvironmentService, environmentService);
terminalProfileService = instantiationService.createInstance(TestTerminalProfileService);
await terminalProfileService.hasRefreshedProfiles;
deepStrictEqual(terminalProfileService.availableProfiles, []);
deepStrictEqual(terminalProfileService.contributedProfiles, [jsdebugProfile]);
terminalInstanceService.setProfiles('fakeremote', [powershellProfile]);
await terminalProfileService.refreshAndAwaitAvailableProfiles();
deepStrictEqual(terminalProfileService.availableProfiles, [powershellProfile]);
deepStrictEqual(terminalProfileService.contributedProfiles, [jsdebugProfile]);
});
test('should fire onDidChangeAvailableProfiles only when available profiles have changed via user config', async () => {
powershellProfile.icon = ThemeIcon.asThemeIcon(Codicon.lightBulb);
let calls: ITerminalProfile[][] = [];
terminalProfileService.onDidChangeAvailableProfiles(e => calls.push(e));
await configurationService.setUserConfiguration('terminal', {
integrated: {
profiles: {
windows: powershellProfile,
linux: powershellProfile,
osx: powershellProfile
}
}
});
await terminalProfileService.hasRefreshedProfiles;
deepStrictEqual(calls, [
[powershellProfile]
]);
deepStrictEqual(terminalProfileService.availableProfiles, [powershellProfile]);
deepStrictEqual(terminalProfileService.contributedProfiles, [jsdebugProfile]);
calls = [];
await terminalProfileService.refreshAndAwaitAvailableProfiles();
deepStrictEqual(calls, []);
});
test('should fire onDidChangeAvailableProfiles when available or contributed profiles have changed via remote/localTerminalService', async () => {
powershellProfile.isDefault = false;
terminalInstanceService.setProfiles(undefined, [powershellProfile]);
const calls: ITerminalProfile[][] = [];
terminalProfileService.onDidChangeAvailableProfiles(e => calls.push(e));
await terminalProfileService.hasRefreshedProfiles;
deepStrictEqual(calls, [
[powershellProfile]
]);
deepStrictEqual(terminalProfileService.availableProfiles, [powershellProfile]);
deepStrictEqual(terminalProfileService.contributedProfiles, [jsdebugProfile]);
});
test('should call refreshAvailableProfiles _onDidChangeExtensions', async () => {
extensionService._onDidChangeExtensions.fire();
const calls: ITerminalProfile[][] = [];
terminalProfileService.onDidChangeAvailableProfiles(e => calls.push(e));
await terminalProfileService.hasRefreshedProfiles;
deepStrictEqual(calls, [
[powershellProfile]
]);
deepStrictEqual(terminalProfileService.availableProfiles, [powershellProfile]);
deepStrictEqual(terminalProfileService.contributedProfiles, [jsdebugProfile]);
});
suite('Profiles Quickpick', () => {
let quickInputService: MockQuickInputService;
let mockTerminalProfileService: MockTerminalProfileService;
let terminalProfileQuickpick: TestTerminalProfileQuickpick;
setup(async () => {
quickInputService = new MockQuickInputService();
mockTerminalProfileService = new MockTerminalProfileService();
instantiationService.stub(IQuickInputService, quickInputService);
instantiationService.stub(ITerminalProfileService, mockTerminalProfileService);
terminalProfileQuickpick = instantiationService.createInstance(TestTerminalProfileQuickpick);
});
test('setDefault', async () => {
powershellProfile.isDefault = false;
mockTerminalProfileService.setProfiles([powershellProfile], [jsdebugProfile]);
mockTerminalProfileService.setDefaultProfileName(jsdebugProfile.title);
const result = await terminalProfileQuickpick.showAndGetResult('setDefault');
deepStrictEqual(result, powershellProfile.profileName);
});
test('setDefault to contributed', async () => {
mockTerminalProfileService.setDefaultProfileName(powershellProfile.profileName);
quickInputService.setPick(jsdebugPick);
const result = await terminalProfileQuickpick.showAndGetResult('setDefault');
const expected = {
config: {
extensionIdentifier: jsdebugProfile.extensionIdentifier,
id: jsdebugProfile.id,
options: { color: undefined, icon: 'debug' },
title: jsdebugProfile.title,
},
keyMods: undefined
};
deepStrictEqual(result, expected);
});
test('createInstance', async () => {
mockTerminalProfileService.setDefaultProfileName(powershellProfile.profileName);
const pick = { ...powershellPick, keyMods: { alt: true, ctrlCmd: false } };
quickInputService.setPick(pick);
const result = await terminalProfileQuickpick.showAndGetResult('createInstance');
deepStrictEqual(result, { config: powershellProfile, keyMods: { alt: true, ctrlCmd: false } });
});
test('createInstance with contributed', async () => {
const pick = { ...jsdebugPick, keyMods: { alt: true, ctrlCmd: false } };
quickInputService.setPick(pick);
const result = await terminalProfileQuickpick.showAndGetResult('createInstance');
const expected = {
config: {
extensionIdentifier: jsdebugProfile.extensionIdentifier,
id: jsdebugProfile.id,
options: { color: undefined, icon: 'debug' },
title: jsdebugProfile.title,
},
keyMods: { alt: true, ctrlCmd: false }
};
deepStrictEqual(result, expected);
});
});
}); | the_stack |
import { Debug, Log, ParserRegistry } from '../globals'
import { ensureBuffer } from '../utils'
import TrajectoryParser from './trajectory-parser'
import { NumberArray } from '../types';
const MagicInts = new Uint32Array([
0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 10, 12, 16, 20, 25, 32, 40, 50, 64,
80, 101, 128, 161, 203, 256, 322, 406, 512, 645, 812, 1024, 1290,
1625, 2048, 2580, 3250, 4096, 5060, 6501, 8192, 10321, 13003,
16384, 20642, 26007, 32768, 41285, 52015, 65536, 82570, 104031,
131072, 165140, 208063, 262144, 330280, 416127, 524287, 660561,
832255, 1048576, 1321122, 1664510, 2097152, 2642245, 3329021,
4194304, 5284491, 6658042, 8388607, 10568983, 13316085, 16777216
])
const FirstIdx = 9
// const LastIdx = MagicInts.length
function sizeOfInt (size: number) {
let num = 1
let numOfBits = 0
while (size >= num && numOfBits < 32) {
numOfBits++
num <<= 1
}
return numOfBits
}
const _tmpBytes = new Uint8Array(32)
function sizeOfInts (numOfInts: number, sizes: Int32Array) {
let numOfBytes = 1
let numOfBits = 0
_tmpBytes[0] = 1
for (let i = 0; i < numOfInts; i++) {
let bytecnt
let tmp = 0
for (bytecnt = 0; bytecnt < numOfBytes; bytecnt++) {
tmp += _tmpBytes[bytecnt] * sizes[i]
_tmpBytes[bytecnt] = tmp & 0xff
tmp >>= 8
}
while (tmp !== 0) {
_tmpBytes[bytecnt++] = tmp & 0xff
tmp >>= 8
}
numOfBytes = bytecnt
}
let num = 1
numOfBytes--
while (_tmpBytes[numOfBytes] >= num) {
numOfBits++
num *= 2
}
return numOfBits + numOfBytes * 8
}
function decodeBits (buf: Int32Array, cbuf: Uint8Array, numOfBits: number, buf2: Uint32Array) {
const mask = (1 << numOfBits) - 1
let lastBB0 = buf2[1]
let lastBB1 = buf2[2]
let cnt = buf[0]
let num = 0
while (numOfBits >= 8) {
lastBB1 = (lastBB1 << 8) | cbuf[cnt++]
num |= (lastBB1 >> lastBB0) << (numOfBits - 8)
numOfBits -= 8
}
if (numOfBits > 0) {
if (lastBB0 < numOfBits) {
lastBB0 += 8
lastBB1 = (lastBB1 << 8) | cbuf[cnt++]
}
lastBB0 -= numOfBits
num |= (lastBB1 >> lastBB0) & ((1 << numOfBits) - 1)
}
num &= mask
buf[0] = cnt
buf[1] = lastBB0
buf[2] = lastBB1
return num
}
const _tmpIntBytes = new Int32Array(32)
function decodeInts (buf: Int32Array, cbuf: Uint8Array, numOfInts: number, numOfBits: number, sizes: NumberArray, nums: Float32Array, buf2: Uint32Array) {
let numOfBytes = 0
_tmpIntBytes[1] = 0
_tmpIntBytes[2] = 0
_tmpIntBytes[3] = 0
while (numOfBits > 8) {
// this is inversed??? why??? because of the endiannness???
_tmpIntBytes[numOfBytes++] = decodeBits(buf, cbuf, 8, buf2)
numOfBits -= 8
}
if (numOfBits > 0) {
_tmpIntBytes[numOfBytes++] = decodeBits(buf, cbuf, numOfBits, buf2)
}
for (let i = numOfInts - 1; i > 0; i--) {
let num = 0
for (let j = numOfBytes - 1; j >= 0; j--) {
num = (num << 8) | _tmpIntBytes[j]
const p = (num / sizes[i]) | 0
_tmpIntBytes[j] = p
num = num - p * sizes[i]
}
nums[i] = num
}
nums[0] = (
_tmpIntBytes[0] |
(_tmpIntBytes[1] << 8) |
(_tmpIntBytes[2] << 16) |
(_tmpIntBytes[3] << 24)
)
}
class XtcParser extends TrajectoryParser {
get type () { return 'xtc' }
get isBinary () { return true }
_parse () {
// https://github.com/gromacs/gromacs/blob/master/src/gromacs/fileio/xtcio.cpp
// https://github.com/gromacs/gromacs/blob/master/src/gromacs/fileio/libxdrf.cpp
if (Debug) Log.time('XtcParser._parse ' + this.name)
const bin = ensureBuffer(this.streamer.data)
const dv = new DataView(bin)
const f = this.frames
const coordinates = f.coordinates
const boxes = f.boxes
const times = f.times
const minMaxInt = new Int32Array(6)
const sizeint = new Int32Array(3)
const bitsizeint = new Int32Array(3)
const sizesmall = new Uint32Array(3)
const thiscoord = new Float32Array(3)
const prevcoord = new Float32Array(3)
let offset = 0
const buf = new Int32Array(3)
const buf2 = new Uint32Array(buf.buffer)
while (true) {
let frameCoords: NumberArray
// const magicnum = dv.getInt32(offset)
const natoms = dv.getInt32(offset + 4)
// const step = dv.getInt32(offset + 8)
offset += 12
const natoms3 = natoms * 3
times.push(dv.getFloat32(offset))
offset += 4
const box = new Float32Array(9)
for (let i = 0; i < 9; ++i) {
box[i] = dv.getFloat32(offset) * 10
offset += 4
}
boxes.push(box)
if (natoms <= 9) { // no compression
frameCoords = new Float32Array(natoms)
for (let i = 0; i < natoms; ++i) {
frameCoords[i] = dv.getFloat32(offset)
offset += 4
}
} else {
buf[0] = buf[1] = buf[2] = 0.0
sizeint[0] = sizeint[1] = sizeint[2] = 0
sizesmall[0] = sizesmall[1] = sizesmall[2] = 0
bitsizeint[0] = bitsizeint[1] = bitsizeint[2] = 0
thiscoord[0] = thiscoord[1] = thiscoord[2] = 0
prevcoord[0] = prevcoord[1] = prevcoord[2] = 0
frameCoords = new Float32Array(natoms3)
let lfp = 0
const lsize = dv.getInt32(offset)
offset += 4
const precision = dv.getFloat32(offset)
offset += 4
minMaxInt[0] = dv.getInt32(offset)
minMaxInt[1] = dv.getInt32(offset + 4)
minMaxInt[2] = dv.getInt32(offset + 8)
minMaxInt[3] = dv.getInt32(offset + 12)
minMaxInt[4] = dv.getInt32(offset + 16)
minMaxInt[5] = dv.getInt32(offset + 20)
sizeint[0] = minMaxInt[3] - minMaxInt[0] + 1
sizeint[1] = minMaxInt[4] - minMaxInt[1] + 1
sizeint[2] = minMaxInt[5] - minMaxInt[2] + 1
offset += 24
let bitsize
if ((sizeint[0] | sizeint[1] | sizeint[2]) > 0xffffff) {
bitsizeint[0] = sizeOfInt(sizeint[0])
bitsizeint[1] = sizeOfInt(sizeint[1])
bitsizeint[2] = sizeOfInt(sizeint[2])
bitsize = 0 // flag the use of large sizes
} else {
bitsize = sizeOfInts(3, sizeint)
}
let smallidx = dv.getInt32(offset)
offset += 4
// if (smallidx == 0) {alert("Undocumented error 1"); return;}
// let tmpIdx = smallidx + 8
// const maxidx = (LastIdx < tmpIdx) ? LastIdx : tmpIdx
// const minidx = maxidx - 8 // often this equal smallidx
let tmpIdx = smallidx - 1
tmpIdx = (FirstIdx > tmpIdx) ? FirstIdx : tmpIdx
let smaller = (MagicInts[tmpIdx] / 2) | 0
let smallnum = (MagicInts[smallidx] / 2) | 0
sizesmall[0] = sizesmall[1] = sizesmall[2] = MagicInts[smallidx]
// larger = MagicInts[maxidx]
let adz = Math.ceil(dv.getInt32(offset) / 4) * 4
offset += 4
// if (tmpIdx == 0) {alert("Undocumented error 2"); return;}
// buf = new Int32Array(bin, offset);
// buf8 = new Uint8Array(bin, offset);
// tmpIdx += 3; rndup = tmpIdx%4;
// for (i=tmpIdx+rndup-1; i>=tmpIdx; i--) buf8[i] = 0;
// now unpack buf2...
const invPrecision = 1.0 / precision
let run = 0
let i = 0
const buf8 = new Uint8Array(bin, offset) // 229...
thiscoord[0] = thiscoord[1] = thiscoord[2] = 0
while (i < lsize) {
if (bitsize === 0) {
thiscoord[0] = decodeBits(buf, buf8, bitsizeint[0], buf2)
thiscoord[1] = decodeBits(buf, buf8, bitsizeint[1], buf2)
thiscoord[2] = decodeBits(buf, buf8, bitsizeint[2], buf2)
} else {
decodeInts(buf, buf8, 3, bitsize, sizeint, thiscoord, buf2)
}
i++
thiscoord[0] += minMaxInt[0]
thiscoord[1] += minMaxInt[1]
thiscoord[2] += minMaxInt[2]
prevcoord[0] = thiscoord[0]
prevcoord[1] = thiscoord[1]
prevcoord[2] = thiscoord[2]
const flag = decodeBits(buf, buf8, 1, buf2)
let isSmaller = 0
if (flag === 1) {
run = decodeBits(buf, buf8, 5, buf2)
isSmaller = run % 3
run -= isSmaller
isSmaller--
}
// if ((lfp-ptrstart)+run > size3){
// fprintf(stderr, "(xdrfile error) Buffer overrun during decompression.\n");
// return 0;
// }
if (run > 0) {
thiscoord[0] = thiscoord[1] = thiscoord[2] = 0
for (let k = 0; k < run; k += 3) {
decodeInts(buf, buf8, 3, smallidx, sizesmall, thiscoord, buf2)
i++
thiscoord[0] += prevcoord[0] - smallnum
thiscoord[1] += prevcoord[1] - smallnum
thiscoord[2] += prevcoord[2] - smallnum
if (k === 0) {
// interchange first with second atom for
// better compression of water molecules
let tmpSwap = thiscoord[0]
thiscoord[0] = prevcoord[0]
prevcoord[0] = tmpSwap
tmpSwap = thiscoord[1]
thiscoord[1] = prevcoord[1]
prevcoord[1] = tmpSwap
tmpSwap = thiscoord[2]
thiscoord[2] = prevcoord[2]
prevcoord[2] = tmpSwap
frameCoords[lfp++] = prevcoord[0] * invPrecision
frameCoords[lfp++] = prevcoord[1] * invPrecision
frameCoords[lfp++] = prevcoord[2] * invPrecision
} else {
prevcoord[0] = thiscoord[0]
prevcoord[1] = thiscoord[1]
prevcoord[2] = thiscoord[2]
}
frameCoords[lfp++] = thiscoord[0] * invPrecision
frameCoords[lfp++] = thiscoord[1] * invPrecision
frameCoords[lfp++] = thiscoord[2] * invPrecision
}
} else {
frameCoords[lfp++] = thiscoord[0] * invPrecision
frameCoords[lfp++] = thiscoord[1] * invPrecision
frameCoords[lfp++] = thiscoord[2] * invPrecision
}
smallidx += isSmaller
if (isSmaller < 0) {
smallnum = smaller
if (smallidx > FirstIdx) {
smaller = (MagicInts[smallidx - 1] / 2) | 0
} else {
smaller = 0
}
} else if (isSmaller > 0) {
smaller = smallnum
smallnum = (MagicInts[smallidx] / 2) | 0
}
sizesmall[0] = sizesmall[1] = sizesmall[2] = MagicInts[smallidx]
if (sizesmall[0] === 0 || sizesmall[1] === 0 || sizesmall[2] === 0) {
console.error('(xdrfile error) Undefined error.')
return
}
}
offset += adz
}
for (let c = 0; c < natoms3; c++) {
frameCoords[c] *= 10
}
coordinates.push(frameCoords)
if (offset >= bin.byteLength) break
}
if (times.length >= 1) {
f.timeOffset = times[0]
}
if (times.length >= 2) {
f.deltaTime = times[1] - times[0]
}
if (Debug) Log.timeEnd('XtcParser._parse ' + this.name)
}
}
ParserRegistry.add('xtc', XtcParser)
export default XtcParser | the_stack |
import Keychain, { privateToPublic } from '../../../src/models/keys/keychain'
// https://en.bitcoin.it/wiki/BIP_0032_TestVectors
describe('BIP32 Keychain tests', () => {
const shortSeed = Buffer.from('000102030405060708090a0b0c0d0e0f', 'hex')
const longSeed = Buffer.from(
'fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542',
'hex'
)
it('create master keychain from seed', () => {
const master = Keychain.fromSeed(shortSeed)
expect(master.privateKey.toString('hex')).toEqual(
'e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35'
)
expect(master.identifier.toString('hex')).toEqual('3442193e1bb70916e914552172cd4e2dbc9df811')
expect(master.fingerprint).toEqual(876747070)
expect(master.chainCode.toString('hex')).toEqual('873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d508')
expect(master.index).toEqual(0)
expect(master.depth).toEqual(0)
expect(master.parentFingerprint).toEqual(0)
})
it('derive children hardened', () => {
const master = Keychain.fromSeed(shortSeed)
const child = master.deriveChild(0, true)
expect(child.privateKey.toString('hex')).toEqual('edb2e14f9ee77d26dd93b4ecede8d16ed408ce149b6cd80b0715a2d911a0afea')
expect(child.identifier.toString('hex')).toEqual('5c1bd648ed23aa5fd50ba52b2457c11e9e80a6a7')
expect(child.fingerprint).toEqual(1545328200)
expect(child.chainCode.toString('hex')).toEqual('47fdacbd0f1097043b78c63c20c34ef4ed9a111d980047ad16282c7ae6236141')
expect(child.index).toEqual(0)
expect(child.depth).toEqual(1)
})
it('derive path', () => {
const master = Keychain.fromSeed(shortSeed)
expect(master.derivePath(`m/0'`).privateKey.toString('hex')).toEqual(
'edb2e14f9ee77d26dd93b4ecede8d16ed408ce149b6cd80b0715a2d911a0afea'
)
const child = master.derivePath(`m/0'/1/2'`)
expect(child.privateKey.toString('hex')).toEqual('cbce0d719ecf7431d88e6a89fa1483e02e35092af60c042b1df2ff59fa424dca')
expect(child.identifier.toString('hex')).toEqual('ee7ab90cde56a8c0e2bb086ac49748b8db9dce72')
expect(child.fingerprint).toEqual(4001020172)
expect(child.chainCode.toString('hex')).toEqual('04466b9cc8e161e966409ca52986c584f07e9dc81f735db683c3ff6ec7b1503f')
expect(child.index).toEqual(2)
expect(child.depth).toEqual(3)
})
it('create master keychain from long seed', () => {
const master = Keychain.fromSeed(longSeed)
expect(master.privateKey.toString('hex')).toEqual(
'4b03d6fc340455b363f51020ad3ecca4f0850280cf436c70c727923f6db46c3e'
)
expect(master.identifier.toString('hex')).toEqual('bd16bee53961a47d6ad888e29545434a89bdfe95')
expect(master.fingerprint).toEqual(3172384485)
expect(master.chainCode.toString('hex')).toEqual('60499f801b896d83179a4374aeb7822aaeaceaa0db1f85ee3e904c4defbd9689')
expect(master.index).toEqual(0)
expect(master.depth).toEqual(0)
expect(master.parentFingerprint).toEqual(0)
})
it('derive path large index', () => {
const master = Keychain.fromSeed(longSeed)
expect(master.derivePath(`m`).privateKey.toString('hex')).toEqual(
'4b03d6fc340455b363f51020ad3ecca4f0850280cf436c70c727923f6db46c3e'
)
let child = master.derivePath(`0/2147483647'`)
expect(child.privateKey.toString('hex')).toEqual('877c779ad9687164e9c2f4f0f4ff0340814392330693ce95a58fe18fd52e6e93')
expect(child.identifier.toString('hex')).toEqual('d8ab493736da02f11ed682f88339e720fb0379d1')
expect(child.fingerprint).toEqual(3635104055)
expect(child.chainCode.toString('hex')).toEqual('be17a268474a6bb9c61e1d720cf6215e2a88c5406c4aee7b38547f585c9a37d9')
expect(child.index).toEqual(2147483647)
expect(child.depth).toEqual(2)
child = child.deriveChild(1, false)
expect(child.privateKey.toString('hex')).toEqual('704addf544a06e5ee4bea37098463c23613da32020d604506da8c0518e1da4b7')
expect(child.identifier.toString('hex')).toEqual('78412e3a2296a40de124307b6485bd19833e2e34')
expect(child.fingerprint).toEqual(2017537594)
expect(child.chainCode.toString('hex')).toEqual('f366f48f1ea9f2d1d3fe958c95ca84ea18e4c4ddb9366c336c927eb246fb38cb')
expect(child.index).toEqual(1)
expect(child.depth).toEqual(3)
child = child.deriveChild(2147483646, true)
expect(child.privateKey.toString('hex')).toEqual('f1c7c871a54a804afe328b4c83a1c33b8e5ff48f5087273f04efa83b247d6a2d')
expect(child.identifier.toString('hex')).toEqual('31a507b815593dfc51ffc7245ae7e5aee304246e')
expect(child.fingerprint).toEqual(832899000)
expect(child.chainCode.toString('hex')).toEqual('637807030d55d01f9a0cb3a7839515d796bd07706386a6eddf06cc29a65a0e29')
expect(child.index).toEqual(2147483646)
expect(child.depth).toEqual(4)
})
it('derive children no hardened', () => {
const master = Keychain.fromSeed(longSeed)
const child = master.deriveChild(0, false)
expect(child.privateKey.toString('hex')).toEqual('abe74a98f6c7eabee0428f53798f0ab8aa1bd37873999041703c742f15ac7e1e')
expect(child.identifier.toString('hex')).toEqual('5a61ff8eb7aaca3010db97ebda76121610b78096')
expect(child.fingerprint).toEqual(1516371854)
expect(child.chainCode.toString('hex')).toEqual('f0909affaa7ee7abe5dd4e100598d4dc53cd709d5a5c2cac40e7412f232f7c9c')
expect(child.index).toEqual(0)
expect(child.depth).toEqual(1)
})
it('create child keychain from public key', () => {
const child = Keychain.fromPublicKey(
Buffer.from('0357bfe1e341d01c69fe5654309956cbea516822fba8a601743a012a7896ee8dc2', 'hex'),
Buffer.from('04466b9cc8e161e966409ca52986c584f07e9dc81f735db683c3ff6ec7b1503f', 'hex'),
`m/0'/1/2'`
)
expect(child.identifier.toString('hex')).toEqual('ee7ab90cde56a8c0e2bb086ac49748b8db9dce72')
expect(child.fingerprint).toEqual(4001020172)
expect(child.index).toEqual(2)
expect(child.depth).toEqual(3)
const grandchild = child.deriveChild(2, false)
expect(grandchild.publicKey.toString('hex')).toEqual(
'02e8445082a72f29b75ca48748a914df60622a609cacfce8ed0e35804560741d29'
)
expect(grandchild.chainCode.toString('hex')).toEqual(
'cfb71883f01676f587d023cc53a35bc7f88f724b1f8c2892ac1275ac822a3edd'
)
expect(grandchild.identifier.toString('hex')).toEqual('d880d7d893848509a62d8fb74e32148dac68412f')
expect(grandchild.fingerprint).toEqual(3632322520)
expect(grandchild.index).toEqual(2)
expect(grandchild.depth).toEqual(4)
})
it('derive ckb keys', () => {
const master = Keychain.fromSeed(shortSeed)
const extendedKey = master.derivePath(`m/44'/309'/0'`)
expect(extendedKey.privateKey.toString('hex')).toEqual(
'bb39d218506b30ca69b0f3112427877d983dd3cd2cabc742ab723e2964d98016'
)
expect(extendedKey.publicKey.toString('hex')).toEqual(
'03e5b310636a0f6e7dcdfffa98f28d7ed70df858bb47acf13db830bfde3510b3f3'
)
expect(extendedKey.chainCode.toString('hex')).toEqual(
'37e85a19f54f0a242a35599abac64a71aacc21e3a5860dd024377ffc7e6827d8'
)
const addressKey = extendedKey.deriveChild(0, false).deriveChild(0, false)
expect(addressKey.privateKey.toString('hex')).toEqual(
'fcba4708f1f07ddc00fc77422d7a70c72b3456f5fef3b2f68368cdee4e6fb498'
)
expect(addressKey.publicKey.toString('hex')).toEqual(
'0331b3c0225388c5010e3507beb28ecf409c022ef6f358f02b139cbae082f5a2a3'
)
expect(addressKey.chainCode.toString('hex')).toEqual(
'c4b7aef857b625bbb0497267ed51151d090f81737f4f22a0ac3673483b927090'
)
})
it('derive ckb keys another seed', () => {
const master = Keychain.fromSeed(
// From mnemonic `tank planet champion pottery together intact quick police asset flower sudden question`
Buffer.from(
'1371018cfad5990f5e451bf586d59c3820a8671162d8700533549b0df61a63330e5cd5099a5d3938f833d51e4572104868bfac7cfe5b4063b1509a995652bc08',
'hex'
)
)
expect(master.privateKey.toString('hex')).toEqual(
'37d25afe073a6ba17badc2df8e91fc0de59ed88bcad6b9a0c2210f325fafca61'
)
expect(master.derivePath(`m/44'/309'/0'`).privateKey.toString('hex')).toEqual(
'2925f5dfcbee3b6ad29100a37ed36cbe92d51069779cc96164182c779c5dc20e'
)
expect(
master
.derivePath(`m/44'/309'/0'`)
.deriveChild(0, false)
.privateKey.toString('hex')
).toEqual('047fae4f38b3204f93a6b39d6dbcfbf5901f2b09f6afec21cbef6033d01801f1')
expect(master.derivePath(`m/44'/309'/0'/0`).privateKey.toString('hex')).toEqual(
'047fae4f38b3204f93a6b39d6dbcfbf5901f2b09f6afec21cbef6033d01801f1'
)
expect(
master
.derivePath(`m/44'/309'/0'`)
.deriveChild(0, false)
.deriveChild(0, false)
.privateKey.toString('hex')
).toEqual('848422863825f69e66dc7f48a3302459ec845395370c23578817456ad6b04b14')
expect(master.derivePath(`m/44'/309'/0'/0/0`).privateKey.toString('hex')).toEqual(
'848422863825f69e66dc7f48a3302459ec845395370c23578817456ad6b04b14'
)
})
it('derive ckb keys from master extended key', () => {
const privateKey = Buffer.from('37d25afe073a6ba17badc2df8e91fc0de59ed88bcad6b9a0c2210f325fafca61', 'hex')
const chainCode = Buffer.from('5f772d1e3cfee5821911aefa5e8f79d20d4cf6678378d744efd08b66b2633b80', 'hex')
const master = new Keychain(privateKey, chainCode)
expect(master.publicKey.toString('hex')).toEqual(
'020720a7a11a9ac4f0330e2b9537f594388ea4f1cd660301f40b5a70e0bc231065'
)
expect(master.derivePath(`m/44'/309'/0'`).privateKey.toString('hex')).toEqual(
'2925f5dfcbee3b6ad29100a37ed36cbe92d51069779cc96164182c779c5dc20e'
)
expect(
master
.derivePath(`m/44'/309'/0'`)
.deriveChild(0, false)
.privateKey.toString('hex')
).toEqual('047fae4f38b3204f93a6b39d6dbcfbf5901f2b09f6afec21cbef6033d01801f1')
expect(master.derivePath(`m/44'/309'/0'/0`).privateKey.toString('hex')).toEqual(
'047fae4f38b3204f93a6b39d6dbcfbf5901f2b09f6afec21cbef6033d01801f1'
)
expect(
master
.derivePath(`m/44'/309'/0'`)
.deriveChild(0, false)
.deriveChild(0, false)
.privateKey.toString('hex')
).toEqual('848422863825f69e66dc7f48a3302459ec845395370c23578817456ad6b04b14')
expect(master.derivePath(`m/44'/309'/0'/0/0`).privateKey.toString('hex')).toEqual(
'848422863825f69e66dc7f48a3302459ec845395370c23578817456ad6b04b14'
)
})
it('private key add', () => {
const privateKey = Buffer.from('9e919c96ac5a4caea7ba0ea1f7dd7bca5dca8a11e66ed633690c71e483a6e3c9', 'hex')
const toAdd = Buffer.from('36e92e33659808bf06c3e4302b657f39ca285f6bb5393019bb4e2f7b96e3f914', 'hex')
// @ts-ignore: Private method
const sum = Keychain.privateKeyAdd(privateKey, toAdd)
expect(sum.toString('hex')).toEqual('d57acaca11f2556dae7df2d22342fb0427f2e97d9ba8064d245aa1601a8adcdd')
})
it('public key add', () => {
const publicKey = Buffer.from('03556b2c7e03b12845a973a6555b49fe44b0836fbf3587709fa73bb040ba181b21', 'hex')
const toAdd = Buffer.from('953fd6b91b51605d32a28ab478f39ab53c90103b93bd688330b118c460e9c667', 'hex')
// @ts-ignore: Private method
const sum = Keychain.publicKeyAdd(publicKey, toAdd)
expect(sum.toString('hex')).toEqual('03db6eab66f918e434bae0e24fd73de1a2b293a2af9bd3ad53123996fa94494f37')
})
})
describe('private to public', () => {
it('derive public key from private key', () => {
const privateKey = Buffer.from('bb39d218506b30ca69b0f3112427877d983dd3cd2cabc742ab723e2964d98016', 'hex')
const publicKey = Buffer.from('03e5b310636a0f6e7dcdfffa98f28d7ed70df858bb47acf13db830bfde3510b3f3', 'hex')
expect(privateToPublic(privateKey)).toEqual(publicKey)
})
it('derive public key from private key wrong length', () => {
expect(() => privateToPublic(Buffer.from(''))).toThrowError()
expect(() =>
privateToPublic(Buffer.from('39d218506b30ca69b0f3112427877d983dd3cd2cabc742ab723e2964d98016', 'hex'))
).toThrowError()
expect(() =>
privateToPublic(Buffer.from('0xbb39d218506b30ca69b0f3112427877d983dd3cd2cabc742ab723e2964d98016', 'hex'))
).toThrowError()
})
}) | the_stack |
import * as ng1 from 'angular';
import { IScope } from 'angular';
import { DataResult, DefaultGetData } from './data';
import { PageButton } from './paging';
import { InternalTableParams, NgTableParams } from './ngTableParams';
/**
* Alias for the types that can be used to filter events
*/
export type EventSelector<T> = NgTableParams<T> | EventSelectorFunc
/**
* Signature of the event hander that is registered to receive the *afterCreated* event
*/
export interface AfterCreatedListener {
(publisher: NgTableParams<any>): any
}
/**
* Signature of the event hander that is registered to receive the *afterReloadData* event
*/
export interface AfterReloadDataListener<T> {
(publisher: NgTableParams<T>, newData: DataResult<T>[], oldData: DataResult<T>[]): any
}
/**
* Signature of the event hander that is registered to receive the *datasetChanged* event
*/
export interface DatasetChangedListener<T> {
(publisher: NgTableParams<T>, newDataset: T[], oldDataset: T[]): any
}
/**
* Signature of the function used to filter the events to only specific instances of
* {@link NgTableParams}
*/
export interface EventSelectorFunc {
(publisher: NgTableParams<any>): boolean
}
/**
* Signature of the event hander that is registered to receive the *pagesChanged* event
*/
export interface PagesChangedListener {
(publisher: NgTableParams<any>, newPages: PageButton[], oldPages: PageButton[]): any
}
/**
* Signature of the event hander that is registered to receive the *afterDataFiltered* event
*/
export interface AfterDataFilteredListener<T> {
(publisher: NgTableParams<T>, newData: DataResult<T>[] ): any
}
/**
* Signature of the event hander that is registered to receive the *afterDataSorted* event
*/
export interface AfterDataSortedListener<T> {
(publisher: NgTableParams<T>, newData: DataResult<T>[] ): any
}
/**
* Signature of the function used to explicitly unregister an event handler so that it stops
* receiving notifications
*/
export interface UnregistrationFunc {
(): void
}
/**
* Strongly typed pub/sub for {@link NgTableParams}
*
* Supported events:
*
* * afterCreated - raised when a new instance of {@link NgTableParams} has finished being constructed
* * afterReloadData - raised when the {@link NgTableParams} `reload` method has finished loading new data
* * datasetChanged - raised when {@link Settings} `dataset` receives a new data array
* * pagesChanged - raised when a new pages array has been generated
*/
export interface NgTableEventsChannel {
/**
* Subscribe to receive notification whenever a new `NgTableParams` instance has finished being constructed.
* Optionally supply an `eventFilter` to restrict which events that should trigger the `listener` to be called. Supply a
* `scope` to have angular automatically unregister the listener when the `scope` is destroyed.
*
* @param listener the function that will be called when the event fires
* @param scope the angular `$scope` that will limit the lifetime of the event subscription
* @param eventFilter a predicate function that should return true to receive the event
* @return a unregistration function that when called will unregister the `listener`
*/
onAfterCreated(listener: AfterCreatedListener, scope: IScope, eventFilter?: EventSelectorFunc): UnregistrationFunc;
/**
* Subscribe to receive notification whenever a new `NgTableParams` instance has finished being constructed.
* Optionally supply an `eventFilter` to restrict which events that should trigger the `listener` to be called.
*
* @param listener the function that will be called when the event fires
* @param eventFilter a predicate function that should return true to receive the event
* @return a unregistration function that when called will unregister the `listener`
*/
onAfterCreated(listener: AfterCreatedListener, eventFilter?: EventSelectorFunc): UnregistrationFunc;
/**
* Subscribe to receive notification whenever the `reload` method of an `NgTableParams` instance has successfully executed
* Optionally supply an `eventFilter` to restrict which events that should trigger the `listener` to be called. Supply a
* `scope` to have angular automatically unregister the listener when the `scope` is destroyed.
*
* @param listener the function that will be called when the event fires
* @param scope the angular `$scope` that will limit the lifetime of the event subscription
* @param eventFilter either the specific `NgTableParams` instance you want to receive events for or a predicate function that should return true to receive the event
* @return a unregistration function that when called will unregister the `listener`
*/
onAfterReloadData<T>(listener: AfterReloadDataListener<T>, scope: IScope, eventFilter?: EventSelector<T>): UnregistrationFunc;
/**
* Subscribe to receive notification whenever the `reload` method of an `NgTableParams` instance has successfully executed
* Optionally supply an `eventFilter` to restrict which events that should trigger the `listener` to be called.
*
* @param listener the function that will be called when the event fires
* @param eventFilter a predicate function that should return true to receive the event
* @return a unregistration function that when called will unregister the `listener`
*/
onAfterReloadData<T>(listener: AfterReloadDataListener<T>, eventFilter?: EventSelector<T>): UnregistrationFunc;
/**
* Subscribe to receive notification whenever a new data rows *array* is supplied as a `settings` value to a `NgTableParams` instance.
* Optionally supply an `eventFilter` to restrict which events that should trigger the `listener` to be called. Supply a
* `scope` to have angular automatically unregister the listener when the `scope` is destroyed.
*
* @param listener the function that will be called when the event fires
* @param scope the angular `$scope` that will limit the lifetime of the event subscription
* @param eventFilter either the specific `NgTableParams` instance you want to receive events for or a predicate function that should return true to receive the event
* @return a unregistration function that when called will unregister the `listener`
*/
onDatasetChanged<T>(listener: DatasetChangedListener<T>, scope: IScope, eventFilter?: EventSelector<T>): UnregistrationFunc;
/**
* Subscribe to receive notification whenever a new data rows *array* is supplied as a `settings` value to a `NgTableParams` instance.
* Optionally supply an `eventFilter` to restrict which events that should trigger the `listener` to be called.
*
* @param listener the function that will be called when the event fires
* @param eventFilter either the specific `NgTableParams` instance you want to receive events for or a predicate function that should return true to receive the event
* @return a unregistration function that when called will unregister the `listener`
*/
onDatasetChanged<T>(listener: DatasetChangedListener<T>, eventFilter?: EventSelector<T>): UnregistrationFunc;
/**
* Subscribe to receive notification whenever the paging buttons for an `NgTableParams` instance change
* Optionally supply an `eventFilter` to restrict which events that should trigger the `listener` to be called. Supply a
* `scope` to have angular automatically unregister the listener when the `scope` is destroyed.
*
* @param listener the function that will be called when the event fires
* @param scope the angular `$scope` that will limit the lifetime of the event subscription
* @param eventFilter either the specific `NgTableParams` instance you want to receive events for or a predicate function that should return true to receive the event
* @return a unregistration function that when called will unregister the `listener`
*/
onPagesChanged<T>(listener: PagesChangedListener, scope: IScope, eventFilter?: EventSelector<T>): UnregistrationFunc;
/**
* Subscribe to receive notification whenever the paging buttons for an `NgTableParams` instance change
* Optionally supply an `eventFilter` to restrict which events that should trigger the `listener` to be called.
*
* @param listener the function that will be called when the event fires
* @param eventFilter either the specific `NgTableParams` instance you want to receive events for or a predicate function that should return true to receive the event
* @return a unregistration function that when called will unregister the `listener`
*/
onPagesChanged<T>(listener: PagesChangedListener, eventFilter?: EventSelector<T>): UnregistrationFunc;
/**
* Subscribe to receive notification whenever a `ngTableDefaultGetData` instance filters data
* Optionally supply an `eventFilter` to restrict which events that should trigger the `listener` to be called.
*
* @param listener the function that will be called when the event fires
* @param scope the angular `$scope` that will limit the lifetime of the event subscription
* @param eventFilter either the specific `DefaultGetData` instance you want to receive events for or a predicate function that should return true to receive the event
* @return a unregistration function that when called will unregister the `listener`
*/
onAfterDataFiltered<T>(listener: AfterDataFilteredListener<T>, scope: IScope, eventFilter?: EventSelector<T> ): UnregistrationFunc;
/**
* Subscribe to receive notification whenever a `ngTableDefaultGetData` instance filters data
* Optionally supply an `eventFilter` to restrict which events that should trigger the `listener` to be called.
*
* @param listener the function that will be called when the event fires
* @param eventFilter either the specific `DefaultGetData` instance you want to receive events for or a predicate function that should return true to receive the event
* @return a unregistration function that when called will unregister the `listener`
*/
onAfterDataFiltered<T>(listener: AfterDataFilteredListener<T>, eventFilter?: EventSelector<T> ): UnregistrationFunc;
/**
* Subscribe to receive notification whenever a `ngTableDefaultGetData` instance orders data
* Optionally supply an `eventFilter` to restrict which events that should trigger the `listener` to be called.
*
* @param listener the function that will be called when the event fires
* @param scope the angular `$scope` that will limit the lifetime of the event subscription
* @param eventFilter either the specific `DefaultGetData` instance you want to receive events for or a predicate function that should return true to receive the event
* @return a unregistration function that when called will unregister the `listener`
*/
onAfterDataSorted<T>(listener: AfterDataSortedListener<T>, scope: IScope, eventFilter?: EventSelector<T> ): UnregistrationFunc;
/**
* Subscribe to receive notification whenever a `ngTableDefaultGetData` instance orders data
* Optionally supply an `eventFilter` to restrict which events that should trigger the `listener` to be called.
*
* @param listener the function that will be called when the event fires
* @param eventFilter either the specific `DefaultGetData` instance you want to receive events for or a predicate function that should return true to receive the event
* @return a unregistration function that when called will unregister the `listener`
*/
onAfterDataSorted<T>(listener: AfterDataSortedListener<T>, eventFilter?: EventSelector<T> ): UnregistrationFunc;
publishAfterCreated<T>(publisher: NgTableParams<T>): void;
publishAfterReloadData<T>(publisher: NgTableParams<T>, newData: T[], oldData: T[]): void;
publishDatasetChanged<T>(publisher: NgTableParams<T>, newDataset: T[] | undefined, oldDataset: T[] | undefined): void;
publishPagesChanged<T>(publisher: NgTableParams<T>, newPages: PageButton[], oldPages: PageButton[]): void;
publishAfterDataFiltered<T>(publisher: NgTableParams<T>, newData: T[]): void;
publishAfterDataSorted<T>(params: NgTableParams<T>, newData: T[]): void;
}
export class NgTableEventsChannel {
static $inject = ['$rootScope'];
constructor(private $rootScope: ng1.IRootScopeService) {
let events = this;
events = this.addTableParamsEvent('afterCreated', events);
events = this.addTableParamsEvent('afterReloadData', events);
events = this.addTableParamsEvent('datasetChanged', events);
events = this.addTableParamsEvent('pagesChanged', events);
events = this.addTableParamsEvent('afterDataFiltered', events);
events = this.addTableParamsEvent('afterDataSorted', events);
}
private addTableParamsEvent(eventName: string, target: {}) {
const fnName = eventName.charAt(0).toUpperCase() + eventName.substring(1);
const event = {
['on' + fnName]: this.createEventSubscriptionFn(eventName),
['publish' + fnName]: this.createPublishEventFn(eventName)
};
return ng1.extend(target, event);
}
private createPublishEventFn(eventName: string) {
return (...args: any[]) => {
this.$rootScope.$broadcast('ngTable:' + eventName, ...args);
}
}
private createEventSubscriptionFn(eventName: string) {
return <T>(
handler: (...args: any[]) => void,
eventSelectorOrScope: EventSelector<T> | ng1.IScope,
eventSelector?: EventSelector<T>) => {
let actualEvtSelector: (publisher: NgTableParams<any>) => boolean;
let scope: ng1.IScope = this.$rootScope;
if (isScopeLike(eventSelectorOrScope)) {
scope = eventSelectorOrScope;
actualEvtSelector = createEventSelectorFn(eventSelector);
} else {
actualEvtSelector = createEventSelectorFn(eventSelectorOrScope);
}
return scope.$on('ngTable:' + eventName, function (event: ng1.IAngularEvent, params: InternalTableParams<any>, ...eventArgs: any[]) {
// don't send events published by the internal NgTableParams created by ngTableController
if (params.isNullInstance) return;
const fnArgs = [params].concat(eventArgs);
if (actualEvtSelector.apply(this, fnArgs)) {
handler.apply(this, fnArgs);
}
});
}
function createEventSelectorFn<T>(eventSelector: EventSelector<T> = () => true): EventSelectorFunc {
if (isEventSelectorFunc(eventSelector)) {
return eventSelector
} else {
// shorthand for subscriber to only receive events from a specific publisher instance
return (publisher: NgTableParams<any>) => publisher === eventSelector;
}
}
function isEventSelectorFunc<T>(val: EventSelector<T>): val is (publisher: NgTableParams<any>) => boolean {
return typeof val === 'function';
}
function isScopeLike(val: any): val is ng1.IScope {
return val && typeof val.$new === 'function';
}
}
} | the_stack |
import {
TREE_VIEW_ROBOCORP_CLOUD_TREE,
TREE_VIEW_ROBOCORP_LOCATORS_TREE,
TREE_VIEW_ROBOCORP_ROBOT_CONTENT_TREE,
TREE_VIEW_ROBOCORP_ROBOTS_TREE,
TREE_VIEW_ROBOCORP_WORK_ITEMS_TREE,
} from "./robocorpViews";
import * as vscode from "vscode";
import { ExtensionContext } from "vscode";
import * as roboCommands from "./robocorpCommands";
import { OUTPUT_CHANNEL } from "./channel";
import { runRobotRCC, uploadRobot } from "./activities";
import { createRccTerminal } from "./rccTerminal";
import { RobotContentTreeDataProvider } from "./viewsRobotContent";
import { WorkItemsTreeDataProvider } from "./viewsWorkItems";
import {
basename,
CloudEntry,
debounce,
getSelectedRobot,
LocatorEntry,
RobotEntry,
RobotEntryType,
treeViewIdToTreeDataProvider,
treeViewIdToTreeView,
} from "./viewsCommon";
import { ROBOCORP_SUBMIT_ISSUE } from "./robocorpCommands";
function getRobotLabel(robotInfo: LocalRobotMetadataInfo): string {
let label: string = undefined;
if (robotInfo.yamlContents) {
label = robotInfo.yamlContents["name"];
}
if (!label) {
if (robotInfo.directory) {
label = basename(robotInfo.directory);
}
}
if (!label) {
label = "";
}
return label;
}
let _globalSentMetric: boolean = false;
export class CloudTreeDataProvider implements vscode.TreeDataProvider<CloudEntry> {
private _onDidChangeTreeData: vscode.EventEmitter<CloudEntry | null> = new vscode.EventEmitter<CloudEntry | null>();
readonly onDidChangeTreeData: vscode.Event<CloudEntry | null> = this._onDidChangeTreeData.event;
public refreshOnce = false;
fireRootChange() {
this._onDidChangeTreeData.fire(null);
}
async getChildren(element?: CloudEntry): Promise<CloudEntry[]> {
if (!element) {
let accountInfoResult: ActionResult<any> = await vscode.commands.executeCommand(
roboCommands.ROBOCORP_GET_LINKED_ACCOUNT_INFO_INTERNAL
);
let ret: CloudEntry[] = [];
if (!accountInfoResult.success) {
ret.push({
"label": "Link to Control Room",
"iconPath": "link",
"viewItemContextValue": "cloudLoginItem",
"command": {
"title": "Link to Control Room",
"command": roboCommands.ROBOCORP_CLOUD_LOGIN,
},
});
} else {
let accountInfo = accountInfoResult.result;
ret.push({
"label": "Linked: " + accountInfo["fullname"] + " (" + accountInfo["email"] + ")",
"iconPath": "link",
"viewItemContextValue": "cloudLogoutItem",
});
}
ret.push({
"label": "Robot Developer Guide",
"iconPath": "book",
"command": {
"title": "Open https://robocorp.com/docs/development-guide",
"command": "vscode.open",
"arguments": [vscode.Uri.parse("https://robocorp.com/docs/development-guide")],
},
});
ret.push({
"label": "RPA Framework Library",
"iconPath": "notebook",
"command": {
"title": "Open https://robocorp.com/docs/libraries",
"command": "vscode.open",
"arguments": [vscode.Uri.parse("https://robocorp.com/docs/libraries")],
},
});
ret.push({
"label": "Submit Issue",
"iconPath": "report",
"command": {
"title": "Submit Issue",
"command": ROBOCORP_SUBMIT_ISSUE,
},
});
return ret;
}
if (element.children) {
return element.children;
}
return [];
}
getTreeItem(element: CloudEntry): vscode.TreeItem {
const treeItem = new vscode.TreeItem(
element.label,
element.children ? vscode.TreeItemCollapsibleState.Collapsed : vscode.TreeItemCollapsibleState.None
);
treeItem.command = element.command;
treeItem.iconPath = new vscode.ThemeIcon(element.iconPath);
if (element.viewItemContextValue) {
treeItem.contextValue = element.viewItemContextValue;
}
return treeItem;
}
}
export class RobotsTreeDataProvider implements vscode.TreeDataProvider<RobotEntry> {
private _onDidChangeTreeData: vscode.EventEmitter<RobotEntry | null> = new vscode.EventEmitter<RobotEntry | null>();
readonly onDidChangeTreeData: vscode.Event<RobotEntry | null> = this._onDidChangeTreeData.event;
fireRootChange() {
this._onDidChangeTreeData.fire(null);
}
async getChildren(element?: RobotEntry): Promise<RobotEntry[]> {
if (element) {
// Get child elements.
if (element.type == RobotEntryType.Task) {
return []; // Tasks don't have children.
}
let yamlContents = element.robot.yamlContents;
if (!yamlContents) {
return [];
}
let tasks: object[] = yamlContents["tasks"];
if (!tasks) {
return [];
}
const robotInfo = element.robot;
return Object.keys(tasks).map((task: string) => ({
"label": task,
"uri": vscode.Uri.file(robotInfo.filePath),
"robot": robotInfo,
"taskName": task,
"iconPath": "symbol-misc",
"type": RobotEntryType.Task,
}));
}
if (!_globalSentMetric) {
_globalSentMetric = true;
vscode.commands.executeCommand(roboCommands.ROBOCORP_SEND_METRIC, {
"name": "vscode.treeview.used",
"value": "1",
});
}
// Get root elements.
let actionResult: ActionResult<LocalRobotMetadataInfo[]> = await vscode.commands.executeCommand(
roboCommands.ROBOCORP_LOCAL_LIST_ROBOTS_INTERNAL
);
if (!actionResult.success) {
OUTPUT_CHANNEL.appendLine(actionResult.message);
return [];
}
let robotsInfo: LocalRobotMetadataInfo[] = actionResult.result;
if (!robotsInfo || robotsInfo.length == 0) {
return [];
}
return robotsInfo.map((robotInfo: LocalRobotMetadataInfo) => ({
"label": getRobotLabel(robotInfo),
"uri": vscode.Uri.file(robotInfo.filePath),
"robot": robotInfo,
"iconPath": "package",
"type": RobotEntryType.Robot,
}));
}
getTreeItem(element: RobotEntry): vscode.TreeItem {
const isTask: boolean = element.type === RobotEntryType.Task;
const treeItem = new vscode.TreeItem(element.label, vscode.TreeItemCollapsibleState.Collapsed);
if (element.type === RobotEntryType.Robot) {
treeItem.contextValue = "robotItem";
} else if (isTask) {
treeItem.contextValue = "taskItem";
treeItem.collapsibleState = vscode.TreeItemCollapsibleState.None;
}
treeItem.iconPath = new vscode.ThemeIcon(element.iconPath);
return treeItem;
}
}
export class LocatorsTreeDataProvider implements vscode.TreeDataProvider<LocatorEntry> {
private _onDidChangeTreeData: vscode.EventEmitter<LocatorEntry | null> =
new vscode.EventEmitter<LocatorEntry | null>();
readonly onDidChangeTreeData: vscode.Event<LocatorEntry | null> = this._onDidChangeTreeData.event;
private lastRobotEntry: RobotEntry = undefined;
fireRootChange() {
this._onDidChangeTreeData.fire(null);
}
onRobotsTreeSelectionChanged() {
let robotEntry: RobotEntry = getSelectedRobot();
if (!this.lastRobotEntry && !robotEntry) {
// nothing changed
return;
}
if (!this.lastRobotEntry && robotEntry) {
// i.e.: we didn't have a selection previously: refresh.
this.fireRootChange();
return;
}
if (!robotEntry && this.lastRobotEntry) {
this.fireRootChange();
return;
}
if (robotEntry.robot.filePath != this.lastRobotEntry.robot.filePath) {
// i.e.: the selection changed: refresh.
this.fireRootChange();
return;
}
}
async getChildren(element?: LocatorEntry): Promise<LocatorEntry[]> {
// i.e.: the contents of this tree depend on what's selected in the robots tree.
const robotsTree = treeViewIdToTreeView.get(TREE_VIEW_ROBOCORP_ROBOTS_TREE);
if (!robotsTree || robotsTree.selection.length == 0) {
this.lastRobotEntry = undefined;
return [
{
name: "<Waiting for Robot Selection...>",
type: "info",
line: 0,
column: 0,
filePath: undefined,
},
];
}
let robotEntry: RobotEntry = robotsTree.selection[0];
let actionResult: ActionResult<LocatorEntry[]> = await vscode.commands.executeCommand(
roboCommands.ROBOCORP_GET_LOCATORS_JSON_INFO,
{ "robotYaml": robotEntry.robot.filePath }
);
if (!actionResult["success"]) {
this.lastRobotEntry = undefined;
return [
{
name: actionResult.message,
type: "error",
line: 0,
column: 0,
filePath: robotEntry.robot.filePath,
},
];
}
this.lastRobotEntry = robotEntry;
return actionResult["result"];
}
getTreeItem(element: LocatorEntry): vscode.TreeItem {
const treeItem = new vscode.TreeItem(element.name);
// https://microsoft.github.io/vscode-codicons/dist/codicon.html
let iconPath = "file-media";
if (element.type === "browser") {
iconPath = "browser";
} else if (element.type === "error") {
iconPath = "error";
}
// Only add context to actual locator items
if (element.type !== "error") {
treeItem.contextValue = "locatorEntry";
}
treeItem.iconPath = new vscode.ThemeIcon(iconPath);
return treeItem;
}
}
export function refreshCloudTreeView() {
let dataProvider: CloudTreeDataProvider = <CloudTreeDataProvider>(
treeViewIdToTreeDataProvider.get(TREE_VIEW_ROBOCORP_CLOUD_TREE)
);
if (dataProvider) {
dataProvider.refreshOnce = true;
dataProvider.fireRootChange();
}
}
export function refreshTreeView(treeViewId: string) {
let dataProvider: RobotsTreeDataProvider = <RobotsTreeDataProvider>treeViewIdToTreeDataProvider.get(treeViewId);
if (dataProvider) {
dataProvider.fireRootChange();
}
}
export function openRobotTreeSelection(robot?: RobotEntry) {
if (!robot) {
robot = getSelectedRobot();
}
if (robot) {
vscode.window.showTextDocument(robot.uri);
}
}
export function cloudUploadRobotTreeSelection(robot?: RobotEntry) {
if (!robot) {
robot = getSelectedRobot();
}
if (robot) {
uploadRobot(robot.robot);
}
}
export async function createRccTerminalTreeSelection(robot?: RobotEntry) {
if (!robot) {
robot = getSelectedRobot();
}
if (robot) {
createRccTerminal(robot.robot);
}
}
export function runSelectedRobot(noDebug: boolean, taskRobotEntry?: RobotEntry) {
if (!taskRobotEntry) {
taskRobotEntry = getSelectedRobot(
"Unable to make launch (Robot task not selected in Robots Tree).",
"Unable to make launch -- only 1 task must be selected."
);
}
runRobotRCC(noDebug, taskRobotEntry.robot.filePath, taskRobotEntry.taskName);
}
export function registerViews(context: ExtensionContext) {
let cloudTreeDataProvider = new CloudTreeDataProvider();
let cloudTree = vscode.window.createTreeView(TREE_VIEW_ROBOCORP_CLOUD_TREE, {
"treeDataProvider": cloudTreeDataProvider,
});
treeViewIdToTreeView.set(TREE_VIEW_ROBOCORP_CLOUD_TREE, cloudTree);
treeViewIdToTreeDataProvider.set(TREE_VIEW_ROBOCORP_CLOUD_TREE, cloudTreeDataProvider);
let treeDataProvider = new RobotsTreeDataProvider();
let robotsTree = vscode.window.createTreeView(TREE_VIEW_ROBOCORP_ROBOTS_TREE, {
"treeDataProvider": treeDataProvider,
});
treeViewIdToTreeView.set(TREE_VIEW_ROBOCORP_ROBOTS_TREE, robotsTree);
treeViewIdToTreeDataProvider.set(TREE_VIEW_ROBOCORP_ROBOTS_TREE, treeDataProvider);
let robotContentTreeDataProvider = new RobotContentTreeDataProvider();
let robotContentTree = vscode.window.createTreeView(TREE_VIEW_ROBOCORP_ROBOT_CONTENT_TREE, {
"treeDataProvider": robotContentTreeDataProvider,
});
treeViewIdToTreeView.set(TREE_VIEW_ROBOCORP_ROBOT_CONTENT_TREE, robotContentTree);
treeViewIdToTreeDataProvider.set(TREE_VIEW_ROBOCORP_ROBOT_CONTENT_TREE, robotContentTreeDataProvider);
context.subscriptions.push(
robotsTree.onDidChangeSelection((e) => robotContentTreeDataProvider.onRobotsTreeSelectionChanged())
);
context.subscriptions.push(
robotContentTree.onDidChangeSelection(async function () {
await robotContentTreeDataProvider.onTreeSelectionChanged(robotContentTree);
})
);
context.subscriptions.push(
robotsTree.onDidChangeSelection((e) => {
let events: RobotEntry[] = e.selection;
if (!events || events.length == 0 || events.length > 1) {
vscode.commands.executeCommand("setContext", "robocorp-code:single-task-selected", false);
vscode.commands.executeCommand("setContext", "robocorp-code:single-robot-selected", false);
return;
}
let robotEntry: RobotEntry = events[0];
vscode.commands.executeCommand(
"setContext",
"robocorp-code:single-task-selected",
robotEntry.type == RobotEntryType.Task
);
vscode.commands.executeCommand("setContext", "robocorp-code:single-robot-selected", true);
})
);
let locatorsDataProvider = new LocatorsTreeDataProvider();
let locatorsTree = vscode.window.createTreeView(TREE_VIEW_ROBOCORP_LOCATORS_TREE, {
"treeDataProvider": locatorsDataProvider,
});
treeViewIdToTreeView.set(TREE_VIEW_ROBOCORP_LOCATORS_TREE, locatorsTree);
treeViewIdToTreeDataProvider.set(TREE_VIEW_ROBOCORP_LOCATORS_TREE, locatorsDataProvider);
context.subscriptions.push(
robotsTree.onDidChangeSelection((e) => locatorsDataProvider.onRobotsTreeSelectionChanged())
);
// Work items tree data provider definition
const workItemsTreeDataProvider = new WorkItemsTreeDataProvider();
const workItemsTree = vscode.window.createTreeView(TREE_VIEW_ROBOCORP_WORK_ITEMS_TREE, {
"treeDataProvider": workItemsTreeDataProvider,
"canSelectMany": true,
});
treeViewIdToTreeView.set(TREE_VIEW_ROBOCORP_WORK_ITEMS_TREE, workItemsTree);
treeViewIdToTreeDataProvider.set(TREE_VIEW_ROBOCORP_WORK_ITEMS_TREE, workItemsTreeDataProvider);
context.subscriptions.push(
robotsTree.onDidChangeSelection((e) => workItemsTreeDataProvider.onRobotsTreeSelectionChanged())
);
context.subscriptions.push(
workItemsTree.onDidChangeSelection(async function () {
await workItemsTreeDataProvider.onTreeSelectionChanged(workItemsTree);
})
);
let robotsWatcher: vscode.FileSystemWatcher = vscode.workspace.createFileSystemWatcher("**/robot.yaml");
let onChangeRobotsYaml = debounce(() => {
// Note: this doesn't currently work if the parent folder is renamed or removed.
// (https://github.com/microsoft/vscode/pull/110858)
refreshTreeView(TREE_VIEW_ROBOCORP_ROBOTS_TREE);
}, 300);
robotsWatcher.onDidChange(onChangeRobotsYaml);
robotsWatcher.onDidCreate(onChangeRobotsYaml);
robotsWatcher.onDidDelete(onChangeRobotsYaml);
let locatorsWatcher: vscode.FileSystemWatcher = vscode.workspace.createFileSystemWatcher("**/locators.json");
let onChangeLocatorsJson = debounce(() => {
// Note: this doesn't currently work if the parent folder is renamed or removed.
// (https://github.com/microsoft/vscode/pull/110858)
refreshTreeView(TREE_VIEW_ROBOCORP_LOCATORS_TREE);
}, 300);
locatorsWatcher.onDidChange(onChangeLocatorsJson);
locatorsWatcher.onDidCreate(onChangeLocatorsJson);
locatorsWatcher.onDidDelete(onChangeLocatorsJson);
context.subscriptions.push(robotsTree);
context.subscriptions.push(locatorsTree);
context.subscriptions.push(robotsWatcher);
context.subscriptions.push(locatorsWatcher);
} | the_stack |
'use strict';
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import {
window,
workspace,
ExtensionContext,
TextEditor,
TextDocument,
TextEditorSelectionChangeEvent,
Selection,
Range,
StatusBarAlignment,
StatusBarItem,
ThemeColor
} from 'vscode';
import Variable from './lib/variables/variable';
import ColorUtil, { IDecoration, DocumentLine, LineExtraction } from './lib/util/color-util';
import Queue from './lib/queue';
import VariablesManager from './lib/variables/variables-manager';
import CacheManager from './lib/cache-manager';
import EditorManager from './lib/editor-manager';
import * as globToRegexp from 'glob-to-regexp';
import VariableDecoration from './lib/variables/variable-decoration';
import { getColorizeConfig, ColorizeConfig } from './lib/colorize-config';
import Listeners from './listeners';
let config: ColorizeConfig = {
languages: [],
isHideCurrentLineDecorations: true,
colorizedVariables: [],
colorizedColors: [],
filesToExcludes: [],
filesToIncludes: [],
inferedFilesToInclude: [],
searchVariables: false,
decorationFn: null
};
class ColorizeContext {
editor: TextEditor = null;
nbLine = 0;
deco: Map < number, IDecoration[] > = new Map();
currentSelection: number[] = null;
statusBar: StatusBarItem;
constructor() {
this.statusBar = window.createStatusBarItem(StatusBarAlignment.Right);
}
updateStatusBar(activated: boolean):void {
// List of icons can be found here https://code.visualstudio.com/api/references/icons-in-labels
const icon = activated
? '$(check)'
: '$(circle-slash)';
const color = activated
? undefined
: new ThemeColor('errorForeground');
const hoverMessage = activated
? 'Colorize is activated for this file'
: 'Colorize is not activated for this file';
this.statusBar.text = `${icon} Colorize`;
this.statusBar.color = color;
this.statusBar.tooltip = hoverMessage;
this.statusBar.show();
}
}
const q = new Queue();
async function initDecorations(context: ColorizeContext) {
if (!context.editor) {
return;
}
const text = context.editor.document.getText();
const fileLines: DocumentLine[] = ColorUtil.textToFileLines(text);
const lines: DocumentLine[] = context.editor.visibleRanges.reduce((acc: DocumentLine[], range: Range) => {
return [
...acc,
...fileLines.slice(range.start.line, range.end.line + 2)
];
}, []);
// removeDuplicateDecorations(context);
await VariablesManager.findVariablesDeclarations(context.editor.document.fileName, fileLines);
const variables: LineExtraction[] = await VariablesManager.findVariables(context.editor.document.fileName, lines);
const colors: LineExtraction[] = await ColorUtil.findColors(lines);
generateDecorations(colors, variables, context.deco);
return EditorManager.decorate(context.editor, context.deco, context.currentSelection);
}
function updateContextDecorations(decorations: Map<number, IDecoration[]>, context: ColorizeContext): void {
const it = decorations.entries();
let tmp = it.next();
while (!tmp.done) {
const line = tmp.value[0];
if (context.deco.has(line)) {
context.deco.set(line, context.deco.get(line).concat(decorations.get(line)));
} else {
context.deco.set(line, decorations.get(line));
}
tmp = it.next();
}
}
function removeDuplicateDecorations(context: ColorizeContext): void {
const it = context.deco.entries();
const m: Map<number, IDecoration[]> = new Map();
let tmp = it.next();
while (!tmp.done) {
const line = tmp.value[0];
const decorations = tmp.value[1];
let newDecorations = [];
// TODO; use reduce?
decorations.forEach((deco: VariableDecoration) => {
deco.generateRange(line);
const exist = newDecorations.findIndex((_: IDecoration) => deco.currentRange.isEqual(_.currentRange));
if (exist !== -1) {
newDecorations[exist].dispose();
newDecorations = newDecorations.filter((_, i) => i !== exist);
}
newDecorations.push(deco);
});
m.set(line, newDecorations);
tmp = it.next();
}
context.deco = m;
}
function updateDecorationMap(map: Map<number, IDecoration[]>, line: number, decoration: IDecoration ) {
if (map.has(line)) {
map.set(line, map.get(line).concat([decoration]));
} else {
map.set(line, [decoration]);
}
}
function generateDecorations(colors: LineExtraction[], variables: LineExtraction[], decorations: Map<number, IDecoration[]>): Map<number, IDecoration[]> {
colors.map(({line, colors}) => colors.forEach((color) => {
const decoration = ColorUtil.generateDecoration(color, line, config.decorationFn);
updateDecorationMap(decorations, line, decoration);
}));
variables.map(({line, colors}) => colors.forEach((variable) => {
const decoration = VariablesManager.generateDecoration(<Variable>variable, line, config.decorationFn);
updateDecorationMap(decorations, line, decoration);
}));
return decorations;
}
/**
* Check if COLORIZE support a language
*
* @param {string} languageId A valid languageId
* @returns {boolean}
*/
function isLanguageSupported(languageId: string): boolean {
return config.languages.indexOf(languageId) !== -1;
}
/**
* Check if the file is the `colorize.include` setting
*
* @param {string} fileName A valid filename (path to the file)
* @returns {boolean}
*/
function isIncludedFile(fileName: string): boolean {
return config.filesToIncludes.find((globPattern: string) => globToRegexp(globPattern).test(fileName)) !== undefined;
}
/**
* Check if a file can be colorized by COLORIZE
*
* @param {TextDocument} document The document to test
* @returns {boolean}
*/
function canColorize(document: TextDocument): boolean { // update to use filesToExcludes. Remove `isLanguageSupported` ? checking path with file extension or include glob pattern should be enough
return isLanguageSupported(document.languageId) || isIncludedFile(document.fileName);
}
function handleTextSelectionChange(event: TextEditorSelectionChangeEvent, cb: () => void) {
if (!config.isHideCurrentLineDecorations || event.textEditor !== extension.editor) {
return cb();
}
if (extension.currentSelection.length !== 0) {
extension.currentSelection.forEach(line => {
const decorations = extension.deco.get(line);
if (decorations !== undefined) {
EditorManager.decorateOneLine(extension.editor, decorations, line);
}
});
}
extension.currentSelection = [];
event.selections.forEach((selection: Selection) => {
const decorations = extension.deco.get(selection.active.line);
if (decorations) {
decorations.forEach(_ => _.hide());
}
});
extension.currentSelection = event.selections.map((selection: Selection) => selection.active.line);
return cb();
}
function handleCloseOpen(document: TextDocument) {
q.push((cb) => {
if (extension.editor && extension.editor.document.fileName === document.fileName) {
CacheManager.saveDecorations(document, extension.deco);
return cb();
}
return cb();
});
}
async function colorize(editor: TextEditor, cb: () => void): Promise<void> {
extension.editor = null;
extension.deco = new Map();
if (!editor || !canColorize(editor.document)) {
extension.updateStatusBar(false);
return cb();
}
extension.updateStatusBar(true);
extension.editor = editor;
extension.currentSelection = editor.selections.map((selection: Selection) => selection.active.line);
const deco = CacheManager.getCachedDecorations(editor.document);
if (deco) {
extension.deco = deco;
extension.nbLine = editor.document.lineCount;
EditorManager.decorate(extension.editor, extension.deco, extension.currentSelection);
} else {
extension.nbLine = editor.document.lineCount;
try {
await initDecorations(extension);
} finally {
CacheManager.saveDecorations(extension.editor.document, extension.deco);
}
}
return cb();
}
function handleChangeActiveTextEditor(editor: TextEditor) {
if (extension.editor !== undefined && extension.editor !== null) {
extension.deco.forEach(decorations => decorations.forEach(deco => deco.hide()));
CacheManager.saveDecorations(extension.editor.document, extension.deco);
}
getVisibleFileEditors().filter(e => e !== editor).forEach(e => {
q.push(cb => colorize(e, cb));
});
q.push(cb => colorize(editor, cb));
}
function cleanDecorationList(context: ColorizeContext, cb: () => void): void {
const it = context.deco.entries();
let tmp = it.next();
while (!tmp.done) {
const line = tmp.value[0];
const decorations = tmp.value[1];
context.deco.set(line, decorations.filter(decoration => !decoration.disposed));
tmp = it.next();
}
return cb();
}
function clearCache() {
extension.deco.clear();
extension.deco = new Map();
CacheManager.clearCache();
}
function handleConfigurationChanged() {
const newConfig = getColorizeConfig();
clearCache();
// delete current decorations then regenerate decorations
ColorUtil.setupColorsExtractors(newConfig.colorizedColors);
q.push(async (cb) => {
// remove event listeners?
VariablesManager.setupVariablesExtractors(newConfig.colorizedVariables);
if (newConfig.searchVariables) {
await VariablesManager.getWorkspaceVariables(newConfig.filesToIncludes.concat(newConfig.inferedFilesToInclude), newConfig.filesToExcludes); // 👍
}
return cb();
});
config = newConfig;
colorizeVisibleTextEditors();
}
function initEventListeners(context: ExtensionContext) {
window.onDidChangeTextEditorSelection((event) => q.push((cb) => handleTextSelectionChange(event, cb)), null, context.subscriptions);
workspace.onDidCloseTextDocument(handleCloseOpen, null, context.subscriptions);
workspace.onDidSaveTextDocument(handleCloseOpen, null, context.subscriptions);
window.onDidChangeActiveTextEditor(handleChangeActiveTextEditor, null, context.subscriptions);
workspace.onDidChangeConfiguration(handleConfigurationChanged, null, context.subscriptions); // Does not update when local config file is edited manualy ><
Listeners.setupEventListeners(context);
}
function getVisibleFileEditors(): TextEditor[] {
return window.visibleTextEditors.filter(editor => editor.document.uri.scheme === 'file');
}
function colorizeVisibleTextEditors() {
extension.nbLine = 65;
getVisibleFileEditors().forEach(editor => {
q.push(cb => colorize(editor, cb));
});
}
let extension: ColorizeContext;
export function activate(context: ExtensionContext): ColorizeContext {
extension = new ColorizeContext();
config = getColorizeConfig();
ColorUtil.setupColorsExtractors(config.colorizedColors);
VariablesManager.setupVariablesExtractors(config.colorizedVariables);
q.push(async cb => {
try {
if (config.searchVariables) {
await VariablesManager.getWorkspaceVariables(config.filesToIncludes.concat(config.inferedFilesToInclude), config.filesToExcludes); // 👍
}
initEventListeners(context);
} catch (error) {
// do something
}
return cb();
});
colorizeVisibleTextEditors();
return extension;
}
// this method is called when your extension is deactivated
export function deactivate(): void {
extension.nbLine = null;
extension.editor = null;
extension.deco.clear();
extension.deco = null;
CacheManager.clearCache();
}
export {
canColorize,
ColorizeContext,
colorize,
config,
extension,
q,
updateContextDecorations,
generateDecorations,
removeDuplicateDecorations,
cleanDecorationList
}; | the_stack |
import { ActorQueryOperation, Bindings } from '@comunica/bus-query-operation';
import { KeysInitSparql } from '@comunica/context-entries';
import { Bus } from '@comunica/core';
import type { IActorQueryOperationOutputBindings } from '@comunica/types';
import { ArrayIterator } from 'asynciterator';
import { Map } from 'immutable';
import { DataFactory } from 'rdf-data-factory';
import type { Algebra } from 'sparqlalgebrajs';
import { Factory, translate } from 'sparqlalgebrajs';
import * as sparqlee from 'sparqlee';
import { isExpressionError } from 'sparqlee';
import { ActorQueryOperationFilterSparqlee } from '../lib/ActorQueryOperationFilterSparqlee';
const arrayifyStream = require('arrayify-stream');
const DF = new DataFactory();
function template(expr: string) {
return `
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX fn: <https://www.w3.org/TR/xpath-functions#>
PREFIX err: <http://www.w3.org/2005/xqt-errors#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
SELECT * WHERE { ?s ?p ?o FILTER (${expr})}
`;
}
function parse(query: string): Algebra.Expression {
const sparqlQuery = translate(template(query));
// Extract filter expression from complete query
return sparqlQuery.input.expression;
}
describe('ActorQueryOperationFilterSparqlee', () => {
let bus: any;
let mediatorQueryOperation: any;
const simpleSPOInput = new Factory().createBgp([ new Factory().createPattern(
DF.variable('s'),
DF.variable('p'),
DF.variable('o'),
) ]);
const truthyExpression = parse('"nonemptystring"');
const falsyExpression = parse('""');
const erroringExpression = parse('?a + ?a');
const unknownExpression = {
args: [],
expressionType: 'operator',
operator: 'DUMMY',
};
beforeEach(() => {
bus = new Bus({ name: 'bus' });
mediatorQueryOperation = {
mediate: (arg: any) => Promise.resolve({
bindingsStream: new ArrayIterator([
Bindings({ '?a': DF.literal('1') }),
Bindings({ '?a': DF.literal('2') }),
Bindings({ '?a': DF.literal('3') }),
], { autoStart: false }),
metadata: () => Promise.resolve({ totalItems: 3 }),
operated: arg,
type: 'bindings',
variables: [ 'a' ],
canContainUndefs: false,
}),
};
});
describe('The ActorQueryOperationFilterSparqlee module', () => {
it('should be a function', () => {
expect(ActorQueryOperationFilterSparqlee).toBeInstanceOf(Function);
});
it('should be a ActorQueryOperationFilterSparqlee constructor', () => {
expect(new (<any> ActorQueryOperationFilterSparqlee)({ name: 'actor', bus, mediatorQueryOperation }))
.toBeInstanceOf(ActorQueryOperationFilterSparqlee);
expect(new (<any> ActorQueryOperationFilterSparqlee)({ name: 'actor', bus, mediatorQueryOperation }))
.toBeInstanceOf(ActorQueryOperation);
});
it('should not be able to create new ActorQueryOperationFilterSparqlee objects without \'new\'', () => {
expect(() => { (<any> ActorQueryOperationFilterSparqlee)(); }).toThrow();
});
});
describe('An ActorQueryOperationFilterSparqlee instance', () => {
let actor: ActorQueryOperationFilterSparqlee;
let factory: Factory;
beforeEach(() => {
actor = new ActorQueryOperationFilterSparqlee({ name: 'actor', bus, mediatorQueryOperation });
factory = new Factory();
});
it('should test on filter', () => {
const op: any = { operation: { type: 'filter', expression: truthyExpression }};
return expect(actor.test(op)).resolves.toBeTruthy();
});
it('should fail on unsupported operators', () => {
const op: any = { operation: { type: 'filter', expression: unknownExpression }};
return expect(actor.test(op)).rejects.toBeTruthy();
});
it('should not test on non-filter', () => {
const op: any = { operation: { type: 'some-other-type' }};
return expect(actor.test(op)).rejects.toBeTruthy();
});
it('should return the full stream for a truthy filter', async() => {
const op: any = { operation: { type: 'filter', input: {}, expression: truthyExpression }};
const output: IActorQueryOperationOutputBindings = <any> await actor.run(op);
expect(await arrayifyStream(output.bindingsStream)).toMatchObject([
Bindings({ '?a': DF.literal('1') }),
Bindings({ '?a': DF.literal('2') }),
Bindings({ '?a': DF.literal('3') }),
]);
expect(output.type).toEqual('bindings');
expect(await (<any> output).metadata()).toMatchObject({ totalItems: 3 });
expect(output.variables).toMatchObject([ 'a' ]);
expect(output.canContainUndefs).toEqual(false);
});
it('should return an empty stream for a falsy filter', async() => {
const op: any = { operation: { type: 'filter', input: {}, expression: falsyExpression }};
const output: IActorQueryOperationOutputBindings = <any> await actor.run(op);
expect(await arrayifyStream(output.bindingsStream)).toMatchObject([]);
expect(await (<any> output).metadata()).toMatchObject({ totalItems: 3 });
expect(output.type).toEqual('bindings');
expect(output.variables).toMatchObject([ 'a' ]);
expect(output.canContainUndefs).toEqual(false);
});
it('should return an empty stream when the expressions error', async() => {
const op: any = { operation: { type: 'filter', input: {}, expression: erroringExpression }};
const output: IActorQueryOperationOutputBindings = <any> await actor.run(op);
expect(await arrayifyStream(output.bindingsStream)).toMatchObject([]);
expect(await (<any> output).metadata()).toMatchObject({ totalItems: 3 });
expect(output.type).toEqual('bindings');
expect(output.variables).toMatchObject([ 'a' ]);
expect(output.canContainUndefs).toEqual(false);
});
it('Should log warning for an expressionError', async() => {
// The order is very important. This item requires isExpressionError to still have it's right definition.
const logWarnSpy = jest.spyOn(<any> actor, 'logWarn');
const op: any = { operation: { type: 'filter', input: {}, expression: erroringExpression }};
const output: IActorQueryOperationOutputBindings = <any> await actor.run(op);
await new Promise<void>(resolve => output.bindingsStream.on('end', resolve));
expect(logWarnSpy).toHaveBeenCalledTimes(3);
logWarnSpy.mock.calls.forEach((call, index) => {
const dataCB = <() => { error: any; bindings: Bindings }> call[2];
const { error, bindings } = dataCB();
expect(isExpressionError(error)).toBeTruthy();
expect(bindings).toEqual({
'?a': DF.literal(String(index + 1), DF.namedNode('http://www.w3.org/2001/XMLSchema#string')),
});
});
});
it('should emit an error for a hard erroring filter', async() => {
// eslint-disable-next-line no-import-assign
Object.defineProperty(sparqlee, 'isExpressionError', { writable: true });
(<any> sparqlee).isExpressionError = jest.fn(() => false);
const op: any = { operation: { type: 'filter', input: {}, expression: erroringExpression }};
const output: IActorQueryOperationOutputBindings = <any> await actor.run(op);
await new Promise<void>(resolve => output.bindingsStream.on('error', () => resolve()));
});
it('should use and respect the baseIRI from the expression context', async() => {
const expression = parse('str(IRI(?a)) = concat("http://example.com/", ?a)');
const context = Map({
[KeysInitSparql.baseIRI]: 'http://example.com',
});
const op: any = { operation: { type: 'filter', input: {}, expression }, context };
const output: IActorQueryOperationOutputBindings = <any> await actor.run(op);
expect(await arrayifyStream(output.bindingsStream)).toMatchObject([
Bindings({ '?a': DF.literal('1') }),
Bindings({ '?a': DF.literal('2') }),
Bindings({ '?a': DF.literal('3') }),
]);
expect(output.type).toEqual('bindings');
expect(await (<any> output).metadata()).toMatchObject({ totalItems: 3 });
expect(output.variables).toMatchObject([ 'a' ]);
expect(output.canContainUndefs).toEqual(false);
});
describe('should be able to handle EXIST filters', () => {
it('like a simple EXIST that is true', async() => {
const resolver = ActorQueryOperation.createExistenceResolver(Map(), actor.mediatorQueryOperation);
const expr: Algebra.ExistenceExpression = factory.createExistenceExpression(
false,
factory.createBgp([]),
);
const result = resolver(expr, Bindings({}));
expect(await result).toBe(true);
});
it('like a simple EXIST that is false', async() => {
const resolver = ActorQueryOperation.createExistenceResolver(Map(), actor.mediatorQueryOperation);
mediatorQueryOperation.mediate = (arg: any) => Promise.resolve({
bindingsStream: new ArrayIterator([], { autoStart: false }),
metadata: () => Promise.resolve({ totalItems: 0 }),
operated: arg,
type: 'bindings',
variables: [ 'a' ],
});
const expr: Algebra.ExistenceExpression = factory.createExistenceExpression(
false,
factory.createBgp([]),
);
const result = resolver(expr, Bindings({}));
expect(await result).toBe(false);
});
it('like a NOT EXISTS', async() => {
const resolver = ActorQueryOperation.createExistenceResolver(Map(), actor.mediatorQueryOperation);
mediatorQueryOperation.mediate = (arg: any) => Promise.resolve({
bindingsStream: new ArrayIterator([], { autoStart: false }),
metadata: () => Promise.resolve({ totalItems: 0 }),
operated: arg,
type: 'bindings',
variables: [ 'a' ],
});
const expr: Algebra.ExistenceExpression = factory.createExistenceExpression(
true,
factory.createBgp([]),
);
const result = resolver(expr, Bindings({}));
expect(await result).toBe(true);
});
it('like an EXIST that errors', async() => {
const resolver = ActorQueryOperation.createExistenceResolver(Map(), actor.mediatorQueryOperation);
const bindingsStream = new ArrayIterator([{}, {}, {}]).transform({
autoStart: false,
transform(item, done, push) {
push(item);
bindingsStream.emit('error', 'Test error');
done();
},
});
mediatorQueryOperation.mediate = (arg: any) => Promise.resolve({
bindingsStream,
metadata: () => Promise.resolve({ totalItems: 3 }),
operated: arg,
type: 'bindings',
variables: [ 'a' ],
});
const expr: Algebra.ExistenceExpression = factory.createExistenceExpression(
false,
factory.createBgp([]),
);
await expect(resolver(expr, Bindings({}))).rejects.toBeTruthy();
});
});
});
}); | the_stack |
import * as _ from 'lodash';
import {Component, ElementRef, EventEmitter, Injector, OnDestroy, OnInit, Output, ViewChild} from '@angular/core';
import {Alert} from '@common/util/alert.util';
import {StringUtil} from '@common/util/string.util';
import {SelectComponent} from '@common/component/select/select.component';
import {
InequalityType,
MeasureInequalityFilter
} from '@domain/workbook/configurations/filter/measure-inequality-filter';
import {MeasurePositionFilter, PositionType} from '@domain/workbook/configurations/filter/measure-position-filter';
import {
Candidate,
InclusionFilter,
InclusionSelectorType,
InclusionSortBy
} from '@domain/workbook/configurations/filter/inclusion-filter';
import {Field, FieldRole} from '@domain/datasource/datasource';
import {CustomField} from '@domain/workbook/configurations/field/custom-field';
import {ContainsType, WildCardFilter} from '@domain/workbook/configurations/filter/wild-card-filter';
import {AggregationType} from '@domain/workbook/configurations/field/measure-field';
import {AdvancedFilter} from '@domain/workbook/configurations/filter/advanced-filter';
import {Dashboard} from '@domain/dashboard/dashboard';
import {DIRECTION} from '@domain/workbook/configurations/sort';
import {RegExprFilter} from '@domain/workbook/configurations/filter/reg-expr-filter';
import {FilterUtil} from '../../util/filter.util';
import {DashboardUtil} from '../../util/dashboard.util';
import {DatasourceService} from '../../../datasource/service/datasource.service';
import {AbstractFilterPopupComponent} from '../abstract-filter-popup.component';
import {CommonUtil} from '@common/util/common.util';
@Component({
selector: 'app-config-filter-inclusion',
templateUrl: './configure-filters-inclusion.component.html',
styles: ['.sys-essential-result { position: relative !important; bottom: 0 !important; left: 0 !important; right: 0 !important; }']
})
export class ConfigureFiltersInclusionComponent extends AbstractFilterPopupComponent implements OnInit, OnDestroy {
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
@ViewChild('inputSearch')
private _inputSearch: ElementRef;
@ViewChild('wildCardContains')
private _wildCardContainsCombo: SelectComponent;
@ViewChild('conditionField')
private _condFieldCombo: SelectComponent;
@ViewChild('conditionAggregation')
private _condAggrCombo: SelectComponent;
@ViewChild('conditionInequality')
private _condInequalityCombo: SelectComponent;
@ViewChild('limitPosition')
private _limitPositionCombo: SelectComponent;
@ViewChild('limitField')
private _limitFieldCombo: SelectComponent;
@ViewChild('limitAggregation')
private _limitAggrCombo: SelectComponent;
// 후보군 리스트
private _candidateList: Candidate[] = [];
// 대시보드 정보
private _board: Dashboard;
// 선택 정보
private _candidateValues: Candidate[] = []; // 기본 선택 값 목록
// 대상 필드 정보
private _targetField: Field | CustomField;
// 필터링 관련 ( 원본값 저장용 )
private _condition: MeasureInequalityFilter;
private _limitation: MeasurePositionFilter;
private _wildcard: WildCardFilter;
private _regExpr: RegExprFilter;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
public selectedValues: Candidate[] = []; // 기본 선택 값 목록
public isShow: boolean = false; // 컴포넌트 표시 여부
public isOnlyShowCandidateValues: boolean = false; // 표시할 후보값만 표시 여부
public useAll: boolean = false; // 전체 선택 표시 여부
public isNoData: boolean = false; // 데이터 없음 표시 여부
// 수정 대상
public targetFilter: InclusionFilter;
// 페이징 관련
public pageCandidateList: Candidate[] = [];
public currentPage: number = 1;
public lastPage: number = 1;
public pageSize: number = 15;
public totalCount: number = 0;
public totalItemCnt: number = 0;
// 검색 관련
public searchText: string = '';
// 신규 후보값 이름
public newCandidateName: string = '';
// 필터링 관련
public condition: MeasureInequalityFilter;
public limitation: MeasurePositionFilter;
public wildcard: WildCardFilter;
public regExpr: RegExprFilter;
public measureFields: Field[] = [];
public useDefineValue: boolean = true;
public usePaging: boolean = true;
public matcherTypeList: any[];
public selectedMatcherType: any;
public sortBy = InclusionSortBy;
public sortDirection = DIRECTION;
@Output()
public goToSelectField: EventEmitter<any> = new EventEmitter();
public itemShowCnt: number = FilterUtil.CANDIDATE_LIMIT;
public commonUtil = CommonUtil;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Constructor
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// 생성자
constructor(private datasourceService: DatasourceService,
protected elementRef: ElementRef,
protected injector: Injector) {
super(elementRef, injector);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Override Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// Init
public ngOnInit() {
super.ngOnInit();
this.matcherTypeList = [
{label: this.translateService.instant('msg.board.th.filter.wildcard'), value: MatcherType.WILDCARD},
{
label: this.translateService.instant('msg.board.th.filter.regular-expression'),
value: MatcherType.REGULAR_EXPRESSION
}
];
this.selectedMatcherType = this.matcherTypeList[0];
}
// Destroy
public ngOnDestroy() {
super.ngOnDestroy();
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* Candidate Limit 을 넘겼는지 여부
*/
public get isOverCandidateWarning(): boolean {
return FilterUtil.CANDIDATE_LIMIT <= this._candidateList.length;
} // get - isOverCandidateWarning
/**
* Candidate 목록의 전체 갯수 조회
*/
public get candidateListSize(): number {
return this._candidateList.length;
} // get - candidateListSize
/**
* 컴포넌트를 표시한다.
* @param {Dashboard} board
* @param {InclusionFilter} targetFilter
* @param {Field | CustomField} targetField
* @param {boolean} useDefineValue
*/
public showComponent(board: Dashboard, targetFilter: InclusionFilter, targetField: (Field | CustomField), useDefineValue: boolean = true) {
this.useDefineValue = useDefineValue;
// 데이터 설정
const preFilterData = {
contains: this.wildCardTypeList[0].value,
aggregation: this.aggregationTypeList[0].value,
inequality: this.conditionTypeList[0].value,
position: this.limitTypeList[0].value
};
const dsFields: Field[] = DashboardUtil.getFieldsForMainDataSource(board.configuration, targetFilter.dataSource);
this.measureFields = dsFields.filter(item => {
return item.role === FieldRole.MEASURE && 'user_expr' !== item.type;
});
const defaultData: InclusionFilter
= FilterUtil.getBasicInclusionFilter(targetField as Field, targetFilter.ui.importanceType, preFilterData);
if (targetFilter.preFilters) {
// lodash merge가 deepMerge 가 잘 되지 않아서 별도로 하위 데이터를 직접 합쳐줌
targetFilter.preFilters = targetFilter.preFilters.map((data: AdvancedFilter) => {
const defaultPreFilter: AdvancedFilter
= defaultData.preFilters.find((preFilter: AdvancedFilter) => data.type === preFilter.type);
return _.merge(defaultPreFilter, data);
});
} else {
targetFilter.preFilters = defaultData.preFilters;
}
targetFilter = _.merge({}, defaultData, targetFilter);
targetFilter.preFilters.forEach((preFilter: AdvancedFilter) => {
if (preFilter.type === 'measure_inequality') {
this._condition = preFilter as MeasureInequalityFilter;
this.condition = _.cloneDeep(this._condition);
} else if (preFilter.type === 'measure_position') {
this._limitation = preFilter as MeasurePositionFilter;
this.limitation = _.cloneDeep(this._limitation);
} else if (preFilter.type === 'wildcard') {
this._wildcard = preFilter as WildCardFilter;
this.wildcard = _.cloneDeep(this._wildcard);
} else if (preFilter.type === 'regexpr') {
this._regExpr = preFilter as RegExprFilter;
this.regExpr = _.cloneDeep(this._regExpr);
}
});
if (StringUtil.isNotEmpty(this.wildcard.value)) {
this.selectedMatcherType = this.matcherTypeList[0];
} else if (StringUtil.isNotEmpty(this.regExpr.expr)) {
this.selectedMatcherType = this.matcherTypeList[1];
}
// 값 정보 설정
if (targetFilter.valueList && 0 < targetFilter.valueList.length) {
this.selectedValues = targetFilter.valueList.map(item => this._stringToCandidate(item));
(1 < this.selectedValues.length) && (targetFilter.selector = InclusionSelectorType.MULTI_LIST);
}
if (targetFilter.candidateValues && 0 < targetFilter.candidateValues.length) {
this._candidateValues = targetFilter.candidateValues.map(item => this._stringToCandidate(item));
}
if (targetFilter.definedValues && 0 < targetFilter.definedValues.length) {
this._candidateList = targetFilter.definedValues.map(item => this._stringToCandidate(item, true));
}
this.itemShowCnt = targetFilter.limit ? targetFilter.limit : FilterUtil.CANDIDATE_LIMIT;
this.loadingShow();
this.datasourceService.getCandidateForFilter(targetFilter, board, [], targetField, 'COUNT', this.searchText, this.itemShowCnt)
.then(result => {
// console.log('getCandidateForFilter');
// console.log('result, ' , result);
this.targetFilter = targetFilter;
this._targetField = targetField;
this._board = board;
this._setCandidateResult(result, targetFilter, targetField);
if (0 === this._candidateValues.length) {
this._candidateValues = this._candidateList.slice(0, 100);
}
// 전체 선택 기능 체크 및 전체 선택 기능이 비활성 일떄, 초기값 기본 선택 - for Essential Filter
this.useAll = !(-1 < targetField.filteringSeq);
if (false === this.useAll && 0 === this.selectedValues.length) {
this.selectedValues.push(this._candidateList[0]);
}
// this.itemShowCnt = this.candidateListSize > 100 ? 100 : this.candidateListSize;
this.isShow = true;
this.safelyDetectChanges();
this.loadingHide();
})
.catch(err => this.commonExceptionHandler(err));
} // function - showComponent
/**
* 현재 설정된 정보를 반환한다.
* @return {InclusionFilter}
*/
public getData(): InclusionFilter {
const filter: InclusionFilter = this.targetFilter;
filter.limit = this.itemShowCnt;
filter.valueList = this.selectedValues.map(item => item.name);
filter.candidateValues = this._candidateValues.map(item => item.name);
filter.definedValues = this._candidateList.filter(item => item.isDefinedValue).map(item => item.name);
return filter;
} // function - getData
// noinspection JSMethodCanBeStatic
/**
* 단일 선택 여부를 반환한다
* @param {InclusionFilter} targetFilter
* @return {boolean}
*/
public isSingleSelect(targetFilter: InclusionFilter): boolean {
return InclusionSelectorType.SINGLE_LIST === targetFilter.selector || InclusionSelectorType.SINGLE_COMBO === targetFilter.selector;
} // function - isSingleSelect
/**
* 선택 형식을 결정한다
* @param {InclusionFilter} targetFilter
* @param {string} type
*/
public setSelectorType(targetFilter: InclusionFilter, type: string) {
if ('SINGLE' === type) {
if (this._isListSelector(targetFilter)) {
targetFilter.selector = InclusionSelectorType.SINGLE_LIST;
} else {
targetFilter.selector = InclusionSelectorType.SINGLE_COMBO;
}
if (1 < this.selectedValues.length) {
this.selectedValues = [this.selectedValues[0]];
this.safelyDetectChanges();
}
} else {
if (this._isListSelector(targetFilter)) {
targetFilter.selector = InclusionSelectorType.MULTI_LIST;
} else {
targetFilter.selector = InclusionSelectorType.MULTI_COMBO;
}
}
} // function - setSelectorType
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method - 검색 관련
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 검색 입력을 비활성 처리 합니다.
*/
public inactiveSearchInput() {
const inputElm = this._inputSearch.nativeElement;
('' === inputElm.value.trim()) && (this.targetFilter['isShowSearch'] = false);
inputElm.blur();
} // function - inactiveSearchInput
/**
* 검색어를 이용한 목록 조회
*/
public candidateFromSearchText() {
this.loadingShow();
const sortBy: string = (this.targetFilter.sort && this.targetFilter.sort.by) ? this.targetFilter.sort.by.toString() : 'COUNT';
this.datasourceService.getCandidateForFilter(this.targetFilter, this._board,[], this._targetField, sortBy, this.searchText, this.itemShowCnt)
.then(result => {
this._setCandidateResult(result, this.targetFilter, this._targetField);
this.safelyDetectChanges();
this.loadingHide();
});
} // function - candidateFromSearchText
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method - 필터링 관련
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 와일드카드에 대한 설명을 반환한다.
* @param {WildCardFilter} filter
* @return {string}
*/
public getWildCardDesc(filter: WildCardFilter): string {
const data = this.wildCardTypeList.find(item => ContainsType[item.value] === filter.contains);
return data ? data.description : '';
} // function - getWildCardDesc
/**
* 컨디션에 대한 설명을 반환한다.
* @param {MeasureInequalityFilter} filter
* @return {string}
*/
public getConditionDesc(filter: MeasureInequalityFilter): string {
const aggData = this.aggregationTypeList.find(item => AggregationType[item.value] === filter.aggregation);
const inequalityData = this.conditionTypeList.find(item => InequalityType[item.value] === filter.inequality);
return (aggData && inequalityData) ? aggData.name + ' of values ' + inequalityData.description : '';
} // function - getConditionDesc
/**
* Limit 에 대한 첫번째 설명
* @param {MeasurePositionFilter} filter
* @return {string}
*/
public getLimitDesc1(filter: MeasurePositionFilter): string {
const data = this.limitTypeList.find(item => PositionType[item.value] === filter.position);
return data ? data.description : '';
} // function - getLimitDesc1
/**
* Limit 에 대한 두번째 설명
* @param {MeasurePositionFilter} filter
* @return {string}
*/
public getLimitDesc2(filter: MeasurePositionFilter): string {
const aggData = this.aggregationTypeList.find(item => AggregationType[item.value] === filter.aggregation);
return aggData ? aggData.name : '';
} // function - getLimitDesc2
// noinspection JSMethodCanBeStatic
/**
* WildCart 설정 여부
* @param {WildCardFilter} filter
*/
public isSetWildCard(filter: WildCardFilter) {
return filter.contains && filter.value;
} // function - isSetWildCard
// noinspection JSMethodCanBeStatic
/**
* Condition 설정 여부
* @param {MeasureInequalityFilter} filter
*/
public isSetCondition(filter: MeasureInequalityFilter) {
return filter.field && filter.aggregation && filter.inequality && filter.value;
} // function - isSetCondition
// noinspection JSMethodCanBeStatic
/**
* Limit 설정 여부
* @param {MeasurePositionFilter} filter
*/
public isSetLimit(filter: MeasurePositionFilter) {
return filter.field && filter.aggregation && filter.position && filter.value;
} // function - isSetLimit
// noinspection JSMethodCanBeStatic
/**
* 와일드 카드의 값을 초기화 시킨다.
*/
public resetWildcard(filter: WildCardFilter) {
filter.value = '';
if (this.isWildCardMatcher()) {
this._wildCardContainsCombo.selected(this.wildCardTypeList[0]);
}
this.safelyDetectChanges();
} // function resetWildcard
/**
* 와일드 카드의 값을 초기화 시킨다.
*/
public resetRegExpr(filter: RegExprFilter) {
filter.expr = '';
this.safelyDetectChanges();
} // function resetRegExpr
// noinspection JSMethodCanBeStatic
/**
* condition의 값을 초기화 시킨다.
*/
public resetCondition(filter: MeasureInequalityFilter) {
filter.value = 10;
filter.field = null;
this._condFieldCombo.clearSelect();
this._condAggrCombo.selected(this.aggregationTypeList[0]);
this._condInequalityCombo.selected(this.conditionTypeList[0]);
this.safelyDetectChanges();
} // function resetCondition
// noinspection JSMethodCanBeStatic
/**
* Limit의 값을 초기화 시킨다.
*/
public resetLimitation(filter: MeasurePositionFilter) {
filter.value = 10;
filter.field = null;
this._limitFieldCombo.clearSelect();
this._limitAggrCombo.selected(this.aggregationTypeList[0]);
this._limitPositionCombo.selected(this.limitTypeList[0]);
this.safelyDetectChanges();
} // function resetLimitation
/**
* 위 3개의 조건을 모두 초기화 시킨다.
*/
public resetAll() {
this.resetWildcard(this.wildcard);
this.resetRegExpr(this.regExpr);
this.resetCondition(this.condition);
this.resetLimitation(this.limitation);
this.candidateWithValidation();
} // function resetAll
/**
* validation 체크이후에 candidate 호출
*/
public candidateWithValidation() {
// validation
if (this._isInvalidFiltering()) {
return;
}
if (this.isWildCardMatcher()) {
this.resetRegExpr(this.regExpr);
} else {
this.resetWildcard(this.wildcard);
}
this._wildcard = _.cloneDeep(this.wildcard);
this._regExpr = _.cloneDeep(this.regExpr);
this._condition = _.cloneDeep(this.condition);
this._limitation = _.cloneDeep(this.limitation);
this.targetFilter.preFilters = [this._wildcard, this._regExpr, this._condition, this._limitation];
this.datasourceService.getCandidateForFilter(this.targetFilter, this._board,[], this._targetField, null, null, this.itemShowCnt).then(result => {
this._candidateList = this._candidateList.filter(item => item.isDefinedValue); // initialize list
this._setCandidateResult(result, this.targetFilter, this._targetField);
this.safelyDetectChanges();
this.loadingHide();
});
} // function - candidateWithValidation
/**
* 필터링 설정 레이어 On/Off
* @param {InclusionFilter} filter
*/
public toggleConfigFilteringLayer(filter: InclusionFilter) {
if (!filter['isShowCandidateFilter']) {
this.wildcard = _.cloneDeep(this._wildcard);
this.condition = _.cloneDeep(this._condition);
this.limitation = _.cloneDeep(this._limitation);
if (this.isWildCardMatcher()) {
this._wildCardContainsCombo.selected(this.wildCardTypeList.find(item => ContainsType[item.value] === this.wildcard.contains));
}
this._condFieldCombo.selected(this.measureFields.find(item => item.name === this.condition.field));
this._condAggrCombo.selected(this.aggregationTypeList.find(item => AggregationType[item.value] === this.condition.aggregation));
this._condInequalityCombo.selected(this.conditionTypeList.find(item => InequalityType[item.value] === this.condition.inequality));
this._limitFieldCombo.selected(this.measureFields.find(item => item.name === this.limitation.field));
this._limitAggrCombo.selected(this.aggregationTypeList.find(item => AggregationType[item.value] === this.limitation.aggregation));
this._limitPositionCombo.selected(this.limitTypeList.find(item => PositionType[item.value] === this.limitation.position));
}
filter['isShowCandidateFilter'] = !filter['isShowCandidateFilter'];
} // function - toggleConfigFilteringLayer
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method - 목록 정렬 관련
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 후보값을 정렬한다.
* @param {InclusionFilter} filter
* @param {InclusionSortBy} sortBy
* @param {DIRECTION} direction
*/
public sortCandidateValues(filter: InclusionFilter, sortBy?: InclusionSortBy, direction?: DIRECTION) {
// 정렬 정보 저장
(sortBy) && (filter.sort.by = sortBy);
(direction) && (filter.sort.direction = direction);
// 데이터 정렬
const allCandidates: Candidate[] = _.cloneDeep(this._candidateList);
if (InclusionSortBy.COUNT === filter.sort.by) {
// value 기준으로 정렬
allCandidates.sort((val1: Candidate, val2: Candidate) => {
return (DIRECTION.ASC === filter.sort.direction) ? val1.count - val2.count : val2.count - val1.count;
});
} else {
// name 기준으로 정렬
allCandidates.sort((val1: Candidate, val2: Candidate) => {
const name1: string = (val1.name) ? val1.name.toUpperCase() : '';
const name2: string = (val2.name) ? val2.name.toUpperCase() : '';
if (name1 < name2) {
return (DIRECTION.ASC === filter.sort.direction) ? -1 : 1;
}
if (name1 > name2) {
return (DIRECTION.ASC === filter.sort.direction) ? 1 : -1;
}
return 0;
});
}
this._candidateList = allCandidates;
// 페이징 초기화
this.setCandidatePage(1, true);
} // function - sortCandidateValues
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method - 목록 페이징 관련
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* candidate list 페이징
* @param {number} page
* @param {boolean} isInitial
*/
public setCandidatePage(page: number, isInitial: boolean = false) {
if (isInitial) {
this.pageCandidateList = [];
this.currentPage = 1;
this.lastPage = 1;
this.totalCount = 0;
this.safelyDetectChanges();
}
if (this._candidateList && 0 < this._candidateList.length) {
let pagedList: Candidate[] = _.cloneDeep(this._candidateList);
if (this.targetFilter && this.targetFilter.showSelectedItem) {
pagedList = pagedList.filter(item => {
return -1 < this.selectedValues.findIndex(val => val.name === item.name);
});
}
// 검색 적용
if ('' !== this.searchText) {
pagedList = pagedList.filter(item => {
return (item.name) ? -1 < item.name.toLowerCase().indexOf(this.searchText.toLowerCase()) : false;
});
}
// 표시 여부 적용
if (this.isOnlyShowCandidateValues) {
pagedList = pagedList.filter(item => this.isShowItem(item));
}
if (this.usePaging) {
// 더이상 페이지가 없을 경우 리턴
if (page <= 0) return;
if (this.lastPage < page) return;
this.currentPage = page;
// 총사이즈
this.totalCount = pagedList.length;
// 마지막 페이지 계산
this.lastPage = (this.totalCount % this.pageSize === 0) ? (this.totalCount / this.pageSize) : Math.floor(this.totalCount / this.pageSize) + 1;
const start = (page * this.pageSize) - this.pageSize;
let end = page * this.pageSize;
if (end > this.totalCount) {
end = this.totalCount;
}
// 현재 페이지에 맞게 데이터 자르기
this.pageCandidateList = pagedList.slice(start, end);
} else {
this.pageCandidateList = pagedList;
}
}
} // function - setCandidatePage
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method - 목록 아이템 관련
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 전체 선택
*/
public candidateSelectAll() {
if (this.isSingleSelect(this.targetFilter)) {
this.selectedValues = [];
} else {
this.selectedValues = [].concat(this._candidateList);
this.toggleAllCandidateValues(true);
}
} // function - candidateSelectAll
public candidateDeselectAll() {
this.selectedValues = [];
}
/**
* 전체 선택 여부
* @return {boolean}
*/
public isCheckedAllItem(): boolean {
if (this.useAll && this.isSingleSelect(this.targetFilter)) {
return 0 === this.selectedValues.length
} else {
return this._candidateList.length === this.selectedValues.length;
}
} // function - isCheckedAllItem
/**
* 선택된 아이템 여부
* @param {Candidate} listItem
* @return {boolean}
*/
public isCheckedItem(listItem: Candidate): boolean {
return -1 < this.selectedValues.findIndex(item => item.name === listItem.name);
} // function - isCheckedItem
/**
* 표시 아이템 여부
* @param {Candidate} listItem
* @return {boolean}
*/
public isShowItem(listItem: Candidate): boolean {
return -1 < this._candidateValues.findIndex(item => item.name === listItem.name);
} // function - isShowItem
/**
* 후보군 값 선택
* @param {Candidate} item
* @param $event
*/
public candidateSelect(item: Candidate, $event?: any) {
const filter: InclusionFilter = this.targetFilter;
if (this.isSingleSelect(filter)) {
// 싱글 리스트
this.selectedValues = [item];
} else {
// 멀티 리스트
const checked = $event.target ? $event.target.checked : $event.currentTarget.checked;
if (checked) {
this.selectedValues.push(item);
} else {
_.remove(this.selectedValues, {name: item.name});
}
}
if (!this.isShowItem(item)) {
this._candidateValues.push(item);
}
} // function - candidateSelect
/**
* 선별값만 보임 여부 설정
*/
public setOnlyShowCandidateValues() {
this.isOnlyShowCandidateValues = !this.isOnlyShowCandidateValues;
this.setCandidatePage(1, true);
} // function - setOnlyShowCandidateValues
/**
* 눈표시
* param { Candidate } item
*/
public candidateShowToggle(item: Candidate) {
if (this.isShowItem(item)) {
_.remove(this._candidateValues, {name: item.name});
// 선택 정보 제거
_.remove(this.selectedValues, {name: item.name});
if (this.isSingleSelect(this.targetFilter) && 0 < this._candidateValues.length) {
this.selectedValues = [this._candidateValues[0]];
}
} else {
this._candidateValues.push(item);
}
if (this.isOnlyShowCandidateValues) {
this.setCandidatePage(1, true);
}
this.safelyDetectChanges();
} // function candidateShowToggle
/**
* 후보군에 사용자 입력값 제거
* @param {string} item
*/
public deleteDefinedValue(item: Candidate) {
_.remove(this._candidateList, {name: item.name});
this.setCandidatePage(1, true);
} // function deleteDefinedValue
/**
* 사용자 정의 값 추가
*/
public addNewCandidateValue() {
if (null === this.newCandidateName || this.newCandidateName.trim().length === 0) {
Alert.warning(this.translateService.instant('msg.board.filter.alert.defined.empty'));
return;
}
// 데이터 추가
this._candidateList.push(this._stringToCandidate(this.newCandidateName, true));
this.setCandidatePage(1, true);
this.newCandidateName = '';
} // function - addNewCandidateValue
/**
* 전체 노출 On/Off
* @param isShowAll
*/
public toggleAllCandidateValues(isShowAll: boolean) {
if (isShowAll) {
this._candidateValues = [].concat(this._candidateList);
} else {
this._candidateValues = [];
this.selectedValues = [];
}
} // function - toggleAllCandidateValues
public onChangeMatcherType(type: any): void {
this.selectedMatcherType = type;
}
public isWildCardMatcher(): boolean {
return this.selectedMatcherType.value === MatcherType.WILDCARD;
}
public isRegularExpressionMatcher(): boolean {
return this.selectedMatcherType.value === MatcherType.REGULAR_EXPRESSION;
}
public isNoFiltering() {
return this.selectedValues.length === 0;
}
/**
* 아이템 목록 조회 개수 변경
*/
public changeShowNum(event: KeyboardEvent){
if(13 === event.keyCode) {
this.searchText = '';
this.itemShowCnt = event.target['value'];
this.datasourceService.getCandidateForFilter(this.targetFilter, this._board,[], this._targetField, null, null, this.itemShowCnt).then(result => {
this._candidateList = this._candidateList.filter(item => item.isDefinedValue);
this._candidateValues = this._candidateList;
this.targetFilter.candidateValues = [];
this._setCandidateResult(result, this.targetFilter, this._targetField);
this.safelyDetectChanges();
this.loadingHide();
});
}
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 유효하지 않은 필터링 조건 체크
*/
private _isInvalidFiltering(): boolean {
// wildcard 50자 제한
if (this.wildcard.value && this.wildcard.value.length > 50) {
Alert.info(this.translateService.instant('msg.board.general.filter.common.maxlength', {value: 50}));
return true;
}
// condition 빈값일때 default 10값 넣어주기
if (_.isEmpty(this.condition.value)) {
this.condition.value = 10;
}
// condition 19자 제한
if (this.condition.value && this.condition.value.toString().length > 19) {
Alert.info(this.translateService.instant('msg.board.general.filter.common.maxlength', {value: 19}));
return true;
}
// limitation 빈값일때 default 10값 넣어주기
if (_.isEmpty(this.limitation.value)) {
this.limitation.value = 10;
}
// limitation 10자 제한
if (this.limitation.value && this.limitation.value.toString().length > 10) {
Alert.info(this.translateService.instant('msg.board.general.filter.common.maxlength', {value: 10}));
return true;
}
return false;
} // function - _isInvalidFiltering
/**
* Candidate 결과 처리
* @param result
* @param {InclusionFilter} targetFilter
* @param {Field|CustomField} targetField
* @private
*/
private _setCandidateResult(result: any[], targetFilter: InclusionFilter, targetField: (Field | CustomField)) {
const defineValues = this._candidateList.filter(item => item.isDefinedValue);
// 값 정보 설정
if (0 === this.selectedValues.length && targetFilter.valueList && 0 < targetFilter.valueList.length) {
this.selectedValues = targetFilter.valueList.map(item => this._stringToCandidate(item));
this._candidateValues = this.selectedValues;
(1 < this.selectedValues.length) && (targetFilter.selector = InclusionSelectorType.MULTI_LIST);
}
if (0 === this._candidateValues.length && targetFilter.candidateValues && 0 < targetFilter.candidateValues.length) {
this._candidateValues
= this._candidateValues.concat(
targetFilter.candidateValues
.filter(item => -1 === this._candidateValues.findIndex(can => can.name === item))
.map(item => this._stringToCandidate(item))
);
this._candidateList = this._candidateValues;
}
if (0 === defineValues.length && targetFilter.definedValues && 0 < targetFilter.definedValues.length) {
this._candidateList =
this._candidateList.concat(
targetFilter.definedValues
.filter(item => -1 === this._candidateList.findIndex(can => can.name === item))
.map(item => this._stringToCandidate(item, true))
);
}
// 목록 설정
this._candidateList =
this._candidateList.concat(
result
.map(item => this._objToCandidate(item, targetField))
.filter(item => -1 === this._candidateList.findIndex(can => can.name === item.name))
);
if (targetFilter.candidateValues && 0 < targetFilter.candidateValues.length) {
this._candidateList =
this._candidateList.concat(
targetFilter.candidateValues
.map(item => this._stringToCandidate(item))
.filter(item => -1 === this._candidateList.findIndex(can => can.name === item.name))
);
}
// 목록에 선택값이 없을 경우 선택값 추가
if (this.selectedValues && 0 < this.selectedValues.length) {
this.selectedValues.forEach((selectedItem) => {
const item = this._candidateList.find(candidateItem => candidateItem.name === selectedItem.name);
if (this.isNullOrUndefined(item)) {
this._candidateList.push(selectedItem);
}
});
}
this.totalItemCnt = this._candidateList.length;
(targetFilter.candidateValues) || (targetFilter.candidateValues = []);
this.isNoData = (0 === this.totalItemCnt);
// 정렬
this.sortCandidateValues(targetFilter);
}// function - _setCandidateResult
// noinspection JSMethodCanBeStatic
/**
* List 형식의 선택자 여부 반환
* @param {InclusionFilter} targetFilter
* @return {boolean}
* @private
*/
private _isListSelector(targetFilter: InclusionFilter): boolean {
return InclusionSelectorType.SINGLE_LIST === targetFilter.selector || InclusionSelectorType.MULTI_LIST === targetFilter.selector;
} // function - _isListSelector
// noinspection JSMethodCanBeStatic
/**
* 객체를 후보값 객체로 변환
* @param item
* @param {Field|CustomField} field
* @return {Candidate}
* @private
*/
private _objToCandidate(item: any, field: (Field | CustomField)): Candidate {
const candidate = new Candidate();
if (item.hasOwnProperty('field') && StringUtil.isNotEmpty(item['field'] + '')) {
candidate.name = item['field'];
candidate.count = item['count'];
} else if (item.hasOwnProperty('.count')) {
candidate.name = item[field.name.replace(/(\S+\.)\S+/gi, '$1field')];
candidate.count = item['.count'];
} else {
candidate.name = item[field.name];
candidate.count = item['count'];
}
return candidate;
} // function - _objToCandidate
// noinspection JSMethodCanBeStatic
/**
* 텍스트를 후보값 객체로 변환
* @param {string} item
* @param {boolean} isDefine
* @return {Candidate}
*/
private _stringToCandidate(item: string, isDefine: boolean = false): Candidate {
const candidate = new Candidate();
candidate.name = item;
candidate.count = 0;
candidate.isDefinedValue = isDefine;
return candidate;
} // function - _stringToCandidate
}
enum MatcherType {
WILDCARD = 'WILDCARD',
REGULAR_EXPRESSION = 'REGULAR_EXPRESSION'
} | the_stack |
import moment from "moment";
import { BasicClient } from "../BasicClient";
import { Candle } from "../Candle";
import { CandlePeriod } from "../CandlePeriod";
import { ClientOptions } from "../ClientOptions";
import { CancelableFn } from "../flowcontrol/Fn";
import { throttle } from "../flowcontrol/Throttle";
import { Level2Point } from "../Level2Point";
import { Level2Snapshot } from "../Level2Snapshots";
import { Level2Update } from "../Level2Update";
import { Market } from "../Market";
import { NotImplementedFn } from "../NotImplementedFn";
import { Ticker } from "../Ticker";
import { Trade } from "../Trade";
import * as zlib from "../ZlibUtils";
const pongBuffer = Buffer.from("pong");
export type OkexClientOptions = ClientOptions & {
sendThrottleMs?: number;
};
/**
* Implements OKEx V3 WebSocket API as defined in
* https://www.okex.com/docs/en/#spot_ws-general
*
* Limits:
* 1 connection / second
* 240 subscriptions / hour
*
* Connection will disconnect after 30 seconds of silence
* it is recommended to send a ping message that contains the
* message "ping".
*
* Order book depth includes maintenance of a checksum for the
* first 25 values in the orderbook. Each update includes a crc32
* checksum that can be run to validate that your order book
* matches the server. If the order book does not match you should
* issue a reconnect.
*
* Refer to: https://www.okex.com/docs/en/#spot_ws-checksum
*/
export class OkexClient extends BasicClient {
public candlePeriod: CandlePeriod;
protected _sendMessage: CancelableFn;
protected _pingInterval: NodeJS.Timeout;
constructor({
wssPath = "wss://real.okex.com:8443/ws/v3",
watcherMs,
sendThrottleMs = 20,
}: OkexClientOptions = {}) {
super(wssPath, "OKEx", undefined, watcherMs);
this.candlePeriod = CandlePeriod._1m;
this.hasTickers = true;
this.hasTrades = true;
this.hasCandles = true;
this.hasLevel2Snapshots = true;
this.hasLevel2Updates = true;
this._sendMessage = throttle(this.__sendMessage.bind(this), sendThrottleMs);
}
protected _beforeClose() {
this._sendMessage.cancel();
}
protected _beforeConnect() {
this._wss.on("connected", this._startPing.bind(this));
this._wss.on("disconnected", this._stopPing.bind(this));
this._wss.on("closed", this._stopPing.bind(this));
}
protected _startPing() {
clearInterval(this._pingInterval);
this._pingInterval = setInterval(this._sendPing.bind(this), 15000);
}
protected _stopPing() {
clearInterval(this._pingInterval);
}
protected _sendPing() {
if (this._wss) {
this._wss.send("ping");
}
}
/**
* Constructs a market argument in a backwards compatible manner where
* the default is a spot market.
*/
protected _marketArg(method: string, market: Market) {
const type = (market.type || "spot").toLowerCase();
return `${type.toLowerCase()}/${method}:${market.id}`;
}
/**
* Gets the exchanges interpretation of the candle period
*/
protected _candlePeriod(period: CandlePeriod) {
switch (period) {
case CandlePeriod._1m:
return "60s";
case CandlePeriod._3m:
return "180s";
case CandlePeriod._5m:
return "300s";
case CandlePeriod._15m:
return "900s";
case CandlePeriod._30m:
return "1800s";
case CandlePeriod._1h:
return "3600s";
case CandlePeriod._2h:
return "7200s";
case CandlePeriod._4h:
return "14400s";
case CandlePeriod._6h:
return "21600s";
case CandlePeriod._12h:
return "43200s";
case CandlePeriod._1d:
return "86400s";
case CandlePeriod._1w:
return "604800s";
}
}
protected __sendMessage(msg) {
this._wss.send(msg);
}
protected _sendSubTicker(remote_id, market) {
this._sendMessage(
JSON.stringify({
op: "subscribe",
args: [this._marketArg("ticker", market)],
}),
);
}
protected _sendUnsubTicker(remote_id, market) {
this._sendMessage(
JSON.stringify({
op: "unsubscribe",
args: [this._marketArg("ticker", market)],
}),
);
}
protected _sendSubTrades(remote_id, market) {
this._sendMessage(
JSON.stringify({
op: "subscribe",
args: [this._marketArg("trade", market)],
}),
);
}
protected _sendUnsubTrades(remote_id, market) {
this._sendMessage(
JSON.stringify({
op: "unsubscribe",
args: [this._marketArg("trade", market)],
}),
);
}
protected _sendSubCandles(remote_id, market) {
this._sendMessage(
JSON.stringify({
op: "subscribe",
args: [this._marketArg("candle" + this._candlePeriod(this.candlePeriod), market)],
}),
);
}
protected _sendUnsubCandles(remote_id, market) {
this._sendMessage(
JSON.stringify({
op: "unsubscribe",
args: [this._marketArg("candle" + this._candlePeriod(this.candlePeriod), market)],
}),
);
}
protected _sendSubLevel2Snapshots(remote_id, market) {
this._sendMessage(
JSON.stringify({
op: "subscribe",
args: [this._marketArg("depth5", market)],
}),
);
}
protected _sendUnsubLevel2Snapshots(remote_id, market) {
this._sendMessage(
JSON.stringify({
op: "unsubscribe",
args: [this._marketArg("depth5", market)],
}),
);
}
protected _sendSubLevel2Updates(remote_id, market) {
this._sendMessage(
JSON.stringify({
op: "subscribe",
args: [this._marketArg("depth_l2_tbt", market)],
}),
);
}
protected _sendUnsubLevel2Updates(remote_id, market) {
this._sendMessage(
JSON.stringify({
op: "unsubscribe",
args: [this._marketArg("depth_l2_tbt", market)],
}),
);
}
protected _sendSubLevel3Snapshots = NotImplementedFn;
protected _sendUnsubLevel3Snapshots = NotImplementedFn;
protected _sendSubLevel3Updates = NotImplementedFn;
protected _sendUnsubLevel3Updates = NotImplementedFn;
protected _onMessage(compressed) {
zlib.inflateRaw(compressed, (err, raw) => {
if (err) {
this.emit("error", err);
return;
}
// ignore pongs
if (raw.equals(pongBuffer)) {
return;
}
// process JSON message
try {
const msg = JSON.parse(raw.toString());
this._processsMessage(msg);
} catch (ex) {
this.emit("error", ex);
}
});
}
protected _processsMessage(msg: any) {
// clear semaphore on subscription event reply
if (msg.event === "subscribe") {
return;
}
// ignore unsubscribe
if (msg.event === "unsubscribe") {
return;
}
// prevent failed messages from
if (!msg.data) {
// eslint-disable-next-line no-console
console.warn("warn: failure response", JSON.stringify(msg));
return;
}
// tickers
if (msg.table.match(/ticker/)) {
this._processTicker(msg);
return;
}
// trades
if (msg.table.match(/trade/)) {
this._processTrades(msg);
return;
}
// candles
if (msg.table.match(/candle/)) {
this._processCandles(msg);
return;
}
// l2 snapshots
if (msg.table.match(/depth5/)) {
this._processLevel2Snapshot(msg);
return;
}
// l2 updates
if (msg.table.match(/depth/)) {
this._processLevel2Update(msg);
return;
}
}
/**
* Process ticker messages in the format
{ table: 'spot/ticker',
data:
[ { instrument_id: 'ETH-BTC',
last: '0.02181',
best_bid: '0.0218',
best_ask: '0.02181',
open_24h: '0.02247',
high_24h: '0.02262',
low_24h: '0.02051',
base_volume_24h: '379522.2418555',
quote_volume_24h: '8243.729793336415',
timestamp: '2019-07-15T17:10:55.671Z' } ] }
*/
protected _processTicker(msg) {
for (const datum of msg.data) {
// ensure market
const remoteId = datum.instrument_id;
const market = this._tickerSubs.get(remoteId);
if (!market) continue;
// construct and emit ticker
const ticker = this._constructTicker(datum, market);
this.emit("ticker", ticker, market);
}
}
/**
* Processes trade messages in the format
{ table: 'spot/trade',
data:
[ { instrument_id: 'ETH-BTC',
price: '0.0218',
side: 'sell',
size: '1.1',
timestamp: '2019-07-15T17:10:56.047Z',
trade_id: '776432498' } ] }
*/
protected _processTrades(msg) {
for (const datum of msg.data) {
// ensure market
const remoteId = datum.instrument_id;
const market = this._tradeSubs.get(remoteId);
if (!market) continue;
// construct and emit trade
const trade = this._constructTrade(datum, market);
this.emit("trade", trade, market);
}
}
/**
* Processes a candle message
{
"table": "spot/candle60s",
"data": [
{
"candle": [
"2020-08-10T20:42:00.000Z",
"0.03332",
"0.03332",
"0.03331",
"0.03332",
"44.058532"
],
"instrument_id": "ETH-BTC"
}
]
}
*/
protected _processCandles(msg) {
for (const datum of msg.data) {
// ensure market
const remoteId = datum.instrument_id;
const market = this._candleSubs.get(remoteId);
if (!market) continue;
// construct and emit candle
const candle = this._constructCandle(datum);
this.emit("candle", candle, market);
}
}
/**
* Processes a level 2 snapshot message in the format:
{ table: 'spot/depth5',
data: [{
asks: [ ['0.02192', '1.204054', '3' ] ],
bids: [ ['0.02191', '15.117671', '3' ] ],
instrument_id: 'ETH-BTC',
timestamp: '2019-07-15T16:54:42.301Z' } ] }
*/
protected _processLevel2Snapshot(msg) {
for (const datum of msg.data) {
// ensure market
const remote_id = datum.instrument_id;
const market = this._level2SnapshotSubs.get(remote_id);
if (!market) return;
// construct snapshot
const snapshot = this._constructLevel2Snapshot(datum, market);
this.emit("l2snapshot", snapshot, market);
}
}
/**
* Processes a level 2 update message in one of two formats.
* The first message received is the "partial" orderbook and contains
* 200 records in it.
*
{ table: 'spot/depth',
action: 'partial',
data:
[ { instrument_id: 'ETH-BTC',
asks: [Array],
bids: [Array],
timestamp: '2019-07-15T17:18:31.737Z',
checksum: 723501244 } ] }
*
* Subsequent calls will include the updates stream for changes to
* the order book:
*
{ table: 'spot/depth',
action: 'update',
data:
[ { instrument_id: 'ETH-BTC',
asks: [Array],
bids: [Array],
timestamp: '2019-07-15T17:18:32.289Z',
checksum: 680530848 } ] }
*/
protected _processLevel2Update(msg) {
const action = msg.action;
for (const datum of msg.data) {
// ensure market
const remote_id = datum.instrument_id;
const market = this._level2UpdateSubs.get(remote_id);
if (!market) continue;
// handle updates
if (action === "partial") {
const snapshot = this._constructLevel2Snapshot(datum, market);
this.emit("l2snapshot", snapshot, market);
} else if (action === "update") {
const update = this._constructLevel2Update(datum, market);
this.emit("l2update", update, market);
} else {
// eslint-disable-next-line no-console
console.error("Unknown action type", msg);
}
}
}
/**
* Constructs a ticker from the datum in the format:
{ instrument_id: 'ETH-BTC',
last: '0.02172',
best_bid: '0.02172',
best_ask: '0.02173',
open_24h: '0.02254',
high_24h: '0.02262',
low_24h: '0.02051',
base_volume_24h: '378400.064179',
quote_volume_24h: '8226.4437921288',
timestamp: '2019-07-15T16:10:40.193Z' }
*/
protected _constructTicker(data, market) {
const {
last,
best_bid,
best_bid_size,
best_ask,
best_ask_size,
open_24h,
high_24h,
low_24h,
base_volume_24h,
volume_24h, // found in futures
timestamp,
} = data;
const change = parseFloat(last) - parseFloat(open_24h);
const changePercent = change / parseFloat(open_24h);
const ts = moment.utc(timestamp).valueOf();
return new Ticker({
exchange: this.name,
base: market.base,
quote: market.quote,
timestamp: ts,
last,
open: open_24h,
high: high_24h,
low: low_24h,
volume: base_volume_24h || volume_24h,
change: change.toFixed(8),
changePercent: changePercent.toFixed(2),
bid: best_bid || "0",
bidVolume: best_bid_size || "0",
ask: best_ask || "0",
askVolume: best_ask_size || "0",
});
}
/**
* Constructs a trade from the message datum in format:
{ instrument_id: 'ETH-BTC',
price: '0.02182',
side: 'sell',
size: '0.94',
timestamp: '2019-07-15T16:38:02.169Z',
trade_id: '776370532' }
*/
protected _constructTrade(datum, market) {
const { price, side, size, timestamp, trade_id, qty } = datum;
const ts = moment.utc(timestamp).valueOf();
return new Trade({
exchange: this.name,
base: market.base,
quote: market.quote,
tradeId: trade_id,
side,
unix: ts,
price,
amount: size || qty,
});
}
/**
* Constructs a candle for the market
{
"candle": [
"2020-08-10T20:42:00.000Z",
"0.03332",
"0.03332",
"0.03331",
"0.03332",
"44.058532"
],
"instrument_id": "ETH-BTC"
}
* @param {*} datum
*/
protected _constructCandle(datum) {
const [datetime, open, high, low, close, volume] = datum.candle;
const ts = moment.utc(datetime).valueOf();
return new Candle(ts, open, high, low, close, volume);
}
/**
* Constructs a snapshot message from the datum in a
* snapshot message data property. Datum in the format:
*
{ instrument_id: 'ETH-BTC',
asks: [ ['0.02192', '1.204054', '3' ] ],
bids: [ ['0.02191', '15.117671', '3' ] ],
timestamp: '2019-07-15T16:54:42.301Z' }
*
* The snapshot may also come from an update, in which case we need
* to include the checksum
*
{ instrument_id: 'ETH-BTC',
asks: [ ['0.02192', '1.204054', '3' ] ],
bids: [ ['0.02191', '15.117671', '3' ] ],
timestamp: '2019-07-15T17:18:31.737Z',
checksum: 723501244 }
*/
protected _constructLevel2Snapshot(datum, market) {
const asks = datum.asks.map(p => new Level2Point(p[0], p[1], p[2]));
const bids = datum.bids.map(p => new Level2Point(p[0], p[1], p[2]));
const ts = moment.utc(datum.timestamp).valueOf();
const checksum = datum.checksum;
return new Level2Snapshot({
exchange: this.name,
base: market.base,
quote: market.quote,
timestampMs: ts,
asks,
bids,
checksum,
});
}
/**
* Constructs an update message from the datum in the update
* stream. Datum is in the format:
{ instrument_id: 'ETH-BTC',
asks: [ ['0.02192', '1.204054', '3' ] ],
bids: [ ['0.02191', '15.117671', '3' ] ],
timestamp: '2019-07-15T17:18:32.289Z',
checksum: 680530848 }
*/
// eslint-disable-next-line @typescript-eslint/explicit-member-accessibility
_constructLevel2Update(datum, market) {
const asks = datum.asks.map(p => new Level2Point(p[0], p[1], p[3]));
const bids = datum.bids.map(p => new Level2Point(p[0], p[1], p[3]));
const ts = moment.utc(datum.timestamp).valueOf();
const checksum = datum.checksum;
return new Level2Update({
exchange: this.name,
base: market.base,
quote: market.quote,
timestampMs: ts,
asks,
bids,
checksum,
});
}
} | the_stack |
import { ApiResponse, RequestOptions } from '../core';
import {
V1CreateRefundRequest,
v1CreateRefundRequestSchema,
} from '../models/v1CreateRefundRequest';
import { V1Order, v1OrderSchema } from '../models/v1Order';
import { V1Payment, v1PaymentSchema } from '../models/v1Payment';
import { V1Refund, v1RefundSchema } from '../models/v1Refund';
import { V1Settlement, v1SettlementSchema } from '../models/v1Settlement';
import {
V1UpdateOrderRequest,
v1UpdateOrderRequestSchema,
} from '../models/v1UpdateOrderRequest';
import { array, boolean, number, optional, string } from '../schema';
import { BaseApi } from './baseApi';
export class V1TransactionsApi extends BaseApi {
/**
* Provides summary information for a merchant's online store orders.
*
* @param locationId The ID of the location to list online store orders for.
* @param order The order in which payments are listed in the response.
* @param limit The maximum number of payments to return in a single response. This value cannot
* exceed 200.
* @param batchToken A pagination cursor to retrieve the next set of results for your original query to
* the endpoint.
* @return Response from the API call
* @deprecated
*/
async listOrders(
locationId: string,
order?: string,
limit?: number,
batchToken?: string,
requestOptions?: RequestOptions
): Promise<ApiResponse<V1Order[]>> {
const req = this.createRequest('GET');
const mapped = req.prepareArgs({
locationId: [locationId, string()],
order: [order, optional(string())],
limit: [limit, optional(number())],
batchToken: [batchToken, optional(string())],
});
req.query('order', mapped.order);
req.query('limit', mapped.limit);
req.query('batch_token', mapped.batchToken);
req.appendTemplatePath`/v1/${mapped.locationId}/orders`;
req.deprecated('V1TransactionsApi.listOrders');
return req.callAsJson(array(v1OrderSchema), requestOptions);
}
/**
* Provides comprehensive information for a single online store order, including the order's history.
*
* @param locationId The ID of the order's associated location.
* @param orderId The order's Square-issued ID. You obtain this value from Order objects returned by
* the List Orders endpoint
* @return Response from the API call
* @deprecated
*/
async retrieveOrder(
locationId: string,
orderId: string,
requestOptions?: RequestOptions
): Promise<ApiResponse<V1Order>> {
const req = this.createRequest('GET');
const mapped = req.prepareArgs({
locationId: [locationId, string()],
orderId: [orderId, string()],
});
req.appendTemplatePath`/v1/${mapped.locationId}/orders/${mapped.orderId}`;
req.deprecated('V1TransactionsApi.retrieveOrder');
return req.callAsJson(v1OrderSchema, requestOptions);
}
/**
* Updates the details of an online store order. Every update you perform on an order corresponds to
* one of three actions:
*
* @param locationId The ID of the order's associated location.
* @param orderId The order's Square-issued ID. You obtain this value from Order
* objects returned by the List Orders endpoint
* @param body An object containing the fields to POST for the request. See
* the corresponding object definition for field details.
* @return Response from the API call
* @deprecated
*/
async updateOrder(
locationId: string,
orderId: string,
body: V1UpdateOrderRequest,
requestOptions?: RequestOptions
): Promise<ApiResponse<V1Order>> {
const req = this.createRequest('PUT');
const mapped = req.prepareArgs({
locationId: [locationId, string()],
orderId: [orderId, string()],
body: [body, v1UpdateOrderRequestSchema],
});
req.json(mapped.body);
req.appendTemplatePath`/v1/${mapped.locationId}/orders/${mapped.orderId}`;
req.deprecated('V1TransactionsApi.updateOrder');
return req.callAsJson(v1OrderSchema, requestOptions);
}
/**
* Provides summary information for all payments taken for a given
* Square account during a date range. Date ranges cannot exceed 1 year in
* length. See Date ranges for details of inclusive and exclusive dates.
*
* *Note**: Details for payments processed with Square Point of Sale while
* in offline mode may not be transmitted to Square for up to 72 hours.
* Offline payments have a `created_at` value that reflects the time the
* payment was originally processed, not the time it was subsequently
* transmitted to Square. Consequently, the ListPayments endpoint might
* list an offline payment chronologically between online payments that
* were seen in a previous request.
*
* @param locationId The ID of the location to list payments for. If you specify me, this endpoint
* returns payments aggregated from all of the business's locations.
* @param order The order in which payments are listed in the response.
* @param beginTime The beginning of the requested reporting period, in ISO 8601 format. If this
* value is before January 1, 2013 (2013-01-01T00:00:00Z), this endpoint returns an
* error. Default value: The current time minus one year.
* @param endTime The end of the requested reporting period, in ISO 8601 format. If this value is
* more than one year greater than begin_time, this endpoint returns an error.
* Default value: The current time.
* @param limit The maximum number of payments to return in a single response. This value
* cannot exceed 200.
* @param batchToken A pagination cursor to retrieve the next set of results for your original query
* to the endpoint.
* @param includePartial Indicates whether or not to include partial payments in the response. Partial
* payments will have the tenders collected so far, but the itemizations will be
* empty until the payment is completed.
* @return Response from the API call
* @deprecated
*/
async listPayments(
locationId: string,
order?: string,
beginTime?: string,
endTime?: string,
limit?: number,
batchToken?: string,
includePartial?: boolean,
requestOptions?: RequestOptions
): Promise<ApiResponse<V1Payment[]>> {
const req = this.createRequest('GET');
const mapped = req.prepareArgs({
locationId: [locationId, string()],
order: [order, optional(string())],
beginTime: [beginTime, optional(string())],
endTime: [endTime, optional(string())],
limit: [limit, optional(number())],
batchToken: [batchToken, optional(string())],
includePartial: [includePartial, optional(boolean())],
});
req.query('order', mapped.order);
req.query('begin_time', mapped.beginTime);
req.query('end_time', mapped.endTime);
req.query('limit', mapped.limit);
req.query('batch_token', mapped.batchToken);
req.query('include_partial', mapped.includePartial);
req.appendTemplatePath`/v1/${mapped.locationId}/payments`;
req.deprecated('V1TransactionsApi.listPayments');
return req.callAsJson(array(v1PaymentSchema), requestOptions);
}
/**
* Provides comprehensive information for a single payment.
*
* @param locationId The ID of the payment's associated location.
* @param paymentId The Square-issued payment ID. payment_id comes from Payment objects returned by the
* List Payments endpoint, Settlement objects returned by the List Settlements endpoint,
* or Refund objects returned by the List Refunds endpoint.
* @return Response from the API call
* @deprecated
*/
async retrievePayment(
locationId: string,
paymentId: string,
requestOptions?: RequestOptions
): Promise<ApiResponse<V1Payment>> {
const req = this.createRequest('GET');
const mapped = req.prepareArgs({
locationId: [locationId, string()],
paymentId: [paymentId, string()],
});
req.appendTemplatePath`/v1/${mapped.locationId}/payments/${mapped.paymentId}`;
req.deprecated('V1TransactionsApi.retrievePayment');
return req.callAsJson(v1PaymentSchema, requestOptions);
}
/**
* Provides the details for all refunds initiated by a merchant or any of the merchant's mobile staff
* during a date range. Date ranges cannot exceed one year in length.
*
* @param locationId The ID of the location to list refunds for.
* @param order The order in which payments are listed in the response.
* @param beginTime The beginning of the requested reporting period, in ISO 8601 format. If this value
* is before January 1, 2013 (2013-01-01T00:00:00Z), this endpoint returns an error.
* Default value: The current time minus one year.
* @param endTime The end of the requested reporting period, in ISO 8601 format. If this value is more
* than one year greater than begin_time, this endpoint returns an error. Default value:
* The current time.
* @param limit The approximate number of refunds to return in a single response. Default: 100. Max:
* 200. Response may contain more results than the prescribed limit when refunds are
* made simultaneously to multiple tenders in a payment or when refunds are generated in
* an exchange to account for the value of returned goods.
* @param batchToken A pagination cursor to retrieve the next set of results for your original query to
* the endpoint.
* @return Response from the API call
* @deprecated
*/
async listRefunds(
locationId: string,
order?: string,
beginTime?: string,
endTime?: string,
limit?: number,
batchToken?: string,
requestOptions?: RequestOptions
): Promise<ApiResponse<V1Refund[]>> {
const req = this.createRequest('GET');
const mapped = req.prepareArgs({
locationId: [locationId, string()],
order: [order, optional(string())],
beginTime: [beginTime, optional(string())],
endTime: [endTime, optional(string())],
limit: [limit, optional(number())],
batchToken: [batchToken, optional(string())],
});
req.query('order', mapped.order);
req.query('begin_time', mapped.beginTime);
req.query('end_time', mapped.endTime);
req.query('limit', mapped.limit);
req.query('batch_token', mapped.batchToken);
req.appendTemplatePath`/v1/${mapped.locationId}/refunds`;
req.deprecated('V1TransactionsApi.listRefunds');
return req.callAsJson(array(v1RefundSchema), requestOptions);
}
/**
* Issues a refund for a previously processed payment. You must issue
* a refund within 60 days of the associated payment.
*
* You cannot issue a partial refund for a split tender payment. You must
* instead issue a full or partial refund for a particular tender, by
* providing the applicable tender id to the V1CreateRefund endpoint.
* Issuing a full refund for a split tender payment refunds all tenders
* associated with the payment.
*
* Issuing a refund for a card payment is not reversible. For development
* purposes, you can create fake cash payments in Square Point of Sale and
* refund them.
*
* @param locationId The ID of the original payment's associated location.
* @param body An object containing the fields to POST for the request. See
* the corresponding object definition for field details.
* @return Response from the API call
* @deprecated
*/
async createRefund(
locationId: string,
body: V1CreateRefundRequest,
requestOptions?: RequestOptions
): Promise<ApiResponse<V1Refund>> {
const req = this.createRequest('POST');
const mapped = req.prepareArgs({
locationId: [locationId, string()],
body: [body, v1CreateRefundRequestSchema],
});
req.json(mapped.body);
req.appendTemplatePath`/v1/${mapped.locationId}/refunds`;
req.deprecated('V1TransactionsApi.createRefund');
return req.callAsJson(v1RefundSchema, requestOptions);
}
/**
* Provides summary information for all deposits and withdrawals
* initiated by Square to a linked bank account during a date range. Date
* ranges cannot exceed one year in length.
*
* *Note**: the ListSettlements endpoint does not provide entry
* information.
*
* @param locationId The ID of the location to list settlements for. If you specify me, this endpoint
* returns settlements aggregated from all of the business's locations.
* @param order The order in which settlements are listed in the response.
* @param beginTime The beginning of the requested reporting period, in ISO 8601 format. If this value
* is before January 1, 2013 (2013-01-01T00:00:00Z), this endpoint returns an error.
* Default value: The current time minus one year.
* @param endTime The end of the requested reporting period, in ISO 8601 format. If this value is more
* than one year greater than begin_time, this endpoint returns an error. Default value:
* The current time.
* @param limit The maximum number of settlements to return in a single response. This value cannot
* exceed 200.
* @param status Provide this parameter to retrieve only settlements with a particular status (SENT
* or FAILED).
* @param batchToken A pagination cursor to retrieve the next set of results for your original query to
* the endpoint.
* @return Response from the API call
* @deprecated
*/
async listSettlements(
locationId: string,
order?: string,
beginTime?: string,
endTime?: string,
limit?: number,
status?: string,
batchToken?: string,
requestOptions?: RequestOptions
): Promise<ApiResponse<V1Settlement[]>> {
const req = this.createRequest('GET');
const mapped = req.prepareArgs({
locationId: [locationId, string()],
order: [order, optional(string())],
beginTime: [beginTime, optional(string())],
endTime: [endTime, optional(string())],
limit: [limit, optional(number())],
status: [status, optional(string())],
batchToken: [batchToken, optional(string())],
});
req.query('order', mapped.order);
req.query('begin_time', mapped.beginTime);
req.query('end_time', mapped.endTime);
req.query('limit', mapped.limit);
req.query('status', mapped.status);
req.query('batch_token', mapped.batchToken);
req.appendTemplatePath`/v1/${mapped.locationId}/settlements`;
req.deprecated('V1TransactionsApi.listSettlements');
return req.callAsJson(array(v1SettlementSchema), requestOptions);
}
/**
* Provides comprehensive information for a single settlement.
*
* The returned `Settlement` objects include an `entries` field that lists
* the transactions that contribute to the settlement total. Most
* settlement entries correspond to a payment payout, but settlement
* entries are also generated for less common events, like refunds, manual
* adjustments, or chargeback holds.
*
* Square initiates its regular deposits as indicated in the
* [Deposit Options with Square](https://squareup.com/help/us/en/article/3807)
* help article. Details for a regular deposit are usually not available
* from Connect API endpoints before 10 p.m. PST the same day.
*
* Square does not know when an initiated settlement **completes**, only
* whether it has failed. A completed settlement is typically reflected in
* a bank account within 3 business days, but in exceptional cases it may
* take longer.
*
* @param locationId The ID of the settlements's associated location.
* @param settlementId The settlement's Square-issued ID. You obtain this value from Settlement objects
* returned by the List Settlements endpoint.
* @return Response from the API call
* @deprecated
*/
async retrieveSettlement(
locationId: string,
settlementId: string,
requestOptions?: RequestOptions
): Promise<ApiResponse<V1Settlement>> {
const req = this.createRequest('GET');
const mapped = req.prepareArgs({
locationId: [locationId, string()],
settlementId: [settlementId, string()],
});
req.appendTemplatePath`/v1/${mapped.locationId}/settlements/${mapped.settlementId}`;
req.deprecated('V1TransactionsApi.retrieveSettlement');
return req.callAsJson(v1SettlementSchema, requestOptions);
}
} | the_stack |
namespace LogDog {
/** Sentinel error: not authenticated. */
let NOT_AUTHENTICATED = new Error('Not Authenticated');
/**
* Resolves an arbitrary error into special sentinels where appropriate.
*
* Currently supports resolving gRPC "unauthenticated" error into the
* NOT_AUTHENTICATED sentinel.
*/
function resolveErr(err: Error): Error {
let grpc = luci.GrpcError.convert(err);
if (grpc && grpc.code === luci.Code.UNAUTHENTICATED) {
return NOT_AUTHENTICATED;
}
return err;
}
/** An individual log stream's status. */
type LogStreamStatus = {
stream: LogDog.StreamPath; state: string; fetchStatus: LogDog.FetchStatus;
finished: boolean;
needsAuth: boolean;
};
type StreamStatusCallback = (v: LogStreamStatus[]) => void;
/** Location where a log stream should be loaded from. */
export enum Location {
/**
* Represents the upper half of a split view. Logs start at 0 and go through
* the HEAD point.
*/
HEAD,
/**
* Represents the lower half of the split view. Logs start at the TAIL point
* and go through the BOTTOM anchor point.
*/
TAIL,
/**
* Represents an anchor point where the split occurred, obtained through a
* single "Tail()" RPC call. If the terminal index is known when the split
* occurs, this should be the terminal index.
*/
BOTTOM,
}
/** A log loading profile type. */
type ModelProfile = {
/** The size of the first fetch. */
initialFetchSize: number;
/** The size of the first fetch, if loading multiple streams. */
multiInitialFetchSize: number;
/** The size of each subsequent fetch. */
fetchSize: number;
};
/**
* Model manages stream loading.
*
* Model pushes state update to the user interface with the ViewBinding that
* is provided to it on construction.
*
* Model represents a view of the loading state of the configured log streams.
* Log streams are individual named sets of consecutive records that are
* either streaming (no known terminal index, so the expectation is that new
* log records are being generated) or finished (known terminal index). The
* Model's job is to understand the state of these streams, load their data,
* and cause it to be output to the user interface.
*
* A Model is bound to a LogProvider, which manages a sequential series of log
* records. If a single log stream is being fetched, the Model will use a
* "LogStream" log provider. If multiple log streams are being fetched, the
* Model will use the "AggregateLogStream" log provider, which internally
* muxes log records from multiple "LogStream" providers together based on an
* ordering.
*
* "AggregateLogStream" is an append-only LogProvider, meaning that it ONLY
* supports emitting log records from its set of streams in order until no
* more records are available.
*
* "LogStream" (single stream) offers a more complex set of options via its
* "split" functionality. At the user's request, the LogStream can split,
* jumping to the highest-indexed log entry in that stream. This is followed
* up with three fetch options, which can be used interchangeably based on the
* user's actions:
* - HEAD fetches logs sequentially starting from 0 and ending at SPLIT.
* - TAIL fetches logs backwards, starting from SPLIT and fetching towards 0.
* - BOTTOM fetches logs from after SPLIT, fetching from SPLIT and ending at
* the log stream's terminal index.
*
* If the HEAD pointer ever reaches the TAIL pointer, all logs between 0 and
* SPLIT have been filled in and the fetching situation turns back into a
* standard sequential fetch.
*
* This scheme is designed around the capabilities of the LogDog log API.
*
* The view may optionally expose itself as "mobile", indicating to the Model
* that it should use mobile-friendly tuning parameters.
*/
export class Model {
/** Default single-stream profile. */
static DEFAULT_PROFILE: ModelProfile = {
initialFetchSize: (1024 * 24), // 24KiB
multiInitialFetchSize: (1024 * 4), // 4KiB
fetchSize: (4 * 1024 * 1024), // 4MiB
};
/** Profile to use for a mobile device, regardless of stream count. */
static MOBILE_PROFILE: ModelProfile = {
initialFetchSize: (1024 * 4), // 4KiB
multiInitialFetchSize: (1024 * 4), // 4KiB
fetchSize: (1024 * 256), // 256KiB
};
/**
* Amount of time after which we consider the build to have been loading
* "for a while".
*/
private static LOADING_WHILE_THRESHOLD_MS = 60000; // 1 Minute
/**
* If >0, the maximum number of log lines to push at a time. We will sleep
* in between these entries to allow the rest of the app to be responsive
* during log dumping.
*/
private static logAppendInterval = 4000;
/**
* Amount of time to sleep in between log append chunks. Larger numbers
* will load logs slower, but will offer more opportunities for user
* interaction in between log dumps.
*/
private static logAppendDelay = 0;
/** Our log provider. */
private provider: LogProvider = this.nullProvider();
/** The LogDog Coordinator client instance. */
readonly client: LogDog.Client;
/**
* Promise that is resolved when authentication state changes. When this
* happens, a new Promise is installed, and future authentication changes
* will resolve the new Promise.
*/
private authChangedPromise: Promise<void>;
/**
* Retained callback (Promise resolve) to invoke when authentication state
* changes.
*/
private authChangedCallback: (() => void);
/** The current fetch Promise. */
private currentOperation: luci.Operation|null = null;
private currentFetchPromise: Promise<void>|null = null;
/** Are we in automatic mode? */
private isAutomatic = false;
/** Are we tailing? */
private fetchFromTail = false;
/** Are we in the middle of rendering logs? */
private rendering = false;
private cachedLogStreamUrl: string|undefined = undefined;
private loadingStateValue: LoadingState = LoadingState.NONE;
private streamStatusValue: StreamStatusEntry[];
/**
* When rendering a Promise that will resolve when the render completes. We
* use this to pipeline parallel data fetching and rendering.
*/
private renderPromise: Promise<void>|null;
constructor(
client: luci.Client, readonly profile: ModelProfile,
readonly view: ViewBinding) {
this.client = new LogDog.Client(client);
this.resetAuthChanged();
}
/**
* Resolves user stream path strings to actual log streams.
*
* After the returned Promise resolves, log stream data can be fetched by
* calling "fetch()".
*
* @return a Promise that will resolve once all log streams have been
* identified and the configured.
*/
async resolve(paths: string[]) {
this.reset();
// For any path that is a query, execute that query.
this.loadingState = LoadingState.RESOLVING;
let streamBlocks: LogDog.StreamPath[][];
try {
streamBlocks = await this.resolvePathsIntoStreams(paths);
} catch (err) {
this.loadingState = LoadingState.ERROR;
console.error('Failed to resolve log streams:', err);
return;
}
// Flatten them all.
let streams: LogDog.StreamPath[] = [];
for (let streamBlock of streamBlocks) {
streams.push.apply(streams, streamBlock);
}
let initialFetchSize = (streams.length <= 1) ?
this.profile.initialFetchSize :
this.profile.multiInitialFetchSize;
// Generate a LogStream client entry for each composite stream.
let logStreams = streams.map((stream) => {
console.log('Resolved log stream:', stream);
return new LogStream(
this.client, stream, initialFetchSize, this.profile.fetchSize);
});
// Reset any existing state.
this.reset();
// If we have exactly one stream, then use it directly. This allows
// it to split.
let provider: LogProvider;
switch (logStreams.length) {
case 0:
provider = this.nullProvider();
break;
case 1:
provider = logStreams[0];
break;
default:
provider = new AggregateLogStream(logStreams);
break;
}
provider.setStreamStatusCallback((st: LogStreamStatus[]) => {
if (this.provider === provider) {
this.streamStatus = this.buildStreamStatus(st);
}
});
this.provider = provider;
this.setIdleLoadingState();
}
private setIdleLoadingState() {
this.loadingState = (this.fetchedFullStream) ? (LoadingState.NONE) :
(LoadingState.PAUSED);
}
private resolvePathsIntoStreams(paths: string[]) {
return Promise.all(paths.map(async path => {
let stream = LogDog.StreamPath.splitProject(path);
if (!LogDog.isQuery(stream.path)) {
return [stream];
}
// This "path" is really a query. Construct and execute.
//
// If we failed due to an auth error, but our auth changed during the
// operation, try again automatically.
let query: LogDog.QueryRequest = {
project: stream.project,
path: stream.path,
streamType: LogDog.StreamType.TEXT,
};
while (true) {
let op = new luci.Operation();
try {
let results = await LogDog.queryAll(op, this.client, query, 100);
return results.map(qr => qr.stream);
} catch (err) {
err = resolveErr(err);
if (err !== NOT_AUTHENTICATED) {
throw err;
}
await this.authChangedPromise;
}
}
}));
}
/**
* Resets the state.
*/
reset() {
this.view.clearLogEntries();
this.clearCurrentOperation();
this.provider = this.nullProvider();
this.updateControls();
}
public get automatic() {
return this.isAutomatic;
}
/**
* Sets whether automatic loading is enabled.
*
* When enabled, a new fetch will immediately be dispatched when a previous
* fetch finishes so long as there is still stream data to load.
*
* This isn't a setter because we need to be able to export it via
* interface.
*/
public set automatic(v: boolean) {
this.isAutomatic = v && !this.fetchedFullStream;
if (v) {
// Passively kick off a new fetch.
this.fetch(false);
}
this.updateControls();
}
private nullProvider(): LogProvider {
return new AggregateLogStream([]);
}
/**
* Clears the current operation, cancelling it if set. If the operation is
* cleared, the current fetch and rendering states will be reset.
*
* @param op if provided, only cancel the current operation if it equals
* the supplied "op". If "op" does not match the current operation, it
* will be cancelled, but the current operation will be left in-tact.
* If "op" is undefined, cancel the current operation regardless.
*/
clearCurrentOperation(op?: luci.Operation) {
if (this.currentOperation) {
if (op && op !== this.currentOperation) {
// Conditional clear, and we are not the current operation, so do
// nothing.
op.cancel();
return;
}
this.currentOperation.cancel();
this.currentOperation = this.currentFetchPromise = null;
this.setIdleLoadingState();
}
}
private get loadingState(): LoadingState {
return this.loadingStateValue;
}
private set loadingState(v: LoadingState) {
if (v !== this.loadingStateValue) {
this.loadingStateValue = v;
this.updateControls();
}
}
private get streamStatus(): StreamStatusEntry[] {
return this.streamStatusValue;
}
private set streamStatus(st: StreamStatusEntry[]) {
this.streamStatusValue = st;
this.updateControls();
}
private updateControls() {
let splitState: SplitState;
if (this.providerCanSplit) {
splitState = SplitState.CAN_SPLIT;
} else {
splitState =
(this.isSplit) ? (SplitState.IS_SPLIT) : (SplitState.CANNOT_SPLIT);
}
this.view.updateControls({
splitState: splitState,
fullyLoaded: (this.fetchedFullStream && (!this.rendering)),
logStreamUrl: this.logStreamUrl,
loadingState: this.loadingState,
streamStatus: this.streamStatus,
});
}
/**
* Note that the authentication state for the client has changed. This will
* trigger an automatic fetch retry if our previous fetch failed due to
* lack of authentication.
*/
notifyAuthenticationChanged() {
// Resolve our current "auth changed" Promise.
this.authChangedCallback();
}
private resetAuthChanged() {
// Resolve our previous function, if it's not already resolved.
if (this.authChangedCallback) {
this.authChangedCallback();
}
// Create a new Promise and install it.
this.authChangedPromise = new Promise<void>((resolve, _) => {
this.authChangedCallback = resolve;
});
}
/**
* Causes the view to immediately split, if possible, creating a region
* representing the end of the log stream.
*
* If the view cannot split, or if it is already split, then this is a
* no-op.
*
* This cancels the current fetch, if one is in progress.
*/
async split() {
// If we haven't already split, and our provider lets us split, then go
// ahead and do so.
if (this.providerCanSplit) {
return this.fetchLocation(Location.TAIL, true);
}
return this.fetch(false);
}
/**
* Fetches the next batch of logs.
*
* By default, if a fetch is already in-progress, this new fetch is ignored.
* If cancel is true, then the current fetch should be cancelled and a new
* fetch initiated.
*
* @param cancel true if we should abandon any current fetches.
* @return A Promise that will resolve when the fetch operation is complete.
*/
async fetch(cancel: boolean) {
if (this.isSplit) {
if (this.fetchFromTail) {
// Next fetch grabs logs from the bottom (continue tailing).
if (!this.fetchedEndOfStream) {
return this.fetchLocation(Location.BOTTOM, cancel);
} else {
return this.fetchLocation(Location.TAIL, cancel);
}
}
// We're split, but not tailing, so fetch logs from HEAD.
return this.fetchLocation(Location.HEAD, cancel);
}
// We're not split. If we haven't reached end of stream, fetch logs from
// HEAD.
return this.fetchLocation(Location.HEAD, cancel);
}
/** Fetch logs from an explicit location. */
async fetchLocation(l: Location, cancel: boolean): Promise<void> {
if (this.currentFetchPromise && (!cancel)) {
return this.currentFetchPromise;
}
this.clearCurrentOperation();
// If our provider is finished, then do nothing.
if (this.fetchedFullStream) {
// There are no more logs.
this.updateControls();
return undefined;
}
// If we're asked to fetch BOTTOM, but we're not split, fetch HEAD
// instead.
if (l === Location.BOTTOM && !this.isSplit) {
l = Location.HEAD;
}
// Rotate our fetch ID. This will effectively cancel any pending fetches.
this.currentOperation = new luci.Operation();
this.currentFetchPromise =
this.fetchLocationImpl(l, this.currentOperation);
return this.currentFetchPromise;
}
private async fetchLocationImpl(l: Location, op: luci.Operation) {
for (let continueFetching = true; continueFetching;) {
this.loadingState = LoadingState.LOADING;
let loadingWhileTimer =
new luci.Timer(Model.LOADING_WHILE_THRESHOLD_MS, () => {
if (this.loadingState === LoadingState.LOADING) {
this.loadingState = LoadingState.LOADING_BEEN_A_WHILE;
}
});
let hasLogs = false;
try {
hasLogs = await this.fetchLocationRound(l, op);
} catch (err) {
console.log('Fetch failed with error:', err);
// Cancel the timer here, since we may enter other states in this
// "catch" block and we don't want to have the timer override them.
loadingWhileTimer.cancel();
// If we've been canceled, discard this result.
if (err === luci.Operation.CANCELLED) {
this.setIdleLoadingState();
return;
}
if (err === NOT_AUTHENTICATED) {
this.loadingState = LoadingState.NEEDS_AUTH;
// We failed because we were not authenticated. Mark this
// so we can retry if that state changes.
await this.authChangedPromise;
// Our authentication state changed during the fetch!
// Retry automatically.
continueFetching = true;
continue;
}
console.error('Failed to load log streams:', err);
return;
} finally {
loadingWhileTimer.cancel();
}
continueFetching = (this.automatic && hasLogs);
if (continueFetching) {
console.log('Automatic: starting next fetch.');
}
}
if (this.renderPromise) {
await this.renderPromise;
}
// Post-fetch cleanup.
this.clearCurrentOperation(op);
this.updateControls();
}
private async fetchLocationRound(l: Location, op: luci.Operation) {
// Clear our loading state (updates controls automatically).
let buf = await this.provider.fetch(op, l);
let hadLogs = !!(buf.peek());
// Resolve any previous rendering Promise that we have. This
// makes sure our rendering and fetching don't get more than
// one round out of sync.
if (this.renderPromise) {
await this.renderPromise;
}
// Initiate the next render. This will happen in the
// background while we enqueue our next fetch.
let doRender = async () => {
this.rendering = true;
await this.renderLogs(buf, l);
this.rendering = false;
this.updateControls();
};
this.renderPromise = doRender();
if (this.fetchedFullStream) {
return false;
}
return hadLogs;
}
private async renderLogs(buf: BufferedLogs, l: Location) {
if (!(buf && buf.peek())) {
return;
}
let logBlock: LogDog.LogEntry[] = [];
// Create a promise loop to push logs at intervals.
let lines = 0;
for (let nextLog = buf.next(); (nextLog); nextLog = buf.next()) {
// Add the next log to the append block.
logBlock.push(nextLog);
if (nextLog.text && nextLog.text.lines) {
lines += nextLog.text.lines.length;
}
// Add logs until we reach our interval lines.
// If we've exceeded our burst, then interleave a sleep (yield). This
// will reduce user jank a bit.
if (Model.logAppendInterval > 0 && lines >= Model.logAppendInterval) {
this.appendBlock(logBlock, l);
await luci.sleepPromise(Model.logAppendDelay);
lines = 0;
}
}
// If there are any buffered logs, append that block.
this.appendBlock(logBlock, l);
}
/**
* Appends the contents of the "block" array to the viewer, consuming
* "block" in the process.
*
* Block will be reset (but not resized) to zero elements after appending.
*/
private appendBlock(block: LogDog.LogEntry[], l: Location) {
if (!block.length) {
return;
}
console.log('Rendering', block.length, 'logs...');
this.view.pushLogEntries(block, l);
block.length = 0;
// Update our status and controls.
this.updateControls();
}
/**
* Sets whether the next fetch will pull from the tail (end) or the top
* (beginning) region.
*
* This is only relevant when there is a log split.
*/
setFetchFromTail(v: boolean) {
this.fetchFromTail = v;
}
private buildStreamStatus(v: LogStreamStatus[]): StreamStatusEntry[] {
let maxStatus = LogDog.FetchStatus.IDLE;
let maxStatusCount = 0;
let needsAuth = false;
// Prune any finished entries and accumulate them for status bar change.
v = (v || []).filter((st) => {
needsAuth = (needsAuth || st.needsAuth);
if (st.fetchStatus > maxStatus) {
maxStatus = st.fetchStatus;
maxStatusCount = 1;
} else if (st.fetchStatus === maxStatus) {
maxStatusCount++;
}
return (!st.finished);
});
return v.map((st): StreamStatusEntry => {
return {
name: '.../+/' + st.stream.name,
desc: st.state,
};
});
}
private get providerCanSplit(): boolean {
let split = this.provider.split();
return (!!(split && split.canSplit()));
}
private get isSplit(): boolean {
let split = this.provider.split();
return (!!(split && split.isSplit()));
}
private get fetchedEndOfStream(): boolean {
return (this.provider.fetchedEndOfStream());
}
private get fetchedFullStream(): boolean {
return (this.fetchedEndOfStream && (!this.isSplit));
}
private get logStreamUrl(): string|undefined {
if (!this.cachedLogStreamUrl) {
this.cachedLogStreamUrl = this.provider.getLogStreamUrl();
}
return this.cachedLogStreamUrl;
}
}
/** Generic interface for a log provider. */
interface LogProvider {
setStreamStatusCallback(cb: StreamStatusCallback): void;
fetch(op: luci.Operation, l: Location): Promise<BufferedLogs>;
getLogStreamUrl(): string|undefined;
/** Will return null if this LogProvider doesn't support splitting. */
split(): SplitLogProvider|null;
fetchedEndOfStream(): boolean;
}
/** Additional methods for log stream splitting, if supported. */
interface SplitLogProvider {
canSplit(): boolean;
isSplit(): boolean;
}
/** A LogStream is a LogProvider manages a single log stream. */
class LogStream implements LogProvider {
/**
* Always begin with a small fetch. We'll disable this afterward the first
* finishes.
*/
private initialFetch = true;
private fetcher: LogDog.Fetcher;
private activeFetch: LogDog.Fetch|undefined;
/** The log stream index of the next head() log. */
private nextHeadIndex = 0;
/**
* The lowest log stream index of all of the tail logs. If this is <0, then
* it is uninitialized.
*/
private firstTailIndex = -1;
/**
* The next log stream index to fetch to continue pulling logs from the
* bottom. If this is <0, it is uninitialized.
*/
private nextBottomIndex = -1;
private streamStatusCallback: StreamStatusCallback;
/** The size of the tail walkback region. */
private static TAIL_WALKBACK = 500;
constructor(
client: LogDog.Client, readonly stream: LogDog.StreamPath,
readonly initialFetchSize: number, readonly fetchSize: number) {
this.fetcher = new LogDog.Fetcher(client, stream);
}
private setActiveFetch(fetch: LogDog.Fetch): LogDog.Fetch {
this.activeFetch = fetch;
this.activeFetch.addStateChangedCallback((_: LogDog.Fetch) => {
this.statusChanged();
});
return fetch;
}
get fetchStatus(): LogDog.FetchStatus {
if (this.activeFetch) {
return this.activeFetch.lastStatus;
}
return LogDog.FetchStatus.IDLE;
}
get fetchError(): Error|undefined {
if (this.activeFetch) {
return this.activeFetch.lastError;
}
return undefined;
}
async fetch(op: luci.Operation, l: Location) {
// Determine which method to use based on the insertion point and current
// log stream fetch state.
let getLogs: Promise<LogDog.LogEntry[]>;
switch (l) {
case Location.HEAD:
getLogs = this.getHead(op);
break;
case Location.TAIL:
getLogs = this.getTail(op);
break;
case Location.BOTTOM:
getLogs = this.getBottom(op);
break;
default:
// Nothing to do.
throw new Error('Unknown Location: ' + l);
}
try {
let logs = await getLogs;
this.initialFetch = false;
this.statusChanged();
return new BufferedLogs(logs);
} catch (err) {
throw resolveErr(err);
}
}
get descriptor() {
return this.fetcher.desc;
}
getLogStreamUrl(): string|undefined {
let desc = this.descriptor;
if (desc) {
return (desc.tags || {})['logdog.viewer_url'];
}
return undefined;
}
setStreamStatusCallback(cb: StreamStatusCallback) {
this.streamStatusCallback = cb;
}
private statusChanged() {
if (this.streamStatusCallback) {
this.streamStatusCallback([this.getStreamStatus()]);
}
}
getStreamStatus(): LogStreamStatus {
let pieces: string[] = [];
let tidx = this.fetcher.terminalIndex;
if (this.nextHeadIndex > 0) {
pieces.push('1..' + this.nextHeadIndex);
} else {
pieces.push('0');
}
if (this.isSplit()) {
if (tidx >= 0) {
pieces.push('| ' + this.firstTailIndex + ' / ' + tidx);
tidx = -1;
} else {
pieces.push(
'| ' + this.firstTailIndex + '..' + this.nextBottomIndex +
' ...');
}
} else if (tidx >= 0) {
pieces.push('/ ' + tidx);
} else {
pieces.push('...');
}
let needsAuth = false;
let finished = this.finished;
if (finished) {
pieces.push('(Finished)');
} else {
switch (this.fetchStatus) {
case LogDog.FetchStatus.IDLE:
case LogDog.FetchStatus.LOADING:
pieces.push('(Loading)');
break;
case LogDog.FetchStatus.STREAMING:
pieces.push('(Streaming)');
break;
case LogDog.FetchStatus.MISSING:
pieces.push('(Missing)');
break;
case LogDog.FetchStatus.ERROR:
let err = this.fetchError;
if (err) {
err = resolveErr(err);
if (err === NOT_AUTHENTICATED) {
pieces.push('(Auth Error)');
needsAuth = true;
} else {
pieces.push('(Error)');
}
} else {
pieces.push('(Error)');
}
break;
default:
// Nothing to do.
break;
}
}
return {
stream: this.stream,
state: pieces.join(' '),
finished: finished,
fetchStatus: this.fetchStatus,
needsAuth: needsAuth,
};
}
split(): SplitLogProvider {
return this;
}
isSplit(): boolean {
// We're split if we have a bottom and we're not finished tailing.
return (
this.firstTailIndex >= 0 &&
(this.nextHeadIndex < this.firstTailIndex));
}
canSplit(): boolean {
return (!(this.isSplit() || this.caughtUp));
}
private get caughtUp(): boolean {
// We're caught up if we have both a head and bottom index, and the head
// is at or past the bottom.
return (
this.nextHeadIndex >= 0 && this.nextBottomIndex >= 0 &&
this.nextHeadIndex >= this.nextBottomIndex);
}
fetchedEndOfStream(): boolean {
let tidx = this.fetcher.terminalIndex;
return (
tidx >= 0 &&
((this.nextHeadIndex > tidx) || (this.nextBottomIndex > tidx)));
}
private get finished(): boolean {
return ((!this.isSplit()) && this.fetchedEndOfStream());
}
private updateIndexes() {
if (this.firstTailIndex >= 0) {
if (this.nextBottomIndex < this.firstTailIndex) {
this.nextBottomIndex = this.firstTailIndex + 1;
}
if (this.nextHeadIndex >= this.firstTailIndex &&
this.nextBottomIndex >= 0) {
// Synchronize our head and bottom pointers.
this.nextHeadIndex = this.nextBottomIndex =
Math.max(this.nextHeadIndex, this.nextBottomIndex);
}
}
}
private nextFetcherOptions(): LogDog.FetcherOptions {
let opts: LogDog.FetcherOptions = {};
if (this.initialFetch && this.initialFetchSize > 0) {
opts.byteCount = this.initialFetchSize;
} else if (this.fetchSize > 0) {
opts.byteCount = this.fetchSize;
}
return opts;
}
private async getHead(op: luci.Operation) {
this.updateIndexes();
if (this.finished) {
// Our HEAD region has met/surpassed our TAIL region, so there are no
// HEAD logs to return. Only bottom.
return [];
}
// If we have a tail pointer, only fetch HEAD up to that point.
let opts = this.nextFetcherOptions();
if (this.firstTailIndex >= 0) {
opts.logCount = (this.firstTailIndex - this.nextHeadIndex);
}
let f =
this.setActiveFetch(this.fetcher.get(op, this.nextHeadIndex, opts));
let logs = await f.p;
if (logs && logs.length) {
this.nextHeadIndex = (logs[logs.length - 1].streamIndex + 1);
this.updateIndexes();
}
return logs;
}
private async getTail(op: luci.Operation) {
// If we haven't performed a Tail before, start with one.
if (this.firstTailIndex < 0) {
let tidx = this.fetcher.terminalIndex;
if (tidx < 0) {
let f = this.setActiveFetch(this.fetcher.getLatest(op));
let logs = await f.p;
// Mark our initial "tail" position.
if (logs && logs.length) {
this.firstTailIndex = logs[0].streamIndex;
this.updateIndexes();
}
return logs;
}
this.firstTailIndex = (tidx + 1);
this.updateIndexes();
}
// We're doing incremental reverse fetches. If we're finished tailing,
// return no logs.
if (!this.isSplit()) {
return [];
}
// Determine our walkback region.
let startIndex = this.firstTailIndex - LogStream.TAIL_WALKBACK;
if (this.nextHeadIndex >= 0) {
if (startIndex < this.nextHeadIndex) {
startIndex = this.nextHeadIndex;
}
} else if (startIndex < 0) {
startIndex = 0;
}
let count = (this.firstTailIndex - startIndex);
// Fetch the full walkback region.
let f = this.setActiveFetch(this.fetcher.getAll(op, startIndex, count));
let logs = await f.p;
this.firstTailIndex = startIndex;
this.updateIndexes();
return logs;
}
private async getBottom(op: luci.Operation) {
this.updateIndexes();
// If there are no more logs in the stream, return no logs.
if (this.fetchedEndOfStream()) {
return [];
}
// If our bottom index isn't initialized, initialize it via tail.
if (this.nextBottomIndex < 0) {
return this.getTail(op);
}
let opts = this.nextFetcherOptions();
let f =
this.setActiveFetch(this.fetcher.get(op, this.nextBottomIndex, opts));
let logs = await f.p;
if (logs && logs.length) {
this.nextBottomIndex = (logs[logs.length - 1].streamIndex + 1);
}
return logs;
}
}
/**
* LogSorter is an interface that used by AggregateLogStream to extract sorted
* logs from a set of BufferedLogs.
*
* It is used to compare two log entries to determine their relative order.
*/
type LogSorter = {
/** Returns true if "a" comes before "b". */
before: (a: LogDog.LogEntry, b: LogDog.LogEntry) => number;
/**
* If implemented, returns an implicit next log in the buffer set.
*
* This is useful if the next log can be determined from the current
* buffered data, even if it is partial or incomplete.
*/
implicitNext?: (prev: LogDog.LogEntry, buffers: BufferedLogs[]) =>
LogDog.LogEntry | null;
};
const prefixIndexLogSorter: LogSorter = {
before: (a: LogDog.LogEntry, b: LogDog.LogEntry) => {
return (a.prefixIndex - b.prefixIndex);
},
implicitNext:
(prev: LogDog.LogEntry, buffers: BufferedLogs[]) => {
let nextPrefixIndex = (prev.prefixIndex + 1);
for (let buf of buffers) {
let le = buf.peek();
if (le && le.prefixIndex === nextPrefixIndex) {
return buf.next();
}
}
return null;
},
};
const timestampLogSorter: LogSorter = {
before: (a: LogDog.LogEntry, b: LogDog.LogEntry) => {
if (a.timestamp) {
if (b.timestamp) {
return a.timestamp.getTime() - b.timestamp.getTime();
}
return 1;
}
if (b.timestamp) {
return -1;
}
return 0;
},
// No implicit "next" with timestamp-based logs, since the next log in
// an empty buffer may actually be the next contiguous log.
implicitNext: undefined,
};
/**
* An aggregate log stream. It presents a single-stream view, but is really
* composed of several log streams interleaved based on their prefix indices
* (if they share a prefix) or timestamps (if they don't).
*
* At least one log entry from each stream must be buffered before any log
* entries can be yielded, since we don't know what ordering to apply
* otherwise. To make this fast, we will make the first request for each
* stream small so it finishes quickly and we can start rendering. Subsequent
* entries will be larger for efficiency.
*
* @param {LogStream} streams the composite streams.
*/
class AggregateLogStream implements LogProvider {
private streams: AggregateLogStream.Entry[];
private active: AggregateLogStream.Entry[];
private currentNextPromise: Promise<BufferedLogs[]>|null;
private readonly logSorter: LogSorter;
private streamStatusCallback: StreamStatusCallback;
constructor(streams: LogStream[]) {
// Input streams, ordered by input order.
this.streams = streams.map<AggregateLogStream.Entry>((ls, i) => {
ls.setStreamStatusCallback((st: LogStreamStatus[]) => {
if (st) {
this.streams[i].status = st[0];
this.statusChanged();
}
});
return new AggregateLogStream.Entry(ls);
});
// Subset of input streams that are still active (not finished).
this.active = this.streams;
// The currently-active "next" promise.
this.currentNextPromise = null;
// Determine our log comparison function. If all of our logs share a
// prefix, we will use the prefix index. Otherwise, we will use the
// timestamp.
let template: LogDog.StreamPath;
let sharedPrefix = this.streams.every((entry) => {
if (!template) {
template = entry.ls.stream;
return true;
}
return template.samePrefixAs(entry.ls.stream);
});
if (sharedPrefix) {
this.logSorter = prefixIndexLogSorter;
} else {
this.logSorter = timestampLogSorter;
}
}
split(): SplitLogProvider|null {
return null;
}
fetchedEndOfStream(): boolean {
return (!this.active.length);
}
setStreamStatusCallback(cb: StreamStatusCallback) {
this.streamStatusCallback = cb;
}
private statusChanged() {
if (this.streamStatusCallback) {
// Iterate through our composite stream statuses and pick the one that
// we want to report.
this.streamStatusCallback(this.streams.map((entry): LogStreamStatus => {
return entry.status;
}));
}
}
getLogStreamUrl(): string|undefined {
// Return the first log stream viewer URL. IF we have a shared prefix,
// this will always work. Otherwise, returning something is better than
// nothing, so if any of the base streams have a URL, we will return it.
for (let s of this.streams) {
let url = s.ls.getLogStreamUrl();
if (url) {
return url;
}
}
return undefined;
}
/**
* Implements LogProvider.next
*/
async fetch(op: luci.Operation, _: Location) {
// If we're already are fetching the next buffer, this is an error.
if (this.currentNextPromise) {
throw new Error('In-progress next(), cannot start another.');
}
// Filter out any finished streams from our active list. A stream is
// finished if it is finished streaming and we don't have a retained
// buffer from it.
//
// This updates our "finished" property, since it's derived from the
// length of our active array.
this.active = this.active.filter((entry) => {
return (
(!entry.buffer) || entry.buffer.peek() ||
(!entry.ls.fetchedEndOfStream()));
});
if (!this.active.length) {
// No active streams, so we're finished. Permanently set our promise to
// the finished state.
return new BufferedLogs(null);
}
let buffers: BufferedLogs[];
this.currentNextPromise = this.ensureActiveBuffers(op);
try {
buffers = await this.currentNextPromise;
} finally {
this.currentNextPromise = null;
}
return this._aggregateBuffers(buffers);
}
private async ensureActiveBuffers(op: luci.Operation) {
// Fill all buffers for all active streams. This may result in an RPC to
// load new buffer content for streams whose buffers are empty.
await Promise.all(this.active.map((entry) => entry.ensure(op)));
// Examine the error status of each stream.
//
// The error is interesting, since we must present a common error view to
// our caller. If all returned errors are "NOT_AUTHENTICATED", we will
// return a NOT_AUTHENTICATED. Otherwise, we will return a generic
// "streams failed" error.
//
// The outer Promise will pull logs for any streams that don't have any.
// On success, the "buffer" for the entry will be populated. On failure,
// an error will be returned. Because Promise.all fails fast, we will
// catch inner errors and return them as values (null if no error).
let buffers = new Array<BufferedLogs>(this.active.length);
let errors = new Array<Error>();
this.active.forEach((entry, idx) => {
buffers[idx] = entry.buffer;
if (entry.lastError) {
errors.push(entry.lastError);
}
});
// We are done, and will return a value.
this.currentNextPromise = null;
if (errors.length) {
throw this._aggregateErrors(errors);
}
return buffers;
}
private _aggregateErrors(errors: Error[]): Error {
let isNotAuthenticated = false;
errors.every((err) => {
if (!err) {
return true;
}
if (err === NOT_AUTHENTICATED) {
isNotAuthenticated = true;
return true;
}
isNotAuthenticated = false;
return false;
});
return (
(isNotAuthenticated) ? (NOT_AUTHENTICATED) :
new Error('Stream Error'));
}
private _aggregateBuffers(buffers: BufferedLogs[]): BufferedLogs {
switch (buffers.length) {
case 0:
// No buffers, so no logs.
return new BufferedLogs(null);
case 1:
// As a special case, if we only have one buffer, and we assume that
// its entries are sorted, then that buffer is a return value.
return new BufferedLogs(buffers[0].getAll());
default:
break;
}
// Preload our peek array.
let peek = new Array<LogDog.LogEntry>(buffers.length);
peek.length = 0;
for (let buf of buffers) {
let le = buf.peek();
if (!le) {
// One of our input buffers had no log entries.
return new BufferedLogs(null);
}
peek.push(le);
}
// Assemble our aggregate buffer array.
//
// As we add log entries, latestAdded will be updated to point to the most
// recently added LogEntry.
let entries: LogDog.LogEntry[] = [];
let latestAdded: LogDog.LogEntry|null = null;
while (true) {
// Choose the next stream.
let earliest = 0;
for (let i = 1; i < buffers.length; i++) {
if (this.logSorter.before(peek[i], peek[earliest])) {
earliest = i;
}
}
// Get the next log from the earliest stream.
let next = buffers[earliest].next();
if (next) {
latestAdded = next;
entries.push(latestAdded);
}
// Repopulate that buffer's "peek" value. If the buffer has no more
// entries, then we're done this round.
next = buffers[earliest].peek();
if (!next) {
break;
}
peek[earliest] = next;
}
// One or more of our buffers is exhausted. If we have the ability to load
// implicit next logs, try and extract more using that.
if (latestAdded && this.logSorter.implicitNext) {
while (true) {
latestAdded = this.logSorter.implicitNext(latestAdded, buffers);
if (!latestAdded) {
break;
}
entries.push(latestAdded);
}
}
return new BufferedLogs(entries);
}
}
/** Internal namespace for AggregateLogStream types. */
namespace AggregateLogStream {
/** Entry is an entry for a single log stream and its buffered logs. */
export class Entry {
buffer = new BufferedLogs(null);
status: LogStreamStatus;
lastError: Error|null;
constructor(readonly ls: LogStream) {
this.status = ls.getStreamStatus();
}
get active() {
return (
(!this.buffer) || this.buffer.peek() ||
this.ls.fetchedEndOfStream());
}
async ensure(op: luci.Operation) {
this.lastError = null;
if (this.buffer && this.buffer.peek()) {
return;
}
try {
this.buffer = await this.ls.fetch(op, Location.HEAD);
} catch (e) {
// Log stream source of error. Raise a generic "failed to
// buffer" error. This will become a permanent failure.
console.error(
'Error loading buffer for', this.ls.stream.fullName(), '(',
this.ls, '): ', e);
this.lastError = e;
}
}
};
}
/**
* A buffer of ordered log entries.
*
* Assumes total ownership of the input log buffer, which can be null to
* indicate no logs.
*/
class BufferedLogs {
private index = 0;
constructor(private logs: LogDog.LogEntry[]|null) {}
/**
* Peek returns the next log in the buffer without modifying the buffer. If
* there are no logs in the buffer, peek will return null.
*/
peek(): LogDog.LogEntry|null {
return (this.logs) ? (this.logs[this.index]) : (null);
}
/**
* Returns a copy of the remaining logs in the buffer.
* If there are no logs, an empty array will be returned.
*/
peekAll(): LogDog.LogEntry[] {
return (this.logs || []).slice(0);
}
/**
* GetAll returns all logs in the buffer. Afterwards, the buffer will be
* empty.
*/
getAll(): LogDog.LogEntry[] {
// Pop all logs.
let logs = this.logs;
this.logs = null;
return (logs || []);
}
/**
* Next fetches the next log in the buffer, removing it from the buffer. If
* no more logs are available, it will return null.
*/
next(): LogDog.LogEntry|null {
if (!(this.logs && this.logs.length)) {
return null;
}
// Get the next log and increment our index.
let log = this.logs[this.index++];
if (this.index >= this.logs.length) {
this.logs = null;
}
return log;
}
}
} | the_stack |
import { Application, Container, Contracts } from "@packages/core-kernel";
import { Peer } from "@packages/core-p2p/src/peer";
import { PeerVerificationResult, PeerVerifier } from "@packages/core-p2p/src/peer-verifier";
import { Blocks } from "@packages/crypto";
describe("PeerVerifier", () => {
let app: Application;
let peerVerifier: PeerVerifier;
let peer: Peer;
const peerCommunicator: Contracts.P2P.PeerCommunicator = {
initialize: jest.fn(),
postBlock: jest.fn(),
postTransactions: jest.fn(),
ping: jest.fn(),
pingPorts: jest.fn(),
getPeers: jest.fn(),
getPeerBlocks: jest.fn(),
hasCommonBlocks: jest.fn(),
};
const logger = { warning: console.log, debug: console.log, info: console.log };
const trigger = { call: jest.fn() };
const stateStore = { getLastBlocks: jest.fn(), getLastHeight: jest.fn() };
const database = {};
const databaseInterceptor = {
getBlocksByHeight: jest.fn(),
};
const dposState = { getRoundInfo: jest.fn(), getRoundDelegates: jest.fn() };
const blockFromDataMock = (blockData) =>
({
verifySignature: () => true,
data: {
height: blockData.height,
generatorPublicKey: blockData.generatorPublicKey,
},
} as Blocks.Block);
const blockWithIdFromDataMock = (blockData) =>
({
verifySignature: () => true,
data: {
id: blockData.id,
height: blockData.height,
generatorPublicKey: blockData.generatorPublicKey,
},
} as Blocks.Block);
const notVerifiedBlockFromDataMock = (blockData) =>
({
verifySignature: () => false,
data: {
height: blockData.height,
generatorPublicKey: blockData.generatorPublicKey,
},
} as Blocks.Block);
beforeAll(() => {
process.env.CORE_P2P_PEER_VERIFIER_DEBUG_EXTRA = "true";
app = new Application(new Container.Container());
app.container.unbindAll();
app.bind(Container.Identifiers.LogService).toConstantValue(logger);
app.bind(Container.Identifiers.TriggerService).toConstantValue(trigger);
app.bind(Container.Identifiers.StateStore).toConstantValue(stateStore);
app.bind(Container.Identifiers.DatabaseInterceptor).toConstantValue(databaseInterceptor);
app.bind(Container.Identifiers.DatabaseService).toConstantValue(database);
app.bind(Container.Identifiers.Application).toConstantValue(app);
app.bind(Container.Identifiers.DposState).toConstantValue(dposState);
app.bind(Container.Identifiers.PeerCommunicator).toConstantValue(peerCommunicator);
});
beforeEach(() => {
jest.resetAllMocks();
peer = new Peer("176.165.56.77", 4000);
peerVerifier = app.resolve<PeerVerifier>(PeerVerifier);
peerVerifier.initialize(peer);
});
describe("checkState", () => {
describe("when claimed state block header does not match claimed state height", () => {
it("should return undefined", async () => {
const claimedState: Contracts.P2P.PeerState = {
height: 18,
forgingAllowed: false,
currentSlot: 18,
header: {
height: 19,
id: "13965046748333390338",
},
};
expect(await peerVerifier.checkState(claimedState, Date.now() + 2000)).toBeUndefined();
});
});
describe("when Case1. Peer height > our height and our highest block is part of the peer's chain", () => {
it("should return PeerVerificationResult not forked", async () => {
const generatorPublicKey = "03c5282b639d0e8f94cfac6c0ed242d1634d8a2c93cbd76c6ed2856a9f19cf6a13";
const claimedState: Contracts.P2P.PeerState = {
height: 18,
forgingAllowed: false,
currentSlot: 18,
header: {
height: 18,
id: "13965046748333390338",
generatorPublicKey,
},
};
const ourHeader = {
height: 15,
id: "11165046748333390338",
};
stateStore.getLastHeight = jest.fn().mockReturnValue(ourHeader.height);
stateStore.getLastBlocks = jest
.fn()
.mockReturnValue([{ data: { height: ourHeader.height }, getHeader: () => ourHeader }]);
databaseInterceptor.getBlocksByHeight = jest.fn().mockImplementation((blockHeights) =>
blockHeights.map((height: number) => ({
height,
id: height.toString().padStart(2, "0").repeat(20), // just using height to mock the id
})),
);
peerCommunicator.hasCommonBlocks = jest.fn().mockImplementation((_, ids) => ({
id: ids[ids.length - 1],
height: parseInt(ids[ids.length - 1].slice(0, 2)),
}));
trigger.call = jest.fn().mockReturnValue([
{
getPublicKey: () => {
return generatorPublicKey;
},
},
]); // getActiveDelegates mock
peerCommunicator.getPeerBlocks = jest.fn().mockImplementation((_, options) => {
const blocks = [];
for (let i = options.fromBlockHeight + 1; i <= options.fromBlockHeight + options.blockLimit; i++) {
blocks.push({ id: i.toString(), height: i, generatorPublicKey });
}
return blocks;
});
const spyFromData = jest
.spyOn(Blocks.BlockFactory, "fromData")
.mockImplementation(blockWithIdFromDataMock);
const result = await peerVerifier.checkState(claimedState, Date.now() + 2000);
expect(result).toBeInstanceOf(PeerVerificationResult);
expect(result.forked).toBeFalse();
const resultAlreadyVerified = await peerVerifier.checkState(claimedState, Date.now() + 2000);
expect(resultAlreadyVerified).toBeInstanceOf(PeerVerificationResult);
expect(resultAlreadyVerified.forked).toBeFalse();
spyFromData.mockRestore();
peerCommunicator.getPeerBlocks = jest.fn();
databaseInterceptor.getBlocksByHeight = jest.fn();
peerCommunicator.hasCommonBlocks = jest.fn();
stateStore.getLastHeight = jest.fn();
trigger.call = jest.fn();
stateStore.getLastBlocks = jest.fn();
});
});
describe("when Case2. Peer height > our height and our highest block is not part of the peer's chain", () => {
const claimedState: Contracts.P2P.PeerState = {
height: 18,
forgingAllowed: false,
currentSlot: 18,
header: {
height: 18,
id: "13965046748333390338",
},
};
const ourHeader = {
height: 15,
id: "11165046748333390338",
};
it("should return PeerVerificationResult forked", async () => {
const generatorPublicKey = "03c5282b639d0e8f94cfac6c0ed242d1634d8a2c93cbd76c6ed2856a9f19cf6a13";
stateStore.getLastHeight = jest
.fn()
.mockReturnValueOnce(ourHeader.height)
.mockReturnValueOnce(ourHeader.height);
stateStore.getLastBlocks = jest
.fn()
.mockReturnValueOnce([{ data: { height: ourHeader.height }, getHeader: () => ourHeader }]);
databaseInterceptor.getBlocksByHeight = jest.fn().mockImplementation((blockHeights) =>
blockHeights.map((height: number) => ({
height,
id: height.toString().padStart(2, "0").repeat(20), // just using height to mock the id
})),
);
peerCommunicator.hasCommonBlocks = jest
.fn()
.mockImplementation((_, ids) => ({ id: ids[0], height: parseInt(ids[0].slice(0, 2)) }));
trigger.call = jest.fn().mockReturnValue([
{
getPublicKey: () => {
return generatorPublicKey;
},
},
]); // getActiveDelegates mock
peerCommunicator.getPeerBlocks = jest.fn().mockImplementation((_, options) => {
const blocks = [];
for (let i = options.fromBlockHeight + 1; i <= options.fromBlockHeight + options.blockLimit; i++) {
blocks.push({ id: i.toString(), height: i, generatorPublicKey });
}
return blocks;
});
const spyFromData = jest.spyOn(Blocks.BlockFactory, "fromData").mockImplementation(blockFromDataMock);
const result = await peerVerifier.checkState(claimedState, Date.now() + 2000);
expect(result).toBeInstanceOf(PeerVerificationResult);
expect(result.forked).toBeTrue();
spyFromData.mockRestore();
peerCommunicator.getPeerBlocks = jest.fn();
databaseInterceptor.getBlocksByHeight = jest.fn();
peerCommunicator.hasCommonBlocks = jest.fn();
});
});
describe("when Case3. Peer height == our height and our latest blocks are the same", () => {
const claimedState: Contracts.P2P.PeerState = {
height: 15,
forgingAllowed: false,
currentSlot: 15,
header: {
height: 15,
id: "13965046748333390338",
},
};
it("should return PeerVerificationResult not forked", async () => {
stateStore.getLastHeight = jest.fn().mockReturnValueOnce(claimedState.height);
stateStore.getLastBlocks = jest
.fn()
.mockReturnValueOnce([
{ data: { height: claimedState.height }, getHeader: () => claimedState.header },
]);
databaseInterceptor.getBlocksByHeight = jest.fn().mockReturnValueOnce([{ id: claimedState.header.id }]);
const result = await peerVerifier.checkState(claimedState, Date.now() + 2000);
expect(result).toBeInstanceOf(PeerVerificationResult);
expect(result.forked).toBeFalse();
});
});
describe("when Case4. Peer height == our height and our latest blocks differ", () => {
const claimedState: Contracts.P2P.PeerState = {
height: 15,
forgingAllowed: false,
currentSlot: 15,
header: {
height: 15,
id: "13965046748333390338",
},
};
const ourHeader = {
height: 15,
id: "11165046748333390338",
};
it.each([[true], [false]])(
"should return PeerVerificationResult forked when claimed state block header is valid",
async (delegatesEmpty) => {
const generatorPublicKey = "03c5282b639d0e8f94cfac6c0ed242d1634d8a2c93cbd76c6ed2856a9f19cf6a13";
stateStore.getLastHeight = jest
.fn()
.mockReturnValueOnce(claimedState.height)
.mockReturnValueOnce(claimedState.height);
stateStore.getLastBlocks = jest
.fn()
.mockReturnValueOnce([{ data: { height: claimedState.height }, getHeader: () => ourHeader }]);
databaseInterceptor.getBlocksByHeight = jest
.fn()
.mockReturnValueOnce([{ id: ourHeader.id }])
.mockImplementation((blockHeights) =>
blockHeights.map((height: number) => ({
height,
id: height.toString().padStart(2, "0").repeat(20), // just using height to mock the id
})),
);
peerCommunicator.hasCommonBlocks = jest
.fn()
.mockImplementation((_, ids) => ({ id: ids[0], height: parseInt(ids[0].slice(0, 2)) }));
if (delegatesEmpty) {
// getActiveDelegates return empty array, should still work using dpos state
trigger.call = jest.fn().mockReturnValue([]); // getActiveDelegates mock
dposState.getRoundInfo = jest
.fn()
.mockReturnValueOnce({ round: 1, maxDelegates: 51 })
.mockReturnValueOnce({ round: 1, maxDelegates: 51 });
dposState.getRoundDelegates = jest
.fn()
.mockReturnValueOnce([
{
getPublicKey: () => {
return generatorPublicKey;
},
},
])
.mockReturnValueOnce([
{
getPublicKey: () => {
return generatorPublicKey;
},
},
]);
} else {
trigger.call = jest.fn().mockReturnValue([
{
getPublicKey: () => {
return generatorPublicKey;
},
},
]); // getActiveDelegates mock
}
peerCommunicator.getPeerBlocks = jest.fn().mockImplementation((_, options) => {
const blocks = [];
for (
let i = options.fromBlockHeight + 1;
i <= options.fromBlockHeight + options.blockLimit;
i++
) {
blocks.push({ id: i.toString(), height: i, generatorPublicKey });
}
return blocks;
});
const spyFromData = jest
.spyOn(Blocks.BlockFactory, "fromData")
.mockImplementation(blockFromDataMock);
const result = await peerVerifier.checkState(claimedState, Date.now() + 2000);
expect(result).toBeInstanceOf(PeerVerificationResult);
expect(result.forked).toBeTrue();
spyFromData.mockRestore();
peerCommunicator.getPeerBlocks = jest.fn();
databaseInterceptor.getBlocksByHeight = jest.fn();
peerCommunicator.hasCommonBlocks = jest.fn();
},
);
it("should return undefined when claimed state block header is invalid", async () => {
stateStore.getLastHeight = jest.fn().mockReturnValue(claimedState.height);
stateStore.getLastBlocks = jest
.fn()
.mockReturnValue([{ data: { height: claimedState.height }, getHeader: () => ourHeader }]);
jest.spyOn(Blocks.BlockFactory, "fromData").mockReturnValue({
verifySignature: () => false,
} as Blocks.Block);
const generatorPublicKey = "03c5282b639d0e8f94cfac6c0ed242d1634d8a2c93cbd76c6ed2856a9f19cf6a13";
trigger.call = jest.fn().mockReturnValue([{ publicKey: generatorPublicKey }]); // getActiveDelegates mock
stateStore.getLastBlocks = jest.fn();
const result = await peerVerifier.checkState(claimedState, Date.now() + 2000);
expect(result).toBeUndefined();
});
it("should return undefined when peer does not return common blocks", async () => {
stateStore.getLastHeight = jest.fn().mockReturnValueOnce(claimedState.height);
stateStore.getLastBlocks = jest
.fn()
.mockReturnValueOnce([{ data: { height: claimedState.height }, getHeader: () => ourHeader }]);
databaseInterceptor.getBlocksByHeight = jest
.fn()
.mockReturnValueOnce([{ id: ourHeader.id }])
.mockImplementation((blockHeights) =>
blockHeights.map((height: number) => ({
height,
id: height.toString().padStart(2, "0").repeat(20), // just using height to mock the id
})),
);
peerCommunicator.hasCommonBlocks = jest.fn();
const result = await peerVerifier.checkState(claimedState, Date.now() + 2000);
expect(result).toBeUndefined();
});
it("should throw when state.getLastHeight does not return a height", async () => {
stateStore.getLastHeight = jest
.fn()
.mockReturnValueOnce(claimedState.height)
.mockRejectedValueOnce(undefined);
stateStore.getLastBlocks = jest
.fn()
.mockReturnValueOnce([{ data: { height: claimedState.height }, getHeader: () => ourHeader }]);
databaseInterceptor.getBlocksByHeight = jest
.fn()
.mockReturnValueOnce([{ id: ourHeader.id }])
.mockImplementation((blockHeights) =>
blockHeights.map((height: number) => ({
height,
id: height.toString().padStart(2, "0").repeat(20), // just using height to mock the id
})),
);
peerCommunicator.hasCommonBlocks = jest.fn();
jest.spyOn(Blocks.BlockFactory, "fromData").mockImplementation(blockFromDataMock);
await expect(peerVerifier.checkState(claimedState, Date.now() + 2000)).toReject();
});
it("should return undefined when peer returns no common block", async () => {
stateStore.getLastHeight = jest
.fn()
.mockReturnValueOnce(claimedState.height)
.mockReturnValueOnce(claimedState.height);
stateStore.getLastBlocks = jest
.fn()
.mockReturnValueOnce([{ data: { height: claimedState.height }, getHeader: () => ourHeader }]);
databaseInterceptor.getBlocksByHeight = jest
.fn()
.mockReturnValueOnce([{ id: ourHeader.id }])
.mockImplementation((blockHeights) =>
blockHeights.map((height: number) => ({
height,
id: height.toString().padStart(2, "0").repeat(20), // just using height to mock the id
})),
);
peerCommunicator.hasCommonBlocks = jest.fn().mockResolvedValueOnce(undefined);
jest.spyOn(Blocks.BlockFactory, "fromData").mockImplementation(blockFromDataMock);
const result = await peerVerifier.checkState(claimedState, Date.now() + 2000);
expect(result).toBeUndefined();
});
it("should return undefined when peer returns unexpected id for common block", async () => {
stateStore.getLastHeight = jest
.fn()
.mockReturnValueOnce(claimedState.height)
.mockReturnValueOnce(claimedState.height);
stateStore.getLastBlocks = jest
.fn()
.mockReturnValueOnce([{ data: { height: claimedState.height }, getHeader: () => ourHeader }]);
databaseInterceptor.getBlocksByHeight = jest
.fn()
.mockReturnValueOnce([{ id: ourHeader.id }])
.mockImplementation((blockHeights) =>
blockHeights.map((height: number) => ({
height,
id: height.toString().padStart(2, "0").repeat(20), // just using height to mock the id
})),
);
peerCommunicator.hasCommonBlocks = jest
.fn()
.mockImplementation((_, ids) => ({ id: "unexpectedId", height: parseInt(ids[0].slice(0, 2)) }));
jest.spyOn(Blocks.BlockFactory, "fromData").mockImplementation(blockFromDataMock);
const result = await peerVerifier.checkState(claimedState, Date.now() + 2000);
expect(result).toBeUndefined();
});
it("should return undefined when peer returns unexpected height for common block", async () => {
stateStore.getLastHeight = jest
.fn()
.mockReturnValueOnce(claimedState.height)
.mockReturnValueOnce(claimedState.height);
stateStore.getLastBlocks = jest
.fn()
.mockReturnValueOnce([{ data: { height: claimedState.height }, getHeader: () => ourHeader }]);
databaseInterceptor.getBlocksByHeight = jest
.fn()
.mockReturnValueOnce([{ id: ourHeader.id }])
.mockImplementation((blockHeights) =>
blockHeights.map((height: number) => ({
height,
id: height.toString().padStart(2, "0").repeat(20), // just using height to mock the id
})),
);
peerCommunicator.hasCommonBlocks = jest
.fn()
.mockImplementation((_, ids) => ({ id: ids[0], height: 1000 + parseInt(ids[0].slice(0, 2)) }));
jest.spyOn(Blocks.BlockFactory, "fromData").mockImplementation(blockFromDataMock);
const result = await peerVerifier.checkState(claimedState, Date.now() + 2000);
expect(result).toBeUndefined();
});
it.each([[true], [false]])(
"should return undefined when getPeerBlocks returns empty or rejects",
async (returnEmpty) => {
stateStore.getLastHeight = jest
.fn()
.mockReturnValueOnce(claimedState.height)
.mockReturnValueOnce(claimedState.height);
stateStore.getLastBlocks = jest
.fn()
.mockReturnValueOnce([{ data: { height: claimedState.height }, getHeader: () => ourHeader }]);
databaseInterceptor.getBlocksByHeight = jest
.fn()
.mockReturnValueOnce([{ id: ourHeader.id }])
.mockImplementation((blockHeights) =>
blockHeights.map((height: number) => ({
height,
id: height.toString().padStart(2, "0").repeat(20), // just using height to mock the id
})),
);
peerCommunicator.hasCommonBlocks = jest
.fn()
.mockImplementation((_, ids) => ({ id: ids[0], height: parseInt(ids[0].slice(0, 2)) }));
jest.spyOn(Blocks.BlockFactory, "fromData").mockImplementation(blockFromDataMock);
const generatorPublicKey = "03c5282b639d0e8f94cfac6c0ed242d1634d8a2c93cbd76c6ed2856a9f19cf6a13";
trigger.call = jest.fn().mockReturnValue([
{
getPublicKey: () => {
return generatorPublicKey;
},
},
]); // getActiveDelegates mock
if (returnEmpty) {
peerCommunicator.getPeerBlocks = jest.fn().mockResolvedValueOnce([]);
} else {
peerCommunicator.getPeerBlocks = jest.fn().mockRejectedValueOnce(new Error("timeout"));
}
const result = await peerVerifier.checkState(claimedState, Date.now() + 2000);
expect(result).toBeUndefined();
},
);
it("should return undefined when peer returns block that does not verify", async () => {
const generatorPublicKey = "03c5282b639d0e8f94cfac6c0ed242d1634d8a2c93cbd76c6ed2856a9f19cf6a13";
stateStore.getLastHeight = jest
.fn()
.mockReturnValueOnce(claimedState.height)
.mockReturnValueOnce(claimedState.height);
stateStore.getLastBlocks = jest
.fn()
.mockReturnValueOnce([{ data: { height: claimedState.height }, getHeader: () => ourHeader }]);
databaseInterceptor.getBlocksByHeight = jest
.fn()
.mockReturnValueOnce([{ id: ourHeader.id }])
.mockImplementation((blockHeights) =>
blockHeights.map((height: number) => ({
height,
id: height.toString().padStart(2, "0").repeat(20), // just using height to mock the id
})),
);
peerCommunicator.hasCommonBlocks = jest
.fn()
.mockImplementation((_, ids) => ({ id: ids[0], height: parseInt(ids[0].slice(0, 2)) }));
trigger.call = jest.fn().mockReturnValue([
{
getPublicKey: () => {
return generatorPublicKey;
},
},
]); // getActiveDelegates mock
peerCommunicator.getPeerBlocks = jest.fn().mockImplementation((_, options) => {
const blocks = [];
for (let i = options.fromBlockHeight + 1; i <= options.fromBlockHeight + options.blockLimit; i++) {
blocks.push({ id: i.toString(), height: i, generatorPublicKey });
}
return blocks;
});
jest.spyOn(Blocks.BlockFactory, "fromData")
.mockImplementationOnce(blockFromDataMock)
.mockImplementation(notVerifiedBlockFromDataMock);
const result = await peerVerifier.checkState(claimedState, Date.now() + 2000);
expect(result).toBeUndefined();
});
it("should return undefined when peer returns block that does not verify", async () => {
const generatorPublicKey = "03c5282b639d0e8f94cfac6c0ed242d1634d8a2c93cbd76c6ed2856a9f19cf6a13";
stateStore.getLastHeight = jest
.fn()
.mockReturnValueOnce(claimedState.height)
.mockReturnValueOnce(claimedState.height);
stateStore.getLastBlocks = jest
.fn()
.mockReturnValueOnce([{ data: { height: claimedState.height }, getHeader: () => ourHeader }]);
databaseInterceptor.getBlocksByHeight = jest
.fn()
.mockReturnValueOnce([{ id: ourHeader.id }])
.mockImplementation((blockHeights) =>
blockHeights.map((height: number) => ({
height,
id: height.toString().padStart(2, "0").repeat(20), // just using height to mock the id
})),
);
peerCommunicator.hasCommonBlocks = jest
.fn()
.mockImplementation((_, ids) => ({ id: ids[0], height: parseInt(ids[0].slice(0, 2)) }));
trigger.call = jest.fn().mockReturnValue([
{
getPublicKey: () => {
return generatorPublicKey;
},
},
]); // getActiveDelegates mock
peerCommunicator.getPeerBlocks = jest.fn().mockImplementation((_, options) => {
const blocks = [];
for (let i = options.fromBlockHeight + 1; i <= options.fromBlockHeight + options.blockLimit; i++) {
blocks.push({ id: i.toString(), height: i + 3000, generatorPublicKey }); // wrong height block
}
return blocks;
});
jest.spyOn(Blocks.BlockFactory, "fromData").mockImplementation(blockFromDataMock);
const result = await peerVerifier.checkState(claimedState, Date.now() + 2000);
expect(result).toBeUndefined();
});
it("should return undefined when peer returns block that is not signed by expected delegate", async () => {
const generatorPublicKey = "03c5282b639d0e8f94cfac6c0ed242d1634d8a2c93cbd76c6ed2856a9f19cf6a13";
const randomPublicKey = "03c5282b639d0e8f94cfac7777242d1634d78a2c93cbd76c6ed2856a9f19cf6a13";
stateStore.getLastHeight = jest
.fn()
.mockReturnValueOnce(claimedState.height)
.mockReturnValueOnce(claimedState.height);
stateStore.getLastBlocks = jest
.fn()
.mockReturnValueOnce([{ data: { height: claimedState.height }, getHeader: () => ourHeader }]);
databaseInterceptor.getBlocksByHeight = jest
.fn()
.mockReturnValueOnce([{ id: ourHeader.id }])
.mockImplementation((blockHeights) =>
blockHeights.map((height: number) => ({
height,
id: height.toString().padStart(2, "0").repeat(20), // just using height to mock the id
})),
);
peerCommunicator.hasCommonBlocks = jest
.fn()
.mockImplementation((_, ids) => ({ id: ids[0], height: parseInt(ids[0].slice(0, 2)) }));
trigger.call = jest.fn().mockReturnValue([
{
getPublicKey: () => {
return generatorPublicKey;
},
},
]); // getActiveDelegates mock
peerCommunicator.getPeerBlocks = jest.fn().mockImplementation((_, options) => {
const blocks = [];
for (let i = options.fromBlockHeight + 1; i <= options.fromBlockHeight + options.blockLimit; i++) {
blocks.push({ id: i.toString(), height: i, generatorPublicKey: randomPublicKey }); // wrong generator public key
}
return blocks;
});
jest.spyOn(Blocks.BlockFactory, "fromData").mockImplementation(blockFromDataMock);
const result = await peerVerifier.checkState(claimedState, Date.now() + 2000);
expect(result).toBeUndefined();
});
it("should throw when deadline is passed", async () => {
const generatorPublicKey = "03c5282b639d0e8f94cfac6c0ed242d1634d8a2c93cbd76c6ed2856a9f19cf6a13";
stateStore.getLastHeight = jest
.fn()
.mockReturnValueOnce(claimedState.height)
.mockReturnValueOnce(claimedState.height);
stateStore.getLastBlocks = jest
.fn()
.mockReturnValueOnce([{ data: { height: claimedState.height }, getHeader: () => ourHeader }]);
databaseInterceptor.getBlocksByHeight = jest
.fn()
.mockReturnValueOnce([{ id: ourHeader.id }])
.mockImplementation((blockHeights) =>
blockHeights.map((height: number) => ({
height,
id: height.toString().padStart(2, "0").repeat(20), // just using height to mock the id
})),
);
peerCommunicator.hasCommonBlocks = jest
.fn()
.mockImplementation((_, ids) => ({ id: ids[0], height: parseInt(ids[0].slice(0, 2)) }));
trigger.call = jest.fn().mockReturnValue([{ publicKey: generatorPublicKey }]); // getActiveDelegates mock
peerCommunicator.getPeerBlocks = jest.fn().mockImplementation((_, options) => {
const blocks = [];
for (let i = options.fromBlockHeight + 1; i <= options.fromBlockHeight + options.blockLimit; i++) {
blocks.push({ id: i.toString(), height: i, generatorPublicKey });
}
return blocks;
});
const spyFromData = jest.spyOn(Blocks.BlockFactory, "fromData").mockImplementation(blockFromDataMock);
await expect(peerVerifier.checkState(claimedState, Date.now() - 1)).rejects.toEqual(
new Error("timeout elapsed before successful completion of the verification"),
);
spyFromData.mockRestore();
peerCommunicator.getPeerBlocks = jest.fn();
databaseInterceptor.getBlocksByHeight = jest.fn();
peerCommunicator.hasCommonBlocks = jest.fn();
});
});
describe("when Case5. Peer height < our height and peer's latest block is part of our chain", () => {
const claimedState: Contracts.P2P.PeerState = {
height: 15,
forgingAllowed: false,
currentSlot: 15,
header: {
height: 15,
id: "13965046748333390338",
},
};
const ourHeight = claimedState.height + 2;
const ourHeader = {
height: ourHeight,
id: "6857401089891373446",
};
it("should return PeerVerificationResult not forked", async () => {
stateStore.getLastHeight = jest.fn().mockReturnValueOnce(ourHeight);
stateStore.getLastBlocks = jest.fn().mockReturnValueOnce([
{ data: { height: ourHeight }, getHeader: () => ourHeader },
{ data: { height: claimedState.height }, getHeader: () => claimedState.header },
]);
databaseInterceptor.getBlocksByHeight = jest.fn().mockReturnValueOnce([{ id: claimedState.header.id }]);
const result = await peerVerifier.checkState(claimedState, Date.now() + 2000);
expect(result).toBeInstanceOf(PeerVerificationResult);
expect(result.forked).toBeFalse();
});
});
describe("when Case6. Peer height < our height and peer's latest block is not part of our chain", () => {
const generatorPublicKey = "03c5282b639d0e8f94cfac6c0ed242d1634d8a2c93cbd76c6ed2856a9f19cf6a13";
const claimedState: Contracts.P2P.PeerState = {
height: 12,
forgingAllowed: false,
currentSlot: 12,
header: {
height: 12,
id: "13965046748333390338",
generatorPublicKey,
},
};
const ourHeader = {
height: 15,
id: "11165046748333390338",
};
it("should return PeerVerificationResult forked", async () => {
stateStore.getLastHeight = jest
.fn()
.mockReturnValueOnce(ourHeader.height)
.mockReturnValueOnce(ourHeader.height);
stateStore.getLastBlocks = jest
.fn()
.mockReturnValueOnce([{ data: { height: ourHeader.height }, getHeader: () => ourHeader }]);
databaseInterceptor.getBlocksByHeight = jest
.fn()
.mockReturnValueOnce([{ id: ourHeader.id }])
.mockImplementation((blockHeights) =>
blockHeights.map((height: number) => ({
height,
id: height.toString().padStart(2, "0").repeat(20), // just using height to mock the id
})),
);
peerCommunicator.hasCommonBlocks = jest
.fn()
.mockImplementation((_, ids) => ({ id: ids[0], height: parseInt(ids[0].slice(0, 2)) }));
trigger.call = jest.fn().mockReturnValue([
{
getPublicKey: () => {
return generatorPublicKey;
},
},
]); // getActiveDelegates mock
peerCommunicator.getPeerBlocks = jest.fn().mockImplementation((_, options) => {
const blocks = [];
for (let i = options.fromBlockHeight + 1; i <= options.fromBlockHeight + options.blockLimit; i++) {
blocks.push({ id: i.toString(), height: i, generatorPublicKey });
}
return blocks;
});
const spyFromData = jest.spyOn(Blocks.BlockFactory, "fromData").mockImplementation(blockFromDataMock);
const result = await peerVerifier.checkState(claimedState, Date.now() + 2000);
expect(result).toBeInstanceOf(PeerVerificationResult);
expect(result.forked).toBeTrue();
spyFromData.mockRestore();
peerCommunicator.getPeerBlocks = jest.fn();
databaseInterceptor.getBlocksByHeight = jest.fn();
peerCommunicator.hasCommonBlocks = jest.fn();
});
});
});
}); | the_stack |
import { ensureDir, readFile, writeFile } from '@ionic/utils-fs';
import Debug from 'debug';
import et from 'elementtree';
import pathlib from 'path';
import util from 'util';
import { Platform } from '../platform';
import type {
ResolvedColorSource,
ResolvedSource,
ResourceConfig,
ResourceValue,
UnknownResource,
} from '../resources';
import { ResourceKey, ResourceType, SourceType } from '../resources';
import { combinationJoiner } from '../utils/array';
import { identity } from '../utils/fn';
const debug = Debug('cordova-res:cordova:config');
export function getConfigPath(directory: string): string {
return pathlib.resolve(directory, 'config.xml');
}
export async function run(
resourcesDirectory: string,
doc: et.ElementTree,
sources: readonly ResolvedSource[],
resources: readonly ResourceConfig[],
errstream: NodeJS.WritableStream | null,
): Promise<void> {
const colors = sources.filter(
(source): source is ResolvedColorSource => source.type === SourceType.COLOR,
);
if (colors.length > 0) {
debug('Color sources found--generating colors document.');
const androidPlatformElement = resolvePlatformElement(
doc.getroot(),
Platform.ANDROID,
);
const colorsPath = pathlib.join(resourcesDirectory, 'values', 'colors.xml');
await runColorsConfig(colorsPath, colors);
const resourceFileElement = resolveElement(
androidPlatformElement,
'resource-file',
[`resource-file[@src='${colorsPath}']`],
);
resourceFileElement.set('src', colorsPath);
resourceFileElement.set('target', '/app/src/main/res/values/colors.xml');
}
runConfig(doc, resources, errstream);
}
export async function resolveColorsDocument(
colorsPath: string,
): Promise<et.ElementTree> {
try {
return await read(colorsPath);
} catch (e) {
if (e.code !== 'ENOENT') {
throw e;
}
const element = et.Element('resources');
return new et.ElementTree(element);
}
}
export async function runColorsConfig(
colorsPath: string,
colors: readonly ResolvedColorSource[],
): Promise<void> {
await ensureDir(pathlib.dirname(colorsPath));
const colorsDocument = await resolveColorsDocument(colorsPath);
const root = colorsDocument.getroot();
for (const color of colors) {
let colorElement = root.find(`color[@name='${color.name}']`);
if (!colorElement) {
debug('Creating node for %o', color.name);
colorElement = et.SubElement(root, 'color');
}
colorElement.set('name', color.name);
colorElement.text = color.color;
}
await write(colorsPath, colorsDocument);
}
export function runConfig(
doc: et.ElementTree,
resources: readonly ResourceConfig[],
errstream: NodeJS.WritableStream | null,
): void {
const root = doc.getroot();
const orientationPreference = getPreference(root, 'Orientation');
debug('Orientation preference: %O', orientationPreference);
const orientation = orientationPreference || 'default';
if (orientation !== 'default') {
errstream?.write(
util.format(
`WARN:\tOrientation preference set to '%s'. Only configuring %s resources.`,
orientation,
orientation,
) + '\n',
);
}
const platforms = groupImages(resources);
for (const [platform, platformResources] of platforms) {
const rules = getPlatformConfigXmlRules(platform);
const platformElement = resolvePlatformElement(root, platform);
const filteredResources = platformResources
.sort(rules.sort)
.filter(
(img: Partial<UnknownResource>) =>
orientation === 'default' ||
typeof img.orientation === 'undefined' ||
img.orientation === orientation,
);
for (const resource of filteredResources) {
runResource(platformElement, resource);
}
}
}
export function runResource(
container: et.Element,
resource: ResourceConfig,
): void {
const rules = getResourceConfigXmlRules(resource);
if (!rules || !rules.included(resource)) {
return;
}
const { nodeName, nodeAttributes } = rules;
const xpaths = getResourceXPaths(rules, resource);
const imgElement = resolveElement(container, nodeName, xpaths);
for (const attr of nodeAttributes) {
const v = resolveAttribute(resource, attr);
if (v) {
imgElement.set(attr, v);
}
}
}
export function resolvePlatformElement(
container: et.Element,
platform: Platform,
): et.Element {
const platformElement = resolveElement(container, 'platform', [
`platform[@name='${platform}']`,
]);
platformElement.set('name', platform);
return platformElement;
}
/**
* Query a container for a subelement and create it if it doesn't exist
*/
export function resolveElement(
container: et.Element,
nodeName: string,
xpaths: string[],
): et.Element {
for (const xpath of xpaths) {
const imgElement = container.find(xpath);
if (imgElement) {
return imgElement;
}
}
debug('Creating %O node (not found by xpaths: %O)', nodeName, xpaths);
return et.SubElement(container, nodeName);
}
export function conformPath(value: string | number): string {
return value.toString().replace(/\\/g, '/');
}
export function resolveAttributeValue(
attr: ResourceKey,
value: string | number,
): string {
const type = getAttributeType(attr);
return type === ResourceKeyType.PATH ? conformPath(value) : value.toString();
}
export function resolveAttribute(
resource: Partial<UnknownResource>,
attr: ResourceKey,
): string | undefined {
const v = resource[attr];
if (v) {
return resolveAttributeValue(attr, v);
}
}
export function groupImages(
images: readonly ResourceConfig[],
): Map<Platform, ResourceConfig[]> {
const platforms = new Map<Platform, ResourceConfig[]>();
for (const image of images) {
let platformImages = platforms.get(image.platform);
if (!platformImages) {
platformImages = [];
}
platformImages.push(image);
platforms.set(image.platform, platformImages);
}
return platforms;
}
export async function read(path: string): Promise<et.ElementTree> {
const contents = await readFile(path, 'utf8');
const doc = et.parse(contents);
return doc;
}
export async function write(path: string, doc: et.ElementTree): Promise<void> {
// Cordova hard codes an indentation of 4 spaces, so we'll follow.
const contents = doc.write({ indent: 4 });
await writeFile(path, contents, 'utf8');
}
export function getPlatforms(container: et.Element): string[] {
const platformElements = container.findall('platform');
const platforms = platformElements.map(el => el.get('name'));
return platforms.filter((p): p is string => typeof p === 'string');
}
export function getPreference(
container: et.Element,
name: string,
): string | undefined {
const preferenceElement = container.find(`preference[@name='${name}']`);
if (!preferenceElement) {
return undefined;
}
const value = preferenceElement.get('value');
if (!value) {
return undefined;
}
return value;
}
export const enum ResourceKeyType {
PATH = 'path',
}
export function getAttributeType(
attr: ResourceKey,
): ResourceKeyType | undefined {
if (
[ResourceKey.FOREGROUND, ResourceKey.BACKGROUND, ResourceKey.SRC].includes(
attr,
)
) {
return ResourceKeyType.PATH;
}
}
export function getResourceXPaths(
rules: ResourceConfigXmlRules,
resource: Partial<UnknownResource>,
): string[] {
const { nodeName } = rules;
const indexes = combinationJoiner(
rules.indexAttributes
.map(indexAttribute =>
getIndexAttributeXPathParts(
rules,
indexAttribute,
resource[indexAttribute.key],
),
)
.filter(index => index.length > 0),
parts => parts.join(''),
);
return indexes.map(index => `${nodeName}${index}`);
}
export function getIndexAttributeXPathParts(
rules: ResourceConfigXmlRules,
indexAttribute: ResourceConfigXmlIndex,
value: UnknownResource[ResourceKey] | undefined,
): string[] {
const { nodeAttributes } = rules;
const { key, values } = indexAttribute;
// If we aren't aware of this key's existence in the XML, we don't want to
// generate any XPaths for it.
if (!nodeAttributes.includes(key)) {
return [];
}
if (values) {
if (typeof value === 'undefined') {
return [];
}
const result = values(value);
if (Array.isArray(result)) {
return result.map(v => `[@${key}='${v}']`);
} else {
return [`[@${key}='${result}']`];
}
}
return [`[@${key}]`];
}
export function pathValues(inputValue: ResourceValue): ResourceValue[] {
if (typeof inputValue !== 'string') {
return [];
}
return [inputValue, inputValue.replace(/\//g, '\\')];
}
export interface PlatformConfigXmlRules {
/**
* Sort the resources as per config.xml requirements
*/
readonly sort: (a: UnknownResource, b: UnknownResource) => -1 | 0 | 1;
}
export const RESOURCE_WEIGHTS: { [R in ResourceType]: number } = {
[ResourceType.ADAPTIVE_ICON]: 1,
[ResourceType.ICON]: 2,
[ResourceType.SPLASH]: 3,
};
export const sortResources = (
a: UnknownResource,
b: UnknownResource,
): -1 | 0 | 1 => {
if (a.type === b.type) {
return 0;
}
return RESOURCE_WEIGHTS[a.type] > RESOURCE_WEIGHTS[b.type] ? 1 : -1;
};
export function getPlatformConfigXmlRules(
platform: Platform,
): PlatformConfigXmlRules {
switch (platform) {
case Platform.ANDROID:
return { sort: sortResources };
case Platform.IOS:
return { sort: sortResources };
case Platform.WINDOWS:
return { sort: sortResources };
}
}
export interface ResourceConfigXmlIndex {
readonly key: ResourceKey;
readonly values?: (
inputValue: ResourceValue,
) => ResourceValue | ResourceValue[];
}
export interface ResourceConfigXmlRules {
/**
* XML node name of this resource (e.g. 'icon', 'splash')
*/
readonly nodeName: string;
/**
* An array of resource keys to copy into the XML node as attributes
*/
readonly nodeAttributes: readonly ResourceKey[];
/**
* An array of resource keys to use as an index when generating the XPath(s)
*/
readonly indexAttributes: ResourceConfigXmlIndex[];
/**
* Get whether a resource should be included in the XML or not
*/
readonly included: (resource: Partial<UnknownResource>) => boolean;
}
export function getResourceConfigXmlRules(
resource: ResourceConfig,
): ResourceConfigXmlRules | undefined {
switch (resource.platform) {
case Platform.ANDROID:
switch (resource.type) {
case ResourceType.ADAPTIVE_ICON:
return {
nodeName: 'icon',
nodeAttributes: [
ResourceKey.FOREGROUND,
ResourceKey.DENSITY,
ResourceKey.BACKGROUND,
],
indexAttributes: [
{ key: ResourceKey.FOREGROUND },
{ key: ResourceKey.BACKGROUND },
{ key: ResourceKey.DENSITY, values: identity },
],
included: () => true,
};
case ResourceType.ICON:
return {
nodeName: 'icon',
nodeAttributes: [ResourceKey.SRC, ResourceKey.DENSITY],
indexAttributes: [
{ key: ResourceKey.SRC },
{ key: ResourceKey.DENSITY, values: identity },
],
included: () => true,
};
case ResourceType.SPLASH:
return {
nodeName: 'splash',
nodeAttributes: [ResourceKey.SRC, ResourceKey.DENSITY],
indexAttributes: [{ key: ResourceKey.DENSITY, values: identity }],
included: () => true,
};
}
case Platform.IOS:
switch (resource.type) {
case ResourceType.ICON:
return {
nodeName: 'icon',
nodeAttributes: [
ResourceKey.SRC,
ResourceKey.WIDTH,
ResourceKey.HEIGHT,
],
indexAttributes: [{ key: ResourceKey.SRC, values: pathValues }],
included: () => true,
};
case ResourceType.SPLASH:
return {
nodeName: 'splash',
nodeAttributes: [
ResourceKey.SRC,
ResourceKey.WIDTH,
ResourceKey.HEIGHT,
],
indexAttributes: [{ key: ResourceKey.SRC, values: pathValues }],
included: () => true,
};
}
case Platform.WINDOWS:
switch (resource.type) {
case ResourceType.ICON:
return {
nodeName: 'icon',
nodeAttributes: [ResourceKey.SRC, ResourceKey.TARGET],
indexAttributes: [{ key: ResourceKey.SRC, values: pathValues }],
included: resource => !!resource.target,
};
case ResourceType.SPLASH:
return {
nodeName: 'splash',
nodeAttributes: [ResourceKey.SRC, ResourceKey.TARGET],
indexAttributes: [{ key: ResourceKey.SRC, values: pathValues }],
included: resource => !!resource.target,
};
}
}
} | the_stack |
import * as assert from "assert";
import * as rhea from "../";
describe('sasl plain', function() {
this.slow(200);
var container: rhea.Container, listener: any;
function authenticate(username: string, password: string) {
return username.split("").reverse().join("") === password;
}
beforeEach(function(done: Function) {
container = rhea.create_container();
container.sasl_server_mechanisms.enable_plain(authenticate);
container.on('disconnected', function () {});
listener = container.listen({port:0});
listener.on('listening', function() {
done();
});
});
afterEach(function() {
listener.close();
});
it('successfully authenticates', function(done: Function) {
container.connect({username:'bob',password:'bob',port:listener.address().port}).on('connection_open', function(context) { context.connection.close(); done(); });
});
it('handles authentication failure', function(done: Function) {
container.connect({username:'whatsit',password:'anyoldrubbish',port:listener.address().port}).on('connection_error', function(context) {
var error = context.connection.get_error();
assert.equal(error.condition, 'amqp:unauthorized-access');
done();
});
});
});
describe('sasl plain callback using promise', function() {
this.slow(200);
var container: rhea.Container, listener: any;
var providerFailure : boolean;
function authenticate(username: string, password: string) {
return new Promise((resolve, reject) => {
process.nextTick(() => {
if (providerFailure) {
reject("provider failure");
} else {
resolve(username.split("").reverse().join("") === password);
}
})
});
}
beforeEach(function(done: Function) {
container = rhea.create_container();
container.sasl_server_mechanisms.enable_plain(authenticate);
container.on('disconnected', function () {});
listener = container.listen({port:0});
listener.on('listening', function() {
done();
});
});
afterEach(function() {
listener.close();
});
it('successfully authenticates', function(done: Function) {
container.connect({username:'bob',password:'bob',port:listener.address().port}).on('connection_open', function(context) { context.connection.close(); done(); });
});
it('handles authentication failure', function(done: Function) {
container.connect({username:'whatsit',password:'anyoldrubbish',port:listener.address().port}).on('connection_error', function(context) {
var error = context.connection.get_error();
assert.equal(error.condition, 'amqp:unauthorized-access');
done();
});
});
it('handles authentication provider failure', function(done: Function) {
providerFailure = true;
// Swallow the expected server side report of the provider failure
container.on('connection_error', function () {});
let connection = container.connect({username:'whatsit',password:'anyoldrubbish',port:listener.address().port});
connection.on('connection_error', function(context) {
var error = context.connection.get_error();
assert.equal(error.condition, 'amqp:internal-error');
done();
});
});
});
describe('sasl init hostname', function() {
this.slow(200);
var container: rhea.Container, listener: any, hostname: string | undefined;
function authenticate(username: string, password: string, __hostname: string): boolean {
hostname = __hostname;
return true;
}
beforeEach(function(done: Function) {
hostname = undefined;
container = rhea.create_container();
container.sasl_server_mechanisms.enable_plain(authenticate);
container.on('disconnected', function () {});
listener = container.listen({port:0});
listener.on('listening', function() {
done();
});
});
afterEach(function() {
listener.close();
});
it('uses host by default', function(done: Function) {
container.connect({username:'a',password:'a', host:'localhost', port:listener.address().port}).on('connection_open', function(context: rhea.EventContext) {
context.connection.close();
assert.equal(hostname, 'localhost');
done();
});
});
it('prefers servername to host', function(done: Function) {
container.connect({username:'a',password:'b', servername:'somethingelse', host:'localhost', port:listener.address().port}).on('connection_open', function(context: rhea.EventContext) {
context.connection.close();
assert.equal(hostname, 'somethingelse');
done();
});
});
it('prefers sasl_init_hostname to servername or host', function(done: Function) {
container.connect({username:'a',password:'b', sasl_init_hostname:'yetanother', servername:'somethingelse', host:'localhost', port:listener.address().port}).on('connection_open', function(context: rhea.EventContext) {
context.connection.close();
assert.equal(hostname, 'yetanother');
done();
});
});
});
describe('sasl anonymous', function() {
this.slow(200);
var container: rhea.Container, listener: any;
beforeEach(function(done: Function) {
container = rhea.create_container();
container.sasl_server_mechanisms.enable_anonymous();
container.on('disconnected', function () {});
listener = container.listen({port:0});
listener.on('listening', function() {
done();
});
});
afterEach(function() {
listener.close();
});
it('successfully authenticates', function(done: Function) {
container.connect({username:'bob',port:listener.address().port}).on('connection_open', function(context) { context.connection.close(); done(); });
});
it('handles authentication failure', function(done: Function) {
container.connect({username:'whatsit',password:'anyoldrubbish',port:listener.address().port}).on('connection_error', function(context: rhea.EventContext) {
var error = context.connection.get_error();
assert.equal((error as rhea.AmqpError).condition, 'amqp:unauthorized-access');
assert.equal((error as rhea.AmqpError).description, 'No suitable mechanism; server supports ANONYMOUS');
done();
});
});
});
describe('user-provided sasl mechanism', function () {
var container: rhea.Container, listener: any;
var testClientSaslMechanism = {
start: function (callback: Function) { callback(null, 'initialResponse'); },
step: function (challenge: any, callback: Function) { callback (null, 'challengeResponse'); }
};
beforeEach(function(done: Function) {
container = rhea.create_container();
container.on('disconnected', function () {});
listener = container.listen({port:0});
listener.on('listening', function() {
done();
});
});
afterEach(function() {
listener.close();
});
it('calls start and step on the custom sasl mechanism', function (done: Function) {
var startCalled = false;
var stepCalled = false;
var connectOptions = {
sasl_mechanisms: {
'CUSTOM': testClientSaslMechanism
},
port: listener.address().port
}
container.sasl_server_mechanisms['CUSTOM'] = function () {
return {
outcome: undefined,
start: function () {
startCalled = true;
return 'initialResponse';
},
step: function () {
stepCalled = true;
this.outcome = <any>true;
return;
}
};
};
container.connect(connectOptions).on('connection_open', function(context) {
context.connection.close();
assert(startCalled);
assert(stepCalled);
done();
});
});
it('handles authentication failure if the custom server sasl mechanism fails', function (done: Function) {
var startCalled = false;
var stepCalled = false;
var connectOptions = {
sasl_mechanisms: {
'CUSTOM': testClientSaslMechanism
},
port: listener.address().port
}
container.sasl_server_mechanisms['CUSTOM'] = function () {
return {
outcome: undefined,
start: function () {
startCalled = true;
return 'initialResponse';
},
step: function () {
stepCalled = true;
this.outcome = <any>false;
return;
}
};
};
container.connect(connectOptions).on('connection_error', function(context) {
var error = context.connection.get_error();
assert.equal(error.condition, 'amqp:unauthorized-access');
assert(startCalled);
assert(stepCalled);
done();
});
});
it('calls start and step on the custom sasl mechanism using promises', function (done: Function) {
var startCalled = false;
var stepCalled = false;
var connectOptions = {
sasl_mechanisms: {
'CUSTOM': testClientSaslMechanism
},
port: listener.address().port
}
container.sasl_server_mechanisms['CUSTOM'] = function () {
return {
outcome: undefined,
start: function () {
return new Promise(resolve => {
process.nextTick(() => {
startCalled = true;
resolve('initialResponse');
});
});
},
step: function () {
return new Promise(resolve => {
process.nextTick(() => {
stepCalled = true;
this.outcome = <any>true;
resolve();
});
});
}
};
};
container.connect(connectOptions).on('connection_open', function(context) {
context.connection.close();
assert(startCalled);
assert(stepCalled);
done();
});
});
}); | the_stack |
import {Action, AnyAction, combineReducers, Reducer} from 'redux';
import {randomBytes} from 'crypto';
import {DriveUser} from '../util/googleDriveUtils';
import {DeviceLayoutReducerType} from './deviceLayoutReducer';
import {AppVersion} from '../util/appVersion';
import {NetworkedAction} from '../util/types';
import {TabletopReducerActionTypes, UpdateTabletopAction} from './tabletopReducer';
import {TabletopPathPoint} from '../presentation/tabletopPathComponent';
import {ObjectVector3} from '../util/scenarioUtils';
// =========================== Action types and generators
export enum ConnectedUserActionTypes {
ADD_CONNECTED_USER = 'add-connected-user',
UPDATE_CONNECTED_USER = 'update-connected-user',
REMOVE_CONNECTED_USER = 'remove-connected-user',
REMOVE_ALL_CONNECTED_USERS = 'remove-all-connected-users',
CHALLENGE_USER = 'challenge-user',
CHALLENGE_RESPONSE = 'challenge-response',
VERIFY_CONNECTION_ACTION = 'verify-connection-action',
VERIFY_GM_ACTION = 'verify-gm-action',
UPDATE_SIGNAL_ERROR = 'update-signal-error',
SET_USER_ALLOWED = 'set-user-allowed',
UPDATE_USER_RULER = 'update-user-ruler'
}
export interface AddConnectedUserActionType extends Action {
type: ConnectedUserActionTypes.ADD_CONNECTED_USER;
peerId: string;
user: DriveUser;
version: AppVersion;
deviceWidth: number;
deviceHeight: number;
deviceLayout: DeviceLayoutReducerType;
}
export function addConnectedUserAction(peerId: string, user: DriveUser, version: AppVersion, deviceWidth: number, deviceHeight: number, deviceLayout: DeviceLayoutReducerType): AddConnectedUserActionType {
return {type: ConnectedUserActionTypes.ADD_CONNECTED_USER, peerId, user, version, deviceWidth, deviceHeight, deviceLayout};
}
interface UpdateConnectedUserDeviceActionType extends Action {
type: ConnectedUserActionTypes.UPDATE_CONNECTED_USER;
peerId: string;
peerKey: string;
deviceWidth: number;
deviceHeight: number;
}
export function updateConnectedUserDeviceAction(peerId: string, deviceWidth: number, deviceHeight: number): UpdateConnectedUserDeviceActionType {
return {type: ConnectedUserActionTypes.UPDATE_CONNECTED_USER, peerId, peerKey: 'device' + peerId, deviceWidth, deviceHeight};
}
export interface RemoveConnectedUserActionType extends Action {
type: ConnectedUserActionTypes.REMOVE_CONNECTED_USER;
peerId: string;
peerKey: string;
}
export function removeConnectedUserAction(peerId: string): RemoveConnectedUserActionType {
return {type: ConnectedUserActionTypes.REMOVE_CONNECTED_USER, peerId, peerKey: 'removeUser' + peerId};
}
interface RemoveAllConnectedUsersActionType extends Action {
type: ConnectedUserActionTypes.REMOVE_ALL_CONNECTED_USERS;
}
export function removeAllConnectedUsersAction(): RemoveAllConnectedUsersActionType {
return {type: ConnectedUserActionTypes.REMOVE_ALL_CONNECTED_USERS};
}
interface ChallengeUserActionType extends NetworkedAction {
type: ConnectedUserActionTypes.CHALLENGE_USER;
peerId: string;
challenge: string;
private: true;
}
export function challengeUserAction(peerId: string): ChallengeUserActionType {
return {type: ConnectedUserActionTypes.CHALLENGE_USER, peerId, challenge: randomBytes(48).toString('hex'), private: true};
}
interface ChallengeResponseActionType extends NetworkedAction {
type: ConnectedUserActionTypes.CHALLENGE_RESPONSE;
peerId: string;
response: string;
private: true;
}
export function challengeResponseAction(peerId: string, response: string): ChallengeResponseActionType {
return {type: ConnectedUserActionTypes.CHALLENGE_RESPONSE, peerId, response, private: true};
}
interface VerifyConnectionActionType extends NetworkedAction {
type: ConnectedUserActionTypes.VERIFY_CONNECTION_ACTION;
peerId: string;
verifiedConnection: boolean;
private: true;
}
export function verifyConnectionAction(peerId: string, verifiedConnection: boolean): VerifyConnectionActionType {
return {type: ConnectedUserActionTypes.VERIFY_CONNECTION_ACTION, peerId, verifiedConnection, private: true};
}
interface VerifyGMActionType extends NetworkedAction {
type: ConnectedUserActionTypes.VERIFY_GM_ACTION;
peerId: string;
verifiedGM: boolean;
private: true;
}
export function verifyGMAction(peerId: string, verifiedGM: boolean): VerifyGMActionType {
return {type: ConnectedUserActionTypes.VERIFY_GM_ACTION, peerId, verifiedGM, private: true};
}
interface UpdateSignalErrorActionType extends Action {
type: ConnectedUserActionTypes.UPDATE_SIGNAL_ERROR;
error: boolean;
}
export function updateSignalErrorAction(error: boolean): UpdateSignalErrorActionType {
return {type: ConnectedUserActionTypes.UPDATE_SIGNAL_ERROR, error};
}
interface SetUserAllowedActionType extends NetworkedAction {
type: ConnectedUserActionTypes.SET_USER_ALLOWED;
peerId: string;
allowed: boolean;
private: true;
}
export function setUserAllowedAction(peerId: string, allowed: boolean): SetUserAllowedActionType {
return {type: ConnectedUserActionTypes.SET_USER_ALLOWED, peerId, allowed, private: true};
}
interface UpdateUserRulerActionType extends NetworkedAction {
type: ConnectedUserActionTypes.UPDATE_USER_RULER;
peerId: string;
ruler?: ConnectedUserRuler;
peerKey: string;
}
export function updateUserRulerAction(peerId: string, ruler?: ConnectedUserRuler): UpdateUserRulerActionType {
return {type: ConnectedUserActionTypes.UPDATE_USER_RULER, peerId, ruler, peerKey: 'ruler_' + peerId};
}
type LocalOnlyAction = ChallengeUserActionType | ChallengeResponseActionType | VerifyConnectionActionType | VerifyGMActionType | SetUserAllowedActionType;
export type ConnectedUserReducerAction = AddConnectedUserActionType | UpdateConnectedUserDeviceActionType |
RemoveConnectedUserActionType | RemoveAllConnectedUsersActionType | LocalOnlyAction | UpdateSignalErrorActionType |
UpdateUserRulerActionType;
// =========================== Reducers
interface ConnectedUserRuler {
start: TabletopPathPoint;
end: ObjectVector3;
distance: string;
}
interface SingleConnectedUser {
user: DriveUser;
version?: AppVersion;
challenge: string;
verifiedConnection: null | boolean;
verifiedGM: null | boolean;
checkedForTabletop: boolean;
deviceWidth: number;
deviceHeight: number;
ruler?: ConnectedUserRuler;
}
export type ConnectedUserUsersType = {[key: string]: SingleConnectedUser};
export interface ConnectedUserReducerType {
signalError: boolean;
users: ConnectedUserUsersType;
}
function localOnlyUpdate(state: {[key: string]: SingleConnectedUser}, action: LocalOnlyAction, update: Partial<SingleConnectedUser>) {
// Only allow actions which originate locally to update the state.
if (!action.fromPeerId && state[action.peerId]) {
return {...state, [action.peerId]: {
...state[action.peerId],
...update
}};
} else {
return state;
}
}
const connectedUserUsersReducer: Reducer<{[key: string]: SingleConnectedUser}> = (state = {}, action: ConnectedUserReducerAction | UpdateTabletopAction) => {
// We need to be picky about what fields we allow actions to update, for security.
switch (action.type) {
case ConnectedUserActionTypes.ADD_CONNECTED_USER:
return {...state, [action.peerId]: {
user: action.user,
version: action.version,
challenge: '',
verifiedConnection: action.user.emailAddress && !action['fromPeerId'] ? true : null,
verifiedGM: null,
checkedForTabletop: false,
deviceWidth: action.deviceWidth,
deviceHeight: action.deviceHeight,
}
};
case ConnectedUserActionTypes.UPDATE_CONNECTED_USER:
return !state[action.peerId] ? state : {...state, [action.peerId]: {
...state[action.peerId],
deviceWidth: action.deviceWidth,
deviceHeight: action.deviceHeight
}
};
case ConnectedUserActionTypes.REMOVE_CONNECTED_USER:
const {[action.peerId]: _, ...result} = state;
return result;
case ConnectedUserActionTypes.REMOVE_ALL_CONNECTED_USERS:
return {};
case ConnectedUserActionTypes.CHALLENGE_USER:
return localOnlyUpdate(state, action, {challenge: action.challenge});
case ConnectedUserActionTypes.VERIFY_CONNECTION_ACTION:
return localOnlyUpdate(state, action, {verifiedConnection: action.verifiedConnection});
case ConnectedUserActionTypes.VERIFY_GM_ACTION:
return localOnlyUpdate(state, action, {verifiedGM: action.verifiedGM});
case ConnectedUserActionTypes.SET_USER_ALLOWED:
return action.allowed
? localOnlyUpdate(state, action, {checkedForTabletop: true, verifiedConnection: true})
: localOnlyUpdate(state, action, {checkedForTabletop: true, verifiedConnection: false});
case TabletopReducerActionTypes.UPDATE_TABLETOP_ACTION:
// Clear checkedForTabletop for everyone
return Object.keys(state).reduce((nextState, peerId) => {
nextState[peerId] = {...state[peerId], checkedForTabletop: false};
return nextState;
}, {});
case ConnectedUserActionTypes.UPDATE_USER_RULER:
return !state[action.peerId] ? state : {...state, [action.peerId]: {
...state[action.peerId],
ruler: action.ruler
}
};
default:
return state;
}
};
const signalErrorReducer: Reducer<boolean> = (state: boolean = false, action: UpdateSignalErrorActionType | AnyAction) => {
switch (action.type) {
case ConnectedUserActionTypes.UPDATE_SIGNAL_ERROR:
return action.error;
default:
return state;
}
};
const connectedUserReducer = combineReducers<ConnectedUserReducerType>({
users: connectedUserUsersReducer,
signalError: signalErrorReducer
});
export default connectedUserReducer;
// =========================== Utility
export function isAllowedUnverifiedAction(action: AnyAction) {
switch (action.type) {
case ConnectedUserActionTypes.ADD_CONNECTED_USER:
case ConnectedUserActionTypes.CHALLENGE_USER:
return true;
default:
return false;
}
} | the_stack |
import BitSource from '../../common/BitSource';
import CharacterSetECI from '../../common/CharacterSetECI';
import DecoderResult from '../../common/DecoderResult';
import StringUtils from '../../common/StringUtils';
import DecodeHintType from '../../DecodeHintType';
import FormatException from '../../FormatException';
import StringBuilder from '../../util/StringBuilder';
import StringEncoding from '../../util/StringEncoding';
import ErrorCorrectionLevel from './ErrorCorrectionLevel';
import Mode from './Mode';
import Version from './Version';
/*import java.io.UnsupportedEncodingException;*/
/*import java.util.ArrayList;*/
/*import java.util.Collection;*/
/*import java.util.List;*/
/*import java.util.Map;*/
/**
* <p>QR Codes can encode text as bits in one of several modes, and can use multiple modes
* in one QR Code. This class decodes the bits back into text.</p>
*
* <p>See ISO 18004:2006, 6.4.3 - 6.4.7</p>
*
* @author Sean Owen
*/
export default class DecodedBitStreamParser {
/**
* See ISO 18004:2006, 6.4.4 Table 5
*/
private static ALPHANUMERIC_CHARS =
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:';
private static GB2312_SUBSET = 1;
public static decode(bytes: Uint8Array,
version: Version,
ecLevel: ErrorCorrectionLevel,
hints: Map<DecodeHintType, any>): DecoderResult /*throws FormatException*/ {
const bits = new BitSource(bytes);
let result = new StringBuilder();
const byteSegments = new Array<Uint8Array>(); // 1
// TYPESCRIPTPORT: I do not use constructor with size 1 as in original Java means capacity and the array length is checked below
let symbolSequence = -1;
let parityData = -1;
try {
let currentCharacterSetECI: CharacterSetECI = null;
let fc1InEffect: boolean = false;
let mode: Mode;
do {
// While still another segment to read...
if (bits.available() < 4) {
// OK, assume we're done. Really, a TERMINATOR mode should have been recorded here
mode = Mode.TERMINATOR;
} else {
const modeBits = bits.readBits(4);
mode = Mode.forBits(modeBits); // mode is encoded by 4 bits
}
switch (mode) {
case Mode.TERMINATOR:
break;
case Mode.FNC1_FIRST_POSITION:
case Mode.FNC1_SECOND_POSITION:
// We do little with FNC1 except alter the parsed result a bit according to the spec
fc1InEffect = true;
break;
case Mode.STRUCTURED_APPEND:
if (bits.available() < 16) {
throw new FormatException();
}
// sequence number and parity is added later to the result metadata
// Read next 8 bits (symbol sequence #) and 8 bits (data: parity), then continue
symbolSequence = bits.readBits(8);
parityData = bits.readBits(8);
break;
case Mode.ECI:
// Count doesn't apply to ECI
const value = DecodedBitStreamParser.parseECIValue(bits);
currentCharacterSetECI = CharacterSetECI.getCharacterSetECIByValue(value);
if (currentCharacterSetECI === null) {
throw new FormatException();
}
break;
case Mode.HANZI:
// First handle Hanzi mode which does not start with character count
// Chinese mode contains a sub set indicator right after mode indicator
const subset = bits.readBits(4);
const countHanzi = bits.readBits(mode.getCharacterCountBits(version));
if (subset === DecodedBitStreamParser.GB2312_SUBSET) {
DecodedBitStreamParser.decodeHanziSegment(bits, result, countHanzi);
}
break;
default:
// "Normal" QR code modes:
// How many characters will follow, encoded in this mode?
const count = bits.readBits(mode.getCharacterCountBits(version));
switch (mode) {
case Mode.NUMERIC:
DecodedBitStreamParser.decodeNumericSegment(bits, result, count);
break;
case Mode.ALPHANUMERIC:
DecodedBitStreamParser.decodeAlphanumericSegment(bits, result, count, fc1InEffect);
break;
case Mode.BYTE:
DecodedBitStreamParser.decodeByteSegment(bits, result, count, currentCharacterSetECI, byteSegments, hints);
break;
case Mode.KANJI:
DecodedBitStreamParser.decodeKanjiSegment(bits, result, count);
break;
default:
throw new FormatException();
}
break;
}
} while (mode !== Mode.TERMINATOR);
} catch (iae/*: IllegalArgumentException*/) {
// from readBits() calls
throw new FormatException();
}
return new DecoderResult(bytes,
result.toString(),
byteSegments.length === 0 ? null : byteSegments,
ecLevel === null ? null : ecLevel.toString(),
symbolSequence,
parityData);
}
/**
* See specification GBT 18284-2000
*/
private static decodeHanziSegment(bits: BitSource,
result: StringBuilder,
count: number /*int*/): void /*throws FormatException*/ {
// Don't crash trying to read more bits than we have available.
if (count * 13 > bits.available()) {
throw new FormatException();
}
// Each character will require 2 bytes. Read the characters as 2-byte pairs
// and decode as GB2312 afterwards
const buffer = new Uint8Array(2 * count);
let offset = 0;
while (count > 0) {
// Each 13 bits encodes a 2-byte character
const twoBytes = bits.readBits(13);
let assembledTwoBytes = (((twoBytes / 0x060) << 8) & 0xFFFFFFFF) | (twoBytes % 0x060);
if (assembledTwoBytes < 0x003BF) {
// In the 0xA1A1 to 0xAAFE range
assembledTwoBytes += 0x0A1A1;
} else {
// In the 0xB0A1 to 0xFAFE range
assembledTwoBytes += 0x0A6A1;
}
buffer[offset] = /*(byte) */((assembledTwoBytes >> 8) & 0xFF);
buffer[offset + 1] = /*(byte) */(assembledTwoBytes & 0xFF);
offset += 2;
count--;
}
try {
result.append(StringEncoding.decode(buffer, StringUtils.GB2312));
// TYPESCRIPTPORT: TODO: implement GB2312 decode. StringView from MDN could be a starting point
} catch (ignored/*: UnsupportedEncodingException*/) {
throw new FormatException(ignored);
}
}
private static decodeKanjiSegment(bits: BitSource,
result: StringBuilder,
count: number /*int*/): void /*throws FormatException*/ {
// Don't crash trying to read more bits than we have available.
if (count * 13 > bits.available()) {
throw new FormatException();
}
// Each character will require 2 bytes. Read the characters as 2-byte pairs
// and decode as Shift_JIS afterwards
const buffer = new Uint8Array(2 * count);
let offset = 0;
while (count > 0) {
// Each 13 bits encodes a 2-byte character
const twoBytes = bits.readBits(13);
let assembledTwoBytes = (((twoBytes / 0x0C0) << 8) & 0xFFFFFFFF) | (twoBytes % 0x0C0);
if (assembledTwoBytes < 0x01F00) {
// In the 0x8140 to 0x9FFC range
assembledTwoBytes += 0x08140;
} else {
// In the 0xE040 to 0xEBBF range
assembledTwoBytes += 0x0C140;
}
buffer[offset] = /*(byte) */(assembledTwoBytes >> 8);
buffer[offset + 1] = /*(byte) */assembledTwoBytes;
offset += 2;
count--;
}
// Shift_JIS may not be supported in some environments:
try {
result.append(StringEncoding.decode(buffer, StringUtils.SHIFT_JIS));
// TYPESCRIPTPORT: TODO: implement SHIFT_JIS decode. StringView from MDN could be a starting point
} catch (ignored/*: UnsupportedEncodingException*/) {
throw new FormatException(ignored);
}
}
private static decodeByteSegment(bits: BitSource,
result: StringBuilder,
count: number /*int*/,
currentCharacterSetECI: CharacterSetECI,
byteSegments: Uint8Array[],
hints: Map<DecodeHintType, any>): void /*throws FormatException*/ {
// Don't crash trying to read more bits than we have available.
if (8 * count > bits.available()) {
throw new FormatException();
}
const readBytes = new Uint8Array(count);
for (let i = 0; i < count; i++) {
readBytes[i] = /*(byte) */bits.readBits(8);
}
let encoding: string;
if (currentCharacterSetECI === null) {
// The spec isn't clear on this mode; see
// section 6.4.5: t does not say which encoding to assuming
// upon decoding. I have seen ISO-8859-1 used as well as
// Shift_JIS -- without anything like an ECI designator to
// give a hint.
encoding = StringUtils.guessEncoding(readBytes, hints);
} else {
encoding = currentCharacterSetECI.getName();
}
try {
result.append(StringEncoding.decode(readBytes, encoding));
} catch (ignored/*: UnsupportedEncodingException*/) {
throw new FormatException(ignored);
}
byteSegments.push(readBytes);
}
private static toAlphaNumericChar(value: number /*int*/): string /*throws FormatException*/ {
if (value >= DecodedBitStreamParser.ALPHANUMERIC_CHARS.length) {
throw new FormatException();
}
return DecodedBitStreamParser.ALPHANUMERIC_CHARS[value];
}
private static decodeAlphanumericSegment(bits: BitSource,
result: StringBuilder,
count: number /*int*/,
fc1InEffect: boolean): void /*throws FormatException*/ {
// Read two characters at a time
const start = result.length();
while (count > 1) {
if (bits.available() < 11) {
throw new FormatException();
}
const nextTwoCharsBits = bits.readBits(11);
result.append(DecodedBitStreamParser.toAlphaNumericChar(Math.floor(nextTwoCharsBits / 45)));
result.append(DecodedBitStreamParser.toAlphaNumericChar(nextTwoCharsBits % 45));
count -= 2;
}
if (count === 1) {
// special case: one character left
if (bits.available() < 6) {
throw new FormatException();
}
result.append(DecodedBitStreamParser.toAlphaNumericChar(bits.readBits(6)));
}
// See section 6.4.8.1, 6.4.8.2
if (fc1InEffect) {
// We need to massage the result a bit if in an FNC1 mode:
for (let i = start; i < result.length(); i++) {
if (result.charAt(i) === '%') {
if (i < result.length() - 1 && result.charAt(i + 1) === '%') {
// %% is rendered as %
result.deleteCharAt(i + 1);
} else {
// In alpha mode, % should be converted to FNC1 separator 0x1D
result.setCharAt(i, String.fromCharCode(0x1D));
}
}
}
}
}
private static decodeNumericSegment(bits: BitSource,
result: StringBuilder,
count: number /*int*/): void /*throws FormatException*/ {
// Read three digits at a time
while (count >= 3) {
// Each 10 bits encodes three digits
if (bits.available() < 10) {
throw new FormatException();
}
const threeDigitsBits = bits.readBits(10);
if (threeDigitsBits >= 1000) {
throw new FormatException();
}
result.append(DecodedBitStreamParser.toAlphaNumericChar(Math.floor(threeDigitsBits / 100)));
result.append(DecodedBitStreamParser.toAlphaNumericChar(Math.floor(threeDigitsBits / 10) % 10));
result.append(DecodedBitStreamParser.toAlphaNumericChar(threeDigitsBits % 10));
count -= 3;
}
if (count === 2) {
// Two digits left over to read, encoded in 7 bits
if (bits.available() < 7) {
throw new FormatException();
}
const twoDigitsBits = bits.readBits(7);
if (twoDigitsBits >= 100) {
throw new FormatException();
}
result.append(DecodedBitStreamParser.toAlphaNumericChar(Math.floor(twoDigitsBits / 10)));
result.append(DecodedBitStreamParser.toAlphaNumericChar(twoDigitsBits % 10));
} else if (count === 1) {
// One digit left over to read
if (bits.available() < 4) {
throw new FormatException();
}
const digitBits = bits.readBits(4);
if (digitBits >= 10) {
throw new FormatException();
}
result.append(DecodedBitStreamParser.toAlphaNumericChar(digitBits));
}
}
private static parseECIValue(bits: BitSource): number /*int*/ /*throws FormatException*/ {
const firstByte = bits.readBits(8);
if ((firstByte & 0x80) === 0) {
// just one byte
return firstByte & 0x7F;
}
if ((firstByte & 0xC0) === 0x80) {
// two bytes
const secondByte = bits.readBits(8);
return (((firstByte & 0x3F) << 8) & 0xFFFFFFFF) | secondByte;
}
if ((firstByte & 0xE0) === 0xC0) {
// three bytes
const secondThirdBytes = bits.readBits(16);
return (((firstByte & 0x1F) << 16) & 0xFFFFFFFF) | secondThirdBytes;
}
throw new FormatException();
}
}
// function Uint8ArrayToString(a: Uint8Array): string {
// const CHUNK_SZ = 0x8000;
// const c = new StringBuilder();
// for (let i = 0, length = a.length; i < length; i += CHUNK_SZ) {
// c.append(String.fromCharCode.apply(null, a.subarray(i, i + CHUNK_SZ)));
// }
// return c.toString();
// } | the_stack |
import { ConcreteRequest } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type ArtworkFullQueryVariables = {
artworkID: string;
};
export type ArtworkFullQueryResponse = {
readonly artwork: {
readonly additional_information: string | null;
readonly description: string | null;
readonly provenance: string | null;
readonly exhibition_history: string | null;
readonly literature: string | null;
readonly partner: {
readonly type: string | null;
readonly id: string;
} | null;
readonly artist: {
readonly biography_blurb: {
readonly text: string | null;
} | null;
} | null;
readonly sale: {
readonly id: string;
readonly isBenefit: boolean | null;
readonly isGalleryAuction: boolean | null;
} | null;
readonly category: string | null;
readonly conditionDescription: {
readonly details: string | null;
} | null;
readonly signature: string | null;
readonly signatureInfo: {
readonly details: string | null;
} | null;
readonly certificateOfAuthenticity: {
readonly details: string | null;
} | null;
readonly framed: {
readonly details: string | null;
} | null;
readonly series: string | null;
readonly publisher: string | null;
readonly manufacturer: string | null;
readonly image_rights: string | null;
readonly context: ({
readonly __typename: "Sale";
readonly isAuction: boolean | null;
} | {
/*This will never be '%other', but we need some
value in case none of the concrete values match.*/
readonly __typename: "%other";
}) | null;
readonly contextGrids: ReadonlyArray<{
readonly artworks: {
readonly edges: ReadonlyArray<{
readonly node: {
readonly id: string;
} | null;
} | null> | null;
} | null;
} | null> | null;
readonly " $fragmentRefs": FragmentRefs<"PartnerCard_artwork" | "AboutWork_artwork" | "OtherWorks_artwork" | "AboutArtist_artwork" | "ArtworkDetails_artwork" | "ContextCard_artwork" | "ArtworkHistory_artwork" | "Artwork_artworkAboveTheFold">;
} | null;
};
export type ArtworkFullQuery = {
readonly response: ArtworkFullQueryResponse;
readonly variables: ArtworkFullQueryVariables;
};
/*
query ArtworkFullQuery(
$artworkID: String!
) {
artwork(id: $artworkID) {
additional_information: additionalInformation
description
provenance
exhibition_history: exhibitionHistory
literature
partner {
type
id
}
artist {
biography_blurb: biographyBlurb {
text
}
id
}
sale {
id
isBenefit
isGalleryAuction
}
category
conditionDescription {
details
}
signature
signatureInfo {
details
}
certificateOfAuthenticity {
details
}
framed {
details
}
series
publisher
manufacturer
image_rights: imageRights
context {
__typename
... on Sale {
isAuction
}
... on Node {
id
}
}
contextGrids {
__typename
artworks: artworksConnection(first: 6) {
edges {
node {
id
}
}
}
}
...PartnerCard_artwork
...AboutWork_artwork
...OtherWorks_artwork
...AboutArtist_artwork
...ArtworkDetails_artwork
...ContextCard_artwork
...ArtworkHistory_artwork
...Artwork_artworkAboveTheFold
id
}
}
fragment PartnerCard_artwork on Artwork {
sale {
isBenefit
isGalleryAuction
id
}
partner {
cities
is_default_profile_public: isDefaultProfilePublic
type
name
slug
id
href
initials
profile {
id
internalID
is_followed: isFollowed
icon {
url(version: "square140")
}
}
}
}
fragment AboutWork_artwork on Artwork {
additional_information: additionalInformation
description
isInAuction
}
fragment OtherWorks_artwork on Artwork {
contextGrids {
__typename
title
ctaTitle
ctaHref
artworks: artworksConnection(first: 6) {
edges {
node {
...GenericGrid_artworks
id
}
}
}
}
}
fragment AboutArtist_artwork on Artwork {
artists {
id
biography_blurb: biographyBlurb {
text
}
...ArtistListItem_artist
}
}
fragment ArtworkDetails_artwork on Artwork {
slug
category
conditionDescription {
label
details
}
signatureInfo {
label
details
}
certificateOfAuthenticity {
label
details
}
framed {
label
details
}
series
publisher
manufacturer
image_rights: imageRights
isBiddable
saleArtwork {
internalID
id
}
}
fragment ContextCard_artwork on Artwork {
id
context {
__typename
... on Sale {
id
name
isLiveOpen
href
formattedStartDateTime
isAuction
coverImage {
url
}
}
... on Fair {
id
name
href
exhibitionPeriod
image {
url
}
}
... on Show {
id
internalID
slug
name
href
exhibitionPeriod
isFollowed
coverImage {
url
}
}
... on Node {
id
}
}
}
fragment ArtworkHistory_artwork on Artwork {
provenance
exhibition_history: exhibitionHistory
literature
}
fragment Artwork_artworkAboveTheFold on Artwork {
...ArtworkHeader_artwork
...CommercialInformation_artwork
slug
internalID
id
is_acquireable: isAcquireable
is_offerable: isOfferable
is_biddable: isBiddable
is_inquireable: isInquireable
availability
}
fragment ArtworkHeader_artwork on Artwork {
...ArtworkActions_artwork
...ArtworkTombstone_artwork
images {
...ImageCarousel_images
}
}
fragment CommercialInformation_artwork on Artwork {
isAcquireable
isOfferable
isInquireable
isInAuction
availability
saleMessage
isForSale
artists {
isConsignable
id
}
editionSets {
id
}
sale {
isClosed
isAuction
isLiveOpen
isPreview
liveStartAt
endAt
startAt
id
}
...CommercialButtons_artwork
...CommercialPartnerInformation_artwork
...CommercialEditionSetInformation_artwork
...ArtworkExtraLinks_artwork
...AuctionPrice_artwork
}
fragment CommercialButtons_artwork on Artwork {
slug
isAcquireable
isOfferable
isInquireable
isInAuction
isBuyNowable
isForSale
editionSets {
id
}
sale {
isClosed
id
}
...BuyNowButton_artwork
...BidButton_artwork
...MakeOfferButton_artwork
}
fragment CommercialPartnerInformation_artwork on Artwork {
availability
isAcquireable
isForSale
isOfferable
shippingOrigin
shippingInfo
priceIncludesTaxDisplay
partner {
name
id
}
}
fragment CommercialEditionSetInformation_artwork on Artwork {
editionSets {
id
internalID
saleMessage
editionOf
dimensions {
in
cm
}
}
...CommercialPartnerInformation_artwork
}
fragment ArtworkExtraLinks_artwork on Artwork {
isAcquireable
isInAuction
isOfferable
title
isForSale
sale {
isClosed
isBenefit
partner {
name
id
}
id
}
artists {
isConsignable
name
id
}
artist {
name
id
}
}
fragment AuctionPrice_artwork on Artwork {
sale {
internalID
isWithBuyersPremium
isClosed
isLiveOpen
id
}
saleArtwork {
reserveMessage
currentBid {
display
}
counts {
bidderPositions
}
id
}
myLotStanding(live: true) {
activeBid {
isWinning
id
}
mostRecentBid {
maxBid {
display
}
id
}
}
}
fragment BuyNowButton_artwork on Artwork {
internalID
saleMessage
}
fragment BidButton_artwork on Artwork {
slug
sale {
slug
registrationStatus {
qualifiedForBidding
id
}
isPreview
isLiveOpen
isClosed
isRegistrationClosed
id
}
myLotStanding(live: true) {
mostRecentBid {
maxBid {
cents
}
id
}
}
saleArtwork {
increments {
cents
}
id
}
}
fragment MakeOfferButton_artwork on Artwork {
internalID
}
fragment ArtworkActions_artwork on Artwork {
id
internalID
slug
title
href
is_saved: isSaved
is_hangable: isHangable
artists {
name
id
}
image {
url
}
sale {
isAuction
isClosed
id
}
widthCm
heightCm
}
fragment ArtworkTombstone_artwork on Artwork {
title
isInAuction
medium
date
cultural_maker: culturalMaker
saleArtwork {
lotLabel
estimate
id
}
partner {
name
id
}
sale {
isClosed
id
}
artists {
name
href
...FollowArtistButton_artist
id
}
dimensions {
in
cm
}
edition_of: editionOf
attribution_class: attributionClass {
shortDescription
id
}
}
fragment ImageCarousel_images on Image {
url: imageURL
width
height
imageVersions
deepZoom {
image: Image {
tileSize: TileSize
url: Url
format: Format
size: Size {
width: Width
height: Height
}
}
}
}
fragment FollowArtistButton_artist on Artist {
id
slug
internalID
is_followed: isFollowed
}
fragment ArtistListItem_artist on Artist {
id
internalID
slug
name
initials
href
is_followed: isFollowed
nationality
birthday
deathday
image {
url
}
}
fragment GenericGrid_artworks on Artwork {
id
image {
aspect_ratio: aspectRatio
}
...ArtworkGridItem_artwork
}
fragment ArtworkGridItem_artwork on Artwork {
title
date
sale_message: saleMessage
is_biddable: isBiddable
is_acquireable: isAcquireable
is_offerable: isOfferable
slug
sale {
is_auction: isAuction
is_closed: isClosed
display_timely_at: displayTimelyAt
id
}
sale_artwork: saleArtwork {
current_bid: currentBid {
display
}
id
}
image {
url(version: "large")
aspect_ratio: aspectRatio
}
artists(shallow: true) {
name
id
}
partner {
name
id
}
href
}
*/
const node: ConcreteRequest = (function(){
var v0 = [
{
"kind": "LocalArgument",
"name": "artworkID",
"type": "String!",
"defaultValue": null
}
],
v1 = [
{
"kind": "Variable",
"name": "id",
"variableName": "artworkID"
}
],
v2 = {
"kind": "ScalarField",
"alias": "additional_information",
"name": "additionalInformation",
"args": null,
"storageKey": null
},
v3 = {
"kind": "ScalarField",
"alias": null,
"name": "description",
"args": null,
"storageKey": null
},
v4 = {
"kind": "ScalarField",
"alias": null,
"name": "provenance",
"args": null,
"storageKey": null
},
v5 = {
"kind": "ScalarField",
"alias": "exhibition_history",
"name": "exhibitionHistory",
"args": null,
"storageKey": null
},
v6 = {
"kind": "ScalarField",
"alias": null,
"name": "literature",
"args": null,
"storageKey": null
},
v7 = {
"kind": "ScalarField",
"alias": null,
"name": "type",
"args": null,
"storageKey": null
},
v8 = {
"kind": "ScalarField",
"alias": null,
"name": "id",
"args": null,
"storageKey": null
},
v9 = {
"kind": "LinkedField",
"alias": "biography_blurb",
"name": "biographyBlurb",
"storageKey": null,
"args": null,
"concreteType": "ArtistBlurb",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "text",
"args": null,
"storageKey": null
}
]
},
v10 = {
"kind": "ScalarField",
"alias": null,
"name": "isBenefit",
"args": null,
"storageKey": null
},
v11 = {
"kind": "ScalarField",
"alias": null,
"name": "isGalleryAuction",
"args": null,
"storageKey": null
},
v12 = {
"kind": "ScalarField",
"alias": null,
"name": "category",
"args": null,
"storageKey": null
},
v13 = {
"kind": "ScalarField",
"alias": null,
"name": "details",
"args": null,
"storageKey": null
},
v14 = [
(v13/*: any*/)
],
v15 = {
"kind": "ScalarField",
"alias": null,
"name": "signature",
"args": null,
"storageKey": null
},
v16 = {
"kind": "ScalarField",
"alias": null,
"name": "series",
"args": null,
"storageKey": null
},
v17 = {
"kind": "ScalarField",
"alias": null,
"name": "publisher",
"args": null,
"storageKey": null
},
v18 = {
"kind": "ScalarField",
"alias": null,
"name": "manufacturer",
"args": null,
"storageKey": null
},
v19 = {
"kind": "ScalarField",
"alias": "image_rights",
"name": "imageRights",
"args": null,
"storageKey": null
},
v20 = {
"kind": "ScalarField",
"alias": null,
"name": "__typename",
"args": null,
"storageKey": null
},
v21 = {
"kind": "ScalarField",
"alias": null,
"name": "isAuction",
"args": null,
"storageKey": null
},
v22 = [
{
"kind": "Literal",
"name": "first",
"value": 6
}
],
v23 = {
"kind": "ScalarField",
"alias": null,
"name": "name",
"args": null,
"storageKey": null
},
v24 = {
"kind": "ScalarField",
"alias": null,
"name": "slug",
"args": null,
"storageKey": null
},
v25 = {
"kind": "ScalarField",
"alias": null,
"name": "href",
"args": null,
"storageKey": null
},
v26 = {
"kind": "ScalarField",
"alias": null,
"name": "initials",
"args": null,
"storageKey": null
},
v27 = {
"kind": "ScalarField",
"alias": null,
"name": "internalID",
"args": null,
"storageKey": null
},
v28 = {
"kind": "ScalarField",
"alias": "is_followed",
"name": "isFollowed",
"args": null,
"storageKey": null
},
v29 = {
"kind": "ScalarField",
"alias": null,
"name": "isLiveOpen",
"args": null,
"storageKey": null
},
v30 = [
(v23/*: any*/),
(v8/*: any*/)
],
v31 = {
"kind": "LinkedField",
"alias": null,
"name": "partner",
"storageKey": null,
"args": null,
"concreteType": "Partner",
"plural": false,
"selections": (v30/*: any*/)
},
v32 = [
(v13/*: any*/),
{
"kind": "ScalarField",
"alias": null,
"name": "label",
"args": null,
"storageKey": null
}
],
v33 = [
{
"kind": "ScalarField",
"alias": null,
"name": "url",
"args": null,
"storageKey": null
}
],
v34 = {
"kind": "LinkedField",
"alias": null,
"name": "coverImage",
"storageKey": null,
"args": null,
"concreteType": "Image",
"plural": false,
"selections": (v33/*: any*/)
},
v35 = {
"kind": "ScalarField",
"alias": null,
"name": "exhibitionPeriod",
"args": null,
"storageKey": null
},
v36 = {
"kind": "LinkedField",
"alias": null,
"name": "image",
"storageKey": null,
"args": null,
"concreteType": "Image",
"plural": false,
"selections": (v33/*: any*/)
},
v37 = {
"kind": "ScalarField",
"alias": null,
"name": "title",
"args": null,
"storageKey": null
},
v38 = {
"kind": "ScalarField",
"alias": null,
"name": "date",
"args": null,
"storageKey": null
},
v39 = {
"kind": "ScalarField",
"alias": "is_biddable",
"name": "isBiddable",
"args": null,
"storageKey": null
},
v40 = {
"kind": "ScalarField",
"alias": "is_acquireable",
"name": "isAcquireable",
"args": null,
"storageKey": null
},
v41 = {
"kind": "ScalarField",
"alias": "is_offerable",
"name": "isOfferable",
"args": null,
"storageKey": null
},
v42 = {
"kind": "ScalarField",
"alias": null,
"name": "display",
"args": null,
"storageKey": null
},
v43 = [
(v42/*: any*/)
],
v44 = {
"kind": "ScalarField",
"alias": null,
"name": "cents",
"args": null,
"storageKey": null
},
v45 = {
"kind": "LinkedField",
"alias": null,
"name": "dimensions",
"storageKey": null,
"args": null,
"concreteType": "dimensions",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "in",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "cm",
"args": null,
"storageKey": null
}
]
},
v46 = {
"kind": "ScalarField",
"alias": null,
"name": "saleMessage",
"args": null,
"storageKey": null
};
return {
"kind": "Request",
"fragment": {
"kind": "Fragment",
"name": "ArtworkFullQuery",
"type": "Query",
"metadata": null,
"argumentDefinitions": (v0/*: any*/),
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "artwork",
"storageKey": null,
"args": (v1/*: any*/),
"concreteType": "Artwork",
"plural": false,
"selections": [
(v2/*: any*/),
(v3/*: any*/),
(v4/*: any*/),
(v5/*: any*/),
(v6/*: any*/),
{
"kind": "LinkedField",
"alias": null,
"name": "partner",
"storageKey": null,
"args": null,
"concreteType": "Partner",
"plural": false,
"selections": [
(v7/*: any*/),
(v8/*: any*/)
]
},
{
"kind": "LinkedField",
"alias": null,
"name": "artist",
"storageKey": null,
"args": null,
"concreteType": "Artist",
"plural": false,
"selections": [
(v9/*: any*/)
]
},
{
"kind": "LinkedField",
"alias": null,
"name": "sale",
"storageKey": null,
"args": null,
"concreteType": "Sale",
"plural": false,
"selections": [
(v8/*: any*/),
(v10/*: any*/),
(v11/*: any*/)
]
},
(v12/*: any*/),
{
"kind": "LinkedField",
"alias": null,
"name": "conditionDescription",
"storageKey": null,
"args": null,
"concreteType": "ArtworkInfoRow",
"plural": false,
"selections": (v14/*: any*/)
},
(v15/*: any*/),
{
"kind": "LinkedField",
"alias": null,
"name": "signatureInfo",
"storageKey": null,
"args": null,
"concreteType": "ArtworkInfoRow",
"plural": false,
"selections": (v14/*: any*/)
},
{
"kind": "LinkedField",
"alias": null,
"name": "certificateOfAuthenticity",
"storageKey": null,
"args": null,
"concreteType": "ArtworkInfoRow",
"plural": false,
"selections": (v14/*: any*/)
},
{
"kind": "LinkedField",
"alias": null,
"name": "framed",
"storageKey": null,
"args": null,
"concreteType": "ArtworkInfoRow",
"plural": false,
"selections": (v14/*: any*/)
},
(v16/*: any*/),
(v17/*: any*/),
(v18/*: any*/),
(v19/*: any*/),
{
"kind": "LinkedField",
"alias": null,
"name": "context",
"storageKey": null,
"args": null,
"concreteType": null,
"plural": false,
"selections": [
(v20/*: any*/),
{
"kind": "InlineFragment",
"type": "Sale",
"selections": [
(v21/*: any*/)
]
}
]
},
{
"kind": "LinkedField",
"alias": null,
"name": "contextGrids",
"storageKey": null,
"args": null,
"concreteType": null,
"plural": true,
"selections": [
{
"kind": "LinkedField",
"alias": "artworks",
"name": "artworksConnection",
"storageKey": "artworksConnection(first:6)",
"args": (v22/*: any*/),
"concreteType": "ArtworkConnection",
"plural": false,
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "edges",
"storageKey": null,
"args": null,
"concreteType": "ArtworkEdge",
"plural": true,
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "node",
"storageKey": null,
"args": null,
"concreteType": "Artwork",
"plural": false,
"selections": [
(v8/*: any*/)
]
}
]
}
]
}
]
},
{
"kind": "FragmentSpread",
"name": "PartnerCard_artwork",
"args": null
},
{
"kind": "FragmentSpread",
"name": "AboutWork_artwork",
"args": null
},
{
"kind": "FragmentSpread",
"name": "OtherWorks_artwork",
"args": null
},
{
"kind": "FragmentSpread",
"name": "AboutArtist_artwork",
"args": null
},
{
"kind": "FragmentSpread",
"name": "ArtworkDetails_artwork",
"args": null
},
{
"kind": "FragmentSpread",
"name": "ContextCard_artwork",
"args": null
},
{
"kind": "FragmentSpread",
"name": "ArtworkHistory_artwork",
"args": null
},
{
"kind": "FragmentSpread",
"name": "Artwork_artworkAboveTheFold",
"args": null
}
]
}
]
},
"operation": {
"kind": "Operation",
"name": "ArtworkFullQuery",
"argumentDefinitions": (v0/*: any*/),
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "artwork",
"storageKey": null,
"args": (v1/*: any*/),
"concreteType": "Artwork",
"plural": false,
"selections": [
(v2/*: any*/),
(v3/*: any*/),
(v4/*: any*/),
(v5/*: any*/),
(v6/*: any*/),
{
"kind": "LinkedField",
"alias": null,
"name": "partner",
"storageKey": null,
"args": null,
"concreteType": "Partner",
"plural": false,
"selections": [
(v7/*: any*/),
(v8/*: any*/),
{
"kind": "ScalarField",
"alias": null,
"name": "cities",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": "is_default_profile_public",
"name": "isDefaultProfilePublic",
"args": null,
"storageKey": null
},
(v23/*: any*/),
(v24/*: any*/),
(v25/*: any*/),
(v26/*: any*/),
{
"kind": "LinkedField",
"alias": null,
"name": "profile",
"storageKey": null,
"args": null,
"concreteType": "Profile",
"plural": false,
"selections": [
(v8/*: any*/),
(v27/*: any*/),
(v28/*: any*/),
{
"kind": "LinkedField",
"alias": null,
"name": "icon",
"storageKey": null,
"args": null,
"concreteType": "Image",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "url",
"args": [
{
"kind": "Literal",
"name": "version",
"value": "square140"
}
],
"storageKey": "url(version:\"square140\")"
}
]
}
]
}
]
},
{
"kind": "LinkedField",
"alias": null,
"name": "artist",
"storageKey": null,
"args": null,
"concreteType": "Artist",
"plural": false,
"selections": [
(v9/*: any*/),
(v8/*: any*/),
(v23/*: any*/)
]
},
{
"kind": "LinkedField",
"alias": null,
"name": "sale",
"storageKey": null,
"args": null,
"concreteType": "Sale",
"plural": false,
"selections": [
(v8/*: any*/),
(v10/*: any*/),
(v11/*: any*/),
(v21/*: any*/),
{
"kind": "ScalarField",
"alias": null,
"name": "isClosed",
"args": null,
"storageKey": null
},
(v29/*: any*/),
{
"kind": "ScalarField",
"alias": null,
"name": "isPreview",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "liveStartAt",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "endAt",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "startAt",
"args": null,
"storageKey": null
},
(v24/*: any*/),
{
"kind": "LinkedField",
"alias": null,
"name": "registrationStatus",
"storageKey": null,
"args": null,
"concreteType": "Bidder",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "qualifiedForBidding",
"args": null,
"storageKey": null
},
(v8/*: any*/)
]
},
{
"kind": "ScalarField",
"alias": null,
"name": "isRegistrationClosed",
"args": null,
"storageKey": null
},
(v31/*: any*/),
(v27/*: any*/),
{
"kind": "ScalarField",
"alias": null,
"name": "isWithBuyersPremium",
"args": null,
"storageKey": null
}
]
},
(v12/*: any*/),
{
"kind": "LinkedField",
"alias": null,
"name": "conditionDescription",
"storageKey": null,
"args": null,
"concreteType": "ArtworkInfoRow",
"plural": false,
"selections": (v32/*: any*/)
},
(v15/*: any*/),
{
"kind": "LinkedField",
"alias": null,
"name": "signatureInfo",
"storageKey": null,
"args": null,
"concreteType": "ArtworkInfoRow",
"plural": false,
"selections": (v32/*: any*/)
},
{
"kind": "LinkedField",
"alias": null,
"name": "certificateOfAuthenticity",
"storageKey": null,
"args": null,
"concreteType": "ArtworkInfoRow",
"plural": false,
"selections": (v32/*: any*/)
},
{
"kind": "LinkedField",
"alias": null,
"name": "framed",
"storageKey": null,
"args": null,
"concreteType": "ArtworkInfoRow",
"plural": false,
"selections": (v32/*: any*/)
},
(v16/*: any*/),
(v17/*: any*/),
(v18/*: any*/),
(v19/*: any*/),
{
"kind": "LinkedField",
"alias": null,
"name": "context",
"storageKey": null,
"args": null,
"concreteType": null,
"plural": false,
"selections": [
(v20/*: any*/),
(v8/*: any*/),
{
"kind": "InlineFragment",
"type": "Sale",
"selections": [
(v21/*: any*/),
(v23/*: any*/),
(v29/*: any*/),
(v25/*: any*/),
{
"kind": "ScalarField",
"alias": null,
"name": "formattedStartDateTime",
"args": null,
"storageKey": null
},
(v34/*: any*/)
]
},
{
"kind": "InlineFragment",
"type": "Fair",
"selections": [
(v23/*: any*/),
(v25/*: any*/),
(v35/*: any*/),
(v36/*: any*/)
]
},
{
"kind": "InlineFragment",
"type": "Show",
"selections": [
(v27/*: any*/),
(v24/*: any*/),
(v23/*: any*/),
(v25/*: any*/),
(v35/*: any*/),
{
"kind": "ScalarField",
"alias": null,
"name": "isFollowed",
"args": null,
"storageKey": null
},
(v34/*: any*/)
]
}
]
},
{
"kind": "LinkedField",
"alias": null,
"name": "contextGrids",
"storageKey": null,
"args": null,
"concreteType": null,
"plural": true,
"selections": [
{
"kind": "LinkedField",
"alias": "artworks",
"name": "artworksConnection",
"storageKey": "artworksConnection(first:6)",
"args": (v22/*: any*/),
"concreteType": "ArtworkConnection",
"plural": false,
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "edges",
"storageKey": null,
"args": null,
"concreteType": "ArtworkEdge",
"plural": true,
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "node",
"storageKey": null,
"args": null,
"concreteType": "Artwork",
"plural": false,
"selections": [
(v8/*: any*/),
{
"kind": "LinkedField",
"alias": null,
"name": "image",
"storageKey": null,
"args": null,
"concreteType": "Image",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": "aspect_ratio",
"name": "aspectRatio",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "url",
"args": [
{
"kind": "Literal",
"name": "version",
"value": "large"
}
],
"storageKey": "url(version:\"large\")"
}
]
},
(v37/*: any*/),
(v38/*: any*/),
{
"kind": "ScalarField",
"alias": "sale_message",
"name": "saleMessage",
"args": null,
"storageKey": null
},
(v39/*: any*/),
(v40/*: any*/),
(v41/*: any*/),
(v24/*: any*/),
{
"kind": "LinkedField",
"alias": null,
"name": "sale",
"storageKey": null,
"args": null,
"concreteType": "Sale",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": "is_auction",
"name": "isAuction",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": "is_closed",
"name": "isClosed",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": "display_timely_at",
"name": "displayTimelyAt",
"args": null,
"storageKey": null
},
(v8/*: any*/)
]
},
{
"kind": "LinkedField",
"alias": "sale_artwork",
"name": "saleArtwork",
"storageKey": null,
"args": null,
"concreteType": "SaleArtwork",
"plural": false,
"selections": [
{
"kind": "LinkedField",
"alias": "current_bid",
"name": "currentBid",
"storageKey": null,
"args": null,
"concreteType": "SaleArtworkCurrentBid",
"plural": false,
"selections": (v43/*: any*/)
},
(v8/*: any*/)
]
},
{
"kind": "LinkedField",
"alias": null,
"name": "artists",
"storageKey": "artists(shallow:true)",
"args": [
{
"kind": "Literal",
"name": "shallow",
"value": true
}
],
"concreteType": "Artist",
"plural": true,
"selections": (v30/*: any*/)
},
(v31/*: any*/),
(v25/*: any*/)
]
}
]
}
]
},
(v20/*: any*/),
(v37/*: any*/),
{
"kind": "ScalarField",
"alias": null,
"name": "ctaTitle",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "ctaHref",
"args": null,
"storageKey": null
}
]
},
{
"kind": "ScalarField",
"alias": null,
"name": "isInAuction",
"args": null,
"storageKey": null
},
{
"kind": "LinkedField",
"alias": null,
"name": "artists",
"storageKey": null,
"args": null,
"concreteType": "Artist",
"plural": true,
"selections": [
(v8/*: any*/),
(v9/*: any*/),
(v27/*: any*/),
(v24/*: any*/),
(v23/*: any*/),
(v26/*: any*/),
(v25/*: any*/),
(v28/*: any*/),
{
"kind": "ScalarField",
"alias": null,
"name": "nationality",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "birthday",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "deathday",
"args": null,
"storageKey": null
},
(v36/*: any*/),
{
"kind": "ScalarField",
"alias": null,
"name": "isConsignable",
"args": null,
"storageKey": null
}
]
},
(v24/*: any*/),
{
"kind": "ScalarField",
"alias": null,
"name": "isBiddable",
"args": null,
"storageKey": null
},
{
"kind": "LinkedField",
"alias": null,
"name": "saleArtwork",
"storageKey": null,
"args": null,
"concreteType": "SaleArtwork",
"plural": false,
"selections": [
(v27/*: any*/),
(v8/*: any*/),
{
"kind": "ScalarField",
"alias": null,
"name": "lotLabel",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "estimate",
"args": null,
"storageKey": null
},
{
"kind": "LinkedField",
"alias": null,
"name": "increments",
"storageKey": null,
"args": null,
"concreteType": "BidIncrementsFormatted",
"plural": true,
"selections": [
(v44/*: any*/)
]
},
{
"kind": "ScalarField",
"alias": null,
"name": "reserveMessage",
"args": null,
"storageKey": null
},
{
"kind": "LinkedField",
"alias": null,
"name": "currentBid",
"storageKey": null,
"args": null,
"concreteType": "SaleArtworkCurrentBid",
"plural": false,
"selections": (v43/*: any*/)
},
{
"kind": "LinkedField",
"alias": null,
"name": "counts",
"storageKey": null,
"args": null,
"concreteType": "SaleArtworkCounts",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "bidderPositions",
"args": null,
"storageKey": null
}
]
}
]
},
(v8/*: any*/),
(v27/*: any*/),
(v37/*: any*/),
(v25/*: any*/),
{
"kind": "ScalarField",
"alias": "is_saved",
"name": "isSaved",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": "is_hangable",
"name": "isHangable",
"args": null,
"storageKey": null
},
(v36/*: any*/),
{
"kind": "ScalarField",
"alias": null,
"name": "widthCm",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "heightCm",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "medium",
"args": null,
"storageKey": null
},
(v38/*: any*/),
{
"kind": "ScalarField",
"alias": "cultural_maker",
"name": "culturalMaker",
"args": null,
"storageKey": null
},
(v45/*: any*/),
{
"kind": "ScalarField",
"alias": "edition_of",
"name": "editionOf",
"args": null,
"storageKey": null
},
{
"kind": "LinkedField",
"alias": "attribution_class",
"name": "attributionClass",
"storageKey": null,
"args": null,
"concreteType": "AttributionClass",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "shortDescription",
"args": null,
"storageKey": null
},
(v8/*: any*/)
]
},
{
"kind": "LinkedField",
"alias": null,
"name": "images",
"storageKey": null,
"args": null,
"concreteType": "Image",
"plural": true,
"selections": [
{
"kind": "ScalarField",
"alias": "url",
"name": "imageURL",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "width",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "height",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "imageVersions",
"args": null,
"storageKey": null
},
{
"kind": "LinkedField",
"alias": null,
"name": "deepZoom",
"storageKey": null,
"args": null,
"concreteType": "DeepZoom",
"plural": false,
"selections": [
{
"kind": "LinkedField",
"alias": "image",
"name": "Image",
"storageKey": null,
"args": null,
"concreteType": "DeepZoomImage",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": "tileSize",
"name": "TileSize",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": "url",
"name": "Url",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": "format",
"name": "Format",
"args": null,
"storageKey": null
},
{
"kind": "LinkedField",
"alias": "size",
"name": "Size",
"storageKey": null,
"args": null,
"concreteType": "DeepZoomImageSize",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": "width",
"name": "Width",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": "height",
"name": "Height",
"args": null,
"storageKey": null
}
]
}
]
}
]
}
]
},
{
"kind": "ScalarField",
"alias": null,
"name": "isAcquireable",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "isOfferable",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "isInquireable",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "availability",
"args": null,
"storageKey": null
},
(v46/*: any*/),
{
"kind": "ScalarField",
"alias": null,
"name": "isForSale",
"args": null,
"storageKey": null
},
{
"kind": "LinkedField",
"alias": null,
"name": "editionSets",
"storageKey": null,
"args": null,
"concreteType": "EditionSet",
"plural": true,
"selections": [
(v8/*: any*/),
(v27/*: any*/),
(v46/*: any*/),
{
"kind": "ScalarField",
"alias": null,
"name": "editionOf",
"args": null,
"storageKey": null
},
(v45/*: any*/)
]
},
{
"kind": "ScalarField",
"alias": null,
"name": "isBuyNowable",
"args": null,
"storageKey": null
},
{
"kind": "LinkedField",
"alias": null,
"name": "myLotStanding",
"storageKey": "myLotStanding(live:true)",
"args": [
{
"kind": "Literal",
"name": "live",
"value": true
}
],
"concreteType": "LotStanding",
"plural": true,
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "mostRecentBid",
"storageKey": null,
"args": null,
"concreteType": "BidderPosition",
"plural": false,
"selections": [
{
"kind": "LinkedField",
"alias": null,
"name": "maxBid",
"storageKey": null,
"args": null,
"concreteType": "BidderPositionMaxBid",
"plural": false,
"selections": [
(v44/*: any*/),
(v42/*: any*/)
]
},
(v8/*: any*/)
]
},
{
"kind": "LinkedField",
"alias": null,
"name": "activeBid",
"storageKey": null,
"args": null,
"concreteType": "BidderPosition",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "isWinning",
"args": null,
"storageKey": null
},
(v8/*: any*/)
]
}
]
},
{
"kind": "ScalarField",
"alias": null,
"name": "shippingOrigin",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "shippingInfo",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "priceIncludesTaxDisplay",
"args": null,
"storageKey": null
},
(v40/*: any*/),
(v41/*: any*/),
(v39/*: any*/),
{
"kind": "ScalarField",
"alias": "is_inquireable",
"name": "isInquireable",
"args": null,
"storageKey": null
}
]
}
]
},
"params": {
"operationKind": "query",
"name": "ArtworkFullQuery",
"id": "b75dcae86a3b9634567d71ea4ff3a5a7",
"text": null,
"metadata": {}
}
};
})();
(node as any).hash = '0104972b5f030fa8c5d5817132b2e140';
export default node; | the_stack |
import { Response } from 'express';
import crypto from 'crypto';
import githubUsernameRegex from 'github-username-regex';
import { AxiosError } from 'axios';
import { DateTime } from 'luxon';
import { GitHubRepositoryPermission } from './entities/repositoryMetadata/repositoryMetadata';
import appPackage from './package.json';
import { ICreateRepositoryApiResult } from './api/createRepo';
import { Repository } from './business/repository';
import { IDictionary, IFunctionPromise, IProviders, ISettledValue, ReposAppRequest, SettledState } from './interfaces';
import { Organization } from './business';
const packageVariableName = 'static-react-package-name';
export function hasStaticReactClientApp() {
const staticClientPackageName = appPackage[packageVariableName];
if (process.env.ENABLE_REACT_CLIENT && staticClientPackageName) {
return staticClientPackageName;
}
}
export function assertUnreachable(nothing: never): never {
throw new Error('This is never expected.');
}
export interface RedisOptions {
auth_pass?: string;
detect_buffers: boolean;
tls?: {
servername: string;
};
}
export function getProviders(req: ReposAppRequest) {
return req.app.settings.providers as IProviders;
}
export function isWebhookIngestionEndpointEnabled(req: ReposAppRequest) {
const { config } = getProviders(req);
return config?.features?.exposeWebhookIngestionEndpoint === true;
}
export interface IResponseForSettingsPersonalAccessTokens extends Response {
newKey?: string;
}
interface ITooManyLinksError extends Error {
links?: any;
tooManyLinks?: boolean;
}
interface IExistingIdentityError extends Error {
anotherAccount?: boolean;
link?: any;
skipLog?: boolean;
}
function tooManyLinksError(self, userLinks, callback) {
const tooManyLinksError: ITooManyLinksError = new Error(`This account has ${userLinks.length} linked GitHub accounts.`);
tooManyLinksError.links = userLinks;
tooManyLinksError.tooManyLinks = true;
return callback(tooManyLinksError, self);
}
function existingGitHubIdentityError(self, link, requestUser, callback) {
const endUser = requestUser.azure.displayName || requestUser.azure.username;
const anotherGitHubAccountError: IExistingIdentityError = new Error(`${endUser}, there is a different GitHub account linked to your corporate identity.`);
anotherGitHubAccountError.anotherAccount = true;
anotherGitHubAccountError.link = link;
anotherGitHubAccountError.skipLog = true;
return callback(anotherGitHubAccountError, self);
}
export function SettleToStateValue<T>(promise: Promise<T>): Promise<ISettledValue<T>> {
return promise.then(value => {
return { value, state: SettledState.Fulfilled };
}, reason => {
return { reason, state: SettledState.Rejected };
});
}
export function permissionsObjectToValue(permissions): GitHubRepositoryPermission {
if (permissions.admin === true) {
return GitHubRepositoryPermission.Admin;
} else if (permissions.push === true) {
return GitHubRepositoryPermission.Push;
} else if (permissions.triage === true) {
return GitHubRepositoryPermission.Triage;
} else if (permissions.maintain === true) {
return GitHubRepositoryPermission.Maintain;
} else if (permissions.pull === true) {
return GitHubRepositoryPermission.Pull;
}
throw new Error(`Unsupported GitHubRepositoryPermission value inside permissions`);
}
export function isPermissionBetterThan(currentBest: GitHubRepositoryPermission, newConsideration: GitHubRepositoryPermission) {
switch (newConsideration) {
case GitHubRepositoryPermission.Admin:
return true;
case GitHubRepositoryPermission.Maintain:
if (currentBest !== GitHubRepositoryPermission.Admin) {
return true;
}
break;
case GitHubRepositoryPermission.Push:
if (currentBest !== GitHubRepositoryPermission.Admin) {
return true;
}
break;
case GitHubRepositoryPermission.Pull:
if (currentBest === null || currentBest === GitHubRepositoryPermission.None) {
return true;
}
break;
case GitHubRepositoryPermission.Triage:
// not really great
break;
default:
throw new Error(`Invalid permission type ${newConsideration}`);
}
return false;
}
export function MassagePermissionsToGitHubRepositoryPermission(value: string): GitHubRepositoryPermission {
// collaborator level APIs return a more generic read/write value, lead to some bad caches in the past...
// TODO: support new collaboration values as they come online for Enterprise Cloud!
switch (value) {
case 'write':
case 'push':
return GitHubRepositoryPermission.Push;
case 'admin':
return GitHubRepositoryPermission.Admin;
case 'triage':
return GitHubRepositoryPermission.Triage;
case 'maintain':
return GitHubRepositoryPermission.Maintain;
case 'pull':
case 'read':
return GitHubRepositoryPermission.Pull;
default:
throw new Error(`Invalid ${value} GitHub repository permission [massagePermissionsToGitHubRepositoryPermission]`);
}
}
export class CreateError {
static CreateStatusCodeError(code: number, message?: string): Error {
const error = new Error(message);
error['status'] = code;
return error;
}
static NotFound(message: string, innerError?: Error): Error {
return ErrorHelper.SetInnerError(CreateError.CreateStatusCodeError(404, message), innerError);
}
static Conflict(message: string, innerError?: Error): Error {
return ErrorHelper.SetInnerError(CreateError.CreateStatusCodeError(409, message), innerError);
}
static ParameterRequired(parameterName: string, optionalDetails?: string): Error {
const msg = `${parameterName} required`;
return CreateError.CreateStatusCodeError(400, optionalDetails ? `${msg}: ${optionalDetails}` : msg);
}
static InvalidParameters(message: string, innerError?: Error): Error {
return ErrorHelper.SetInnerError(CreateError.CreateStatusCodeError(400, message), innerError);
}
static NotAuthenticated(message: string): Error {
return CreateError.CreateStatusCodeError(401, message);
}
static NotAuthorized(message: string): Error {
return CreateError.CreateStatusCodeError(403, message);
}
static ServerError(message: string, innerError?: Error): Error {
return ErrorHelper.SetInnerError(CreateError.CreateStatusCodeError(500, message), innerError);
}
}
export class ErrorHelper {
static EnsureHasStatus(error: Error, code: number): Error {
if (!error['status']) {
error['status'] = code;
}
return error;
}
public static WrapError(innerError: Error, message: string): Error {
const err = new Error(message);
err['innerError'] = innerError;
return err;
}
public static SetInnerError(error: Error, innerError: Error) {
if (error && innerError) {
error['innerError'] = innerError;
}
return error;
}
public static HasStatus(error: Error): boolean {
return error && error['status'];
}
public static IsNotFound(error: Error): boolean {
const statusNumber = ErrorHelper.GetStatus(error);
return (statusNumber && statusNumber === 404);
}
public static IsUnavailableForExternalLegalRequest(error: Error): boolean {
const statusNumber = ErrorHelper.GetStatus(error);
return (statusNumber && statusNumber === 451); // https://developer.github.com/changes/2016-03-17-the-451-status-code-is-now-supported/
}
public static IsConflict(error: Error): boolean {
const statusNumber = ErrorHelper.GetStatus(error);
if (statusNumber && statusNumber === 409) {
return true;
}
// would be nice to be able to get rid of this clause someday
if (error.message && error.message.includes('already exists')) {
return true;
}
return false;
}
public static NotImplemented() {
return new Error('Not implemented');
}
public static GetStatus(error: Error): number {
const asAny = error as any;
if (asAny?.isAxiosError === true) {
const axiosError = asAny as AxiosError;
if (axiosError?.response?.status) {
return axiosError.response.status;
}
}
if (asAny?.statusCode && typeof (asAny.statusCode) === 'number') {
return asAny.statusCode as number;
}
if (asAny?.code && typeof (asAny.code) === 'number') {
return asAny.code as number;
}
if (asAny?.status) {
const status = asAny.status;
const type = typeof (status);
if (type === 'number') {
return status;
} else if (type === 'string') {
return Number(status);
} else {
console.warn(`Unsupported error.status type: ${type}`);
return null;
}
}
return null;
}
}
export function setImmediateAsync(f: IFunctionPromise<void>): void {
const safeCall = () => {
try {
f().catch(error => {
console.warn(`setImmediateAsync caught error: ${error}`);
});
} catch (ignoredFailure) {
console.warn(`setImmediateAsync call error: ${ignoredFailure}`);
}
};
setImmediate(safeCall.bind(null));
}
export function stripDistFolderName(dirname: string) {
// This is a hacky backup for init failure scenarios where the dirname may
// not actually point at the app root.
if (dirname.endsWith('dist')) {
dirname = dirname.replace('\\dist', '');
dirname = dirname.replace('/dist', '');
}
return dirname;
}
export function sha256(str: string) {
const hash = crypto.createHash('sha256').update(str).digest('base64');
return hash;
}
export interface ICustomizedNewRepositoryLogic {
createContext(req: any): INewRepositoryContext;
getAdditionalTelemetryProperties(context: INewRepositoryContext): IDictionary<string>;
validateRequest(context: INewRepositoryContext, req: any): Promise<void>;
stripRequestBody(context: INewRepositoryContext, body: any): void;
afterRepositoryCreated(context: INewRepositoryContext, corporateId: string, success: ICreateRepositoryApiResult, organization: Organization): Promise<void>;
shouldNotifyManager(context: INewRepositoryContext, corporateId: string): boolean;
getNewMailViewProperties(context: INewRepositoryContext, repository: Repository): Promise<ICustomizedNewRepoProperties>;
sufficientTeamsConfigured(context: INewRepositoryContext, body: any): boolean;
skipApproval(context: INewRepositoryContext, body: any): boolean;
additionalCreateRepositoryParameters(context: INewRepositoryContext): any;
}
export function splitSemiColonCommas(value: string) {
return value ? value.replace(/;/g, ',').split(',') : [];
}
export interface ICustomizedNewRepoProperties {
viewProperties: any;
to?: string[];
cc?: string[];
bcc?: string[];
}
export interface ICustomizedTeamPermissionsWebhookLogic {
shouldSkipEnforcement(repository: Repository): Promise<boolean>;
}
export interface INewRepositoryContext {
isCustomContext: boolean;
}
export function validateGitHubLogin(username: string) {
// There are some legitimate usernames at GitHub that have a dash
// in them. While GitHub no longer allows this for new accounts,
// they are grandfathered in.
if (!githubUsernameRegex.test(username) && !username.endsWith('-')) {
console.warn(`Invalid GitHub username format: ${username}`);
// throw new Error(`Invalid GitHub username format: ${username}`);
}
return username;
} | the_stack |
import { AWSError, CodeCommit } from 'aws-sdk';
import { commonAws, HandlerArgs } from 'aws-resource-providers-common';
import { Action, BaseResource, exceptions, handlerEvent, Logger } from 'cfn-rpdk';
import { ResourceModel, TemplateContent } from './models';
class Resource extends BaseResource<ResourceModel> {
static convertToEpoch(value?: Date): number {
if (value) {
return value.getTime() / 1000.0;
}
return null;
}
static extractResourceId(arn: string): string {
if (arn.length) {
return arn.split('/').pop();
}
return arn;
}
static formatArn(region: string, awsAccountId: string, resourceId: string): string {
if (region && awsAccountId && resourceId) {
return `arn:community:codecommit:${region}:${awsAccountId}:approval-rule-template/${resourceId}`;
}
return null;
}
private async getRuleTemplate(service: CodeCommit, logger: Logger, approvalRuleTemplateName: string): Promise<ResourceModel> {
const request: CodeCommit.GetApprovalRuleTemplateInput = {
approvalRuleTemplateName,
};
logger.log({ message: 'before invoke getApprovalRuleTemplate', request });
const response = await service.getApprovalRuleTemplate(request).promise();
logger.log({ message: 'after invoke getApprovalRuleTemplate', response });
const { approvalRuleTemplateId, approvalRuleTemplateContent } = response.approvalRuleTemplate;
const model = new ResourceModel();
model.id = approvalRuleTemplateId;
model.name = approvalRuleTemplateName;
model.description = response.approvalRuleTemplate.approvalRuleTemplateDescription;
model.creationDate = Resource.convertToEpoch(response.approvalRuleTemplate.creationDate);
model.lastModifiedDate = Resource.convertToEpoch(response.approvalRuleTemplate.lastModifiedDate);
model.lastModifiedUser = response.approvalRuleTemplate.lastModifiedUser;
model.ruleContentSha256 = response.approvalRuleTemplate.ruleContentSha256;
model.content = approvalRuleTemplateContent && TemplateContent.deserialize(JSON.parse(approvalRuleTemplateContent));
return Promise.resolve(model);
}
private async listRuleTemplates(service: CodeCommit, logger: Logger, filter?: Pick<ResourceModel, 'id' | 'name'>): Promise<ResourceModel[]> {
let rules: ResourceModel[] = [];
if (service) {
logger.log({ message: 'before invoke listApprovalRuleTemplates' });
const response = await service.listApprovalRuleTemplates().promise();
logger.log({ message: 'after invoke listApprovalRuleTemplates', response });
rules = await Promise.all(
response.approvalRuleTemplateNames.map((approvalRuleTemplateName: string) => {
return this.getRuleTemplate(service, logger, approvalRuleTemplateName);
})
);
if (filter) {
return rules.filter((rule: ResourceModel) => {
return (filter.id && filter.id === rule.id) || (filter.name && filter.name === rule.name);
});
}
}
return Promise.resolve(rules);
}
@handlerEvent(Action.Create)
@commonAws({ serviceName: 'CodeCommit', debug: true })
public async create(action: Action, args: HandlerArgs<ResourceModel>, service: CodeCommit, model: ResourceModel): Promise<ResourceModel> {
const { awsAccountId, logicalResourceIdentifier, region } = args.request;
if (model.arn) {
throw new exceptions.InvalidRequest('Read only property [Arn] cannot be provided by the user.');
} else if (model.id) {
throw new exceptions.InvalidRequest('Read only property [Id] cannot be provided by the user.');
}
const request: CodeCommit.CreateApprovalRuleTemplateInput = {
approvalRuleTemplateName: model.name,
approvalRuleTemplateDescription: model.description,
approvalRuleTemplateContent: model.content && JSON.stringify(model.content.serialize()),
};
try {
args.logger.log({ action, message: 'before createApprovalRuleTemplate', request });
const response = await service.createApprovalRuleTemplate(request).promise();
args.logger.log({ action, message: 'after invoke createApprovalRuleTemplate', response });
const { approvalRuleTemplateId, approvalRuleTemplateName } = response.approvalRuleTemplate;
const result = new ResourceModel();
result.arn = Resource.formatArn(region, awsAccountId, approvalRuleTemplateId);
result.id = approvalRuleTemplateId;
result.name = approvalRuleTemplateName;
result.description = response.approvalRuleTemplate.approvalRuleTemplateDescription;
result.content = model.content;
result.creationDate = Resource.convertToEpoch(response.approvalRuleTemplate.creationDate);
result.lastModifiedDate = Resource.convertToEpoch(response.approvalRuleTemplate.lastModifiedDate);
result.lastModifiedUser = response.approvalRuleTemplate.lastModifiedUser;
result.ruleContentSha256 = response.approvalRuleTemplate.ruleContentSha256;
args.logger.log({ action, message: 'done', result });
return Promise.resolve(result);
} catch (err) {
console.log(err);
if (err?.code === 'ApprovalRuleTemplateNameAlreadyExistsException') {
throw new exceptions.AlreadyExists(this.typeName, logicalResourceIdentifier);
} else {
// Raise the original exception
throw err;
}
}
}
@handlerEvent(Action.Update)
@commonAws({ serviceName: 'CodeCommit', debug: true })
public async update(action: Action, args: HandlerArgs<ResourceModel>, service: CodeCommit, model: ResourceModel): Promise<ResourceModel> {
const { awsAccountId, logicalResourceIdentifier, previousResourceState, region } = args.request;
const { arn, id } = previousResourceState;
if (!model.arn && !model.id) {
throw new exceptions.NotFound(this.typeName, logicalResourceIdentifier);
} else if (model.arn !== arn) {
args.logger.log(this.typeName, `[NEW ${model.arn}] [${logicalResourceIdentifier}]`, `does not match identifier from saved resource [OLD ${arn}].`);
throw new exceptions.NotUpdatable('Read only property [Arn] cannot be updated.');
} else if (model.id !== id) {
args.logger.log(this.typeName, `[NEW ${model.id}] [${logicalResourceIdentifier}]`, `does not match identifier from saved resource [OLD ${id}].`);
throw new exceptions.NotUpdatable('Read only property [Id] cannot be updated.');
}
try {
const serializedContent = model.content && model.content.serialize();
if (serializedContent !== previousResourceState.content.serialize()) {
const request: CodeCommit.UpdateApprovalRuleTemplateContentInput = {
approvalRuleTemplateName: previousResourceState.name,
// existingRuleContentSha256: previousResourceState.ruleContentSha256, # Removing because this will only succeed if content has been modified by CFN
newRuleContent: JSON.stringify(serializedContent),
};
args.logger.log({ action, message: 'before updateApprovalRuleTemplateContent', request });
const response = await service.updateApprovalRuleTemplateContent(request).promise();
args.logger.log({ action, message: 'after invoke updateApprovalRuleTemplateContent', response });
}
if (model.description !== previousResourceState.description) {
const request: CodeCommit.UpdateApprovalRuleTemplateDescriptionInput = {
approvalRuleTemplateName: previousResourceState.name,
approvalRuleTemplateDescription: model.description,
};
args.logger.log({ action, message: 'before updateApprovalRuleTemplateDescription', request });
const response = await service.updateApprovalRuleTemplateDescription(request).promise();
args.logger.log({ action, message: 'after invoke updateApprovalRuleTemplateDescription', response });
}
if (model.name !== previousResourceState.name) {
const request: CodeCommit.UpdateApprovalRuleTemplateNameInput = {
oldApprovalRuleTemplateName: previousResourceState.name,
newApprovalRuleTemplateName: model.name,
};
args.logger.log({ action, message: 'before invoke updateApprovalRuleTemplateName', request });
const response = await service.updateApprovalRuleTemplateName(request).promise();
args.logger.log({ action, message: 'after invoke updateApprovalRuleTemplateName', response });
}
model = await this.getRuleTemplate(service, args.logger, model.name);
model.arn = Resource.formatArn(region, awsAccountId, model.id);
args.logger.log({ action, message: 'done', model });
return Promise.resolve(model);
} catch (err) {
if (err?.code === 'ApprovalRuleTemplateDoesNotExistException') {
throw new exceptions.NotFound(this.typeName, id || logicalResourceIdentifier);
} else {
// Raise the original exception
throw err;
}
}
}
@handlerEvent(Action.Delete)
@commonAws({ serviceName: 'CodeCommit', debug: true })
public async delete(action: Action, args: HandlerArgs<ResourceModel>, service: CodeCommit, model: ResourceModel): Promise<null> {
const { awsAccountId, logicalResourceIdentifier, region } = args.request;
let { arn, id, name } = model;
if (!arn && !id && !name) {
throw new exceptions.NotFound(this.typeName, logicalResourceIdentifier);
}
if (!arn) {
arn = Resource.formatArn(region, awsAccountId, id);
}
if (!id) {
id = Resource.extractResourceId(arn);
}
const rules = await this.listRuleTemplates(service, args.logger, { id, name }).catch((err: AWSError) => {
if (err?.code === 'ApprovalRuleTemplateDoesNotExistException') {
throw new exceptions.NotFound(this.typeName, id || logicalResourceIdentifier);
} else {
// Raise the original exception
throw err;
}
});
if (!rules.length) {
throw new exceptions.NotFound(this.typeName, id || logicalResourceIdentifier);
}
name = rules[0].name;
const request: CodeCommit.DeleteApprovalRuleTemplateInput = {
approvalRuleTemplateName: name,
};
args.logger.log({ action, message: 'before invoke deleteApprovalRuleTemplate', request });
const response = await service.deleteApprovalRuleTemplate(request).promise();
args.logger.log({ action, message: 'after invoke deleteApprovalRuleTemplate', response });
args.logger.log({ action, message: 'done' });
return Promise.resolve(null);
}
@handlerEvent(Action.Read)
@commonAws({ serviceName: 'CodeCommit', debug: true })
public async read(action: Action, args: HandlerArgs<ResourceModel>, service: CodeCommit, model: ResourceModel): Promise<ResourceModel> {
const { awsAccountId, logicalResourceIdentifier, region } = args.request;
let { arn, id } = model;
const name = model.name;
if (!arn && !id && !name) {
throw new exceptions.NotFound(this.typeName, logicalResourceIdentifier);
}
if (!arn) {
arn = Resource.formatArn(region, awsAccountId, id);
}
if (!id) {
id = Resource.extractResourceId(arn);
}
try {
const rules = await this.listRuleTemplates(service, args.logger, { id, name });
if (!rules.length) {
throw new exceptions.NotFound(this.typeName, id || logicalResourceIdentifier);
}
const result = rules[0];
result.arn = Resource.formatArn(region, awsAccountId, result.id);
args.logger.log({ action, message: 'done', result });
return Promise.resolve(result);
} catch (err) {
if (err?.code === 'ApprovalRuleTemplateDoesNotExistException') {
throw new exceptions.NotFound(this.typeName, id || logicalResourceIdentifier);
} else {
// Raise the original exception
throw err;
}
}
}
}
export const resource = new Resource(ResourceModel.TYPE_NAME, ResourceModel);
export const entrypoint = resource.entrypoint;
export const testEntrypoint = resource.testEntrypoint; | the_stack |
import * as React from "react";
import { ISpace, getCurrentBoard } from "./boards";
import { Space, SpaceSubtype, BoardType } from "./types";
import { updateRightClickMenu } from "./renderer";
import { $setting, get } from "./views/settings";
import basic3Image from "./img/toolbar/basic3.png";
import minigameduel3Image from "./img/toolbar/minigameduel3.png";
import reverse3Image from "./img/toolbar/reverse3.png";
import happeningduel3Image from "./img/toolbar/happeningduel3.png";
import gameguyduelImage from "./img/toolbar/gameguyduel.png";
import powerupImage from "./img/toolbar/powerup.png";
import startblueImage from "./img/toolbar/startblue.png";
import startredImage from "./img/toolbar/startred.png";
import { getValidSelectedSpaceIndices } from "./app/appControl";
import { setSpacePositionsAction, setSpaceTypeAction } from "./app/boardState";
import { store } from "./app/store";
import { ToolbarImages } from "./images";
const {
blueImage,
blue3Image,
redImage,
red3Image,
happeningImage,
happening3Image,
chanceImage,
chance2Image,
chance3Image,
bowserImage,
bowser3Image,
minigameImage,
shroomImage,
otherImage,
starImage,
blackstarImage,
arrowImage,
startImage,
itemImage,
item3Image,
battleImage,
battle3Image,
bankImage,
bank3Image,
gameguyImage,
banksubtypeImage,
banksubtype2Image,
bankcoinsubtypeImage,
itemshopsubtypeImage,
itemshopsubtype2Image,
toadImage,
mstarImage,
booImage,
bowsercharacterImage,
koopaImage,
} = ToolbarImages;
let _globalHandler: any;
interface IRightClickMenuProps {
space?: ISpace | null;
spaceIndex: number;
}
interface IRightClickMenuState {
oldX?: number;
oldY?: number;
}
export class RightClickMenu extends React.Component<IRightClickMenuProps, IRightClickMenuState> {
state: IRightClickMenuState = {}
private rcMenu: any;
componentDidMount() {
//console.log("RightClickMenu.componentDidMount");
_globalHandler = this.globalClickHandler.bind(this);
document.addEventListener("click", _globalHandler);
}
componentWillUnmount() {
//console.log("RightClickMenu.componentWillUnmount");
document.removeEventListener("click", _globalHandler);
_globalHandler = null;
}
globalClickHandler = (event: any) => {
// console.log("globalClickHandler", event);
// If we click inside the menu, don't close obviously.
// But also let the canvas handlers decide what happens if they are clicked.
if (this.elementIsWithin(event.target) || event.target.tagName.toUpperCase() === "CANVAS")
return;
updateRightClickMenu(-1);
}
handleClick = (event: any) => {
event.stopPropagation();
event.nativeEvent.stopImmediatePropagation();
}
onContextMenu = (event: any) => {
event.preventDefault(); // No right click on right click menu.
}
onTypeChanged = (type: Space, subtype?: SpaceSubtype) => {
const spaceIndices = getValidSelectedSpaceIndices();
store.dispatch(setSpaceTypeAction({ spaceIndices, type, subtype }));
this.forceUpdate();
}
getPlacement(space: ISpace) {
let x = (!isNaN(this.state.oldX!) ? this.state.oldX! : space.x) - 8;
let y = (!isNaN(this.state.oldY!) ? this.state.oldY! : space.y) + 15;
return "translateX(" + x + "px) translateY(" + y + "px)";
}
elementIsWithin(el: HTMLElement) {
if (!el || !this.refs || !this.rcMenu)
return true;
return this.rcMenu.contains(el);
}
onChangeX = (event: any) => {
let newX = parseInt(event.target.value, 10);
let isBlank = event.target.value === "";
let curBgWidth = getCurrentBoard().bg.width;
if ((!isBlank && isNaN(newX)) || newX < 0 || newX > curBgWidth)
return;
if (!this.state.oldX)
this.setState({ oldX: this.props.space!.x });
store.dispatch(setSpacePositionsAction({
spaceIndices: [this.props.spaceIndex],
coords: [{
x: isBlank ? 0 : newX
}]
}));
this.forceUpdate();
}
onChangeY = (event: any) => {
let newY = parseInt(event.target.value, 10);
let isBlank = event.target.value === "";
let curBgHeight = getCurrentBoard().bg.height;
if ((!isBlank && isNaN(newY)) || newY < 0 || newY > curBgHeight)
return;
if (!this.state.oldY)
this.setState({ oldY: this.props.space!.y });
store.dispatch(setSpacePositionsAction({
spaceIndices: [this.props.spaceIndex],
coords: [{
y: isBlank ? 0 : newY
}]
}));
this.forceUpdate();
}
onCoordSet = (event?: any) => {
store.dispatch(setSpacePositionsAction({
spaceIndices: [this.props.spaceIndex],
coords: [{
x: this.props.space!.x || 0,
y: this.props.space!.y || 0,
}]
}));
this.setState({ oldX: undefined, oldY: undefined });
this.forceUpdate();
}
onKeyUp = (event: any) => {
if (event.key === "Enter")
this.onCoordSet();
}
render() {
let space = this.props.space;
if (!space)
return null;
let style = { transform: this.getPlacement(space) };
return (
<div ref={(menu) => this.rcMenu = menu} className="rcMenu" style={style}
onClick={this.handleClick}
onContextMenu={this.onContextMenu}>
<span>X:</span>
<input type="text" value={space.x} onChange={this.onChangeX}
onBlur={this.onCoordSet} onKeyUp={this.onKeyUp} />
<span>Y:</span>
<input type="text" value={space.y} onChange={this.onChangeY}
onBlur={this.onCoordSet} onKeyUp={this.onKeyUp} />
<RCSpaceTypeToggle type={space.type} subtype={space.subtype} typeChanged={this.onTypeChanged} />
</div>
);
}
};
interface IRCMenuItem {
name: string;
icon: string;
type?: Space;
subtype?: SpaceSubtype;
advanced?: boolean;
}
const RCSpaceTypeToggleTypes_1: IRCMenuItem[] = [
{ name: "Change to blue space", icon: blueImage, type: Space.BLUE },
{ name: "Change to red space", icon: redImage, type: Space.RED },
{ name: "Change to happening space", icon: happeningImage, type: Space.HAPPENING },
{ name: "Change to chance time space", icon: chanceImage, type: Space.CHANCE },
{ name: "Change to minigame space", icon: minigameImage, type: Space.MINIGAME },
{ name: "Change to shroom space", icon: shroomImage, type: Space.SHROOM },
{ name: "Change to Bowser space", icon: bowserImage, type: Space.BOWSER },
{ name: "Change to invisible space", icon: otherImage, type: Space.OTHER },
{ name: "Change to star space", icon: starImage, type: Space.STAR, advanced: true },
{ name: "Change to start space", icon: startImage, type: Space.START, advanced: true },
];
const RCSpaceTypeToggleSubTypes_1: IRCMenuItem[] = [
{ name: "Show Toad", icon: toadImage, subtype: SpaceSubtype.TOAD },
{ name: "Show Boo", icon: booImage, subtype: SpaceSubtype.BOO },
{ name: "Show Bowser", icon: bowsercharacterImage, subtype: SpaceSubtype.BOWSER },
{ name: "Show Koopa Troopa", icon: koopaImage, subtype: SpaceSubtype.KOOPA },
];
const RCSpaceTypeToggleTypes_2: IRCMenuItem[] = [
{ name: "Change to blue space", icon: blueImage, type: Space.BLUE },
{ name: "Change to red space", icon: redImage, type: Space.RED },
{ name: "Change to happening space", icon: happeningImage, type: Space.HAPPENING },
{ name: "Change to chance time space", icon: chance2Image, type: Space.CHANCE },
{ name: "Change to Bowser space", icon: bowserImage, type: Space.BOWSER },
{ name: "Change to item space", icon: itemImage, type: Space.ITEM },
{ name: "Change to battle space", icon: battleImage, type: Space.BATTLE },
{ name: "Change to bank space", icon: bankImage, type: Space.BANK },
{ name: "Change to invisible space", icon: otherImage, type: Space.OTHER },
{ name: "Change to star space", icon: starImage, type: Space.STAR, advanced: true },
{ name: "Change to black star space", icon: blackstarImage, type: Space.BLACKSTAR, advanced: true },
{ name: "Change to start space", icon: startImage, type: Space.START, advanced: true },
{ name: "Change to arrow space", icon: arrowImage, type: Space.ARROW },
];
const RCSpaceTypeToggleSubTypes_2: IRCMenuItem[] = [
{ name: "Show Toad", icon: toadImage, subtype: SpaceSubtype.TOAD },
{ name: "Show Boo", icon: booImage, subtype: SpaceSubtype.BOO },
{ name: "Show bank", icon: banksubtype2Image, subtype: SpaceSubtype.BANK },
{ name: "Show bank coin stack", icon: bankcoinsubtypeImage, subtype: SpaceSubtype.BANKCOIN },
{ name: "Show item shop", icon: itemshopsubtype2Image, subtype: SpaceSubtype.ITEMSHOP },
];
const RCSpaceTypeToggleTypes_3: IRCMenuItem[] = [
{ name: "Change to blue space", icon: blue3Image, type: Space.BLUE },
{ name: "Change to red space", icon: red3Image, type: Space.RED },
{ name: "Change to happening space", icon: happening3Image, type: Space.HAPPENING },
{ name: "Change to chance time space", icon: chance3Image, type: Space.CHANCE },
{ name: "Change to Bowser space", icon: bowser3Image, type: Space.BOWSER },
{ name: "Change to item space", icon: item3Image, type: Space.ITEM },
{ name: "Change to battle space", icon: battle3Image, type: Space.BATTLE },
{ name: "Change to bank space", icon: bank3Image, type: Space.BANK },
{ name: "Change to Game Guy space", icon: gameguyImage, type: Space.GAMEGUY },
{ name: "Change to invisible space", icon: otherImage, type: Space.OTHER },
{ name: "Change to star space", icon: starImage, type: Space.STAR, advanced: true },
{ name: "Change to start space", icon: startImage, type: Space.START, advanced: true },
{ name: "Change to arrow space", icon: arrowImage, type: Space.ARROW },
];
const RCSpaceTypeToggleSubTypes_3: IRCMenuItem[] = [
{ name: "Show Millenium Star", icon: mstarImage, subtype: SpaceSubtype.TOAD },
{ name: "Show Boo", icon: booImage, subtype: SpaceSubtype.BOO },
{ name: "Show bank", icon: banksubtypeImage, subtype: SpaceSubtype.BANK },
{ name: "Show bank coin stack", icon: bankcoinsubtypeImage, subtype: SpaceSubtype.BANKCOIN },
{ name: "Show item shop", icon: itemshopsubtypeImage, subtype: SpaceSubtype.ITEMSHOP },
];
const RCSpaceTypeToggleTypes_3_Duel: IRCMenuItem[] = [
// Types
{ name: "Change to basic space", icon: basic3Image, type: Space.DUEL_BASIC },
{ name: "Change to Mini-Game space", icon: minigameduel3Image, type: Space.MINIGAME },
{ name: "Change to reverse space", icon: reverse3Image, type: Space.DUEL_REVERSE },
{ name: "Change to happening space", icon: happeningduel3Image, type: Space.HAPPENING },
{ name: "Change to Game Guy space", icon: gameguyduelImage, type: Space.GAMEGUY },
{ name: "Change to power-up space", icon: powerupImage, type: Space.DUEL_POWERUP },
{ name: "Change to invisible space", icon: otherImage, type: Space.OTHER },
{ name: "Change to blue start space", icon: startblueImage, type: Space.DUEL_START_BLUE, advanced: true },
{ name: "Change to red start space", icon: startredImage, type: Space.DUEL_START_RED, advanced: true },
];
function _getRCSpaceTypeToggles() {
const curBoard = getCurrentBoard();
let types: IRCMenuItem[] = [];
switch (curBoard.game) {
case 1:
types = RCSpaceTypeToggleTypes_1;
break;
case 2:
types = RCSpaceTypeToggleTypes_2;
break;
case 3:
switch (curBoard.type) {
case BoardType.DUEL:
types = RCSpaceTypeToggleTypes_3_Duel;
break;
case BoardType.NORMAL:
default:
types = RCSpaceTypeToggleTypes_3;
break;
}
break;
}
if (!get($setting.uiAdvanced)) {
types = types.filter(a => !a.advanced);
}
return types;
}
function _getRCSpaceSubTypeToggles() {
const curBoard = getCurrentBoard();
let types: IRCMenuItem[] = [];
switch (curBoard.game) {
case 1:
types = RCSpaceTypeToggleSubTypes_1;
break;
case 2:
types = RCSpaceTypeToggleSubTypes_2;
break;
case 3:
switch (curBoard.type) {
case BoardType.DUEL:
types = []; // SpaceSubTypeToggleTypes_3_Duel;
break;
default:
types = RCSpaceTypeToggleSubTypes_3;
break;
}
break;
}
if (!get($setting.uiAdvanced)) {
types = types!.filter((a: IRCMenuItem) => !a.advanced);
}
return types;
}
interface IRCSpaceTypeToggleProps {
type: Space;
subtype?: SpaceSubtype;
typeChanged: (type: Space, subtype?: SpaceSubtype) => any;
}
const RCSpaceTypeToggle = class RCSpaceTypeToggle extends React.Component<IRCSpaceTypeToggleProps> {
onTypeChanged = (type: Space, subtype?: SpaceSubtype) => {
this.props.typeChanged(type, subtype);
}
render() {
let type = this.props.type;
if (type === Space.START && !get($setting.uiAdvanced))
return null; // Can't switch start space type
let subtype = this.props.subtype;
let onTypeChanged = this.onTypeChanged;
let makeToggle = (item: any) => {
let key = item.type + "-" + item.subtype;
let selected = type === item.type || (type === Space.OTHER && subtype !== undefined && subtype === item.subtype);
//if (type !== Space.OTHER && item.subtype !== undefined)
// return null;
return (
<RCSpaceTypeToggleBtn key={key} type={item.type} subtype={item.subtype}
icon={item.icon} title={item.name} selected={selected} typeChanged={onTypeChanged} />
);
};
let typeToggles = _getRCSpaceTypeToggles()!.map(makeToggle);
let subTypeToggles = _getRCSpaceSubTypeToggles()!.map(makeToggle);
return (
<div className="rcSpaceToggleContainer">
{typeToggles}
<br />
{subTypeToggles}
</div>
);
}
};
interface IRCSpaceTypeToggleBtnProps {
type: Space;
subtype: SpaceSubtype;
selected?: boolean;
icon?: string;
title?: string;
typeChanged: (type: Space, subtype?: SpaceSubtype) => any;
}
const RCSpaceTypeToggleBtn = class RCSpaceTypeToggleBtn extends React.Component<IRCSpaceTypeToggleBtnProps> {
onTypeChanged = () => {
if (this.props.subtype !== undefined && this.props.selected)
this.props.typeChanged(this.props.type, undefined);
else
this.props.typeChanged(this.props.type, this.props.subtype);
}
render() {
let btnClass = "rcSpaceToggleButton";
if (this.props.selected)
btnClass += " selected";
let size = this.props.subtype !== undefined ? 25 : 20;
return (
<div className={btnClass} title={this.props.title} onClick={this.onTypeChanged}>
<img src={this.props.icon} height={size} width={size} alt="" />
</div>
);
}
}; | the_stack |
import React from "react"
import makeStyles from "@material-ui/core/styles/makeStyles"
import Typography from "@material-ui/core/Typography"
import TextField from "@material-ui/core/TextField"
import IconButton from "@material-ui/core/IconButton"
import Tooltip from "@material-ui/core/Tooltip"
import Autocomplete from "@material-ui/lab/Autocomplete"
import Refresh from "@material-ui/icons/Refresh"
import LinkedTextField from "@/components/LinkedTextField"
import LabeledCheckbox from "@/components/LabeledCheckbox"
import Grid from "@material-ui/core/Grid"
import Switch from "@material-ui/core/Switch"
import ExternalLink from "@/components/ExternalLink"
import { Url } from "@/constants"
import WithHelpText from "@/components/WithHelpText"
import useFormStyles from "@/hooks/useFormStyles"
import useEvent from "./useEvent"
import Parameters from "./Parameters"
import useInputs from "./useInputs"
import { Category, ClientIds, EventType, InstanceId, Parameter } from "./types"
import { eventsForCategory } from "./event"
import useUserProperties from "./useUserProperties"
import Items from "./Items"
import ValidateEvent from "./ValidateEvent"
export enum Label {
APISecret = "api_secret",
FirebaseAppID = "firebase_app_id",
AppInstanceID = "app_instance_id",
MeasurementID = "measurement_id",
ClientID = "client_id",
UserId = "user_id",
EventCategory = "event_category",
EventName = "event_name",
TimestampMicros = "timestamp_micros",
NonPersonalizedAds = "non_personalized_ads",
Payload = "payload",
}
const ga4MeasurementProtocol = (
<ExternalLink href={Url.ga4MeasurementProtocol}>
GA4 Measurement Protocol
</ExternalLink>
)
const useStyles = makeStyles(theme => ({
clientSwitch: {
marginBottom: theme.spacing(2),
},
unifiedParameters: {},
fullWidth: {
width: "100%",
},
parameterPair: {
display: "flex",
"& > *:not(:first-child)": {
marginLeft: theme.spacing(1),
},
},
validateHeading: {
marginTop: theme.spacing(3),
},
parameters: {
"&> :not(:first-child)": {
marginTop: theme.spacing(1),
},
},
items: {
"&> :not(:first-child)": {
marginTop: theme.spacing(3),
},
"&> :last-child": {
marginTop: theme.spacing(1),
},
},
}))
export const EventCtx = React.createContext<
| {
eventName: string
type: EventType
parameters: Parameter[]
items: Parameter[][] | undefined
userProperties: Parameter[]
timestamp_micros: string | undefined
non_personalized_ads: boolean | undefined
clientIds: ClientIds
instanceId: InstanceId
api_secret: string
}
| undefined
>(undefined)
export const ShowAdvancedCtx = React.createContext(false)
export const UseFirebaseCtx = React.createContext(false)
const EventBuilder: React.FC = () => {
const formClasses = useFormStyles()
const classes = useStyles()
const [showAdvanced, setShowAdvanced] = React.useState(false)
const {
userProperties,
addNumberUserProperty,
addStringUserProperty,
removeUserProperty,
setUserPropertyName,
setUserPopertyValue,
} = useUserProperties()
const {
parameters,
items,
type,
setType,
eventName,
setEventName,
setParamName,
setParamValue,
addStringParam,
addNumberParam,
setItemParamName,
setItemParamValue,
removeParam,
addItem,
removeItem,
addItemsParam,
addItemNumberParam,
addItemStringParam,
removeItemParam,
removeItems,
categories,
} = useEvent()
const {
useFirebase,
setUseFirebase,
category,
setCategory,
api_secret,
setAPISecret,
firebase_app_id,
setFirebaseAppId,
app_instance_id,
setAppInstanceId,
measurement_id,
setMeasurementId,
client_id,
setClientId,
user_id,
setUserId,
timestamp_micros,
setTimestampMicros,
non_personalized_ads,
setNonPersonalizedAds,
} = useInputs(categories)
return (
<div>
<Typography variant="h3">Overview</Typography>
<Typography>
The GA4 Event Builder allows you to create, validate, and send events
using the {ga4MeasurementProtocol}.
</Typography>
<Typography variant="h4">Usage</Typography>
<Typography>
First, choose the client you are using with the toggle below. Mobile
implementations should use firebase, and web implementations should use
gtag.js
</Typography>
<WithHelpText
notched
shrink
label="client"
className={classes.clientSwitch}
>
<Grid component="label" container alignItems="center" spacing={1}>
<Grid item>gtag.js</Grid>
<Grid item>
<Switch
data-testid="use firebase"
checked={useFirebase}
onChange={e => {
setUseFirebase(e.target.checked)
}}
name="use firebase"
color="primary"
/>
</Grid>
<Grid item>firebase</Grid>
</Grid>
</WithHelpText>
<Typography>
After choosing a client, fill out the inputs below.
</Typography>
<section className={formClasses.form}>
<LinkedTextField
required
href="https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference#api_secret"
linkTitle="See api_secret on devsite."
value={api_secret || ""}
label={Label.APISecret}
id={Label.APISecret}
helperText="The API secret for the property to send the event to."
onChange={setAPISecret}
/>
{useFirebase ? (
<>
<LinkedTextField
required
href="https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference?client_type=firebase#firebase_app_id"
linkTitle="See firebase_app_id on devsite."
value={firebase_app_id || ""}
label={Label.FirebaseAppID}
id={Label.FirebaseAppID}
helperText="The identifier for your firebase app."
onChange={setFirebaseAppId}
/>
<LinkedTextField
required
href="https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference?client_type=firebase#app_instance_id"
linkTitle="See app_instance_id on devsite."
value={app_instance_id || ""}
label={Label.AppInstanceID}
id={Label.AppInstanceID}
helperText="The unique identifier for a specific Firebase installation."
onChange={setAppInstanceId}
/>
</>
) : (
<>
<LinkedTextField
required
href="https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference?client_type=gtag#measurement_id"
linkTitle="See measurement_id on devsite."
value={measurement_id || ""}
label={Label.MeasurementID}
id={Label.MeasurementID}
helperText="The identifier for your data stream."
onChange={setMeasurementId}
/>
<LinkedTextField
required
href="https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference?client_type=gtag#client_id"
linkTitle="See client_id on devsite."
value={client_id || ""}
label={Label.ClientID}
id={Label.ClientID}
helperText="The unique identifier for an instance of a web client."
onChange={setClientId}
/>
</>
)}
<LinkedTextField
href={`https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference?client_type=${
useFirebase ? "firebase" : "gtag"
}#user_id`}
linkTitle="See user_id on devsite."
value={user_id || ""}
label={Label.UserId}
id={Label.UserId}
helperText="The unique identifier for a given user."
onChange={setUserId}
/>
<Autocomplete<Category, false, true, true>
data-testid={Label.EventCategory}
fullWidth
disableClearable
autoComplete
autoHighlight
autoSelect
options={Object.values(Category)}
getOptionLabel={category => category}
value={category}
onChange={(_event, value) => {
setCategory(value as Category)
const events = eventsForCategory(value as Category)
if (events.length > 0) {
setType(events[0].type)
}
}}
renderInput={params => (
<TextField
{...params}
label={Label.EventCategory}
id={Label.EventCategory}
size="small"
variant="outlined"
helperText="The category for the event"
/>
)}
/>
{type === EventType.CustomEvent ? (
<TextField
fullWidth
variant="outlined"
size="small"
label={Label.EventName}
id={Label.EventName}
value={eventName}
helperText="The name of the event"
onChange={e => {
setEventName(e.target.value)
}}
/>
) : (
<Autocomplete<EventType, false, true, true>
data-testid={Label.EventName}
fullWidth
disableClearable
autoComplete
autoHighlight
autoSelect
options={eventsForCategory(category).map(e => e.type)}
getOptionLabel={eventType => eventType}
value={type}
onChange={(_event, value) => {
setType(value as EventType)
}}
renderInput={params => (
<TextField
{...params}
label={Label.EventName}
id={Label.EventName}
size="small"
variant="outlined"
helperText={
<>
The name of the event. See{" "}
<ExternalLink
href={`https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference/events#${type}`}
>
{type}
</ExternalLink>{" "}
on devsite.
</>
}
/>
)}
/>
)}
<LinkedTextField
label={Label.TimestampMicros}
id={Label.TimestampMicros}
linkTitle="See timestamp_micros on devsite."
href={`https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference?client_type=${
useFirebase ? "firebase" : "gtag"
}#timestamp_micros`}
value={timestamp_micros || ""}
onChange={setTimestampMicros}
helperText="The timestamp of the event."
extraAction={
<Tooltip title="Set to now.">
<IconButton
size="small"
onClick={() => {
setTimestampMicros((new Date().getTime() * 1000).toString())
}}
>
<Refresh />
</IconButton>
</Tooltip>
}
/>
<WithHelpText
helpText={
<>
Check to indicate events should not be used for personalized ads.
See{" "}
<ExternalLink
href={`https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference?client_type=${
useFirebase ? "firebase" : "gtag"
}#non_personalized_ads`}
>
non_personalized_ads
</ExternalLink>{" "}
on devsite.
</>
}
>
<LabeledCheckbox
checked={non_personalized_ads}
setChecked={setNonPersonalizedAds}
id={Label.NonPersonalizedAds}
>
{Label.NonPersonalizedAds}
</LabeledCheckbox>
</WithHelpText>
</section>
<Typography variant="h4">Event details</Typography>
<Typography>
Finally, specify the parameters to send with the event. By default, only
recommended parameters for the event will appear here. Check "show
advanced options" to add custom parameters or user properties.
</Typography>
<LabeledCheckbox checked={showAdvanced} onChange={setShowAdvanced}>
show advanced options
</LabeledCheckbox>
<section className={formClasses.form}>
<ShowAdvancedCtx.Provider
value={showAdvanced || type === EventType.CustomEvent}
>
<Typography variant="h5">Parameters</Typography>
<Parameters
removeParam={removeParam}
parameters={parameters}
addStringParam={addStringParam}
addNumberParam={addNumberParam}
setParamName={setParamName}
setParamValue={setParamValue}
addItemsParam={items === undefined ? addItemsParam : undefined}
/>
{items !== undefined && (
<>
<Typography variant="h5">Items</Typography>
<Items
items={items}
addItem={addItem}
removeItem={removeItem}
removeItemParam={removeItemParam}
addItemNumberParam={addItemNumberParam}
addItemStringParam={addItemStringParam}
setItemParamName={setItemParamName}
setItemParamValue={setItemParamValue}
removeItems={removeItems}
/>
</>
)}
{(showAdvanced ||
(userProperties !== undefined && userProperties.length !== 0)) && (
<>
<Typography variant="h5">User properties</Typography>
<Parameters
removeParam={removeUserProperty}
parameters={userProperties}
addStringParam={addStringUserProperty}
addNumberParam={addNumberUserProperty}
setParamName={setUserPropertyName}
setParamValue={setUserPopertyValue}
/>
</>
)}
</ShowAdvancedCtx.Provider>
</section>
<Typography variant="h3" className={classes.validateHeading}>
Validate & Send event
</Typography>
<UseFirebaseCtx.Provider value={useFirebase}>
<EventCtx.Provider
value={{
type,
clientIds: useFirebase
? { app_instance_id, user_id }
: { client_id, user_id },
items,
parameters,
eventName,
userProperties,
timestamp_micros,
non_personalized_ads,
instanceId: useFirebase ? { firebase_app_id } : { measurement_id },
api_secret: api_secret!,
}}
>
<ValidateEvent
client_id={client_id || ""}
user_id={user_id || ""}
api_secret={api_secret || ""}
measurement_id={measurement_id || ""}
app_instance_id={app_instance_id || ""}
firebase_app_id={firebase_app_id || ""}
/>
</EventCtx.Provider>
</UseFirebaseCtx.Provider>
</div>
)
}
export default EventBuilder | the_stack |
import {
Component,
Input,
OnInit,
OnChanges,
OnDestroy,
SimpleChange,
ViewChildren,
QueryList,
Type,
ElementRef,
} from '@angular/core';
import { CoreDomUtils } from '@services/utils/dom';
import { CoreDynamicComponent } from '@components/dynamic-component/dynamic-component';
import { CoreCourseAnyCourseData } from '@features/courses/services/courses';
import {
CoreCourse,
CoreCourseModuleCompletionStatus,
CoreCourseProvider,
} from '@features/course/services/course';
import {
CoreCourseHelper,
CoreCourseSection,
} from '@features/course/services/course-helper';
import { CoreCourseFormatDelegate } from '@features/course/services/format-delegate';
import { CoreEventObserver, CoreEvents } from '@singletons/events';
import { IonContent, IonRefresher } from '@ionic/angular';
import { CoreUtils } from '@services/utils/utils';
import { CoreCourseCourseIndexComponent, CoreCourseIndexSectionWithModule } from '../course-index/course-index';
import { CoreBlockHelper } from '@features/block/services/block-helper';
import { CoreNavigator } from '@services/navigator';
import { CoreCourseModuleDelegate } from '@features/course/services/module-delegate';
import { CoreCourseViewedModulesDBRecord } from '@features/course/services/database/course';
import { CoreUserToursAlignment, CoreUserToursSide } from '@features/usertours/services/user-tours';
import { CoreCourseCourseIndexTourComponent } from '../course-index-tour/course-index-tour';
import { CoreDom } from '@singletons/dom';
import { CoreUserTourDirectiveOptions } from '@directives/user-tour';
/**
* Component to display course contents using a certain format. If the format isn't found, use default one.
*
* The inputs of this component will be shared with the course format components. Please use CoreCourseFormatDelegate
* to register your handler for course formats.
*
* Example usage:
*
* <core-course-format [course]="course" [sections]="sections"></core-course-format>
*/
@Component({
selector: 'core-course-format',
templateUrl: 'course-format.html',
styleUrls: ['course-format.scss'],
})
export class CoreCourseFormatComponent implements OnInit, OnChanges, OnDestroy {
static readonly LOAD_MORE_ACTIVITIES = 20; // How many activities should load each time showMoreActivities is called.
@Input() course!: CoreCourseAnyCourseData; // The course to render.
@Input() sections: CoreCourseSectionToDisplay[] = []; // List of course sections.
@Input() initialSectionId?: number; // The section to load first (by ID).
@Input() initialSectionNumber?: number; // The section to load first (by number).
@Input() moduleId?: number; // The module ID to scroll to. Must be inside the initial selected section.
@ViewChildren(CoreDynamicComponent) dynamicComponents?: QueryList<CoreDynamicComponent>;
// All the possible component classes.
courseFormatComponent?: Type<unknown>;
courseSummaryComponent?: Type<unknown>;
singleSectionComponent?: Type<unknown>;
allSectionsComponent?: Type<unknown>;
canLoadMore = false;
showSectionId = 0;
data: Record<string, unknown> = {}; // Data to pass to the components.
courseIndexTour: CoreUserTourDirectiveOptions = {
id: 'course-index',
component: CoreCourseCourseIndexTourComponent,
side: CoreUserToursSide.Top,
alignment: CoreUserToursAlignment.End,
getFocusedElement: nativeButton => {
const innerButton = Array.from(nativeButton.shadowRoot?.children ?? []).find(child => child.tagName === 'BUTTON');
return innerButton as HTMLElement ?? nativeButton;
},
};
displayCourseIndex = false;
displayBlocks = false;
hasBlocks = false;
selectedSection?: CoreCourseSection;
previousSection?: CoreCourseSection;
nextSection?: CoreCourseSection;
allSectionsId: number = CoreCourseProvider.ALL_SECTIONS_ID;
stealthModulesSectionId: number = CoreCourseProvider.STEALTH_MODULES_SECTION_ID;
loaded = false;
highlighted?: string;
lastModuleViewed?: CoreCourseViewedModulesDBRecord;
viewedModules: Record<number, boolean> = {};
completionStatusIncomplete = CoreCourseModuleCompletionStatus.COMPLETION_INCOMPLETE;
protected selectTabObserver?: CoreEventObserver;
protected modViewedObserver?: CoreEventObserver;
protected lastCourseFormat?: string;
protected viewedModulesInitialized = false;
constructor(
protected content: IonContent,
protected elementRef: ElementRef,
) {
// Pass this instance to all components so they can use its methods and properties.
this.data.coreCourseFormatComponent = this;
}
/**
* @inheritdoc
*/
ngOnInit(): void {
if (this.course === undefined) {
CoreDomUtils.showErrorModal('Course not set');
CoreNavigator.back();
return;
}
// Listen for select course tab events to select the right section if needed.
this.selectTabObserver = CoreEvents.on(CoreEvents.SELECT_COURSE_TAB, (data) => {
if (data.name) {
return;
}
let section: CoreCourseSection | undefined;
if (data.sectionId !== undefined && this.sections) {
section = this.sections.find((section) => section.id == data.sectionId);
} else if (data.sectionNumber !== undefined && this.sections) {
section = this.sections.find((section) => section.section == data.sectionNumber);
}
if (section) {
this.sectionChanged(section);
}
});
this.modViewedObserver = CoreEvents.on(CoreEvents.COURSE_MODULE_VIEWED, (data) => {
if (data.courseId !== this.course.id) {
return;
}
this.viewedModules[data.cmId] = true;
if (!this.lastModuleViewed || data.timeaccess > this.lastModuleViewed.timeaccess) {
this.lastModuleViewed = data;
if (this.selectedSection && this.selectedSection.id !== this.allSectionsId) {
// Change section to display the one with the last viewed module
const lastViewedSection = this.getViewedModuleSection(this.sections, data);
if (lastViewedSection && lastViewedSection.id !== this.selectedSection?.id) {
this.sectionChanged(lastViewedSection, data.cmId);
}
}
}
});
}
/**
* Detect changes on input properties.
*/
async ngOnChanges(changes: { [name: string]: SimpleChange }): Promise<void> {
this.setInputData();
if (changes.course && this.course) {
// Course has changed, try to get the components.
this.getComponents();
this.displayCourseIndex = CoreCourseFormatDelegate.displayCourseIndex(this.course);
this.displayBlocks = CoreCourseFormatDelegate.displayBlocks(this.course);
this.hasBlocks = await CoreBlockHelper.hasCourseBlocks(this.course.id);
}
if (changes.sections && this.sections) {
this.treatSections(this.sections);
}
}
/**
* Set the input data for components.
*/
protected setInputData(): void {
this.data.course = this.course;
this.data.sections = this.sections;
this.data.initialSectionId = this.initialSectionId;
this.data.initialSectionNumber = this.initialSectionNumber;
this.data.moduleId = this.moduleId;
}
/**
* Get the components classes.
*/
protected async getComponents(): Promise<void> {
if (!this.course || this.course.format == this.lastCourseFormat) {
return;
}
// Format has changed or it's the first time, load all the components.
this.lastCourseFormat = this.course.format;
this.highlighted = CoreCourseFormatDelegate.getSectionHightlightedName(this.course);
const currentSectionData = await CoreCourseFormatDelegate.getCurrentSection(this.course, this.sections);
currentSectionData.section.highlighted = true;
await Promise.all([
this.loadCourseFormatComponent(),
this.loadCourseSummaryComponent(),
this.loadSingleSectionComponent(),
this.loadAllSectionsComponent(),
]);
}
/**
* Load course format component.
*
* @return Promise resolved when done.
*/
protected async loadCourseFormatComponent(): Promise<void> {
this.courseFormatComponent = await CoreCourseFormatDelegate.getCourseFormatComponent(this.course);
}
/**
* Load course summary component.
*
* @return Promise resolved when done.
*/
protected async loadCourseSummaryComponent(): Promise<void> {
this.courseSummaryComponent = await CoreCourseFormatDelegate.getCourseSummaryComponent(this.course);
}
/**
* Load single section component.
*
* @return Promise resolved when done.
*/
protected async loadSingleSectionComponent(): Promise<void> {
this.singleSectionComponent = await CoreCourseFormatDelegate.getSingleSectionComponent(this.course);
}
/**
* Load all sections component.
*
* @return Promise resolved when done.
*/
protected async loadAllSectionsComponent(): Promise<void> {
this.allSectionsComponent = await CoreCourseFormatDelegate.getAllSectionsComponent(this.course);
}
/**
* Treat received sections.
*
* @param sections Sections to treat.
* @return Promise resolved when done.
*/
protected async treatSections(sections: CoreCourseSection[]): Promise<void> {
const hasAllSections = sections[0].id == CoreCourseProvider.ALL_SECTIONS_ID;
const hasSeveralSections = sections.length > 2 || (sections.length == 2 && !hasAllSections);
await this.initializeViewedModules();
if (this.selectedSection) {
const selectedSection = this.selectedSection;
// We have a selected section, but the list has changed. Search the section in the list.
let newSection = sections.find(section => this.compareSections(section, selectedSection));
if (!newSection) {
// Section not found, calculate which one to use.
const currentSectionData = await CoreCourseFormatDelegate.getCurrentSection(this.course, sections);
newSection = currentSectionData.section;
}
this.sectionChanged(newSection);
return;
}
// There is no selected section yet, calculate which one to load.
if (!hasSeveralSections) {
// Always load "All sections" to display the section title. If it isn't there just load the section.
this.loaded = true;
this.sectionChanged(sections[0]);
} else if (this.initialSectionId || this.initialSectionNumber) {
// We have an input indicating the section ID to load. Search the section.
const section = sections.find((section) =>
section.id == this.initialSectionId || (section.section && section.section == this.initialSectionNumber));
// Don't load the section if it cannot be viewed by the user.
if (section && this.canViewSection(section)) {
this.loaded = true;
this.sectionChanged(section);
}
}
if (!this.loaded) {
// No section specified, not found or not visible, load current section or the section with last module viewed.
const currentSectionData = await CoreCourseFormatDelegate.getCurrentSection(this.course, sections);
const lastModuleViewed = this.lastModuleViewed;
let section = currentSectionData.section;
let moduleId: number | undefined;
if (!currentSectionData.forceSelected && lastModuleViewed) {
// Search the section with the last module viewed.
const lastModuleSection = this.getViewedModuleSection(sections, lastModuleViewed);
section = lastModuleSection || section;
moduleId = lastModuleSection ? lastModuleViewed?.cmId : undefined;
} else if (lastModuleViewed && currentSectionData.section.modules.some(module => module.id === lastModuleViewed.cmId)) {
// Last module viewed is inside the highlighted section.
moduleId = lastModuleViewed.cmId;
}
this.loaded = true;
this.sectionChanged(section, moduleId);
}
return;
}
/**
* Initialize viewed modules.
*
* @return Promise resolved when done.
*/
protected async initializeViewedModules(): Promise<void> {
if (this.viewedModulesInitialized) {
return;
}
const viewedModules = await CoreCourse.getViewedModules(this.course.id);
this.viewedModulesInitialized = true;
this.lastModuleViewed = viewedModules[0];
viewedModules.forEach(entry => {
this.viewedModules[entry.cmId] = true;
});
}
/**
* Get the section of a viewed module.
*
* @param sections List of sections.
* @param viewedModule Viewed module.
* @return Section, undefined if not found.
*/
protected getViewedModuleSection(
sections: CoreCourseSection[],
viewedModule: CoreCourseViewedModulesDBRecord,
): CoreCourseSection | undefined {
if (viewedModule.sectionId) {
const lastModuleSection = sections.find(section => section.id === viewedModule.sectionId);
if (lastModuleSection) {
return lastModuleSection;
}
}
// No sectionId or section not found. Search the module.
return sections.find(
section => section.modules.some(module => module.id === viewedModule.cmId),
);
}
/**
* Get selected section ID. If viewing all sections, use current scrolled section.
*
* @return Section ID, undefined if not found.
*/
protected async getSelectedSectionId(): Promise<number | undefined> {
if (this.selectedSection?.id !== this.allSectionsId) {
return this.selectedSection?.id;
}
// Check current scrolled section.
const allSectionElements: NodeListOf<HTMLElement> =
this.elementRef.nativeElement.querySelectorAll('section.core-course-module-list-wrapper');
const scroll = await this.content.getScrollElement();
const containerTop = scroll.getBoundingClientRect().top;
const element = Array.from(allSectionElements).find((element) => {
const position = element.getBoundingClientRect();
// The bottom is inside the container or lower.
return position.bottom >= containerTop;
});
return Number(element?.getAttribute('id')) || undefined;
}
/**
* Display the course index modal.
*/
async openCourseIndex(): Promise<void> {
const selectedId = await this.getSelectedSectionId();
const data = await CoreDomUtils.openModal<CoreCourseIndexSectionWithModule>({
component: CoreCourseCourseIndexComponent,
componentProps: {
course: this.course,
sections: this.sections,
selectedId: selectedId,
},
});
if (!data) {
return;
}
const section = this.sections.find((section) => section.id == data.sectionId);
if (!section) {
return;
}
this.sectionChanged(section);
if (!data.moduleId) {
return;
}
const module = section.modules.find((module) => module.id == data.moduleId);
if (!module) {
return;
}
if (!module.handlerData) {
module.handlerData =
await CoreCourseModuleDelegate.getModuleDataFor(module.modname, module, this.course.id);
}
if (CoreCourseHelper.canUserViewModule(module, section) && module.handlerData?.action) {
module.handlerData.action(data.event, module, module.course);
}
this.moduleId = data.moduleId;
}
/**
* Open course downloads page.
*/
async gotoCourseDownloads(): Promise<void> {
const selectedId = await this.getSelectedSectionId();
CoreNavigator.navigateToSitePath(
`storage/${this.course.id}`,
{
params: {
title: this.course.fullname,
sectionId: selectedId,
},
},
);
}
/**
* Function called when selected section changes.
*
* @param newSection The new selected section.
* @param moduleId The module to scroll to.
*/
sectionChanged(newSection: CoreCourseSection, moduleId?: number): void {
const previousValue = this.selectedSection;
this.selectedSection = newSection;
this.data.section = this.selectedSection;
if (newSection.id != this.allSectionsId) {
// Select next and previous sections to show the arrows.
const i = this.sections.findIndex((value) => this.compareSections(value, newSection));
let j: number;
for (j = i - 1; j >= 1; j--) {
if (this.canViewSection(this.sections[j])) {
break;
}
}
this.previousSection = j >= 1 ? this.sections[j] : undefined;
for (j = i + 1; j < this.sections.length; j++) {
if (this.canViewSection(this.sections[j])) {
break;
}
}
this.nextSection = j < this.sections.length ? this.sections[j] : undefined;
} else {
this.previousSection = undefined;
this.nextSection = undefined;
this.canLoadMore = false;
this.showSectionId = 0;
this.showMoreActivities();
}
// Scroll to module if needed. Give more priority to the input.
const moduleIdToScroll = this.moduleId && previousValue === undefined ? this.moduleId : moduleId;
if (moduleIdToScroll) {
this.scrollToModule(moduleIdToScroll);
}
if (!previousValue || previousValue.id !== newSection.id) {
// First load or section changed.
if (!moduleIdToScroll) {
this.content.scrollToTop(0);
}
CoreUtils.ignoreErrors(
CoreCourse.logView(this.course.id, newSection.section, undefined, this.course.fullname),
);
}
}
/**
* Scroll to a certain module.
*
* @param moduleId Module ID.
*/
protected scrollToModule(moduleId: number): void {
CoreDom.scrollToElement(
this.elementRef.nativeElement,
'#core-course-module-' + moduleId,
{ addYAxis: -10 },
);
}
/**
* Compare if two sections are equal.
*
* @param section1 First section.
* @param section2 Second section.
* @return Whether they're equal.
*/
compareSections(section1: CoreCourseSection, section2: CoreCourseSection): boolean {
return section1 && section2 ? section1.id === section2.id : section1 === section2;
}
/**
* Refresh the data.
*
* @param refresher Refresher.
* @param done Function to call when done.
* @param afterCompletionChange Whether the refresh is due to a completion change.
* @return Promise resolved when done.
*/
async doRefresh(refresher?: IonRefresher, done?: () => void, afterCompletionChange?: boolean): Promise<void> {
const promises = this.dynamicComponents?.map(async (component) => {
await component.callComponentFunction('doRefresh', [refresher, done, afterCompletionChange]);
}) || [];
if (this.course) {
const courseId = this.course.id;
promises.push(CoreCourse.invalidateCourseBlocks(courseId).then(async () => {
this.hasBlocks = await CoreBlockHelper.hasCourseBlocks(courseId);
return;
}));
}
await Promise.all(promises);
refresher?.complete();
done?.();
}
/**
* Show more activities (only used when showing all the sections at the same time).
*
* @param infiniteComplete Infinite scroll complete function. Only used from core-infinite-loading.
*/
showMoreActivities(infiniteComplete?: () => void): void {
this.canLoadMore = false;
const sections = this.sections || [];
let modulesLoaded = 0;
let i: number;
for (i = this.showSectionId + 1; i < sections.length; i++) {
if (!sections[i].hasContent || !sections[i].modules) {
continue;
}
modulesLoaded += sections[i].modules.reduce((total, module) =>
!CoreCourseHelper.isModuleStealth(module, sections[i]) ? total + 1 : total, 0);
if (modulesLoaded >= CoreCourseFormatComponent.LOAD_MORE_ACTIVITIES) {
break;
}
}
this.showSectionId = i;
this.canLoadMore = i < sections.length;
if (this.canLoadMore) {
// Check if any of the following sections have any content.
let thereAreMore = false;
for (i++; i < sections.length; i++) {
if (sections[i].hasContent && sections[i].modules && sections[i].modules?.length > 0) {
thereAreMore = true;
break;
}
}
this.canLoadMore = thereAreMore;
}
infiniteComplete && infiniteComplete();
}
/**
* @inheritdoc
*/
ngOnDestroy(): void {
this.selectTabObserver?.off();
this.modViewedObserver?.off();
}
/**
* User entered the page that contains the component.
*/
ionViewDidEnter(): void {
this.dynamicComponents?.forEach((component) => {
component.callComponentFunction('ionViewDidEnter');
});
}
/**
* User left the page that contains the component.
*/
ionViewDidLeave(): void {
this.dynamicComponents?.forEach((component) => {
component.callComponentFunction('ionViewDidLeave');
});
}
/**
* Check whether a section can be viewed.
*
* @param section The section to check.
* @return Whether the section can be viewed.
*/
canViewSection(section: CoreCourseSection): boolean {
return CoreCourseHelper.canUserViewSection(section) && !CoreCourseHelper.isSectionStealth(section);
}
}
type CoreCourseSectionToDisplay = CoreCourseSection & {
highlighted?: boolean;
}; | the_stack |
import * as React from 'react'
import { Dialog, DialogContent, DialogFooter } from '../dialog'
import { Row } from '../lib/row'
import { OkCancelButtonGroup } from '../dialog/ok-cancel-button-group'
import { PullRequest } from '../../models/pull-request'
import { Dispatcher } from '../dispatcher'
import { CICheckRunList } from '../check-runs/ci-check-run-list'
import {
IRefCheck,
getLatestPRWorkflowRunsLogsForCheckRun,
getCheckRunActionsWorkflowRuns,
isFailure,
getCheckRunStepURL,
} from '../../lib/ci-checks/ci-checks'
import { Account } from '../../models/account'
import { API, IAPIWorkflowJobStep } from '../../lib/api'
import { Octicon, syncClockwise } from '../octicons'
import * as OcticonSymbol from '../octicons/octicons.generated'
import { Button } from '../lib/button'
import { RepositoryWithGitHubRepository } from '../../models/repository'
import { CICheckRunActionsJobStepList } from '../check-runs/ci-check-run-actions-job-step-list'
import { LinkButton } from '../lib/link-button'
import { encodePathAsUrl } from '../../lib/path'
const PaperStackImage = encodePathAsUrl(__dirname, 'static/paper-stack.svg')
const BlankSlateImage = encodePathAsUrl(
__dirname,
'static/empty-no-pull-requests.svg'
)
interface IPullRequestChecksFailedProps {
readonly dispatcher: Dispatcher
readonly shouldChangeRepository: boolean
readonly accounts: ReadonlyArray<Account>
readonly repository: RepositoryWithGitHubRepository
readonly pullRequest: PullRequest
readonly commitMessage: string
readonly commitSha: string
readonly checks: ReadonlyArray<IRefCheck>
readonly onSubmit: () => void
readonly onDismissed: () => void
}
interface IPullRequestChecksFailedState {
readonly switchingToPullRequest: boolean
readonly selectedCheckID: number
readonly checks: ReadonlyArray<IRefCheck>
readonly loadingActionWorkflows: boolean
readonly loadingActionLogs: boolean
}
/**
* Dialog to show the result of a CI check run.
*/
export class PullRequestChecksFailed extends React.Component<
IPullRequestChecksFailedProps,
IPullRequestChecksFailedState
> {
private checkRunsLoadCancelled: boolean = false
public constructor(props: IPullRequestChecksFailedProps) {
super(props)
const { checks } = this.props
const selectedCheck = checks.find(isFailure) ?? checks[0]
this.state = {
switchingToPullRequest: false,
selectedCheckID: selectedCheck.id,
checks,
loadingActionWorkflows: true,
loadingActionLogs: true,
}
}
private get selectedCheck(): IRefCheck | undefined {
return this.state.checks.find(
check => check.id === this.state.selectedCheckID
)
}
private get loadingChecksInfo(): boolean {
return this.state.loadingActionWorkflows || this.state.loadingActionLogs
}
public render() {
let okButtonTitle = __DARWIN__
? 'Switch to Pull Request'
: 'Switch to pull request'
if (this.props.shouldChangeRepository) {
okButtonTitle = __DARWIN__
? 'Switch to Repository and Pull Request'
: 'Switch to repository and pull request'
}
const { pullRequest } = this.props
const loadingChecksInfo = this.loadingChecksInfo
const failedChecks = this.state.checks.filter(isFailure)
const pluralChecks = failedChecks.length > 1 ? 'checks' : 'check'
const header = (
<div className="ci-check-run-dialog-header">
<Octicon symbol={OcticonSymbol.xCircleFill} />
<div className="title-container">
<div className="summary">
{failedChecks.length} {pluralChecks} failed in your pull request
</div>
<span className="pr-title">
<span className="pr-title">{pullRequest.title}</span>{' '}
<span className="pr-number">#{pullRequest.pullRequestNumber}</span>{' '}
</span>
</div>
{this.renderRerunButton()}
</div>
)
return (
<Dialog
id="pull-request-checks-failed"
type="normal"
title={header}
dismissable={false}
onSubmit={this.props.onSubmit}
onDismissed={this.props.onDismissed}
loading={loadingChecksInfo || this.state.switchingToPullRequest}
>
<DialogContent>
<Row>
<div className="ci-check-run-dialog-container">
<div className="ci-check-run-content">
{this.renderCheckRunJobs()}
{this.renderCheckRunSteps()}
</div>
</div>
</Row>
</DialogContent>
<DialogFooter>
<Row>
{this.renderSummary()}
<OkCancelButtonGroup
onCancelButtonClick={this.props.onDismissed}
cancelButtonText="Dismiss"
okButtonText={okButtonTitle}
onOkButtonClick={this.onSubmit}
/>
</Row>
</DialogFooter>
</Dialog>
)
}
private renderSummary() {
const failedChecks = this.state.checks.filter(isFailure)
const pluralThem = failedChecks.length > 1 ? 'them' : 'it'
return (
<div className="footer-question">
<span>
Do you want to switch to that Pull Request now and start fixing{' '}
{pluralThem}?
</span>
</div>
)
}
private renderCheckRunJobs() {
return (
<CICheckRunList
checkRuns={this.state.checks}
loadingActionLogs={this.state.loadingActionLogs}
loadingActionWorkflows={this.state.loadingActionWorkflows}
selectable={true}
onViewCheckDetails={this.onViewOnGitHub}
onCheckRunClick={this.onCheckRunClick}
/>
)
}
private renderCheckRunSteps() {
const selectedCheck = this.selectedCheck
if (selectedCheck === undefined) {
return null
}
let stepsContent = null
if (this.loadingChecksInfo) {
stepsContent = this.renderCheckRunStepsLoading()
} else if (selectedCheck.actionJobSteps === undefined) {
stepsContent = this.renderEmptyLogOutput()
} else {
stepsContent = (
<CICheckRunActionsJobStepList
steps={selectedCheck.actionJobSteps}
onViewJobStep={this.onViewJobStep}
/>
)
}
return (
<div className="ci-check-run-job-steps-container">{stepsContent}</div>
)
}
private renderCheckRunStepsLoading(): JSX.Element {
return (
<div className="loading-check-runs">
<img src={BlankSlateImage} className="blankslate-image" />
<div className="title">Stand By</div>
<div className="call-to-action">Check run steps incoming!</div>
</div>
)
}
private renderEmptyLogOutput() {
return (
<div className="no-steps-to-display">
<div className="text">
There are no steps to display for this check.
<div>
<LinkButton onClick={this.onViewSelectedCheckRunOnGitHub}>
View check details
</LinkButton>
</div>
</div>
<img src={PaperStackImage} className="blankslate-image" />
</div>
)
}
private onViewJobStep = (step: IAPIWorkflowJobStep): void => {
const { repository, pullRequest, dispatcher } = this.props
const checkRun = this.selectedCheck
if (checkRun === undefined) {
return
}
const url = getCheckRunStepURL(
checkRun,
step,
repository.gitHubRepository,
pullRequest.pullRequestNumber
)
if (url !== null) {
dispatcher.openInBrowser(url)
}
}
public componentDidMount() {
this.loadCheckRunLogs()
}
public componentWillUnmount() {
this.checkRunsLoadCancelled = true
}
private renderRerunButton = () => {
const { checks } = this.state
return (
<div className="ci-check-rerun">
<Button onClick={this.rerunChecks} disabled={checks.length === 0}>
<Octicon symbol={syncClockwise} /> Re-run checks
</Button>
</div>
)
}
private rerunChecks = () => {
this.props.dispatcher.rerequestCheckSuites(
this.props.repository.gitHubRepository,
this.state.checks
)
}
private async loadCheckRunLogs() {
const { pullRequest, repository } = this.props
const { gitHubRepository } = repository
const account = this.props.accounts.find(
a => a.endpoint === gitHubRepository.endpoint
)
if (account === undefined) {
this.setState({
loadingActionWorkflows: false,
loadingActionLogs: false,
})
return
}
const api = API.fromAccount(account)
/*
Until we retrieve the actions workflows, we don't know if a check run has
action logs to output, thus, we want to show loading until then. However,
once the workflows have been retrieved and since the logs retrieval and
parsing can be noticeably time consuming. We go ahead and flip a flag so
that we know we can go ahead and display the checkrun `output` content if
a check run does not have action logs to retrieve/parse.
*/
const checkRunsWithActionsUrls = await getCheckRunActionsWorkflowRuns(
api,
gitHubRepository.owner.login,
gitHubRepository.name,
pullRequest.head.ref,
this.props.checks
)
if (this.checkRunsLoadCancelled) {
return
}
this.setState({
checks: checkRunsWithActionsUrls,
loadingActionWorkflows: false,
})
const checks = await getLatestPRWorkflowRunsLogsForCheckRun(
api,
gitHubRepository.owner.login,
gitHubRepository.name,
checkRunsWithActionsUrls
)
if (this.checkRunsLoadCancelled) {
return
}
this.setState({ checks, loadingActionLogs: false })
}
private onCheckRunClick = (checkRun: IRefCheck): void => {
this.setState({ selectedCheckID: checkRun.id })
}
private onViewSelectedCheckRunOnGitHub = () => {
const selectedCheck = this.selectedCheck
if (selectedCheck !== undefined) {
this.onViewOnGitHub(selectedCheck)
}
}
private onViewOnGitHub = (checkRun: IRefCheck) => {
const { repository, pullRequest, dispatcher } = this.props
// Some checks do not provide htmlURLS like ones for the legacy status
// object as they do not have a view in the checks screen. In that case we
// will just open the PR and they can navigate from there... a little
// dissatisfying tho more of an edgecase anyways.
const url =
checkRun.htmlUrl ??
`${repository.gitHubRepository.htmlURL}/pull/${pullRequest.pullRequestNumber}`
if (url === null) {
// The repository should have a htmlURL.
return
}
dispatcher.openInBrowser(url)
}
private onSubmit = async (event: React.MouseEvent<HTMLButtonElement>) => {
event.preventDefault()
const { dispatcher, repository, pullRequest } = this.props
this.setState({ switchingToPullRequest: true })
await dispatcher.selectRepository(repository)
await dispatcher.checkoutPullRequest(repository, pullRequest)
this.setState({ switchingToPullRequest: false })
this.props.onDismissed()
}
} | the_stack |
'use strict';
import * as vscode from 'vscode';
import * as sinon from 'sinon';
import * as path from 'path';
import * as fs from 'fs-extra';
import * as chai from 'chai';
import * as sinonChai from 'sinon-chai';
import * as chaiAsPromised from 'chai-as-promised';
import { UserInputUtilHelper } from './userInputUtilHelper';
import { ExtensionCommands } from '../../ExtensionCommands';
import { BlockchainGatewayExplorerProvider } from '../../extension/explorer/gatewayExplorer';
import { BlockchainTreeItem } from '../../extension/explorer/model/BlockchainTreeItem';
import { UserInputUtil } from '../../extension/commands/UserInputUtil';
import { FabricEnvironmentRegistry, FabricEnvironmentRegistryEntry, FabricNode, FabricNodeType, FabricWalletRegistry, FabricWalletRegistryEntry, FabricEnvironment, FabricGatewayRegistryEntry, FabricGatewayRegistry } from 'ibm-blockchain-platform-common';
import { ExtensionUtil } from '../../extension/util/ExtensionUtil';
import { EnvironmentFactory } from '../../extension/fabric/environments/EnvironmentFactory';
import { FabricGatewayConnectionManager } from '../../extension/fabric/FabricGatewayConnectionManager';
chai.use(sinonChai);
chai.use(chaiAsPromised);
export class GatewayHelper {
mySandBox: sinon.SinonSandbox;
userInputUtilHelper: UserInputUtilHelper;
constructor(sandbox: sinon.SinonSandbox, userInputUtilHelper: UserInputUtilHelper) {
this.mySandBox = sandbox;
this.userInputUtilHelper = userInputUtilHelper;
}
public async createGateway(name: string, fromEnvironment: boolean, environmentName?: string, mspId?: string, caName?: string): Promise<void> {
const blockchainGatewayExplorerProvider: BlockchainGatewayExplorerProvider = ExtensionUtil.getBlockchainGatewayExplorerProvider();
const treeItems: Array<BlockchainTreeItem> = await blockchainGatewayExplorerProvider.getChildren();
const treeItem: any = treeItems.find((item: any) => {
return item.gateway && item.gateway.name === name;
});
if (!treeItem) {
this.userInputUtilHelper.inputBoxStub.withArgs('Enter a name for the gateway').resolves(name);
if (!fromEnvironment) {
this.userInputUtilHelper.showQuickPickStub.resolves(UserInputUtil.ADD_GATEWAY_FROM_CCP);
this.userInputUtilHelper.browseStub.withArgs('Enter a file path to a connection profile file').resolves(path.join(this.userInputUtilHelper.cucumberDir, 'hlfv1', 'connection.json'));
} else {
this.userInputUtilHelper.showQuickPickStub.resolves(UserInputUtil.ADD_GATEWAY_FROM_ENVIRONMENT);
const fabricEnvironmentRegistryEntry: FabricEnvironmentRegistryEntry = await FabricEnvironmentRegistry.instance().get(environmentName);
this.userInputUtilHelper.showEnvironmentQuickPickStub.resolves({ label: environmentName, data: fabricEnvironmentRegistryEntry });
const environment: FabricEnvironment = EnvironmentFactory.getEnvironment(fabricEnvironmentRegistryEntry);
const nodes: FabricNode[] = await environment.getNodes();
let peerNode: FabricNode;
if (mspId) {
peerNode = nodes.find((_node: FabricNode) => {
return _node.type === FabricNodeType.PEER && _node.msp_id === mspId;
});
} else {
peerNode = nodes.find((_node: FabricNode) => {
return _node.type === FabricNodeType.PEER;
});
}
this.userInputUtilHelper.showOrgQuickPickStub.resolves({ label: peerNode.msp_id, data: peerNode });
let caNode: FabricNode;
if (caName) {
caNode = nodes.find((_node: FabricNode) => {
return _node.type === FabricNodeType.CERTIFICATE_AUTHORITY && _node.name === caName;
});
} else {
caNode = nodes.find((_node: FabricNode) => {
return _node.type === FabricNodeType.CERTIFICATE_AUTHORITY;
});
}
this.userInputUtilHelper.showNodesInEnvironmentQuickPickStub.resolves({ label: caNode.name, data: caNode });
}
await vscode.commands.executeCommand(ExtensionCommands.ADD_GATEWAY);
}
}
public async connectToFabric(name: string, walletName: string, identityName: string = 'greenConga', expectAssociated: boolean = true): Promise<void> {
let gatewayEntry: FabricGatewayRegistryEntry;
gatewayEntry = await FabricGatewayRegistry.instance().get(name);
if (!expectAssociated) {
const walletEntry: FabricWalletRegistryEntry = await FabricWalletRegistry.instance().get(walletName, gatewayEntry.fromEnvironment);
this.userInputUtilHelper.showWalletsQuickPickStub.resolves({
name: walletEntry.name,
data: walletEntry
});
}
this.userInputUtilHelper.showIdentitiesQuickPickStub.withArgs('Choose an identity to connect with').resolves(identityName);
await vscode.commands.executeCommand(ExtensionCommands.CONNECT_TO_GATEWAY, gatewayEntry);
}
public async submitTransaction(name: string, version: string, contractLanguage: string, transaction: string, channel: string, args: string, gatewayName: string, contractName?: string, transientData?: string, evaluate?: boolean, transactionLabel?: string): Promise<void> {
let gatewayEntry: FabricGatewayRegistryEntry;
try {
gatewayEntry = await FabricGatewayConnectionManager.instance().getGatewayRegistryEntry();
} catch (error) {
gatewayEntry = new FabricGatewayRegistryEntry();
gatewayEntry.name = gatewayName;
gatewayEntry.associatedWallet = 'Org1';
}
// If software or saas instance.
if (process.env.OPSTOOLS_FABRIC) {
this.userInputUtilHelper.showChannelFromGatewayQuickPickBoxStub.withArgs('Choose a channel to select a smart contract from').resolves({
label: channel,
data: ['Org1 Peer', 'Org2 Peer']
});
}
if (gatewayEntry.transactionDataDirectories) {
if (transactionLabel !== undefined) {
interface ITransactionData {
transactionName: string;
transactionLabel?: string;
arguments?: string[];
transientData?: any;
}
const txdataFilePath: string = path.join(gatewayEntry.transactionDataDirectories[0].transactionDataPath, 'conga-transactions.txdata');
const fileJson: ITransactionData[] = await fs.readJSON(txdataFilePath);
const chosenTransaction: ITransactionData = fileJson.find((txdata: ITransactionData) => {
return txdata.transactionLabel === transactionLabel;
});
this.userInputUtilHelper.showQuickPickItemStub.withArgs('Do you want to provide a file of transaction data for this transaction?').resolves({
label: txdataFilePath,
description: chosenTransaction.transactionLabel,
data: chosenTransaction
});
} else {
this.userInputUtilHelper.showQuickPickItemStub.withArgs('Do you want to provide a file of transaction data for this transaction?').resolves({
label: 'No (manual entry)',
description: '',
data: undefined
});
}
}
this.userInputUtilHelper.showGatewayQuickPickStub.resolves({
label: gatewayName,
data: gatewayEntry
});
if (contractLanguage === 'Go' || contractLanguage === 'Java') {
this.userInputUtilHelper.showClientInstantiatedSmartContractsStub.resolves({
label: `${name}@${version}`,
data: { name: name, channel: channel, version: version }
});
this.userInputUtilHelper.showTransactionStub.resolves({
label: null,
data: { name: transaction, contract: null }
});
} else {
this.userInputUtilHelper.showClientInstantiatedSmartContractsStub.resolves({
label: `${name}@${version}`,
data: { name: name, channel: channel, version: version }
});
this.userInputUtilHelper.showTransactionStub.resolves({
label: `${name} - ${transaction}`,
data: { name: transaction, contract: contractName }
});
}
this.userInputUtilHelper.inputBoxStub.withArgs('optional: What are the arguments to the transaction, (e.g. ["arg1", "arg2"])').resolves(args);
if (!transientData) {
transientData = '';
}
const transientDataWithoutQuotes: string = transientData.slice(1, -1);
this.userInputUtilHelper.inputBoxStub.withArgs('optional: What is the transient data for the transaction, e.g. {"key": "value"}', '{}').resolves(transientDataWithoutQuotes);
this.userInputUtilHelper.showQuickPickStub.withArgs('Select a peer-targeting policy for this transaction', [UserInputUtil.DEFAULT, UserInputUtil.CUSTOM]).resolves(UserInputUtil.DEFAULT);
if (evaluate) {
await vscode.commands.executeCommand(ExtensionCommands.EVALUATE_TRANSACTION);
} else {
await vscode.commands.executeCommand(ExtensionCommands.SUBMIT_TRANSACTION);
}
}
public async exportConnectionProfile(gatewayName: string): Promise<void> {
const gatewayEntry: FabricGatewayRegistryEntry = await FabricGatewayRegistry.instance().get(gatewayName);
const profilePath: string = path.join(this.userInputUtilHelper.cucumberDir, 'tmp', 'profiles');
await fs.ensureDir(profilePath);
const profileFile: string = path.join(profilePath, `${gatewayEntry.name}_connection.json`);
const profileUri: vscode.Uri = vscode.Uri.file(profileFile);
this.userInputUtilHelper.showSaveDialogStub.withArgs(sinon.match.any).resolves(profileUri);
this.userInputUtilHelper.showGatewayQuickPickStub.resolves({ label: gatewayEntry.name, data: gatewayEntry });
this.userInputUtilHelper.getWorkspaceFoldersStub.callThrough();
await vscode.commands.executeCommand(ExtensionCommands.EXPORT_CONNECTION_PROFILE);
}
public async associateTransactionDataDirectory(name: string, version: string, gatewayName: string): Promise<void> {
let gatewayEntry: FabricGatewayRegistryEntry;
try {
gatewayEntry = await FabricGatewayConnectionManager.instance().getGatewayRegistryEntry();
} catch (error) {
gatewayEntry = new FabricGatewayRegistryEntry();
gatewayEntry.name = gatewayName;
gatewayEntry.associatedWallet = 'Org1';
}
this.userInputUtilHelper.showClientInstantiatedSmartContractsStub.resolves({
label: `${name}@${version}`,
data: { name: name, channel: 'mychannel', version: version }
});
const contractDirectory: string = path.join(__dirname, '..', '..', '..', 'cucumber', 'tmp', 'contracts', name);
const workspaceFolder: vscode.WorkspaceFolder = { index: 0, name: name, uri: vscode.Uri.file(contractDirectory) };
this.userInputUtilHelper.getWorkspaceFoldersStub.returns([workspaceFolder]);
this.userInputUtilHelper.browseWithOptionsStub.resolves({
description: path.join(contractDirectory, 'transaction_data')
});
await vscode.commands.executeCommand(ExtensionCommands.ASSOCIATE_TRANSACTION_DATA_DIRECTORY);
}
} | the_stack |
import * as ts from 'typescript'
import {
ContainerType,
FieldDefinition,
FunctionType,
InterfaceWithFields,
ListType,
MapType,
SetType,
SyntaxType,
} from '@creditkarma/thrift-parser'
import { COMMON_IDENTIFIERS, THRIFT_IDENTIFIERS } from '../identifiers'
import { WRITE_METHODS, WriteMethodName } from './methods'
import { Resolver } from '../../../resolver'
import {
coerceType,
createConstStatement,
createFunctionParameter,
createMethodCall,
createMethodCallStatement,
createNotNullCheck,
getInitializerForField,
isNotVoid,
propertyAccessForIdentifier,
} from '../utils'
import {
createAnyType,
createVoidType,
thriftTypeForFieldType,
typeNodeForFieldType,
} from '../types'
import { DefinitionType, IRenderState, IResolveResult } from '../../../types'
import { looseNameForStruct, throwForField, toolkitName } from './utils'
export function createTempVariables(
node: InterfaceWithFields,
state: IRenderState,
withDefault: boolean = true,
): Array<ts.VariableStatement> {
const structFields: Array<FieldDefinition> = node.fields.filter(
(next: FieldDefinition): boolean => {
return next.fieldType.type !== SyntaxType.VoidKeyword
},
)
if (structFields.length > 0) {
return [
createConstStatement(
COMMON_IDENTIFIERS.obj,
createAnyType(),
ts.createObjectLiteral(
node.fields.map(
(
next: FieldDefinition,
): ts.ObjectLiteralElementLike => {
return ts.createPropertyAssignment(
next.name.value,
getInitializerForField(
COMMON_IDENTIFIERS.args,
next,
state,
withDefault,
true,
),
)
},
),
true, // multiline
),
),
]
} else {
return []
}
}
export function createEncodeMethod(
node: InterfaceWithFields,
state: IRenderState,
): ts.MethodDeclaration {
const tempVariables: Array<ts.VariableStatement> = createTempVariables(
node,
state,
)
return ts.createMethod(
undefined,
undefined,
undefined,
COMMON_IDENTIFIERS.encode,
undefined,
undefined,
[
createFunctionParameter(
COMMON_IDENTIFIERS.args,
ts.createTypeReferenceNode(
ts.createIdentifier(looseNameForStruct(node, state)),
undefined,
),
),
createFunctionParameter(
COMMON_IDENTIFIERS.output,
ts.createTypeReferenceNode(
THRIFT_IDENTIFIERS.TProtocol,
undefined,
),
),
],
createVoidType(),
ts.createBlock(
[
...tempVariables,
writeStructBegin(node.name.value),
...node.fields.filter(isNotVoid).map((field) => {
return createWriteForField(node, field, state)
}),
writeFieldStop(),
writeStructEnd(),
ts.createReturn(),
],
true,
),
)
}
/**
* Write field to output protocol.
*
* If field is required, but not set, throw error.
*
* If field is optional and has a default value write the default if value not set.
*/
export function createWriteForField(
node: InterfaceWithFields,
field: FieldDefinition,
state: IRenderState,
): ts.IfStatement {
const isFieldNull: ts.BinaryExpression = createNotNullCheck(
`obj.${field.name.value}`,
)
const thenWrite: ts.Statement = createWriteForFieldType(
node,
field,
ts.createIdentifier(`obj.${field.name.value}`),
state,
)
const elseThrow: ts.Statement | undefined = throwForField(field)
return ts.createIf(
isFieldNull,
thenWrite, // Then block
elseThrow === undefined ? undefined : ts.createBlock([elseThrow], true),
)
}
/**
* This generates the method calls to write for a single field
*
* EXAMPLE
*
* output.writeFieldBegin("id", Thrift.Type.I32, 1);
* output.writeI32(obj.id);
* output.writeFieldEnd();
*/
export function createWriteForFieldType(
node: InterfaceWithFields,
field: FieldDefinition,
fieldName: ts.Identifier,
state: IRenderState,
): ts.Block {
return ts.createBlock([
writeFieldBegin(field, state),
...writeValueForField(node, field.fieldType, fieldName, state),
writeFieldEnd(),
])
}
export function writeValueForIdentifier(
id: string,
definition: DefinitionType,
node: InterfaceWithFields,
fieldName: ts.Identifier,
state: IRenderState,
): Array<ts.Expression> {
switch (definition.type) {
case SyntaxType.ConstDefinition:
throw new TypeError(
`Identifier[${definition.name.value}] is a value being used as a type`,
)
case SyntaxType.ServiceDefinition:
throw new TypeError(
`Service[${definition.name.value}] is being used as a type`,
)
case SyntaxType.StructDefinition:
case SyntaxType.UnionDefinition:
case SyntaxType.ExceptionDefinition:
return [
createMethodCall(
ts.createIdentifier(toolkitName(id, state)),
'encode',
[fieldName, COMMON_IDENTIFIERS.output],
),
]
case SyntaxType.EnumDefinition:
return [
writeMethodForName(
WRITE_METHODS[SyntaxType.I32Keyword],
fieldName,
),
]
case SyntaxType.TypedefDefinition:
return writeValueForType(
node,
definition.definitionType,
fieldName,
state,
)
default:
const msg: never = definition
throw new Error(`Non-exhaustive match for: ${msg}`)
}
}
export function writeValueForType(
node: InterfaceWithFields,
fieldType: FunctionType,
fieldName: ts.Identifier,
state: IRenderState,
): Array<ts.Expression> {
switch (fieldType.type) {
case SyntaxType.Identifier:
const result: IResolveResult = Resolver.resolveIdentifierDefinition(
fieldType,
{
currentNamespace: state.currentNamespace,
namespaceMap: state.project.namespaces,
},
)
return writeValueForIdentifier(
fieldType.value,
result.definition,
node,
fieldName,
state,
)
/**
* Container types:
*
* SetType | MapType | ListType
*/
case SyntaxType.SetType:
return [
writeSetBegin(fieldType, fieldName, state),
forEach(node, fieldType, fieldName, state),
writeSetEnd(),
]
case SyntaxType.MapType:
return [
writeMapBegin(fieldType, fieldName, state),
forEach(node, fieldType, fieldName, state),
writeMapEnd(),
]
case SyntaxType.ListType:
return [
writeListBegin(fieldType, fieldName, state),
forEach(node, fieldType, fieldName, state),
writeListEnd(),
]
/**
* Base types:
*
* SyntaxType.StringKeyword | SyntaxType.DoubleKeyword | SyntaxType.BoolKeyword |
* SyntaxType.I8Keyword | SyntaxType.I16Keyword | SyntaxType.I32Keyword |
* SyntaxType.I64Keyword | SyntaxType.BinaryKeyword | SyntaxType.ByteKeyword
*/
case SyntaxType.BoolKeyword:
case SyntaxType.BinaryKeyword:
case SyntaxType.StringKeyword:
case SyntaxType.DoubleKeyword:
case SyntaxType.I8Keyword:
case SyntaxType.ByteKeyword:
case SyntaxType.I16Keyword:
case SyntaxType.I32Keyword:
return [
writeMethodForName(WRITE_METHODS[fieldType.type], fieldName),
]
case SyntaxType.I64Keyword:
return [
writeMethodForName(
WRITE_METHODS[fieldType.type],
coerceType(fieldName, fieldType),
),
]
case SyntaxType.VoidKeyword:
return []
default:
const msg: never = fieldType
throw new Error(`Non-exhaustive match for: ${msg}`)
}
}
function writeMethodForName(
methodName: WriteMethodName,
fieldName: ts.Expression,
): ts.CallExpression {
return createMethodCall('output', methodName, [fieldName])
}
export function writeValueForField(
node: InterfaceWithFields,
fieldType: FunctionType,
fieldName: ts.Identifier,
state: IRenderState,
): Array<ts.ExpressionStatement> {
return writeValueForType(node, fieldType, fieldName, state).map(
ts.createStatement,
)
}
/**
* Loop through container types and write the values for all children
*
* EXAMPLE FOR SET
*
* // thrift
* node MyStruct {
* 1: required set<string> field1;
* }
*
* // typescript
* obj.field1.forEach((value_1: string): void => {
* output.writeString(value_1);
* });
*/
function forEach(
node: InterfaceWithFields,
fieldType: ContainerType,
fieldName: ts.Identifier,
state: IRenderState,
): ts.CallExpression {
const value: ts.Identifier = ts.createUniqueName('value')
const forEachParameters: Array<ts.ParameterDeclaration> = [
createFunctionParameter(
value,
typeNodeForFieldType(fieldType.valueType, state, true),
),
]
const forEachStatements: Array<ts.Statement> = [
...writeValueForField(node, fieldType.valueType, value, state),
]
// If map we have to handle key type as well as value type
if (fieldType.type === SyntaxType.MapType) {
const key: ts.Identifier = ts.createUniqueName('key')
forEachParameters.push(
createFunctionParameter(
key,
typeNodeForFieldType(fieldType.keyType, state, true),
),
)
forEachStatements.unshift(
...writeValueForField(node, fieldType.keyType, key, state),
)
}
return createMethodCall(fieldName, 'forEach', [
ts.createArrowFunction(
undefined, // modifiers
undefined, // type parameters
forEachParameters, // parameters
createVoidType(), // return type,
ts.createToken(ts.SyntaxKind.EqualsGreaterThanToken), // greater than equals token
ts.createBlock(forEachStatements, true), // body
),
])
}
// output.writeStructBegin(<structName>)
export function writeStructBegin(structName: string): ts.ExpressionStatement {
return createMethodCallStatement('output', 'writeStructBegin', [
ts.createLiteral(structName),
])
}
// output.writeStructEnd()
export function writeStructEnd(): ts.ExpressionStatement {
return createMethodCallStatement('output', 'writeStructEnd')
}
// output.writeMapBeing(<field.keyType>, <field.valueType>, <field.size>)
export function writeMapBegin(
fieldType: MapType,
fieldName: string | ts.Identifier,
state: IRenderState,
): ts.CallExpression {
return createMethodCall('output', 'writeMapBegin', [
thriftTypeForFieldType(fieldType.keyType, state),
thriftTypeForFieldType(fieldType.valueType, state),
propertyAccessForIdentifier(fieldName, 'size'),
])
}
// output.writeMapEnd()
export function writeMapEnd(): ts.CallExpression {
return createMethodCall('output', 'writeMapEnd')
}
// output.writeListBegin(<field.type>, <field.length>)
export function writeListBegin(
fieldType: ListType,
fieldName: string | ts.Identifier,
state: IRenderState,
): ts.CallExpression {
return createMethodCall('output', 'writeListBegin', [
thriftTypeForFieldType(fieldType.valueType, state),
propertyAccessForIdentifier(fieldName, 'length'),
])
}
// output.writeListEnd()
export function writeListEnd(): ts.CallExpression {
return createMethodCall('output', 'writeListEnd')
}
// output.writeSetBegin(<field.type>, <field.size>)
export function writeSetBegin(
fieldType: SetType,
fieldName: string | ts.Identifier,
state: IRenderState,
): ts.CallExpression {
return createMethodCall('output', 'writeSetBegin', [
thriftTypeForFieldType(fieldType.valueType, state),
propertyAccessForIdentifier(fieldName, 'size'),
])
}
// output.writeSetEnd()
export function writeSetEnd(): ts.CallExpression {
return createMethodCall('output', 'writeSetEnd')
}
// output.writeFieldBegin(<field.name>, <field.fieldType>, <field.fieldID>)
export function writeFieldBegin(
field: FieldDefinition,
state: IRenderState,
): ts.ExpressionStatement {
if (field.fieldID !== null) {
return createMethodCallStatement('output', 'writeFieldBegin', [
ts.createLiteral(field.name.value),
thriftTypeForFieldType(field.fieldType, state),
ts.createLiteral(field.fieldID.value),
])
} else {
throw new Error(`FieldID on line ${field.loc.start.line} is null`)
}
}
// output.writeFieldEnd
export function writeFieldEnd(): ts.ExpressionStatement {
return createMethodCallStatement('output', 'writeFieldEnd')
}
// output.writeFieldStop
export function writeFieldStop(): ts.ExpressionStatement {
return createMethodCallStatement('output', 'writeFieldStop')
} | the_stack |
import { Spreadsheet, DialogBeforeOpenEventArgs, getUpdateUsingRaf } from '../index';
import { applyProtect, protectSheet, protectCellFormat, editAlert, enableFormulaInput, protectWorkbook, keyUp, unProtectSheetPassword, completeAction, setProtectWorkbook, removeWorkbookProtection } from '../common/event';
import { unProtectWorkbook, getPassWord, importProtectWorkbook, UnProtectWorksheet, hideAutoFillElement } from '../common/event';
import { clearCopy, protectSelection, clearUndoRedoCollection, focus, isLockedCells } from '../common/index';
import { Dialog } from '../services/dialog';
import { ListView, SelectedCollection, SelectEventArgs } from '@syncfusion/ej2-lists';
import { L10n, EventHandler, closest, getComponent, isNullOrUndefined } from '@syncfusion/ej2-base';
import { locale, updateToggleItem, dialog } from '../common/index';
import { CheckBox } from '@syncfusion/ej2-buttons';
import { SheetModel } from '../../workbook';
import { CellModel, getSheet, protectsheetHandler, getRangeIndexes } from '../../workbook/index';
import { BeforeOpenEventArgs } from '@syncfusion/ej2-popups';
import { OpenOptions } from '../common/interface';
/**
* The `Protect-sheet` module is used to handle the Protecting functionalities in Spreadsheet.
*/
export class ProtectSheet {
private parent: Spreadsheet;
private dialog: Dialog;
private optionList: ListView;
private password: string = '';
/**
* Constructor for protectSheet module in Spreadsheet.
*
* @param {Spreadsheet} parent - Specify the spreadsheet.
* @private
*/
constructor(parent: Spreadsheet) {
this.parent = parent;
this.init();
}
private init(): void {
this.addEventListener();
}
/**
* To destroy the protectSheet module.
*
* @returns {void} - To destroy the protectSheet module.
* @hidden
*/
public destroy(): void {
this.removeEventListener();
this.parent = null;
}
private addEventListener(): void {
this.parent.on(applyProtect, this.protect, this);
this.parent.on(protectSheet, this.protectSheetHandler, this);
this.parent.on(editAlert, this.editProtectedAlert, this);
this.parent.on(protectWorkbook, this.protectWorkbook, this);
this.parent.on(keyUp, this.KeyUpHandler, this);
this.parent.on(unProtectWorkbook, this.unProtectWorkbook, this);
this.parent.on(UnProtectWorksheet, this.unProtectsheet, this);
this.parent.on(unProtectSheetPassword, this.unProtectSheetPassword, this);
this.parent.on(getPassWord, this.getPassWord, this);
this.parent.on(importProtectWorkbook, this.importProtectWorkbook, this);
this.parent.on(setProtectWorkbook, this.protectWorkbookHandler, this);
this.parent.on(removeWorkbookProtection, this.removeWorkbookProtection, this);
}
private removeEventListener(): void {
if (!this.parent.isDestroyed) {
this.parent.off(applyProtect, this.protect);
this.parent.off(protectSheet, this.protectSheetHandler);
this.parent.off(editAlert, this.editProtectedAlert);
this.parent.off(protectWorkbook, this.protectWorkbook);
this.parent.off(keyUp, this.KeyUpHandler);
this.parent.off(unProtectWorkbook, this.unProtectWorkbook);
this.parent.off(UnProtectWorksheet, this.unProtectsheet);
this.parent.off(unProtectSheetPassword, this.unProtectSheetPassword);
this.parent.off(getPassWord, this.getPassWord);
this.parent.off(importProtectWorkbook, this.importProtectWorkbook);
this.parent.off(setProtectWorkbook, this.protectWorkbookHandler);
this.parent.off(removeWorkbookProtection, this.removeWorkbookProtection);
}
}
private protect(args: { isActive: boolean, sheetIndex: number }): void {
this.parent.notify(clearCopy, null);
if (!args.isActive) {
this.createDialogue();
} else {
this.parent.setSheetPropertyOnMute(getSheet(this.parent, args.sheetIndex), 'isProtected', false);
this.parent.notify(updateToggleItem, { props: 'Protect' });
this.parent.notify(protectSheet, args);
this.parent.notify(protectSelection, null);
}
}
private createDialogue(): void {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
const listData: { [key: string]: Object }[] = [
{ text: l10n.getConstant('SelectCells'), id: '1' },
{ text: l10n.getConstant('SelectUnLockedCells'), id: '6' },
{ text: l10n.getConstant('FormatCells'), id: '2' },
{ text: l10n.getConstant('FormatRows'), id: '3' },
{ text: l10n.getConstant('FormatColumns'), id: '4' },
{ text: l10n.getConstant('InsertLinks'), id: '5' }];
this.optionList = new ListView({
width: '250px',
dataSource: listData,
showCheckBox: true,
select: this.dialogOpen.bind(this)
});
const dialogElem: HTMLElement = this.parent.createElement('div', { className: 'e-sheet-password-dialog' });
const pwdCont: HTMLElement = this.parent.createElement('div', { className: 'e-sheet-password-content' });
const textH: HTMLElement = this.parent.createElement('div', { className: 'e-header', innerHTML: l10n.getConstant('SheetPassword') });
const pwdInput: HTMLElement = this.parent.createElement('input', { className: 'e-input e-text', attrs: { 'type': 'password' } });
pwdInput.setAttribute('placeholder', l10n.getConstant('EnterThePassword'));
pwdCont.appendChild(pwdInput);
pwdCont.insertBefore(textH, pwdInput);
dialogElem.appendChild(pwdCont);
const protectHeaderCntent: HTMLElement = this.parent.createElement('div', {
className: 'e-protect-content',
innerHTML: l10n.getConstant('ProtectAllowUser')
});
this.parent.setSheetPropertyOnMute(this.parent.getActiveSheet(), 'isProtected', false);
const checkbox: CheckBox = new CheckBox({ checked: true, label: l10n.getConstant('ProtectContent'), cssClass: 'e-protect-checkbox' });
const listViewElement: HTMLElement = this.parent.createElement('div', {
className: 'e-protect-option-list',
id: this.parent.element.id + '_option_list'
});
const headerContent: HTMLElement = this.parent.createElement(
'div', { className: 'e-header-content', innerHTML: l10n.getConstant('ProtectSheet') });
const checkBoxElement: HTMLElement = this.parent.createElement(
'input', { id: this.parent.element.id + '_protect_check', attrs: { type: 'checkbox' } });
this.dialog = this.parent.serviceLocator.getService('dialog');
this.dialog.show({
header: headerContent.outerHTML,
content: dialogElem.outerHTML + checkBoxElement.outerHTML + protectHeaderCntent.outerHTML + listViewElement.outerHTML,
showCloseIcon: true, isModal: true,
cssClass: 'e-protect-dlg',
beforeOpen: (args: BeforeOpenEventArgs): void => {
const dlgArgs: DialogBeforeOpenEventArgs = {
dialogName: 'ProtectSheetDialog',
element: args.element, target: args.target, cancel: args.cancel
};
this.parent.trigger('dialogBeforeOpen', dlgArgs);
if (dlgArgs.cancel) {
args.cancel = true;
}
focus(this.parent.element);
},
open: (): void => {
this.okBtnFocus();
},
beforeClose: (): void => {
const checkboxElement: HTMLInputElement = document.getElementById(
this.parent.element.id + '_protect_check') as HTMLInputElement;
EventHandler.remove(checkboxElement, 'focus', this.okBtnFocus);
EventHandler.remove(checkbox.element, 'click', this.checkBoxClickHandler);
focus(this.parent.element);
},
buttons: [{
click: (this.selectOption.bind(this, this.dialog, this)),
buttonModel: { content: l10n.getConstant('Ok'), isPrimary: true }
},
{
click: (this.cancelClick.bind(this, this.dialog, this)),
buttonModel: { content: l10n.getConstant('Cancel')}
}]
}, false);
checkbox.appendTo('#' + this.parent.element.id + '_protect_check');
this.optionList.appendTo('#' + this.parent.element.id + '_option_list');
this.optionList.selectMultipleItems([{ id: '1' }, { id: '6'}]);
EventHandler.add(checkbox.element, 'click', this.checkBoxClickHandler, this);
}
private okBtnFocus(): void {
const checkboxElement: HTMLInputElement = document.getElementById(this.parent.element.id + '_protect_check') as HTMLInputElement;
checkboxElement.addEventListener('focus', (): void => {
this.dialog.dialogInstance.element.getElementsByClassName('e-footer-content')[0].querySelector('button').focus();
});
}
private cancelClick(): void {
const sheetDlgPopup: HTMLElement = document.querySelector('.e-protect-dlg');
const sheetDlg: Dialog = getComponent(sheetDlgPopup, 'dialog');
sheetDlg.destroy();
}
private checkBoxClickHandler(): void {
const ch: HTMLInputElement = document.getElementById(this.parent.element.id + '_protect_check') as HTMLInputElement;
if (ch.checked === false) {
this.dialog.dialogInstance.element.getElementsByClassName('e-footer-content')[0].querySelector('button').disabled = true;
} else {
this.dialog.dialogInstance.element.getElementsByClassName('e-footer-content')[0].querySelector('button').disabled = false;
this.dialog.dialogInstance.element.getElementsByClassName('e-footer-content')[0].querySelector('button').focus();
}
}
private dialogOpen(args: SelectEventArgs): void {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
if (args.text === l10n.getConstant('SelectCells') && args.isChecked && args.isInteracted) {
this.optionList.checkItem( { id: '6' } );
}
if (args.text === l10n.getConstant('SelectUnLockedCells') && !args.isChecked && args.isInteracted) {
this.optionList.uncheckItem( { id: '1' } );
}
this.dialog.dialogInstance.element.getElementsByClassName('e-footer-content')[0].querySelector('button').focus();
}
private selectOption(): void {
const actSheet: SheetModel = this.parent.getActiveSheet();
const pwd: HTMLElement = this.parent.element.querySelector('.e-sheet-password-dialog').
getElementsByClassName('e-sheet-password-content')[0].querySelector('.e-input');
if ((pwd as CellModel).value.length === 0) {
this.parent.setSheetPropertyOnMute(actSheet, 'isProtected', true);
this.parent.setSheetPropertyOnMute(actSheet, 'password', (pwd as CellModel).value);
this.updateProtectSheet((pwd as CellModel).value);
this.dialog.hide();
if (!actSheet.protectSettings.selectCells && !actSheet.protectSettings.selectUnLockedCells) {
this.parent.notify(hideAutoFillElement, null);
} else if (actSheet.protectSettings.selectUnLockedCells &&
isLockedCells(this.parent, getRangeIndexes(actSheet.selectedRange))) {
this.parent.notify(hideAutoFillElement, null);
}
} else {
this.reEnterSheetPassword();
}
}
private selectSheetPassword(): void {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
const actSheet: SheetModel = this.parent.getActiveSheet();
const pwd: HTMLElement = this.parent.element.querySelector('.e-sheet-password-dialog').
getElementsByClassName('e-sheet-password-content')[0].querySelector('.e-input');
const cnfrmPwd: HTMLElement = this.parent.element.querySelector('.e-reenterpwd-dialog').
getElementsByClassName('e-reenterpwd-content')[0].querySelector('.e-input');
const pwdSpan: HTMLElement = this.parent.createElement('span', {
className: 'e-reenterpwd-alert-span'
});
if ((pwd as CellModel).value === (cnfrmPwd as CellModel).value) {
this.parent.setSheetPropertyOnMute(actSheet, 'isProtected', true);
this.parent.setSheetPropertyOnMute(actSheet, 'password', (pwd as CellModel).value);
this.updateProtectSheet((pwd as CellModel).value);
this.dialog.hide();
const sheetDlgPopup: HTMLElement = document.querySelector('.e-protect-dlg');
const sheetDlg: Dialog = getComponent(sheetDlgPopup, 'dialog');
sheetDlg.destroy();
if (!actSheet.protectSettings.selectCells && !actSheet.protectSettings.selectUnLockedCells) {
this.parent.notify(hideAutoFillElement, null);
}
}
else {
if ((pwd as CellModel).value === '') {
pwdSpan.textContent = l10n.getConstant('PasswordAlertMsg');
} else if ((cnfrmPwd as CellModel).value === '') {
pwdSpan.textContent = l10n.getConstant('ConfirmPasswordAlertMsg');
} else if ((pwd as CellModel).value !== (cnfrmPwd as CellModel).value) {
pwdSpan.textContent = l10n.getConstant('PasswordAlert');
}
(this.parent.element.querySelector('.e-reenterpwd-dlg').querySelector('.e-reenterpwd-dialog')).appendChild(pwdSpan);
}
}
private updateProtectSheet(password: string): void {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
const selectedItems: SelectedCollection = this.optionList.getSelectedItems() as SelectedCollection;
const protectSettings: { [key: string]: boolean | string } = {
selectCells: selectedItems.text.indexOf(l10n.getConstant('SelectCells')) > -1,
formatCells: selectedItems.text.indexOf(l10n.getConstant('FormatCells')) > -1,
formatRows: selectedItems.text.indexOf(l10n.getConstant('FormatRows')) > -1,
formatColumns: selectedItems.text.indexOf(l10n.getConstant('FormatColumns')) > -1,
insertLink: selectedItems.text.indexOf(l10n.getConstant('InsertLinks')) > -1,
selectUnLockedCells: selectedItems.text.indexOf(l10n.getConstant('SelectUnLockedCells')) > -1
};
this.parent.notify(protectsheetHandler, { protectSettings: protectSettings, password: password, triggerEvent: true });
this.parent.notify(protectSelection, null);
this.parent.notify(clearUndoRedoCollection, null);
}
private protectSheetHandler(args: { sheetIndex: number, triggerEvent: boolean }): void {
const sheetIndex: number = isNullOrUndefined(args && args.sheetIndex) ? this.parent.activeSheetIndex : args.sheetIndex;
const sheet: SheetModel = getSheet(this.parent, sheetIndex);
const id: string = this.parent.element.id;
const disableHomeBtnId: string[] = [id + '_undo', id + '_redo', id + '_cut', id + '_copy', id + '_paste', id + '_number_format',
id + '_font_name', id + '_font_size', id + '_bold', id + '_italic', id + '_line-through', id + '_underline',
id + '_font_color_picker', id + '_fill_color_picker', id + '_borders', id + '_merge_cells', id + '_text_align',
id + '_vertical_align', id + '_wrap', id + '_sorting', id + '_clear', id + '_conditionalformatting'];
const enableHomeBtnId: string[] = [id + '_cut', id + '_copy', id + '_number_format', id + '_font_name', id + '_font_size',
id + '_bold', id + '_italic', id + '_line-through', id + '_underline', id + '_font_color_picker', id + '_fill_color_picker',
id + '_borders', id + '_text_align', id + '_vertical_align', id + '_wrap', id + '_sorting',
id + '_clear', id + '_conditionalformatting'];
const enableFrmlaBtnId: string[] = [id + '_insert_function'];
const enableInsertBtnId: string[] = [id + '_hyperlink', id + '_', id + '_chart'];
const imageBtnId: string[] = [id + '_image'];
const findBtnId: string[] = [id + '_find'];
const dataValidationBtnId: string[] = [id + '_datavalidation'];
const chartBtnId: string[] = [id + '_chart'];
const sheetElement: HTMLElement = document.getElementById(this.parent.element.id + '_sheet_panel');
if (sheetElement) {
if (sheet.isProtected) {
if (sheet.protectSettings.selectCells) {
sheetElement.classList.remove('e-protected');
} else if (sheet.protectSettings.selectUnLockedCells && !isLockedCells(this.parent, getRangeIndexes(sheet.selectedRange))){
sheetElement.classList.remove('e-protected');
} else {
sheetElement.classList.add('e-protected');
}
} else {
sheetElement.classList.add('e-protected');
}
if (!sheet.isProtected) {
sheetElement.classList.remove('e-protected');
}
}
this.parent.dataBind();
this.parent.notify(protectCellFormat, {
disableHomeBtnId: disableHomeBtnId,
enableHomeBtnId: enableHomeBtnId, enableFrmlaBtnId: enableFrmlaBtnId, enableInsertBtnId: enableInsertBtnId,
findBtnId: findBtnId, dataValidationBtnId: dataValidationBtnId, imageBtnId: imageBtnId, chartBtnId: chartBtnId
});
this.parent.notify(enableFormulaInput, null);
if (sheet.isProtected) {
this.parent.notify(updateToggleItem, { props: 'Protect' });
}
if (args && args.triggerEvent) {
this.parent.notify(completeAction, { action: 'protectSheet', eventArgs: { sheetIndex: sheetIndex, isProtected: sheet.isProtected, password: sheet.password, protectSettings: (sheet.protectSettings as { properties: {} }).properties || sheet.protectSettings } });
}
}
private editProtectedAlert(): void {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
this.dialog = this.parent.serviceLocator.getService('dialog');
this.dialog.show({
content: l10n.getConstant('EditAlert'),
isModal: true,
closeOnEscape: true,
showCloseIcon: true,
width: '400px',
cssClass: 'e-editAlert-dlg',
beforeOpen: (args: BeforeOpenEventArgs): void => {
const dlgArgs: DialogBeforeOpenEventArgs = {
dialogName: 'EditAlertDialog',
content: l10n.getConstant('EditAlert'),
element: args.element, target: args.target, cancel: args.cancel
};
this.parent.trigger('dialogBeforeOpen', dlgArgs);
if (dlgArgs.cancel) {
args.cancel = true;
getUpdateUsingRaf((): void => this.dialog.destroyDialog());
}
this.dialog.dialogInstance.content = dlgArgs.content;
focus(this.parent.element);
},
close: (): void => focus(this.parent.element)
});
}
private protectWorkbook(): void {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
const dialogInst: Dialog = (this.parent.serviceLocator.getService(dialog) as Dialog);
dialogInst.show({
width: 323, isModal: true, showCloseIcon: true, cssClass: 'e-protectworkbook-dlg',
header: l10n.getConstant('ProtectWorkbook'),
beforeOpen: (args: BeforeOpenEventArgs): void => {
const dlgArgs: DialogBeforeOpenEventArgs = {
dialogName: 'ProtectWorkbook',
element: args.element, target: args.target, cancel: args.cancel
};
this.parent.trigger('dialogBeforeOpen', dlgArgs);
if (dlgArgs.cancel) {
args.cancel = true;
}
dialogInst.dialogInstance.content = this.passwordProtectContent(); dialogInst.dialogInstance.dataBind();
this.parent.element.focus();
},
buttons: [{
buttonModel: {
content: l10n.getConstant('Ok'), isPrimary: true
},
click: (): void => {
this.alertMessage();
this.dlgClickHandler(dialogInst);
}
}]
});
}
private passwordProtectContent(): HTMLElement {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
const dialogElem: HTMLElement = this.parent.createElement('div', { className: 'e-password-dialog' });
const pwdCont: HTMLElement = this.parent.createElement('div', { className: 'e-password-content' });
const cnfrmPwdCont: HTMLElement = this.parent.createElement('div', { className: 'e-password-content' });
const textH: HTMLElement = this.parent.createElement('div', { className: 'e-header', innerHTML: l10n.getConstant('Password') });
const urlH: HTMLElement = this.parent.createElement('div', { className: 'e-header', innerHTML: l10n.getConstant('ConfirmPassword') });
const pwdInput: HTMLElement = this.parent.createElement('input', { className: 'e-input e-text', attrs: { 'type': 'password' } });
const cnfrmPwdInput: HTMLElement = this.parent.createElement('input', { className: 'e-input e-text', attrs: { 'type': 'password' } });
pwdInput.setAttribute('placeholder', l10n.getConstant('EnterThePassword'));
cnfrmPwdInput.setAttribute('placeholder', l10n.getConstant('EnterTheConfirmPassword'));
pwdCont.appendChild(pwdInput);
pwdCont.insertBefore(textH, pwdInput);
cnfrmPwdCont.appendChild(cnfrmPwdInput);
cnfrmPwdCont.insertBefore(urlH, cnfrmPwdInput);
dialogElem.appendChild(cnfrmPwdCont);
dialogElem.insertBefore(pwdCont, cnfrmPwdCont);
return dialogElem;
}
private KeyUpHandler(e: MouseEvent): void {
const trgt: Element = e.target as Element;
if (trgt.classList.contains('e-text') && closest(trgt, '.e-password-content')) {
if (closest(trgt, '.e-password-dialog') && closest(trgt, '.e-password-dialog').
getElementsByClassName('e-password-content')[1] === trgt.parentElement) {
const dlgEle: Element = closest(trgt, '.e-protectworkbook-dlg');
const ftrEle: HTMLElement = dlgEle.getElementsByClassName('e-footer-content')[0] as HTMLElement;
const okBtn: HTMLElement = ftrEle.firstChild as HTMLElement;
if ((trgt as CellModel).value !== '') {
okBtn.removeAttribute('disabled');
}
else {
okBtn.setAttribute('disabled', 'true');
}
}
}
if (trgt.classList.contains('e-text') && closest(trgt, '.e-unprotectpwd-content')) {
if (closest(trgt, '.e-unprotectpwd-dialog') && closest(trgt, '.e-unprotectpwd-dialog').
getElementsByClassName('e-unprotectpwd-content')[0] === trgt.parentElement) {
const dlgElement: Element = closest(trgt, '.e-unprotectworkbook-dlg');
const ftrElement: HTMLElement = dlgElement.getElementsByClassName('e-footer-content')[0] as HTMLElement;
const okButton: HTMLElement = ftrElement.firstChild as HTMLElement;
if ((trgt as CellModel).value !== '') {
okButton.removeAttribute('disabled');
}
else {
okButton.setAttribute('disabled', 'true');
}
}
}
if (trgt.classList.contains('e-text') && closest(trgt, '.e-reenterpwd-content')) {
if (closest(trgt, '.e-reenterpwd-dialog') && closest(trgt, '.e-reenterpwd-dialog').
getElementsByClassName('e-reenterpwd-content')[0] === trgt.parentElement) {
const dlgCnt: Element = closest(trgt, '.e-reenterpwd-dlg');
const ftrCnt: HTMLElement = dlgCnt.getElementsByClassName('e-footer-content')[0] as HTMLElement;
const okBtnElem: HTMLElement = ftrCnt.firstChild as HTMLElement;
if ((trgt as CellModel).value !== '') {
okBtnElem.removeAttribute('disabled');
}
else {
okBtnElem.setAttribute('disabled', 'true');
}
}
}
if (trgt.classList.contains('e-text') && closest(trgt, '.e-unprotectsheetpwd-content')) {
if (closest(trgt, '.e-unprotectsheetpwd-dialog') && closest(trgt, '.e-unprotectsheetpwd-dialog').
getElementsByClassName('e-unprotectsheetpwd-content')[0] === trgt.parentElement) {
const dlg: Element = closest(trgt, '.e-unprotectworksheet-dlg');
const ftr: HTMLElement = dlg.getElementsByClassName('e-footer-content')[0] as HTMLElement;
const btn: HTMLElement = ftr.firstChild as HTMLElement;
if ((trgt as CellModel).value !== '') {
btn.removeAttribute('disabled');
}
else {
btn.setAttribute('disabled', 'true');
}
}
}
if (trgt.classList.contains('e-text') && closest(trgt, '.e-importprotectpwd-content')) {
if (closest(trgt, '.e-importprotectpwd-dialog') && closest(trgt, '.e-importprotectpwd-dialog').
getElementsByClassName('e-importprotectpwd-content')[0] === trgt.parentElement) {
const dlgElem: Element = closest(trgt, '.e-importprotectworkbook-dlg');
const ftrElem: HTMLElement = dlgElem.getElementsByClassName('e-footer-content')[0] as HTMLElement;
const btn: HTMLElement = ftrElem.firstChild as HTMLElement;
if ((trgt as CellModel).value !== '') {
btn.removeAttribute('disabled');
}
else {
btn.setAttribute('disabled', 'true');
}
}
}
}
private alertMessage(): void {
const spanElem: Element = this.parent.element.querySelector('.e-pwd-alert-span');
const unpotectSpanElem: Element = this.parent.element.querySelector('.e-unprotectpwd-alert-span');
const importpotectSpanElem: Element = this.parent.element.querySelector('.e-importprotectpwd-alert-span');
const protectSheetSpanElem: Element = this.parent.element.querySelector('.e-reenterpwd-alert-span');
const unProtectSheetSpanElem: Element = this.parent.element.querySelector('.e-unprotectsheetpwd-alert-span');
if (spanElem) {
spanElem.remove();
}
if (unpotectSpanElem) {
unpotectSpanElem.remove();
}
if (importpotectSpanElem) {
importpotectSpanElem.remove();
}
if (protectSheetSpanElem) {
protectSheetSpanElem.remove();
}
if (unProtectSheetSpanElem) {
unProtectSheetSpanElem.remove();
}
}
private dlgClickHandler(dialogInst: Dialog): void {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
const pwdVal: HTMLElement = this.parent.element.querySelector('.e-password-dialog').
getElementsByClassName('e-password-content')[0].querySelector('.e-input');
const cnfrmPwd: HTMLElement = this.parent.element.querySelector('.e-password-dialog').
getElementsByClassName('e-password-content')[1].querySelector('.e-input');
const pwdSpan: HTMLElement = this.parent.createElement('span', {
className: 'e-pwd-alert-span'
});
if ((pwdVal as CellModel).value === (cnfrmPwd as CellModel).value) {
dialogInst.hide();
this.parent.notify(updateToggleItem, { props: 'Protectworkbook' });
this.protectWorkbookHandler({ password: (pwdVal as CellModel).value });
this.parent.notify(completeAction, { action: 'protectWorkbook', eventArgs: { isProtected: true, password: (pwdVal as CellModel).value } });
} else if ((pwdVal as CellModel).value === '') {
pwdSpan.textContent = l10n.getConstant('PasswordAlertMsg');
} else if ((cnfrmPwd as CellModel).value === '') {
pwdSpan.textContent = l10n.getConstant('ConfirmPasswordAlertMsg');
} else if ((pwdVal as CellModel).value !== (cnfrmPwd as CellModel).value) {
pwdSpan.textContent = l10n.getConstant('PasswordAlert');
}
(this.parent.element.querySelector('.e-protectworkbook-dlg').querySelector('.e-dlg-content')).appendChild(pwdSpan);
}
private protectWorkbookHandler(args: { password: string }): void {
this.parent.password = args.password;
this.parent.isProtected = true;
if (this.parent.showSheetTabs) {
this.parent.element.querySelector('.e-add-sheet-tab').setAttribute('disabled', 'true');
this.parent.element.querySelector('.e-add-sheet-tab').classList.add('e-disabled');
}
this.parent.notify(updateToggleItem, { props: 'Protectworkbook' });
}
private unProtectWorkbook(): void {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
const dialogInst: Dialog = (this.parent.serviceLocator.getService(dialog) as Dialog);
dialogInst.show({
width: 323, isModal: true, showCloseIcon: true, cssClass: 'e-unprotectworkbook-dlg',
header: l10n.getConstant('UnProtectWorkbook'),
beforeOpen: (args: BeforeOpenEventArgs): void => {
const dlgArgs: DialogBeforeOpenEventArgs = {
dialogName: 'UnProtectWorkbook',
element: args.element, target: args.target, cancel: args.cancel
};
this.parent.trigger('dialogBeforeOpen', dlgArgs);
if (dlgArgs.cancel) {
args.cancel = true;
}
dialogInst.dialogInstance.content = this.unProtectPasswordContent(); dialogInst.dialogInstance.dataBind();
this.parent.element.focus();
},
buttons: [{
buttonModel: {
content: l10n.getConstant('Ok'), isPrimary: true, disabled: true
},
click: (): void => {
this.alertMessage();
this.unprotectdlgOkClick(dialogInst);
}
}]
});
}
private unProtectsheet(args : { isImportedSheet?: boolean}): void {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
const dialogInst: Dialog = (this.parent.serviceLocator.getService(dialog) as Dialog);
dialogInst.show({
width: 323, isModal: true, showCloseIcon: true, cssClass: 'e-unprotectworksheet-dlg',
header: l10n.getConstant('UnProtectWorksheet'),
beforeOpen: (args: BeforeOpenEventArgs): void => {
const dlgArgs: DialogBeforeOpenEventArgs = {
dialogName: 'UnProtectSheet',
element: args.element, target: args.target, cancel: args.cancel
};
this.parent.trigger('dialogBeforeOpen', dlgArgs);
if (dlgArgs.cancel) {
args.cancel = true;
}
dialogInst.dialogInstance.content = this.unProtectSheetPasswordContent(); dialogInst.dialogInstance.dataBind();
this.parent.element.focus();
},
buttons: [{
buttonModel: {
content: l10n.getConstant('Ok'), isPrimary: true, disabled: this.parent.openModule.isImportedFile &&
(this.parent.openModule.unProtectSheetIdx.indexOf(this.parent.activeSheetIndex) === -1) ? false : true
},
click: (): void => {
this.alertMessage();
this.unprotectSheetdlgOkClick(dialogInst, args && args.isImportedSheet);
}
}]
});
}
private reEnterSheetPassword(): void {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
const dialogInst: Dialog = (this.parent.serviceLocator.getService(dialog) as Dialog);
dialogInst.show({
width: 323, isModal: true, showCloseIcon: true, cssClass: 'e-reenterpwd-dlg',
header: l10n.getConstant('ConfirmPassword'),
beforeOpen: (args: BeforeOpenEventArgs): void => {
const dlgArgs: DialogBeforeOpenEventArgs = {
dialogName: 'Re-enterPassword',
element: args.element, target: args.target, cancel: args.cancel
};
this.parent.trigger('dialogBeforeOpen', dlgArgs);
if (dlgArgs.cancel) {
args.cancel = true;
}
dialogInst.dialogInstance.content = this.reEnterSheetPasswordContent(); dialogInst.dialogInstance.dataBind();
this.parent.element.focus();
},
buttons: [{
buttonModel: {
content: l10n.getConstant('Ok'), isPrimary: true, disabled: true
},
click: (): void => {
this.alertMessage();
this.selectSheetPassword();
}
}]
});
}
private unProtectPasswordContent(): HTMLElement {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
const dlgElem: HTMLElement = this.parent.createElement('div', { className: 'e-unprotectpwd-dialog' });
const pwdCont: HTMLElement = this.parent.createElement('div', { className: 'e-unprotectpwd-content' });
const textHeader: HTMLElement = this.parent.createElement('div', { className: 'e-header', innerHTML: l10n.getConstant('EnterThePassword') });
const pwdInputElem: HTMLElement = this.parent.createElement('input', { className: 'e-input e-text', attrs: { 'type': 'password' } });
pwdCont.appendChild(pwdInputElem);
pwdCont.insertBefore(textHeader, pwdInputElem);
dlgElem.appendChild(pwdCont);
return dlgElem;
}
private reEnterSheetPasswordContent(): HTMLElement {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
const dialogElem: HTMLElement = this.parent.createElement('div', { className: 'e-reenterpwd-dialog' });
const pwdCont: HTMLElement = this.parent.createElement('div', { className: 'e-reenterpwd-content' });
const textH: HTMLElement = this.parent.createElement('div', { className: 'e-header', innerHTML: l10n.getConstant('ReEnterPassword') });
const pwdInput: HTMLElement = this.parent.createElement('input', { className: 'e-input e-text', attrs: { 'type': 'password' } });
pwdCont.appendChild(pwdInput);
pwdCont.insertBefore(textH, pwdInput);
dialogElem.appendChild(pwdCont);
return dialogElem;
}
private unProtectSheetPasswordContent(): HTMLElement {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
const dialogCnt: HTMLElement = this.parent.createElement('div', { className: 'e-unprotectsheetpwd-dialog' });
const pwdCnt: HTMLElement = this.parent.createElement('div', { className: 'e-unprotectsheetpwd-content' });
const textH: HTMLElement = this.parent.createElement('div', { className: 'e-header', innerHTML: l10n.getConstant('EnterThePassword') });
const pwdInput: HTMLElement = this.parent.createElement('input', { className: 'e-input e-text', attrs: { 'type': 'password' } });
pwdCnt.appendChild(pwdInput);
pwdCnt.insertBefore(textH, pwdInput);
dialogCnt.appendChild(pwdCnt);
return dialogCnt;
}
private unprotectdlgOkClick(dialogInst: Dialog): void {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
const pwd: HTMLElement = this.parent.element.querySelector('.e-unprotectpwd-dialog').
getElementsByClassName('e-unprotectpwd-content')[0].querySelector('.e-input');
if (this.parent.password === (pwd as CellModel).value) {
dialogInst.hide();
this.removeWorkbookProtection();
this.parent.notify(completeAction, { action: 'protectWorkbook', eventArgs: { isProtected: false } });
} else {
const pwdSpan: Element = this.parent.createElement('span', {
className: 'e-unprotectpwd-alert-span',
innerHTML: l10n.getConstant('UnProtectPasswordAlert')
});
(this.parent.element.querySelector('.e-unprotectworkbook-dlg').querySelector('.e-dlg-content')).appendChild(pwdSpan);
}
}
private removeWorkbookProtection(): void {
this.parent.password = '';
this.parent.isProtected = false;
if (this.parent.showSheetTabs) {
this.parent.element.querySelector('.e-add-sheet-tab').removeAttribute('disabled');
this.parent.element.querySelector('.e-add-sheet-tab').classList.remove('e-disabled');
}
const elem: Element = document.getElementById(this.parent.element.id + '_protectworkbook');
if (elem) {
elem.classList.remove('e-active');
}
this.parent.notify(updateToggleItem, { props: 'Protectworkbook' });
}
private unprotectSheetdlgOkClick(dialogInst: Dialog, isImportedSheet?: boolean): void {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
const sheet: SheetModel = this.parent.getActiveSheet();
const pwd: HTMLElement = this.parent.element.querySelector('.e-unprotectsheetpwd-dialog').
getElementsByClassName('e-unprotectsheetpwd-content')[0].querySelector('.e-input');
if (isImportedSheet && sheet.password.length === 0) {
const impArgs: OpenOptions = {
sheetPassword: (pwd as CellModel).value,
sheetIndex: this.parent.activeSheetIndex
};
this.parent.open(impArgs);
}
else {
if (sheet.password === (pwd as CellModel).value) {
dialogInst.hide();
this.unProtectSheetPassword();
} else {
const pwdSpan: Element = this.parent.createElement('span', {
className: 'e-unprotectsheetpwd-alert-span',
innerHTML: l10n.getConstant('UnProtectPasswordAlert')
});
(this.parent.element.querySelector('.e-unprotectworksheet-dlg').querySelector('.e-dlg-content')).appendChild(pwdSpan);
}
}
}
private unProtectSheetPassword(): void {
const sheet: SheetModel = this.parent.getActiveSheet();
const sheetIdx: number = this.parent.activeSheetIndex;
this.parent.setSheetPropertyOnMute(sheet, 'isProtected', !sheet.isProtected);
this.parent.setSheetPropertyOnMute(sheet, 'password', '');
const isActive: boolean = sheet.isProtected ? false : true;
this.parent.notify(applyProtect, { isActive: isActive, id: this.parent.element.id + '_protect', sheetIndex: sheetIdx, triggerEvent: true });
if (this.parent.openModule.isImportedFile && this.parent.openModule.unProtectSheetIdx.indexOf(sheetIdx) === -1 ) {
this.parent.openModule.unProtectSheetIdx.push(sheetIdx);
}
}
private getPassWord(args: { [key: string]: string }): void {
args.passWord = this.password;
}
private importProtectWorkbook(fileArgs: OpenOptions): void {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
const dialogInst: Dialog = (this.parent.serviceLocator.getService(dialog) as Dialog);
dialogInst.show({
width: 323, isModal: true, showCloseIcon: true, cssClass: 'e-importprotectworkbook-dlg',
header: l10n.getConstant('UnProtectWorkbook'),
beforeOpen: (args: BeforeOpenEventArgs): void => {
const dlgArgs: DialogBeforeOpenEventArgs = {
dialogName: 'ImportProtectWorkbook',
element: args.element, target: args.target, cancel: args.cancel
};
this.parent.trigger('dialogBeforeOpen', dlgArgs);
if (dlgArgs.cancel) {
args.cancel = true;
}
dialogInst.dialogInstance.content = this.importProtectPasswordContent(fileArgs);
dialogInst.dialogInstance.dataBind();
this.parent.element.focus();
},
buttons: [{
buttonModel: {
content: l10n.getConstant('Ok'), isPrimary: true, disabled: true
},
click: (): void => {
this.alertMessage();
this.importOkClick(fileArgs);
}
}]
});
}
private importProtectPasswordContent(args: OpenOptions): HTMLElement {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
const dialogElem: HTMLElement = this.parent.createElement('div', { className: 'e-importprotectpwd-dialog' });
const pwdCont: HTMLElement = this.parent.createElement('div', { className: 'e-importprotectpwd-content' });
const textSpan: HTMLElement = this.parent.createElement('span', {
className: 'e-header',
innerHTML: '"' + (args.file as File).name + '"' + ' ' + l10n.getConstant('IsProtected')
});
const pwdInput: HTMLElement = this.parent.createElement('input', { className: 'e-input e-text', attrs: { 'type': 'password' } });
pwdInput.setAttribute('placeholder', l10n.getConstant('EnterThePassword'));
pwdCont.appendChild(textSpan);
pwdCont.appendChild(pwdInput);
dialogElem.appendChild(pwdCont);
return dialogElem;
}
private importOkClick(args: OpenOptions): void {
const pwd: HTMLElement = this.parent.element.querySelector('.e-importprotectpwd-dialog').
getElementsByClassName('e-importprotectpwd-content')[0].querySelector('.e-input');
this.parent.password = (pwd as CellModel).value;
const impArgs: OpenOptions = {
file: args.file,
password: (pwd as CellModel).value
};
this.parent.open(impArgs);
}
/**
* Get the module name.
*
* @returns {string} - Get the module name.
*
* @private
*/
public getModuleName(): string {
return 'protectSheet';
}
} | the_stack |
import * as React from "react";
import * as PropTypes from "prop-types";
import IS_NODE_ENV from "../utils/nodeJS/IS_NODE_ENV";
import Slider from "../Slider";
import * as tinycolor from "tinycolor2";
export interface DataProps {
/**
* init ColorPicker Default color.
*/
defaultColor?: string;
/**
* init ColorPicker Default size. passed number covert to `px`.
*/
size?: number;
/**
* onChange ColorPicker color event `callback`.
*/
onChangeColor?: (color?: string) => void;
/**
* onChanged color event `callback`.
*/
onChangedColor?: (color?: string) => void;
/**
* setTimeout to onChanged color event `callback`. default is 0.
*/
onChangedColorTimeout?: number;
}
export interface ColorPickerProps extends DataProps, React.HTMLAttributes<HTMLDivElement> {}
export interface ColorPickerState {
h?: number;
s?: number;
v?: number;
dragging?: boolean;
}
const emptyFunc = () => {};
export class ColorPicker extends React.Component<ColorPickerProps, ColorPickerState> {
static defaultProps: ColorPickerProps = {
size: 336,
defaultColor: "hsv(210, 100%, 100%)",
onChangeColor: emptyFunc,
onChangedColor: emptyFunc,
onChangedColorTimeout: 1000 / 24
};
state: ColorPickerState = tinycolor(this.props.defaultColor).toHsv();
static contextTypes = { theme: PropTypes.object };
context: { theme: ReactUWP.ThemeType };
canvas?: HTMLCanvasElement;
ctx?: CanvasRenderingContext2D;
moveColorTimer: any = null;
originBodyStyle = IS_NODE_ENV ? void 0 : { ...document.body.style };
colorSelectorElm: HTMLDivElement;
colorMainBarElm: HTMLDivElement;
slider: Slider;
componentDidMount() {
this.renderCanvas();
this.canvas.addEventListener("touchstart", this.handleChooseColor as any, false);
this.canvas.addEventListener("touchend", this.handleEnd as any, false);
}
componentDidUpdate() {
this.renderCanvas();
}
componentWillUnmount() {
clearTimeout(this.moveColorTimer);
this.canvas.removeEventListener("touchstart", this.handleChooseColor as any, false);
this.canvas.removeEventListener("touchend", this.handleEnd as any, false);
}
renderCanvas() {
let { size } = this.props;
size = size * 0.8125;
Object.assign(this.canvas, {
width: size,
height: size
});
const _xPosition = size / 2;
const _yPosition = _xPosition;
const _r = _xPosition;
const _pi_2 = Math.PI * 2;
const _c = _r * _pi_2;
this.ctx = this.canvas.getContext("2d");
const { ctx } = this;
this.setCanvas2devicePixelRatio();
// use save when using clip Path
ctx.save();
ctx.arc(_xPosition, _yPosition, _r, 0, _pi_2, true);
ctx.clip();
const { v, s } = this.state;
for (let i = -1; i < 360; i++) {
ctx.beginPath();
ctx.moveTo(_xPosition, _yPosition);
if (i === -1) {
ctx.arc(_xPosition, _yPosition, _r, -_pi_2 / 360, 0, true);
} else {
ctx.arc(_xPosition, _yPosition, _r, 0, _pi_2 * i / 360, true);
}
ctx.closePath();
const radialGradient = ctx.createRadialGradient(_xPosition, _yPosition, 0, _xPosition, _yPosition, _r);
radialGradient.addColorStop(0, tinycolor(`hsv(${Math.abs(i)}, 0%, ${v * 100}%)`).toHexString());
radialGradient.addColorStop(1, tinycolor(`hsv(${Math.abs(i)}, 100%, ${v * 100}%)`).toHexString());
ctx.fillStyle = radialGradient;
ctx.fill();
}
// reset clip to default
ctx.restore();
}
setCanvas2devicePixelRatio = () => {
const { devicePixelRatio } = window;
const { canvas, ctx } = this;
if (!devicePixelRatio) return;
const { width, height } = canvas;
Object.assign(canvas, {
width: width * devicePixelRatio,
height: height * devicePixelRatio
} as HTMLCanvasElement);
Object.assign(canvas.style, {
width: `${width}px`,
height: `${height}px`
} as CSSStyleDeclaration);
ctx.scale(devicePixelRatio, devicePixelRatio);
}
colorBarTimer: any = null;
handleColorBarChange = (v: number) => {
clearTimeout(this.colorBarTimer);
const { h, s } = this.state;
const { onChangeColor, onChangedColor, onChangedColorTimeout } = this.props;
const colorHexString = tinycolor({ h, s, v }).toHexString();
onChangeColor(colorHexString);
this.setState({ v }, () => onChangeColor(colorHexString));
this.colorBarTimer = setTimeout(() => {
onChangedColor(colorHexString);
}, onChangedColorTimeout);
}
clickTimer: any = null;
handleChooseColor = (e: React.MouseEvent<HTMLCanvasElement> | React.TouchEvent<HTMLCanvasElement>, isClickEvent = true) => {
e.preventDefault();
const isTouchEvent = e.type.includes("touch");
const { prefixStyle } = this.context.theme;
if (isClickEvent && (e.type === "mousedown" || e.type === "touchstart")) {
document.documentElement.addEventListener("mousemove", this.handleTouchMouseMove, false);
document.documentElement.addEventListener("mouseup", this.handleEnd);
this.canvas.addEventListener("touchmove", this.handleTouchMouseMove, false);
document.documentElement.addEventListener("touchend", this.handleEnd);
Object.assign(document.body.style, {
userSelect: "none",
msUserSelect: "none",
webkitUserSelect: "none",
cursor: "default"
});
}
const { size, onChangeColor, onChangedColor, onChangedColorTimeout } = this.props;
const { v } = this.state;
const clientReact = this.canvas.getBoundingClientRect();
const colorPickerBoardSize = size * 0.8125 / 2;
const { clientX, clientY } = isTouchEvent ? (e as React.TouchEvent<HTMLCanvasElement>).changedTouches[0] : (e as React.MouseEvent<HTMLCanvasElement>);
const x = clientX - clientReact.left - colorPickerBoardSize;
const y = clientReact.top - clientY + colorPickerBoardSize;
const r = Math.sqrt(x * x + y * y);
let h = Math.asin(y / r) / Math.PI * 180;
if (x > 0 && y > 0) h = 360 - h;
if (x > 0 && y < 0) h = -h;
if (x < 0 && y < 0) h = 180 + h;
if (x < 0 && y > 0) h = 180 + h;
let s = r / colorPickerBoardSize;
if (s > 1) s = 1;
const colorHexString = tinycolor({ h, s, v }).toHexString();
if (this.slider) {
const halfLightColor = tinycolor({ h, s, v: 1 });
this.slider.barElm.style.backgroundImage = `linear-gradient(90deg, #000, ${halfLightColor.toHexString()})`;
}
if (isClickEvent && e.type === "click") {
onChangeColor(colorHexString);
this.setState({ h, s }, () => {
clearTimeout(this.clickTimer);
this.clickTimer = setTimeout(() => {
onChangedColor(colorHexString);
}, 0);
});
} else {
onChangeColor(colorHexString);
clearTimeout(this.moveColorTimer);
const r = colorPickerBoardSize * s;
const mainBoardDotSize = size / 25;
const x = Math.cos(h / 180 * Math.PI) * r;
const y = Math.sin(h / 180 * Math.PI) * r;
Object.assign(this.colorSelectorElm.style, prefixStyle({
transform: `translate3d(${x}px, ${y}px, 0)`
}));
if (this.colorMainBarElm) {
this.colorMainBarElm.style.background = colorHexString;
}
this.moveColorTimer = setTimeout(() => {
onChangedColor(colorHexString);
this.setState({ h, s });
}, onChangedColorTimeout);
}
}
handleTouchMouseMove = (e: any) => {
if (!this.state.dragging) {
this.setState({ dragging: true });
}
this.handleChooseColor(e, false);
}
handleEnd = (e: any) => {
if (this.state.dragging) {
this.setState({ dragging: false });
}
clearTimeout(this.moveColorTimer);
Object.assign(document.body.style, {
userSelect: void 0,
msUserSelect: void 0,
webkitUserSelect: void 0,
cursor: void 0,
...this.originBodyStyle
});
document.documentElement.removeEventListener("mousemove", this.handleTouchMouseMove);
this.canvas.removeEventListener("touchmove", this.handleTouchMouseMove);
document.documentElement.removeEventListener("mouseup", this.handleEnd);
document.documentElement.removeEventListener("touchend", this.handleEnd);
}
render() {
const {
size,
defaultColor,
onChangeColor,
onChangedColor,
onChangedColorTimeout,
className,
...attributes
} = this.props;
const { h, s, v, dragging } = this.state;
const { context: { theme } } = this;
const color = tinycolor({ h, s, v });
const halfLightColor = tinycolor({ h, s, v: 1 });
const colorPickerBoardSize = size * 0.8125 / 2;
const r = colorPickerBoardSize * s;
const mainBoardDotSize = size / 25;
const x = Math.cos(h / 180 * Math.PI) * r;
const y = Math.sin(h / 180 * Math.PI) * r;
const selectorSize = colorPickerBoardSize - mainBoardDotSize / 2;
const styles = getStyles(this);
styles.colorSelector = {
...styles.colorSelector,
top: selectorSize,
left: selectorSize,
width: mainBoardDotSize,
height: mainBoardDotSize,
borderRadius: mainBoardDotSize,
background: "none",
boxShadow: `0 0 0 4px #fff`
};
const classes = theme.prepareStyles({
className: "color-picker",
styles
});
return (
<div {...attributes} style={classes.root.style} className={theme.classNames(classes.root.className, className)}>
<div {...classes.board}>
<div style={{ position: "relative" }}>
<canvas
{...classes.mainBoard}
ref={canvas => this.canvas = canvas}
onClick={this.handleChooseColor}
onMouseDown={this.handleChooseColor}
onMouseUp={this.handleEnd}
>
Your Browser not support canvas.
</canvas>
<div
ref={colorSelectorElm => this.colorSelectorElm = colorSelectorElm}
className={classes.colorSelector.className}
style={theme.prefixStyle({
...classes.colorSelector.style,
transform: `translate3d(${x}px, ${y}px, 0)`
})}
/>
</div>
<div
{...classes.colorMainBar}
ref={colorMainBarElm => this.colorMainBarElm = colorMainBarElm}
/>
</div>
<Slider
maxValue={1}
ref={slider => this.slider = slider}
onChangeValue={this.handleColorBarChange}
style={{ marginTop: size * 0.0125, width: "100%" }}
initValue={v}
width={size}
barHeight={size * 0.025}
barBackgroundImage={`linear-gradient(90deg, #000, ${halfLightColor.toHexString()})`}
useSimpleController
/>
</div>
);
}
}
function getStyles(colorPicker: ColorPicker): {
root?: React.CSSProperties;
board?: React.CSSProperties;
mainBoard?: React.CSSProperties;
colorMainBar?: React.CSSProperties;
colorSelector?: React.CSSProperties;
} {
const {
context: { theme },
props: {
style,
size
},
state: { h, s, v }
} = colorPicker;
const { prefixStyle } = theme;
const currColor = tinycolor({ h, s, v }).toHslString();
return {
root: prefixStyle({
display: "inline-block",
verticalAlign: "middle",
width: size,
flexDirection: "column",
...style
}),
board: prefixStyle({
display: "flex",
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between"
}),
mainBoard: prefixStyle({
userDrag: "none",
margin: 0,
userSelect: "none"
} as any),
colorMainBar: {
height: size * 0.8125,
marginLeft: size * 0.025,
width: size * 0.125,
background: currColor
},
colorSelector: prefixStyle({
pointerEvents: "none",
userDrag: "none",
position: "absolute"
} as any)
};
}
export default ColorPicker; | the_stack |
import { IdentityTypes, RequestLogicTypes, SignatureTypes } from '@requestnetwork/types';
import Utils from '@requestnetwork/utils';
import ReduceExpectedAmountAction from '../../../src/actions/reduceExpectedAmount';
import Version from '../../../src/version';
const CURRENT_VERSION = Version.currentVersion;
import * as TestData from '../utils/test-data-generator';
const requestIdMock = '011c2610cbc5bee43b6bc9800e69ec832fb7d50ea098a88877a0afdcac5981d3f8';
const arbitraryExpectedAmount = '123400000000000000';
const biggerThanArbitraryExpectedAmount = '223400000000000000';
const arbitraryDeltaAmount = '100000000000000000';
const arbitraryDeltaAmountNegative = '-100000000000000000';
const arbitraryExpectedAmountAfterDelta = '23400000000000000';
/* eslint-disable @typescript-eslint/no-unused-expressions */
describe('actions/reduceExpectedAmount', () => {
describe('format', () => {
it('can reduce expected amount without extensionsData', async () => {
const actionReduceAmount = await ReduceExpectedAmountAction.format(
{
deltaAmount: arbitraryDeltaAmount,
requestId: requestIdMock,
},
TestData.payeeRaw.identity,
TestData.fakeSignatureProvider,
);
// 'action is wrong'
expect(actionReduceAmount.data.name).toBe(
RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT,
);
// 'requestId is wrong'
expect(actionReduceAmount.data.parameters.requestId).toBe(requestIdMock);
// 'deltaAmount is wrong'
expect(actionReduceAmount.data.parameters.deltaAmount).toBe(arbitraryDeltaAmount);
// 'extensionsData is wrong'
expect(actionReduceAmount.data.parameters.extensionsData).toBeUndefined();
});
it('can reduce expected amount with extensionsData', async () => {
const actionReduceAmount = await ReduceExpectedAmountAction.format(
{
deltaAmount: arbitraryDeltaAmount,
extensionsData: TestData.oneExtension,
requestId: requestIdMock,
},
TestData.payeeRaw.identity,
TestData.fakeSignatureProvider,
);
// 'action is wrong'
expect(actionReduceAmount.data.name).toBe(
RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT,
);
// 'requestId is wrong'
expect(actionReduceAmount.data.parameters.requestId).toBe(requestIdMock);
// 'deltaAmount is wrong'
expect(actionReduceAmount.data.parameters.deltaAmount).toBe(arbitraryDeltaAmount);
// 'extensionsData is wrong'
expect(actionReduceAmount.data.parameters.extensionsData).toEqual(TestData.oneExtension);
});
it('cannot reduce expected amount with not a number', () => {
expect(() => {
ReduceExpectedAmountAction.format(
{
deltaAmount: 'this not a number',
requestId: requestIdMock,
},
TestData.payeeRaw.identity,
TestData.fakeSignatureProvider,
);
}).toThrowError('deltaAmount must be a string representing a positive integer');
});
it('cannot reduce expected amount with decimal', () => {
expect(() => {
ReduceExpectedAmountAction.format(
{
deltaAmount: '0.1234',
requestId: requestIdMock,
},
TestData.payeeRaw.identity,
TestData.fakeSignatureProvider,
);
}).toThrowError('deltaAmount must be a string representing a positive integer');
});
it('cannot reduce expected amount with negative', () => {
expect(() => {
ReduceExpectedAmountAction.format(
{
deltaAmount: '-1234',
requestId: requestIdMock,
},
TestData.payeeRaw.identity,
TestData.fakeSignatureProvider,
);
}).toThrowError('deltaAmount must be a string representing a positive integer');
});
});
describe('applyActionToRequest', () => {
it('can reduce expected amount by payee', async () => {
const actionReduceAmount = await ReduceExpectedAmountAction.format(
{
deltaAmount: arbitraryDeltaAmount,
requestId: requestIdMock,
},
TestData.payeeRaw.identity,
TestData.fakeSignatureProvider,
);
const request = ReduceExpectedAmountAction.applyActionToRequest(
actionReduceAmount,
2,
Utils.deepCopy(TestData.requestCreatedNoExtension),
);
// 'requestId is wrong'
expect(request.requestId).toBe(requestIdMock);
// 'currency is wrong'
expect(request.currency).toEqual({
type: RequestLogicTypes.CURRENCY.ETH,
value: 'ETH',
});
// 'state is wrong'
expect(request.state).toBe(RequestLogicTypes.STATE.CREATED);
// 'expectedAmount is wrong'
expect(request.expectedAmount).toBe(arbitraryExpectedAmountAfterDelta);
// 'extensions is wrong'
expect(request.extensions).toEqual({});
// 'request.creator is wrong'
expect(request).toHaveProperty('creator');
// 'request.creator.type is wrong'
expect(request.creator.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.creator.value is wrong'
expect(request.creator.value).toBe(TestData.payeeRaw.address);
// 'request.payee is wrong'
expect(request).toHaveProperty('payee');
if (request.payee) {
// 'request.payee.type is wrong'
expect(request.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.payee.value is wrong'
expect(request.payee.value).toBe(TestData.payeeRaw.address);
}
// 'request.payer is wrong'
expect(request).toHaveProperty('payer');
if (request.payer) {
// 'request.payer.type is wrong'
expect(request.payer.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.payer.value is wrong'
expect(request.payer.value).toBe(TestData.payerRaw.address);
}
// 'request.events is wrong'
expect(request.events[1]).toEqual({
actionSigner: TestData.payeeRaw.identity,
name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT,
parameters: { extensionsDataLength: 0, deltaAmount: arbitraryDeltaAmount },
timestamp: 2,
});
});
it('cannot reduce expected amount by payer', async () => {
const actionReduceAmount = await ReduceExpectedAmountAction.format(
{
deltaAmount: arbitraryDeltaAmount,
requestId: requestIdMock,
},
TestData.payerRaw.identity,
TestData.fakeSignatureProvider,
);
expect(() => {
ReduceExpectedAmountAction.applyActionToRequest(
actionReduceAmount,
2,
Utils.deepCopy(TestData.requestCreatedNoExtension),
);
}).toThrowError('signer must be the payee');
});
it('cannot reduce expected amount by third party', async () => {
const actionReduceAmount = await ReduceExpectedAmountAction.format(
{
deltaAmount: arbitraryDeltaAmount,
requestId: requestIdMock,
},
TestData.otherIdRaw.identity,
TestData.fakeSignatureProvider,
);
expect(() => {
ReduceExpectedAmountAction.applyActionToRequest(
actionReduceAmount,
2,
Utils.deepCopy(TestData.requestCreatedNoExtension),
);
}).toThrowError('signer must be the payee');
});
it('cannot reduce expected amount if no requestId', () => {
const action = {
data: {
name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT,
parameters: {
deltaAmount: arbitraryDeltaAmount,
},
version: CURRENT_VERSION,
},
signature: {
method: SignatureTypes.METHOD.ECDSA,
value:
'0xdd44c2d34cba689921c60043a78e189b4aa35d5940723bf98b9bb9083385de316333204ce3bbeced32afe2ea203b76153d523d924c4dca4a1d9fc466e0160f071c',
},
};
expect(() => {
ReduceExpectedAmountAction.applyActionToRequest(
action,
2,
Utils.deepCopy(TestData.requestCreatedNoExtension),
);
}).toThrowError('requestId must be given');
});
it('cannot reduce expected amount if no deltaAmount', () => {
const action = {
data: {
name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT,
parameters: {
requestId: requestIdMock,
},
version: CURRENT_VERSION,
},
signature: {
method: SignatureTypes.METHOD.ECDSA,
value:
'0xdd44c2d34cba689921c60043a78e189b4aa35d5940723bf98b9bb9083385de316333204ce3bbeced32afe2ea203b76153d523d924c4dca4a1d9fc466e0160f071c',
},
};
expect(() => {
ReduceExpectedAmountAction.applyActionToRequest(
action,
2,
Utils.deepCopy(TestData.requestCreatedNoExtension),
);
}).toThrowError('deltaAmount must be given');
});
it('cannot reduce expected amount if no payee in state', () => {
const requestContextNoPayer = {
creator: {
type: IdentityTypes.TYPE.ETHEREUM_ADDRESS,
value: TestData.payeeRaw.address,
},
currency: {
type: RequestLogicTypes.CURRENCY.ETH,
value: 'ETH',
},
events: [
{
actionSigner: {
type: IdentityTypes.TYPE.ETHEREUM_ADDRESS,
value: TestData.payeeRaw.address,
},
name: RequestLogicTypes.ACTION_NAME.CREATE,
parameters: {
expectedAmount: '123400000000000000',
extensionsDataLength: 0,
isSignedRequest: false,
},
timestamp: 1,
},
],
expectedAmount: arbitraryExpectedAmount,
extensions: {},
extensionsData: [],
payer: {
type: IdentityTypes.TYPE.ETHEREUM_ADDRESS,
value: TestData.payeeRaw.address,
},
requestId: requestIdMock,
state: RequestLogicTypes.STATE.CREATED,
timestamp: 1544426030,
version: CURRENT_VERSION,
};
const action = {
data: {
name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT,
parameters: {
deltaAmount: arbitraryDeltaAmount,
requestId: requestIdMock,
},
version: CURRENT_VERSION,
},
signature: {
method: SignatureTypes.METHOD.ECDSA,
value:
'0xdd44c2d34cba689921c60043a78e189b4aa35d5940723bf98b9bb9083385de316333204ce3bbeced32afe2ea203b76153d523d924c4dca4a1d9fc466e0160f071c',
},
};
expect(() => {
ReduceExpectedAmountAction.applyActionToRequest(action, 2, requestContextNoPayer);
}).toThrowError('the request must have a payee');
});
it('cannot reduce expected amount if state === CANCELED in state', async () => {
const actionReduceAmount = await ReduceExpectedAmountAction.format(
{
deltaAmount: arbitraryDeltaAmount,
requestId: requestIdMock,
},
TestData.payeeRaw.identity,
TestData.fakeSignatureProvider,
);
expect(() => {
ReduceExpectedAmountAction.applyActionToRequest(
actionReduceAmount,
2,
Utils.deepCopy(TestData.requestCanceledNoExtension),
);
}).toThrowError('the request must not be canceled');
});
it('can reduce expected amount if state === ACCEPTED in state', async () => {
const actionReduceAmount = await ReduceExpectedAmountAction.format(
{
deltaAmount: arbitraryDeltaAmount,
requestId: requestIdMock,
},
TestData.payeeRaw.identity,
TestData.fakeSignatureProvider,
);
const request = ReduceExpectedAmountAction.applyActionToRequest(
actionReduceAmount,
2,
Utils.deepCopy(TestData.requestAcceptedNoExtension),
);
// 'requestId is wrong'
expect(request.requestId).toBe(requestIdMock);
// 'currency is wrong'
expect(request.currency).toEqual({
type: RequestLogicTypes.CURRENCY.ETH,
value: 'ETH',
});
// 'state is wrong'
expect(request.state).toBe(RequestLogicTypes.STATE.ACCEPTED);
// 'expectedAmount is wrong'
expect(request.expectedAmount).toBe(arbitraryExpectedAmountAfterDelta);
// 'extensions is wrong'
expect(request.extensions).toEqual({});
// 'request.creator is wrong'
expect(request).toHaveProperty('creator');
// 'request.creator.type is wrong'
expect(request.creator.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.creator.value is wrong'
expect(request.creator.value).toBe(TestData.payeeRaw.address);
// 'request.payee is wrong'
expect(request).toHaveProperty('payee');
if (request.payee) {
// 'request.payee.type is wrong'
expect(request.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.payee.value is wrong'
expect(request.payee.value).toBe(TestData.payeeRaw.address);
}
// 'request.payer is wrong'
expect(request).toHaveProperty('payer');
if (request.payer) {
// 'request.payer.type is wrong'
expect(request.payer.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.payer.value is wrong'
expect(request.payer.value).toBe(TestData.payerRaw.address);
}
// 'request.events is wrong'
expect(request.events[2]).toEqual({
actionSigner: TestData.payeeRaw.identity,
name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT,
parameters: { extensionsDataLength: 0, deltaAmount: arbitraryDeltaAmount },
timestamp: 2,
});
});
it('can reduce expected amount with extensionsData and no extensionsData before', async () => {
const newExtensionsData = [{ id: 'extension1', value: 'whatever' }];
const actionReduceAmount = await ReduceExpectedAmountAction.format(
{
deltaAmount: arbitraryDeltaAmount,
extensionsData: newExtensionsData,
requestId: requestIdMock,
},
TestData.payeeRaw.identity,
TestData.fakeSignatureProvider,
);
const request = ReduceExpectedAmountAction.applyActionToRequest(
actionReduceAmount,
2,
Utils.deepCopy(TestData.requestCreatedNoExtension),
);
// 'requestId is wrong'
expect(request.requestId).toBe(requestIdMock);
// 'currency is wrong'
expect(request.currency).toEqual({
type: RequestLogicTypes.CURRENCY.ETH,
value: 'ETH',
});
// 'state is wrong'
expect(request.state).toBe(RequestLogicTypes.STATE.CREATED);
// 'expectedAmount is wrong'
expect(request.expectedAmount).toBe(arbitraryExpectedAmountAfterDelta);
// 'request.extensionsData is wrong'
expect(request.extensionsData).toEqual(newExtensionsData);
// 'request.creator is wrong'
expect(request).toHaveProperty('creator');
// 'request.creator.type is wrong'
expect(request.creator.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.creator.value is wrong'
expect(request.creator.value).toBe(TestData.payeeRaw.address);
// 'request.payee is wrong'
expect(request).toHaveProperty('payee');
if (request.payee) {
// 'request.payee.type is wrong'
expect(request.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.payee.value is wrong'
expect(request.payee.value).toBe(TestData.payeeRaw.address);
}
// 'request.payer is wrong'
expect(request).toHaveProperty('payer');
if (request.payer) {
// 'request.payer.type is wrong'
expect(request.payer.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.payer.value is wrong'
expect(request.payer.value).toBe(TestData.payerRaw.address);
}
// 'request.events is wrong'
expect(request.events[1]).toEqual({
actionSigner: TestData.payeeRaw.identity,
name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT,
parameters: { extensionsDataLength: 1, deltaAmount: arbitraryDeltaAmount },
timestamp: 2,
});
});
it('can reduce expected amount with extensionsData and extensionsData before', async () => {
const newExtensionsData = [{ id: 'extension1', value: 'whatever' }];
const actionReduceAmount = await ReduceExpectedAmountAction.format(
{
deltaAmount: arbitraryDeltaAmount,
extensionsData: newExtensionsData,
requestId: requestIdMock,
},
TestData.payeeRaw.identity,
TestData.fakeSignatureProvider,
);
const request = ReduceExpectedAmountAction.applyActionToRequest(
actionReduceAmount,
2,
Utils.deepCopy(TestData.requestCreatedWithExtensions),
);
// 'requestId is wrong'
expect(request.requestId).toBe(requestIdMock);
// 'currency is wrong'
expect(request.currency).toEqual({
type: RequestLogicTypes.CURRENCY.ETH,
value: 'ETH',
});
// 'state is wrong'
expect(request.state).toBe(RequestLogicTypes.STATE.CREATED);
// 'expectedAmount is wrong'
expect(request.expectedAmount).toBe(arbitraryExpectedAmountAfterDelta);
// 'request.extensionsData is wrong'
expect(request.extensionsData).toEqual(TestData.oneExtension.concat(newExtensionsData));
// 'request.creator is wrong'
expect(request).toHaveProperty('creator');
// 'request.creator.type is wrong'
expect(request.creator.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.creator.value is wrong'
expect(request.creator.value).toBe(TestData.payeeRaw.address);
// 'request.payee is wrong'
expect(request).toHaveProperty('payee');
if (request.payee) {
// 'request.payee.type is wrong'
expect(request.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.payee.value is wrong'
expect(request.payee.value).toBe(TestData.payeeRaw.address);
}
// 'request.payer is wrong'
expect(request).toHaveProperty('payer');
if (request.payer) {
// 'request.payer.type is wrong'
expect(request.payer.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.payer.value is wrong'
expect(request.payer.value).toBe(TestData.payerRaw.address);
}
// 'request.events is wrong'
expect(request.events[1]).toEqual({
actionSigner: TestData.payeeRaw.identity,
name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT,
parameters: { extensionsDataLength: 1, deltaAmount: arbitraryDeltaAmount },
timestamp: 2,
});
});
it('can reduce expected amount without extensionsData and extensionsData before', async () => {
const actionReduceAmount = await ReduceExpectedAmountAction.format(
{
deltaAmount: arbitraryDeltaAmount,
requestId: requestIdMock,
},
TestData.payeeRaw.identity,
TestData.fakeSignatureProvider,
);
const request = ReduceExpectedAmountAction.applyActionToRequest(
actionReduceAmount,
2,
Utils.deepCopy(TestData.requestCreatedWithExtensions),
);
// 'requestId is wrong'
expect(request.requestId).toBe(requestIdMock);
// 'currency is wrong'
expect(request.currency).toEqual({
type: RequestLogicTypes.CURRENCY.ETH,
value: 'ETH',
});
// 'state is wrong'
expect(request.state).toBe(RequestLogicTypes.STATE.CREATED);
// 'expectedAmount is wrong'
expect(request.expectedAmount).toBe(arbitraryExpectedAmountAfterDelta);
// 'request.extensionsData is wrong'
expect(request.extensionsData).toEqual(TestData.oneExtension);
// 'request.creator is wrong'
expect(request).toHaveProperty('creator');
// 'request.creator.type is wrong'
expect(request.creator.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.creator.value is wrong'
expect(request.creator.value).toBe(TestData.payeeRaw.address);
// 'request.payee is wrong'
expect(request).toHaveProperty('payee');
if (request.payee) {
// 'request.payee.type is wrong'
expect(request.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.payee.value is wrong'
expect(request.payee.value).toBe(TestData.payeeRaw.address);
}
// 'request.payer is wrong'
expect(request).toHaveProperty('payer');
if (request.payer) {
// 'request.payer.type is wrong'
expect(request.payer.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.payer.value is wrong'
expect(request.payer.value).toBe(TestData.payerRaw.address);
}
// 'request.events is wrong'
expect(request.events[1]).toEqual({
actionSigner: TestData.payeeRaw.identity,
name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT,
parameters: { extensionsDataLength: 0, deltaAmount: arbitraryDeltaAmount },
timestamp: 2,
});
});
it('cannot reduce expected amount with a negative amount', () => {
const action = {
data: {
name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT,
parameters: {
deltaAmount: arbitraryDeltaAmountNegative,
requestId: requestIdMock,
},
version: CURRENT_VERSION,
},
signature: {
method: SignatureTypes.METHOD.ECDSA,
value:
'0xdd44c2d34cba689921c60043a78e189b4aa35d5940723bf98b9bb9083385de316333204ce3bbeced32afe2ea203b76153d523d924c4dca4a1d9fc466e0160f071c',
},
};
expect(() => {
ReduceExpectedAmountAction.applyActionToRequest(
action,
2,
Utils.deepCopy(TestData.requestCreatedNoExtension),
);
}).toThrowError('deltaAmount must be a string representing a positive integer');
});
it('cannot reduce expected amount with not a number', () => {
const action = {
data: {
name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT,
parameters: {
deltaAmount: 'Not a number',
requestId: requestIdMock,
},
version: CURRENT_VERSION,
},
signature: {
method: SignatureTypes.METHOD.ECDSA,
value:
'0xdd44c2d34cba689921c60043a78e189b4aa35d5940723bf98b9bb9083385de316333204ce3bbeced32afe2ea203b76153d523d924c4dca4a1d9fc466e0160f071c',
},
};
expect(() => {
ReduceExpectedAmountAction.applyActionToRequest(
action,
2,
Utils.deepCopy(TestData.requestCreatedNoExtension),
);
}).toThrowError('deltaAmount must be a string representing a positive integer');
});
it('cannot reduce expected amount with decimal', () => {
const action = {
data: {
name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT,
parameters: {
deltaAmount: '0.0234',
requestId: requestIdMock,
},
version: CURRENT_VERSION,
},
signature: {
method: SignatureTypes.METHOD.ECDSA,
value:
'0xdd44c2d34cba689921c60043a78e189b4aa35d5940723bf98b9bb9083385de316333204ce3bbeced32afe2ea203b76153d523d924c4dca4a1d9fc466e0160f071c',
},
};
expect(() => {
ReduceExpectedAmountAction.applyActionToRequest(
action,
2,
Utils.deepCopy(TestData.requestCreatedNoExtension),
);
}).toThrowError('deltaAmount must be a string representing a positive integer');
});
it('can reduce expected amount to zero', async () => {
const actionReduceAmount = await ReduceExpectedAmountAction.format(
{
deltaAmount: arbitraryExpectedAmount,
requestId: requestIdMock,
},
TestData.payeeRaw.identity,
TestData.fakeSignatureProvider,
);
const request = ReduceExpectedAmountAction.applyActionToRequest(
actionReduceAmount,
2,
Utils.deepCopy(TestData.requestCreatedNoExtension),
);
// 'requestId is wrong'
expect(request.requestId).toBe(requestIdMock);
// 'currency is wrong'
expect(request.currency).toEqual({
type: RequestLogicTypes.CURRENCY.ETH,
value: 'ETH',
});
// 'state is wrong'
expect(request.state).toBe(RequestLogicTypes.STATE.CREATED);
// 'expectedAmount is wrong'
expect(request.expectedAmount).toBe('0');
// 'extensions is wrong'
expect(request.extensions).toEqual({});
// 'request.creator is wrong'
expect(request).toHaveProperty('creator');
// 'request.creator.type is wrong'
expect(request.creator.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.creator.value is wrong'
expect(request.creator.value).toBe(TestData.payeeRaw.address);
// 'request.payee is wrong'
expect(request).toHaveProperty('payee');
if (request.payee) {
// 'request.payee.type is wrong'
expect(request.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.payee.value is wrong'
expect(request.payee.value).toBe(TestData.payeeRaw.address);
}
// 'request.payer is wrong'
expect(request).toHaveProperty('payer');
if (request.payer) {
// 'request.payer.type is wrong'
expect(request.payer.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.payer.value is wrong'
expect(request.payer.value).toBe(TestData.payerRaw.address);
}
// 'request.events is wrong'
expect(request.events[1]).toEqual({
actionSigner: TestData.payeeRaw.identity,
name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT,
parameters: { extensionsDataLength: 0, deltaAmount: TestData.arbitraryExpectedAmount },
timestamp: 2,
});
});
it('cannot reduce expected amount below zero', async () => {
const actionReduceAmount = await ReduceExpectedAmountAction.format(
{
deltaAmount: biggerThanArbitraryExpectedAmount,
requestId: requestIdMock,
},
TestData.payeeRaw.identity,
TestData.fakeSignatureProvider,
);
expect(() => {
ReduceExpectedAmountAction.applyActionToRequest(
actionReduceAmount,
2,
Utils.deepCopy(TestData.requestCreatedNoExtension),
);
}).toThrowError('result of reduce is not valid');
});
});
}); | the_stack |
// clang-format off
import 'chrome://settings/lazy_load.js';
import {webUIListenerCallback} from 'chrome://resources/js/cr.m.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {CrInputElement, SettingsSyncEncryptionOptionsElement, SettingsSyncPageElement} from 'chrome://settings/lazy_load.js';
// <if expr="not chromeos_ash and not chromeos_lacros">
import {CrDialogElement} from 'chrome://settings/lazy_load.js';
// </if>
import {CrButtonElement, CrRadioButtonElement, CrRadioGroupElement, PageStatus, Router, routes, StatusAction, SyncBrowserProxyImpl} from 'chrome://settings/settings.js';
import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js';
import {waitBeforeNextRender} from 'chrome://webui-test/test_util.js';
// <if expr="not chromeos_ash and not chromeos_lacros">
import {eventToPromise} from 'chrome://webui-test/test_util.js';
// </if>
// <if expr="not chromeos_ash">
import {simulateStoredAccounts} from './sync_test_util.js';
// </if>
import {getSyncAllPrefs, setupRouterWithSyncRoutes, SyncRoutes} from './sync_test_util.js';
import {TestSyncBrowserProxy} from './test_sync_browser_proxy.js';
// clang-format on
suite('SyncSettingsTests', function() {
let syncPage: SettingsSyncPageElement;
let browserProxy: TestSyncBrowserProxy;
let encryptionElement: SettingsSyncEncryptionOptionsElement;
let encryptionRadioGroup: CrRadioGroupElement;
let encryptWithGoogle: CrRadioButtonElement;
let encryptWithPassphrase: CrRadioButtonElement;
function setupSyncPage() {
document.body.innerHTML = '';
syncPage = document.createElement('settings-sync-page');
const router = Router.getInstance();
router.navigateTo((router.getRoutes() as SyncRoutes).SYNC);
// Preferences should exist for embedded
// 'personalization_options.html'. We don't perform tests on them.
syncPage.prefs = {
profile: {password_manager_leak_detection: {value: true}},
signin: {
allowed_on_next_startup:
{type: chrome.settingsPrivate.PrefType.BOOLEAN, value: true}
},
safebrowsing:
{enabled: {value: true}, scout_reporting_enabled: {value: true}},
};
document.body.appendChild(syncPage);
webUIListenerCallback('page-status-changed', PageStatus.CONFIGURE);
assertFalse(
syncPage.shadowRoot!
.querySelector<HTMLElement>('#' + PageStatus.CONFIGURE)!.hidden);
assertTrue(
syncPage.shadowRoot!
.querySelector<HTMLElement>('#' + PageStatus.SPINNER)!.hidden);
// Start with Sync All with no encryption selected. Also, ensure
// that this is not a supervised user, so that Sync Passphrase is
// enabled.
webUIListenerCallback('sync-prefs-changed', getSyncAllPrefs());
syncPage.set('syncStatus', {
supervisedUser: false,
statusAction: StatusAction.NO_ACTION,
});
flush();
}
suiteSetup(function() {
loadTimeData.overrideValues({signinAllowed: true});
});
setup(async function() {
setupRouterWithSyncRoutes();
browserProxy = new TestSyncBrowserProxy();
SyncBrowserProxyImpl.setInstance(browserProxy);
setupSyncPage();
await waitBeforeNextRender(syncPage);
encryptionElement =
syncPage.shadowRoot!.querySelector('settings-sync-encryption-options')!;
assertTrue(!!encryptionElement);
encryptionRadioGroup =
encryptionElement.shadowRoot!.querySelector('#encryptionRadioGroup')!;
encryptWithGoogle = encryptionElement.shadowRoot!.querySelector(
'cr-radio-button[name="encrypt-with-google"]')!;
encryptWithPassphrase = encryptionElement.shadowRoot!.querySelector(
'cr-radio-button[name="encrypt-with-passphrase"]')!;
assertTrue(!!encryptionRadioGroup);
assertTrue(!!encryptWithGoogle);
assertTrue(!!encryptWithPassphrase);
});
teardown(function() {
syncPage.remove();
});
// #######################
// TESTS FOR ALL PLATFORMS
// #######################
test('NotifiesHandlerOfNavigation', async function() {
await browserProxy.whenCalled('didNavigateToSyncPage');
// Navigate away.
const router = Router.getInstance();
router.navigateTo((router.getRoutes() as SyncRoutes).PEOPLE);
await browserProxy.whenCalled('didNavigateAwayFromSyncPage');
// Navigate back to the page.
browserProxy.resetResolver('didNavigateToSyncPage');
router.navigateTo((router.getRoutes() as SyncRoutes).SYNC);
await browserProxy.whenCalled('didNavigateToSyncPage');
// Remove page element.
browserProxy.resetResolver('didNavigateAwayFromSyncPage');
syncPage.remove();
await browserProxy.whenCalled('didNavigateAwayFromSyncPage');
// Recreate page element.
browserProxy.resetResolver('didNavigateToSyncPage');
syncPage = document.createElement('settings-sync-page');
router.navigateTo((router.getRoutes() as SyncRoutes).SYNC);
document.body.appendChild(syncPage);
await browserProxy.whenCalled('didNavigateToSyncPage');
});
test('SyncSectionLayout_SignedIn', function() {
const syncSection =
syncPage.shadowRoot!.querySelector<HTMLElement>('#sync-section')!;
const otherItems =
syncPage.shadowRoot!.querySelector<HTMLElement>('#other-sync-items')!;
syncPage.syncStatus = {
signedIn: true,
disabled: false,
hasError: false,
statusAction: StatusAction.NO_ACTION,
};
flush();
assertFalse(syncSection.hidden);
assertTrue(
syncPage.shadowRoot!.querySelector<HTMLElement>(
'#sync-separator')!.hidden);
assertTrue(otherItems.classList.contains('list-frame'));
assertEquals(
otherItems.querySelectorAll(':scope > cr-expand-button').length, 1);
assertEquals(otherItems.querySelectorAll(':scope > cr-link-row').length, 3);
// Test sync paused state.
syncPage.syncStatus = {
signedIn: true,
disabled: false,
hasError: true,
statusAction: StatusAction.REAUTHENTICATE
};
assertTrue(syncSection.hidden);
assertFalse(
syncPage.shadowRoot!.querySelector<HTMLElement>(
'#sync-separator')!.hidden);
// Test passphrase error state.
syncPage.syncStatus = {
signedIn: true,
disabled: false,
hasError: true,
statusAction: StatusAction.ENTER_PASSPHRASE
};
assertFalse(syncSection.hidden);
assertTrue(
syncPage.shadowRoot!.querySelector<HTMLElement>(
'#sync-separator')!.hidden);
});
test('SyncSectionLayout_SignedOut', function() {
const syncSection =
syncPage.shadowRoot!.querySelector<HTMLElement>('#sync-section')!;
syncPage.syncStatus = {
signedIn: false,
disabled: false,
hasError: false,
statusAction: StatusAction.NO_ACTION,
};
flush();
assertTrue(syncSection.hidden);
assertFalse(
syncPage.shadowRoot!.querySelector<HTMLElement>(
'#sync-separator')!.hidden);
});
test('SyncSectionLayout_SyncDisabled', function() {
const syncSection =
syncPage.shadowRoot!.querySelector<HTMLElement>('#sync-section')!;
syncPage.syncStatus = {
signedIn: false,
disabled: true,
hasError: false,
statusAction: StatusAction.NO_ACTION,
};
flush();
assertTrue(syncSection.hidden);
});
test('LoadingAndTimeout', function() {
const configurePage = syncPage.shadowRoot!.querySelector<HTMLElement>(
'#' + PageStatus.CONFIGURE)!;
const spinnerPage = syncPage.shadowRoot!.querySelector<HTMLElement>(
'#' + PageStatus.SPINNER)!;
// NOTE: This isn't called in production, but the test suite starts the
// tests with PageStatus.CONFIGURE.
webUIListenerCallback('page-status-changed', PageStatus.SPINNER);
assertTrue(configurePage.hidden);
assertFalse(spinnerPage.hidden);
webUIListenerCallback('page-status-changed', PageStatus.CONFIGURE);
assertFalse(configurePage.hidden);
assertTrue(spinnerPage.hidden);
// Should remain on the CONFIGURE page even if the passphrase failed.
webUIListenerCallback('page-status-changed', PageStatus.PASSPHRASE_FAILED);
assertFalse(configurePage.hidden);
assertTrue(spinnerPage.hidden);
});
test('EncryptionExpandButton', function() {
const encryptionDescription =
syncPage.shadowRoot!.querySelector<HTMLElement>(
'#encryptionDescription')!;
const encryptionCollapse = syncPage.$.encryptionCollapse;
// No encryption with custom passphrase.
assertFalse(encryptionCollapse.opened);
encryptionDescription.click();
assertTrue(encryptionCollapse.opened);
// Push sync prefs with |prefs.encryptAllData| unchanged. The encryption
// menu should not collapse.
webUIListenerCallback('sync-prefs-changed', getSyncAllPrefs());
flush();
assertTrue(encryptionCollapse.opened);
encryptionDescription.click();
assertFalse(encryptionCollapse.opened);
// Data encrypted with custom passphrase.
// The encryption menu should be expanded.
const prefs = getSyncAllPrefs();
prefs.encryptAllData = true;
webUIListenerCallback('sync-prefs-changed', prefs);
flush();
assertTrue(encryptionCollapse.opened);
// Clicking |reset Sync| does not change the expansion state.
const link =
encryptionDescription.querySelector<HTMLAnchorElement>('a[href]');
assertTrue(!!link);
link!.target = '';
link!.href = '#';
// Prevent the link from triggering a page navigation when tapped.
// Breaks the test in Vulcanized mode.
link!.addEventListener('click', e => e.preventDefault());
link!.click();
assertTrue(encryptionCollapse.opened);
});
test('RadioBoxesEnabledWhenUnencrypted', function() {
// Verify that the encryption radio boxes are enabled.
assertFalse(encryptionRadioGroup.disabled);
assertEquals(encryptWithGoogle.getAttribute('aria-disabled'), 'false');
assertEquals(encryptWithPassphrase.getAttribute('aria-disabled'), 'false');
assertTrue(encryptWithGoogle.checked);
// Select 'Encrypt with passphrase' to create a new passphrase.
assertFalse(
!!encryptionElement.shadowRoot!.querySelector('#create-password-box'));
encryptWithPassphrase.click();
flush();
assertTrue(
!!encryptionElement.shadowRoot!.querySelector('#create-password-box'));
const saveNewPassphrase =
encryptionElement.shadowRoot!.querySelector<CrButtonElement>(
'#saveNewPassphrase');
assertTrue(!!saveNewPassphrase);
// Test that a sync prefs update does not reset the selection.
webUIListenerCallback('sync-prefs-changed', getSyncAllPrefs());
flush();
assertTrue(encryptWithPassphrase.checked);
});
test('ClickingLinkDoesNotChangeRadioValue', function() {
assertFalse(encryptionRadioGroup.disabled);
assertEquals(encryptWithPassphrase.getAttribute('aria-disabled'), 'false');
assertFalse(encryptWithPassphrase.checked);
const link =
encryptWithPassphrase.querySelector<HTMLAnchorElement>('a[href]');
assertTrue(!!link);
// Suppress opening a new tab, since then the test will continue running
// on a background tab (which has throttled timers) and will timeout.
link!.target = '';
link!.href = '#';
// Prevent the link from triggering a page navigation when tapped.
// Breaks the test in Vulcanized mode.
link!.addEventListener('click', function(e) {
e.preventDefault();
});
link!.click();
assertFalse(encryptWithPassphrase.checked);
});
test('SaveButtonDisabledWhenPassphraseOrConfirmationEmpty', function() {
encryptWithPassphrase.click();
flush();
assertTrue(
!!encryptionElement.shadowRoot!.querySelector('#create-password-box'));
const saveNewPassphrase =
encryptionElement.shadowRoot!.querySelector<CrButtonElement>(
'#saveNewPassphrase')!;
const passphraseInput =
encryptionElement.shadowRoot!.querySelector<CrInputElement>(
'#passphraseInput')!;
const passphraseConfirmationInput =
encryptionElement.shadowRoot!.querySelector<CrInputElement>(
'#passphraseConfirmationInput')!;
passphraseInput.value = '';
passphraseConfirmationInput.value = '';
assertTrue(saveNewPassphrase.disabled);
passphraseInput.value = 'foo';
passphraseConfirmationInput.value = '';
assertTrue(saveNewPassphrase.disabled);
passphraseInput.value = 'foo';
passphraseConfirmationInput.value = 'bar';
assertFalse(saveNewPassphrase.disabled);
});
test('CreatingPassphraseMismatchedPassphrase', function() {
encryptWithPassphrase.click();
flush();
assertTrue(
!!encryptionElement.shadowRoot!.querySelector('#create-password-box'));
const saveNewPassphrase =
encryptionElement.shadowRoot!.querySelector<CrButtonElement>(
'#saveNewPassphrase');
assertTrue(!!saveNewPassphrase);
const passphraseInput =
encryptionElement.shadowRoot!.querySelector<CrInputElement>(
'#passphraseInput')!;
const passphraseConfirmationInput =
encryptionElement.shadowRoot!.querySelector<CrInputElement>(
'#passphraseConfirmationInput')!;
passphraseInput.value = 'foo';
passphraseConfirmationInput.value = 'bar';
saveNewPassphrase!.click();
flush();
assertFalse(passphraseInput.invalid);
assertTrue(passphraseConfirmationInput.invalid);
});
test('CreatingPassphraseValidPassphrase', async function() {
encryptWithPassphrase.click();
flush();
assertTrue(
!!encryptionElement.shadowRoot!.querySelector('#create-password-box'));
const saveNewPassphrase =
encryptionElement.shadowRoot!.querySelector<CrButtonElement>(
'#saveNewPassphrase');
assertTrue(!!saveNewPassphrase);
const passphraseInput =
encryptionElement.shadowRoot!.querySelector<CrInputElement>(
'#passphraseInput')!;
const passphraseConfirmationInput =
encryptionElement.shadowRoot!.querySelector<CrInputElement>(
'#passphraseConfirmationInput')!;
passphraseInput.value = 'foo';
passphraseConfirmationInput.value = 'foo';
browserProxy.encryptionPassphraseSuccess = true;
saveNewPassphrase!.click();
const passphrase = await browserProxy.whenCalled('setEncryptionPassphrase');
assertEquals('foo', passphrase);
// Fake backend response.
const newPrefs = getSyncAllPrefs();
newPrefs.encryptAllData = true;
webUIListenerCallback('sync-prefs-changed', newPrefs);
flush();
await waitBeforeNextRender(syncPage);
// Need to re-retrieve this, as a different show passphrase radio
// button is shown for custom passphrase users.
encryptWithPassphrase = encryptionElement.shadowRoot!.querySelector(
'cr-radio-button[name="encrypt-with-passphrase"]')!;
// Assert that the radio boxes are disabled after encryption enabled.
assertTrue(encryptionRadioGroup.disabled);
assertEquals(-1, encryptWithGoogle.$.button.tabIndex);
assertEquals(-1, encryptWithPassphrase.$.button.tabIndex);
});
test('RadioBoxesHiddenWhenPassphraseRequired', function() {
const prefs = getSyncAllPrefs();
prefs.encryptAllData = true;
prefs.passphraseRequired = true;
webUIListenerCallback('sync-prefs-changed', prefs);
flush();
assertTrue(
syncPage.shadowRoot!
.querySelector<HTMLElement>('#encryptionDescription')!.hidden);
assertEquals(
encryptionElement.shadowRoot!
.querySelector<HTMLElement>(
'#encryptionRadioGroupContainer')!.style.display,
'none');
});
test(
'ExistingPassphraseSubmitButtonDisabledWhenExistingPassphraseEmpty',
function() {
const prefs = getSyncAllPrefs();
prefs.encryptAllData = true;
prefs.passphraseRequired = true;
webUIListenerCallback('sync-prefs-changed', prefs);
flush();
const existingPassphraseInput =
syncPage.shadowRoot!.querySelector<CrInputElement>(
'#existingPassphraseInput')!;
const submitExistingPassphrase =
syncPage.shadowRoot!.querySelector<CrButtonElement>(
'#submitExistingPassphrase')!;
existingPassphraseInput.value = '';
assertTrue(submitExistingPassphrase.disabled);
existingPassphraseInput.value = 'foo';
assertFalse(submitExistingPassphrase.disabled);
});
test('EnterExistingWrongPassphrase', async function() {
const prefs = getSyncAllPrefs();
prefs.encryptAllData = true;
prefs.passphraseRequired = true;
webUIListenerCallback('sync-prefs-changed', prefs);
flush();
const existingPassphraseInput =
syncPage.shadowRoot!.querySelector<CrInputElement>(
'#existingPassphraseInput');
assertTrue(!!existingPassphraseInput);
existingPassphraseInput!.value = 'wrong';
browserProxy.decryptionPassphraseSuccess = false;
const submitExistingPassphrase =
syncPage.shadowRoot!.querySelector<CrButtonElement>(
'#submitExistingPassphrase');
assertTrue(!!submitExistingPassphrase);
submitExistingPassphrase!.click();
const passphrase = await browserProxy.whenCalled('setDecryptionPassphrase');
assertEquals('wrong', passphrase);
assertTrue(existingPassphraseInput!.invalid);
});
test('EnterExistingCorrectPassphrase', async function() {
const prefs = getSyncAllPrefs();
prefs.encryptAllData = true;
prefs.passphraseRequired = true;
webUIListenerCallback('sync-prefs-changed', prefs);
flush();
const existingPassphraseInput =
syncPage.shadowRoot!.querySelector<CrInputElement>(
'#existingPassphraseInput');
assertTrue(!!existingPassphraseInput);
existingPassphraseInput!.value = 'right';
browserProxy.decryptionPassphraseSuccess = true;
const submitExistingPassphrase =
syncPage.shadowRoot!.querySelector<CrButtonElement>(
'#submitExistingPassphrase');
assertTrue(!!submitExistingPassphrase);
submitExistingPassphrase!.click();
const passphrase = await browserProxy.whenCalled('setDecryptionPassphrase');
assertEquals('right', passphrase);
// Fake backend response.
const newPrefs = getSyncAllPrefs();
newPrefs.encryptAllData = true;
webUIListenerCallback('sync-prefs-changed', newPrefs);
flush();
// Verify that the encryption radio boxes are shown but disabled.
assertTrue(encryptionRadioGroup.disabled);
assertEquals(-1, encryptWithGoogle.$.button.tabIndex);
assertEquals(-1, encryptWithPassphrase.$.button.tabIndex);
});
test('SyncAdvancedRow', function() {
flush();
const syncAdvancedRow =
syncPage.shadowRoot!.querySelector<HTMLElement>('#sync-advanced-row')!;
assertFalse(syncAdvancedRow.hidden);
syncAdvancedRow.click();
flush();
assertEquals(
routes.SYNC_ADVANCED.path, Router.getInstance().getCurrentRoute().path);
});
// This test checks whether the passphrase encryption options are
// disabled. This is important for supervised accounts. Because sync
// is required for supervision, passphrases should remain disabled.
test('DisablingSyncPassphrase', function() {
// We initialize a new SyncPrefs object for each case, because
// otherwise the webUIListener doesn't update.
// 1) Normal user (full data encryption allowed)
// EXPECTED: encryptionOptions enabled
const prefs1 = getSyncAllPrefs();
prefs1.customPassphraseAllowed = true;
webUIListenerCallback('sync-prefs-changed', prefs1);
syncPage.syncStatus = {
supervisedUser: false,
statusAction: StatusAction.NO_ACTION,
};
flush();
assertFalse(encryptionRadioGroup.disabled);
assertEquals(encryptWithGoogle.getAttribute('aria-disabled'), 'false');
assertEquals(encryptWithPassphrase.getAttribute('aria-disabled'), 'false');
// 2) Normal user (full data encryption not allowed)
// customPassphraseAllowed is usually false only for supervised
// users, but it's better to be check this case.
// EXPECTED: encryptionOptions disabled
const prefs2 = getSyncAllPrefs();
prefs2.customPassphraseAllowed = false;
webUIListenerCallback('sync-prefs-changed', prefs2);
syncPage.syncStatus = {
supervisedUser: false,
statusAction: StatusAction.NO_ACTION,
};
flush();
assertTrue(encryptionRadioGroup.disabled);
assertEquals(encryptWithGoogle.getAttribute('aria-disabled'), 'true');
assertEquals(encryptWithPassphrase.getAttribute('aria-disabled'), 'true');
// 3) Supervised user (full data encryption not allowed)
// EXPECTED: encryptionOptions disabled
const prefs3 = getSyncAllPrefs();
prefs3.customPassphraseAllowed = false;
webUIListenerCallback('sync-prefs-changed', prefs3);
syncPage.syncStatus = {
supervisedUser: true,
statusAction: StatusAction.NO_ACTION,
};
flush();
assertTrue(encryptionRadioGroup.disabled);
assertEquals(encryptWithGoogle.getAttribute('aria-disabled'), 'true');
assertEquals(encryptWithPassphrase.getAttribute('aria-disabled'), 'true');
// 4) Supervised user (full data encryption allowed)
// This never happens in practice, but just to be safe.
// EXPECTED: encryptionOptions disabled
const prefs4 = getSyncAllPrefs();
prefs4.customPassphraseAllowed = true;
webUIListenerCallback('sync-prefs-changed', prefs4);
syncPage.syncStatus = {
supervisedUser: true,
statusAction: StatusAction.NO_ACTION,
};
flush();
assertTrue(encryptionRadioGroup.disabled);
assertEquals(encryptWithGoogle.getAttribute('aria-disabled'), 'true');
assertEquals(encryptWithPassphrase.getAttribute('aria-disabled'), 'true');
});
// The sync dashboard is not accessible by supervised
// users, so it should remain hidden.
test('SyncDashboardHiddenFromSupervisedUsers', function() {
const dashboardLink =
syncPage.shadowRoot!.querySelector<HTMLElement>('#syncDashboardLink')!;
const prefs = getSyncAllPrefs();
webUIListenerCallback('sync-prefs-changed', prefs);
// Normal user
syncPage.syncStatus = {
supervisedUser: false,
statusAction: StatusAction.NO_ACTION
};
flush();
assertFalse(dashboardLink.hidden);
// Supervised user
syncPage.syncStatus = {
supervisedUser: true,
statusAction: StatusAction.NO_ACTION
};
flush();
assertTrue(dashboardLink.hidden);
});
// ######################################
// TESTS THAT ARE SKIPPED ON CHROMEOS ASH
// ######################################
// <if expr="not chromeos_ash">
test('SyncSetupCancel', async function() {
syncPage.syncStatus = {
syncSystemEnabled: true,
firstSetupInProgress: true,
signedIn: true,
statusAction: StatusAction.NO_ACTION,
};
flush();
simulateStoredAccounts([{email: 'foo@foo.com'}]);
const cancelButton =
syncPage.shadowRoot!.querySelector('settings-sync-account-control')!
.shadowRoot!.querySelector<HTMLElement>(
'#setup-buttons cr-button:not(.action-button)');
// <if expr="chromeos_lacros">
// On Lacros, turning off sync is not supported yet.
// TODO(https://crbug.com/1217645): Add the cancel button.
assertFalse(!!cancelButton);
// </if>
// <if expr="not chromeos_lacros">
assertTrue(!!cancelButton);
// Clicking the setup cancel button aborts sync.
cancelButton!.click();
const abort = await browserProxy.whenCalled('didNavigateAwayFromSyncPage');
assertTrue(abort);
// </if>
});
test('SyncSetupConfirm', async function() {
syncPage.syncStatus = {
syncSystemEnabled: true,
firstSetupInProgress: true,
signedIn: true,
statusAction: StatusAction.NO_ACTION,
};
flush();
simulateStoredAccounts([{email: 'foo@foo.com'}]);
const confirmButton =
syncPage.shadowRoot!.querySelector('settings-sync-account-control')!
.shadowRoot!.querySelector<HTMLElement>(
'#setup-buttons .action-button');
assertTrue(!!confirmButton);
confirmButton!.click();
const abort = await browserProxy.whenCalled('didNavigateAwayFromSyncPage');
assertFalse(abort);
});
// On Lacros, turning off sync is not supported yet.
// TODO(https://crbug.com/1217645): Enable this test after adding support.
// <if expr="not chromeos_lacros">
test('SyncSetupLeavePage', async function() {
syncPage.syncStatus = {
syncSystemEnabled: true,
firstSetupInProgress: true,
signedIn: true,
statusAction: StatusAction.NO_ACTION,
};
flush();
// Navigating away while setup is in progress opens the 'Cancel sync?'
// dialog.
const router = Router.getInstance();
router.navigateTo(routes.BASIC);
await eventToPromise('cr-dialog-open', syncPage);
assertEquals(
(router.getRoutes() as SyncRoutes).SYNC, router.getCurrentRoute());
assertTrue(syncPage.shadowRoot!
.querySelector<CrDialogElement>('#setupCancelDialog')!.open);
// Clicking the cancel button on the 'Cancel sync?' dialog closes
// the dialog and removes it from the DOM.
syncPage.shadowRoot!.querySelector<CrDialogElement>('#setupCancelDialog')!
.querySelector<HTMLElement>('.cancel-button')!.click();
await eventToPromise(
'close',
syncPage.shadowRoot!.querySelector<CrDialogElement>(
'#setupCancelDialog')!);
flush();
assertEquals(
(router.getRoutes() as SyncRoutes).SYNC, router.getCurrentRoute());
assertFalse(!!syncPage.shadowRoot!.querySelector<CrDialogElement>(
'#setupCancelDialog'));
// Navigating away while setup is in progress opens the
// dialog again.
router.navigateTo(routes.BASIC);
await eventToPromise('cr-dialog-open', syncPage);
assertTrue(syncPage.shadowRoot!
.querySelector<CrDialogElement>('#setupCancelDialog')!.open);
// Clicking the confirm button on the dialog aborts sync.
syncPage.shadowRoot!.querySelector<CrDialogElement>('#setupCancelDialog')!
.querySelector<HTMLElement>('.action-button')!.click();
const abort = await browserProxy.whenCalled('didNavigateAwayFromSyncPage');
assertTrue(abort);
});
// </if>
test('SyncSetupSearchSettings', async function() {
syncPage.syncStatus = {
syncSystemEnabled: true,
firstSetupInProgress: true,
signedIn: true,
statusAction: StatusAction.NO_ACTION,
};
flush();
// Searching settings while setup is in progress cancels sync.
const router = Router.getInstance();
router.navigateTo(
(router.getRoutes() as SyncRoutes).BASIC,
new URLSearchParams('search=foo'));
const abort = await browserProxy.whenCalled('didNavigateAwayFromSyncPage');
assertTrue(abort);
});
test('ShowAccountRow', function() {
assertFalse(
!!syncPage.shadowRoot!.querySelector('settings-sync-account-control'));
syncPage.syncStatus = {
syncSystemEnabled: false,
statusAction: StatusAction.NO_ACTION
};
flush();
assertFalse(
!!syncPage.shadowRoot!.querySelector('settings-sync-account-control'));
syncPage.syncStatus = {
syncSystemEnabled: true,
statusAction: StatusAction.NO_ACTION
};
flush();
assertTrue(
!!syncPage.shadowRoot!.querySelector('settings-sync-account-control'));
});
test('ShowAccountRow_SigninAllowedFalse', function() {
loadTimeData.overrideValues({signinAllowed: false});
setupSyncPage();
assertFalse(
!!syncPage.shadowRoot!.querySelector('settings-sync-account-control'));
syncPage.syncStatus = {
syncSystemEnabled: false,
statusAction: StatusAction.NO_ACTION
};
flush();
assertFalse(
!!syncPage.shadowRoot!.querySelector('settings-sync-account-control'));
syncPage.syncStatus = {
syncSystemEnabled: true,
statusAction: StatusAction.NO_ACTION
};
flush();
assertFalse(
!!syncPage.shadowRoot!.querySelector('settings-sync-account-control'));
});
// </if>
}); | the_stack |
import { assert } from "chai";
import {
AddWinsCSet,
CRDTApp,
FalseWinsCBoolean,
TrueWinsCBoolean,
LWWCMap,
CNumber,
TestingCRDTAppGenerator,
DeletingMutCSet,
ResettableCCounter,
OptionalLWWCVariable,
} from "../../src";
import {
CMapDeleteEvent,
CMapSetEvent,
InitToken,
Pre,
Optional,
LazyMutCMap,
CollabIDSerializer,
CollabID,
} from "@collabs/core";
import { debug } from "../debug";
import seedrandom = require("seedrandom");
describe("standard", () => {
let appGen: TestingCRDTAppGenerator;
let alice: CRDTApp;
let bob: CRDTApp;
let rng: seedrandom.prng;
beforeEach(() => {
rng = seedrandom("42");
appGen = new TestingCRDTAppGenerator();
alice = appGen.newApp(undefined, rng);
bob = appGen.newApp(undefined, rng);
});
describe("TrueWinsCBoolean", () => {
let aliceFlag: TrueWinsCBoolean;
let bobFlag: TrueWinsCBoolean;
beforeEach(() => {
aliceFlag = alice.registerCollab("ewFlagId", Pre(TrueWinsCBoolean)());
bobFlag = bob.registerCollab("ewFlagId", Pre(TrueWinsCBoolean)());
alice.load(Optional.empty());
bob.load(Optional.empty());
if (debug) {
addEventListeners(aliceFlag, "Alice");
addEventListeners(bobFlag, "Bob");
}
});
function addEventListeners(flag: TrueWinsCBoolean, name: string): void {
flag.on("Set", (event, caller) => {
if (caller.value) {
console.log(`${name}: ${event.meta.sender} enabled`);
} else {
console.log(`${name}: ${event.meta.sender} disabled`);
}
});
}
it("is initially false", () => {
assert.isFalse(aliceFlag.value);
assert.isFalse(bobFlag.value);
});
it("works with non-concurrent updates", () => {
aliceFlag.value = true;
assert.isTrue(aliceFlag.value);
assert.isFalse(bobFlag.value);
appGen.releaseAll();
assert.isTrue(aliceFlag.value);
assert.isTrue(bobFlag.value);
aliceFlag.value = false;
assert.isFalse(aliceFlag.value);
assert.isTrue(bobFlag.value);
appGen.releaseAll();
assert.isFalse(aliceFlag.value);
assert.isFalse(bobFlag.value);
});
it("works with non-concurrent updates", () => {
aliceFlag.value = true;
bobFlag.value = false;
assert.isTrue(aliceFlag.value);
assert.isFalse(bobFlag.value);
// Enable wins
appGen.releaseAll();
assert.isTrue(aliceFlag.value);
assert.isTrue(bobFlag.value);
});
describe("enable", () => {
it("emits a Set event", async () => {
const promise = Promise.all([
aliceFlag.nextEvent("Set"),
bobFlag.nextEvent("Set"),
]);
aliceFlag.value = true;
appGen.releaseAll();
await promise;
});
});
describe("disable", () => {
it("emits a Set event", async () => {
aliceFlag.value = true;
appGen.releaseAll();
const promise = Promise.all([
aliceFlag.nextEvent("Set"),
bobFlag.nextEvent("Set"),
]);
aliceFlag.value = false;
appGen.releaseAll();
await promise;
});
});
});
describe("FalseWinsCBoolean", () => {
let aliceFlag: FalseWinsCBoolean;
let bobFlag: FalseWinsCBoolean;
beforeEach(() => {
aliceFlag = alice.registerCollab("dwFlagId", Pre(FalseWinsCBoolean)());
bobFlag = bob.registerCollab("dwFlagId", Pre(FalseWinsCBoolean)());
alice.load(Optional.empty());
bob.load(Optional.empty());
if (debug) {
addEventListeners(aliceFlag, "Alice");
addEventListeners(bobFlag, "Bob");
}
});
function addEventListeners(flag: FalseWinsCBoolean, name: string): void {
flag.on("Set", (event, caller) => {
if (caller.value) {
console.log(`${name}: ${event.meta.sender} enabled`);
} else {
console.log(`${name}: ${event.meta.sender} disabled`);
}
});
}
it("is initially true", () => {
assert.isTrue(aliceFlag.value);
assert.isTrue(bobFlag.value);
});
it("works with non-concurrent updates", () => {
bobFlag.value = true;
appGen.releaseAll();
assert.isTrue(aliceFlag.value);
assert.isTrue(bobFlag.value);
aliceFlag.value = false;
appGen.releaseAll();
assert.isFalse(aliceFlag.value);
assert.isFalse(bobFlag.value);
});
it("works with non-concurrent updates", () => {
aliceFlag.value = true;
bobFlag.value = false;
assert.isTrue(aliceFlag.value);
assert.isFalse(bobFlag.value);
// Disable wins
appGen.releaseAll();
assert.isFalse(aliceFlag.value);
assert.isFalse(bobFlag.value);
});
describe("enable", () => {
it("emits a Set event", async () => {
aliceFlag.value = false;
appGen.releaseAll();
const promise = Promise.all([
aliceFlag.nextEvent("Set"),
bobFlag.nextEvent("Set"),
]);
aliceFlag.value = true;
appGen.releaseAll();
await promise;
});
});
describe("disable", () => {
it("emits a Set event", async () => {
const promise = Promise.all([
aliceFlag.nextEvent("Set"),
bobFlag.nextEvent("Set"),
]);
aliceFlag.value = false;
appGen.releaseAll();
await promise;
});
});
});
describe("Number", () => {
let aliceNumber: CNumber;
let bobNumber: CNumber;
function init(initialValue: number, name = "numberId"): void {
aliceNumber = alice.registerCollab(name, Pre(CNumber)(initialValue));
bobNumber = bob.registerCollab(name, Pre(CNumber)(initialValue));
alice.load(Optional.empty());
bob.load(Optional.empty());
if (debug) {
addEventListeners(aliceNumber, "Alice");
addEventListeners(bobNumber, "Bob");
}
}
function addEventListeners(number: CNumber, name: string): void {
number.on("Add", (event) =>
console.log(`${name}: ${event.meta.sender} added ${event.arg}`)
);
number.on("Mult", (event) =>
console.log(`${name}: ${event.meta.sender} multed ${event.arg}`)
);
number.on("Min", (event) =>
console.log(`${name}: ${event.meta.sender} minned ${event.arg}`)
);
number.on("Max", (event) =>
console.log(`${name}: ${event.meta.sender} maxed ${event.arg}`)
);
}
it("is initially 0", () => {
init(0);
assert.strictEqual(aliceNumber.value, 0);
assert.strictEqual(bobNumber.value, 0);
});
describe("add", () => {
it("works with non-concurrent updates", () => {
init(0);
aliceNumber.add(3);
appGen.releaseAll();
assert.strictEqual(aliceNumber.value, 3);
assert.strictEqual(bobNumber.value, 3);
bobNumber.add(-4);
appGen.releaseAll();
assert.strictEqual(aliceNumber.value, -1);
assert.strictEqual(bobNumber.value, -1);
});
it("works with concurrent updates", () => {
init(0);
aliceNumber.add(3);
bobNumber.add(-4);
assert.strictEqual(aliceNumber.value, 3);
assert.strictEqual(bobNumber.value, -4);
appGen.releaseAll();
assert.strictEqual(aliceNumber.value, -1);
assert.strictEqual(bobNumber.value, -1);
});
});
describe("add and mult", () => {
it("works with non-concurrent updates", () => {
init(0);
aliceNumber.add(3);
appGen.releaseAll();
assert.strictEqual(aliceNumber.value, 3);
assert.strictEqual(bobNumber.value, 3);
bobNumber.mult(-4);
appGen.releaseAll();
assert.strictEqual(aliceNumber.value, -12);
assert.strictEqual(bobNumber.value, -12);
aliceNumber.add(7);
appGen.releaseAll();
assert.strictEqual(aliceNumber.value, -5);
assert.strictEqual(bobNumber.value, -5);
});
it("works with concurrent updates", () => {
init(0);
aliceNumber.add(2);
assert.strictEqual(aliceNumber.value, 2);
assert.strictEqual(bobNumber.value, 0);
bobNumber.add(1);
bobNumber.mult(5);
assert.strictEqual(aliceNumber.value, 2);
assert.strictEqual(bobNumber.value, 5);
// Arbitration order places multiplication last
appGen.releaseAll();
assert.strictEqual(aliceNumber.value, 15);
assert.strictEqual(bobNumber.value, 15);
});
it("works with the example from the paper", () => {
// See https://arxiv.org/abs/2004.04303, §3.1
init(1, "numberIdPaper");
aliceNumber.mult(2);
aliceNumber.add(1);
bobNumber.mult(3);
bobNumber.add(4);
assert.strictEqual(aliceNumber.value, 3);
assert.strictEqual(bobNumber.value, 7);
appGen.releaseAll();
assert.strictEqual(aliceNumber.value, 17);
assert.strictEqual(bobNumber.value, 17);
});
});
describe("multiple ops", () => {
it("works with non-concurrent updates", () => {
init(0);
aliceNumber.add(3);
appGen.releaseAll();
assert.strictEqual(aliceNumber.value, 3);
assert.strictEqual(bobNumber.value, 3);
bobNumber.mult(-4);
appGen.releaseAll();
assert.strictEqual(aliceNumber.value, -12);
assert.strictEqual(bobNumber.value, -12);
aliceNumber.min(10);
appGen.releaseAll();
assert.strictEqual(aliceNumber.value, -12);
assert.strictEqual(bobNumber.value, -12);
aliceNumber.max(-5);
appGen.releaseAll();
assert.strictEqual(aliceNumber.value, -5);
assert.strictEqual(bobNumber.value, -5);
});
it("works with concurrent updates", () => {
init(0);
aliceNumber.add(2);
assert.strictEqual(aliceNumber.value, 2);
assert.strictEqual(bobNumber.value, 0);
bobNumber.add(1);
bobNumber.mult(5);
assert.strictEqual(aliceNumber.value, 2);
assert.strictEqual(bobNumber.value, 5);
// Arbitration order places multiplication last
appGen.releaseAll();
assert.strictEqual(aliceNumber.value, 15);
assert.strictEqual(bobNumber.value, 15);
aliceNumber.min(2);
bobNumber.mult(5);
assert.strictEqual(aliceNumber.value, 2);
assert.strictEqual(bobNumber.value, 75);
// Arbitration order places multiplication last
appGen.releaseAll();
assert.strictEqual(aliceNumber.value, 10);
assert.strictEqual(bobNumber.value, 10);
aliceNumber.max(3);
bobNumber.add(5);
assert.strictEqual(aliceNumber.value, 10);
assert.strictEqual(bobNumber.value, 15);
// Arbitration order places addition last
appGen.releaseAll();
assert.strictEqual(aliceNumber.value, 15);
assert.strictEqual(bobNumber.value, 15);
});
});
// describe("reset", () => {
// it("resets to the initial value", () => {
// aliceNumber.add(1);
// aliceNumber.reset();
// appGen.releaseAll();
// assert.strictEqual(aliceNumber.value, 0);
// assert.strictEqual(bobNumber.value, 0);
// });
// it("works with non-concurrent updates", () => {
// aliceNumber.add(3);
// appGen.releaseAll();
// assert.strictEqual(aliceNumber.value, 3);
// assert.strictEqual(bobNumber.value, 3);
// aliceNumber.reset();
// aliceNumber.add(11);
// appGen.releaseAll();
// assert.strictEqual(aliceNumber.value, 11);
// assert.strictEqual(bobNumber.value, 11);
// });
// it("lets concurrent adds survive", () => {
// aliceNumber.reset();
// bobNumber.add(10);
// appGen.releaseAll();
// assert.strictEqual(aliceNumber.value, 10);
// assert.strictEqual(bobNumber.value, 10);
// });
// });
});
describe("AddWinsCSet", () => {
let aliceSet: AddWinsCSet<string>;
let bobSet: AddWinsCSet<string>;
beforeEach(() => {
aliceSet = alice.registerCollab("awSetId", Pre(AddWinsCSet)());
bobSet = bob.registerCollab("awSetId", Pre(AddWinsCSet)());
alice.load(Optional.empty());
bob.load(Optional.empty());
if (debug) {
addEventListeners(aliceSet, "Alice");
addEventListeners(bobSet, "Bob");
}
});
function addEventListeners(set: AddWinsCSet<string>, name: string): void {
set.on("Add", (event) =>
console.log(`${name}: ${event.meta.sender} added ${event.value}`)
);
set.on("Delete", (event) =>
console.log(`${name}: ${event.meta.sender} deleted ${event.value}`)
);
}
it("is initially empty", () => {
assert.deepStrictEqual(new Set(aliceSet), new Set());
assert.deepStrictEqual(new Set(bobSet), new Set());
});
describe("add", () => {
it("works with non-concurrent updates", () => {
aliceSet.add("element");
appGen.releaseAll();
assert.deepStrictEqual(new Set(aliceSet), new Set(["element"]));
assert.deepStrictEqual(new Set(bobSet), new Set(["element"]));
bobSet.add("7");
appGen.releaseAll();
assert.deepStrictEqual(new Set(aliceSet), new Set(["element", "7"]));
assert.deepStrictEqual(new Set(bobSet), new Set(["element", "7"]));
aliceSet.add("7");
appGen.releaseAll();
assert.deepStrictEqual(new Set(aliceSet), new Set(["element", "7"]));
assert.deepStrictEqual(new Set(bobSet), new Set(["element", "7"]));
});
it("works with concurrent updates", () => {
aliceSet.add("first");
assert.deepStrictEqual(new Set(aliceSet), new Set(["first"]));
assert.deepStrictEqual(new Set(bobSet), new Set([]));
bobSet.add("second");
assert.deepStrictEqual(new Set(aliceSet), new Set(["first"]));
assert.deepStrictEqual(new Set(bobSet), new Set(["second"]));
appGen.releaseAll();
assert.deepStrictEqual(new Set(aliceSet), new Set(["first", "second"]));
assert.deepStrictEqual(new Set(bobSet), new Set(["first", "second"]));
});
});
describe("delete", () => {
it("deletes existing elements", () => {
aliceSet.add("element");
appGen.releaseAll();
assert.deepStrictEqual(new Set(aliceSet), new Set(["element"]));
assert.deepStrictEqual(new Set(bobSet), new Set(["element"]));
aliceSet.delete("element");
appGen.releaseAll();
assert.deepStrictEqual(new Set(aliceSet), new Set([]));
assert.deepStrictEqual(new Set(bobSet), new Set([]));
});
it("does not delete non-existing elements", () => {
bobSet.delete("nonexistent");
appGen.releaseAll();
assert.deepStrictEqual(new Set(aliceSet), new Set([]));
assert.deepStrictEqual(new Set(bobSet), new Set([]));
});
it("does not delete concurrently added elements", () => {
// Adds win over deletes
aliceSet.add("concurrent");
aliceSet.delete("concurrent");
bobSet.add("concurrent");
appGen.releaseAll();
assert.deepStrictEqual(new Set(aliceSet), new Set(["concurrent"]));
assert.deepStrictEqual(new Set(bobSet), new Set(["concurrent"]));
});
});
describe("clear", () => {
it("lets concurrent adds survive", () => {
bobSet.add("first");
bobSet.add("second");
appGen.releaseAll();
assert.deepStrictEqual(new Set(aliceSet), new Set(["first", "second"]));
assert.deepStrictEqual(new Set(bobSet), new Set(["first", "second"]));
bobSet.clear();
aliceSet.add("survivor");
assert.deepStrictEqual(
new Set(aliceSet),
new Set(["survivor", "first", "second"])
);
assert.deepStrictEqual(new Set(bobSet), new Set([]));
appGen.releaseAll();
assert.deepStrictEqual(new Set(aliceSet), new Set(["survivor"]));
assert.deepStrictEqual(new Set(bobSet), new Set(["survivor"]));
});
});
describe("gc", () => {
it.skip("garbage collects deleted entries", async () => {
for (let i = 0; i < 100; i++) {
aliceSet.add(i + "");
}
appGen.releaseAll();
for (let i = 0; i < 100; i++) {
if (i < 50) aliceSet.delete(i + "");
else bobSet.delete(i + "");
}
appGen.releaseAll();
// TODO: use memtest to force gc
await new Promise((resolve) => setTimeout(resolve, 1000));
// @ts-ignore private
assert.strictEqual(aliceSet.booleanMap.size, 0);
// @ts-ignore flagMap is private
assert.strictEqual(bobSet.booleanMap.size, 0);
});
it.skip("does not garbage collect non-deleted entries", async () => {
for (let i = 0; i < 100; i++) {
aliceSet.add(i + "");
}
appGen.releaseAll();
// Check nothing has happened synchronously
assert.strictEqual(aliceSet.size, 100);
assert.strictEqual(bobSet.size, 100);
// @ts-ignore flagMap is private
assert.strictEqual(aliceSet.booleanMap.size, 100);
// @ts-ignore flagMap is private
assert.strictEqual(bobSet.booleanMap.size, 100);
// TODO: Wait for GC to actually run
await new Promise((resolve) => setTimeout(resolve, 1000));
assert.strictEqual(aliceSet.size, 100);
assert.strictEqual(bobSet.size, 100);
// @ts-ignore flagMap is private
assert.strictEqual(aliceSet.booleanMap.size, 100);
// @ts-ignore flagMap is private
assert.strictEqual(bobSet.booleanMap.size, 100);
});
});
});
describe("LazyMutCMap", () => {
let aliceMap: LazyMutCMap<string, ResettableCCounter>;
let bobMap: LazyMutCMap<string, ResettableCCounter>;
beforeEach(() => {
const valueConstructor = (valueInitToken: InitToken) =>
new ResettableCCounter(valueInitToken);
aliceMap = alice.registerCollab(
"map",
Pre(LazyMutCMap)(valueConstructor)
);
bobMap = bob.registerCollab("map", Pre(LazyMutCMap)(valueConstructor));
if (debug) {
addEventListeners(aliceMap, "Alice");
addEventListeners(bobMap, "Bob");
}
});
function load() {
alice.load(Optional.empty());
bob.load(Optional.empty());
}
function addEventListeners<K, V extends Object | null>(
map: LazyMutCMap<any, any>,
name: string
): void {
// TODO: add listeners
}
it("is initially empty", () => {
load();
assert.deepStrictEqual(new Set(aliceMap.keys()), new Set([]));
assert.deepStrictEqual(new Set(bobMap.keys()), new Set([]));
});
describe("has", () => {
it("returns true if the key is nontrivial", () => {
load();
aliceMap.get("test").add(1); // Mutate it nontrivially
assert.isTrue(aliceMap.has("test"));
assert.isFalse(bobMap.has("test"));
appGen.releaseAll();
assert.isTrue(aliceMap.has("test"));
assert.isTrue(bobMap.has("test"));
});
it("returns false if the key is trivial", () => {
load();
aliceMap.get("test"); // Don't actually mutate it
assert.isFalse(aliceMap.has("test"));
assert.isFalse(bobMap.has("test"));
appGen.releaseAll();
assert.isFalse(aliceMap.has("test"));
assert.isFalse(bobMap.has("test"));
});
});
describe("get", () => {
it("returns the value", () => {
load();
const aliceTest = aliceMap.get("test");
const bobTest = bobMap.get("test");
assert.isOk(aliceTest);
assert.isOk(bobTest);
assert.strictEqual(aliceTest.value, 0);
assert.strictEqual(bobTest.value, 0);
});
it("returns a CRDT that can be modified", () => {
load();
aliceMap.set("test");
appGen.releaseAll();
const aliceTest = aliceMap.get("test")!;
const bobTest = bobMap.get("test")!;
aliceTest.add(3);
bobTest.add(4);
appGen.releaseAll();
assert.strictEqual(aliceTest.value, 7);
assert.strictEqual(bobTest.value, 7);
});
});
describe("gc", () => {
it("deletes elements that canGC", () => {
load();
bobMap.get("test").add(1); // Make nontrivial.
appGen.releaseAll();
assert.deepStrictEqual(new Set(aliceMap.keys()), new Set(["test"]));
bobMap.get("test").reset();
appGen.releaseAll();
assert.deepStrictEqual(new Set(aliceMap.keys()), new Set([]));
assert.deepStrictEqual(new Set(bobMap.keys()), new Set([]));
});
it("lets concurrent value operation survive", () => {
load();
aliceMap.get("variable").add(1);
appGen.releaseAll();
assert.deepStrictEqual(new Set(aliceMap.keys()), new Set(["variable"]));
assert.deepStrictEqual(new Set(bobMap.keys()), new Set(["variable"]));
const bobVariable = bobMap.get("variable");
aliceMap.get("variable").reset();
bobVariable.add(3);
appGen.releaseAll();
assert.deepStrictEqual(new Set(aliceMap.keys()), new Set(["variable"]));
assert.deepStrictEqual(new Set(bobMap.keys()), new Set(["variable"]));
assert.strictEqual(bobVariable.value, 3);
const aliceVariable = aliceMap.get("variable");
assert.strictEqual(aliceVariable.value, 3);
});
});
describe("value CRDT", () => {
it("can be used as values in other CRDTs", () => {
let aliceSet = alice.registerCollab(
"valueSet",
Pre(AddWinsCSet)(new CollabIDSerializer(aliceMap))
);
let bobSet = bob.registerCollab(
"valueSet",
Pre(AddWinsCSet)(new CollabIDSerializer(bobMap))
);
load();
aliceMap.set("test");
let aliceCounter = aliceMap.get("test")!;
bobMap.set("test");
let bobCounter = bobMap.get("test")!;
appGen.releaseAll();
aliceSet.add(CollabID.fromCollab(aliceCounter));
assert.strictEqual(
aliceSet.has(CollabID.fromCollab(aliceCounter)),
true
);
appGen.releaseAll();
assert.strictEqual(bobSet.has(CollabID.fromCollab(bobCounter)), true);
});
});
});
describe("LWWCMap", () => {
let aliceMap: LWWCMap<string, number>;
let bobMap: LWWCMap<string, number>;
beforeEach(() => {
aliceMap = alice.registerCollab("lwwMap", Pre(LWWCMap)());
bobMap = bob.registerCollab("lwwMap", Pre(LWWCMap)());
alice.load(Optional.empty());
bob.load(Optional.empty());
if (debug) {
addEventListeners(aliceMap, "Alice");
addEventListeners(bobMap, "Bob");
}
});
function addEventListeners<K, V extends Object | null>(
map: LWWCMap<any, any>,
name: string
): void {
// TODO: add listeners
}
it("is initially empty", () => {
assert.deepStrictEqual(new Set(aliceMap.keys()), new Set([]));
assert.deepStrictEqual(new Set(bobMap.keys()), new Set([]));
assert.deepStrictEqual(new Set(aliceMap.values()), new Set([]));
assert.deepStrictEqual(new Set(bobMap.values()), new Set([]));
assert.deepStrictEqual(new Set(aliceMap.entries()), new Set([]));
assert.deepStrictEqual(new Set(bobMap.entries()), new Set([]));
});
describe("set", () => {
it("works with non-concurrent updates", () => {
aliceMap.set("test", 7);
appGen.releaseAll();
assert.deepStrictEqual(new Set(aliceMap.keys()), new Set(["test"]));
assert.deepStrictEqual(new Set(bobMap.keys()), new Set(["test"]));
assert.deepStrictEqual(new Set(aliceMap.values()), new Set([7]));
assert.deepStrictEqual(new Set(bobMap.values()), new Set([7]));
assert.deepStrictEqual(
new Set(aliceMap.entries()),
new Set([["test", 7]])
);
assert.deepStrictEqual(
new Set(bobMap.entries()),
new Set([["test", 7]])
);
});
it("emits right events", async () => {
const promise = Promise.all([
aliceMap.nextEvent("Set"),
bobMap.nextEvent("Set"),
]);
// function checkKeyAdd(event: KeyEvent<string>) {
// assert.strictEqual(event.key, "test");
// // TODO: this depends on the value getting through,
// // but it isn't set until after the add.
// // Will work once events are async.
// //assert.strictEqual(event.value, 7);
// }
// aliceMap.on("KeyAdd", checkKeyAdd);
// bobMap.on("KeyAdd", checkKeyAdd);
function checkValueChange(
event: CMapSetEvent<string, number>,
caller: LWWCMap<string, number>
) {
assert.strictEqual(event.key, "test");
assert.strictEqual(caller.get(event.key), 7);
}
aliceMap.on("Set", checkValueChange);
bobMap.on("Set", checkValueChange);
aliceMap.on("Delete", () =>
assert.fail("Did not expect KeyDelete event from Alice")
);
bobMap.on("Delete", () => {
assert.fail("Did not expect KeyDelete event from Bob");
});
aliceMap.set("test", 7);
appGen.releaseAll();
await promise;
});
});
describe("has", () => {
it("returns true if the key is in the map", () => {
aliceMap.set("test", 7);
assert.isTrue(aliceMap.has("test"));
assert.isFalse(bobMap.has("test"));
appGen.releaseAll();
assert.isTrue(aliceMap.has("test"));
assert.isTrue(bobMap.has("test"));
});
it("returns false if the key is not in the map", () => {
aliceMap.set("test", 7);
assert.isFalse(aliceMap.has("not in map"));
assert.isFalse(bobMap.has("not in map"));
appGen.releaseAll();
assert.isFalse(aliceMap.has("not in map"));
assert.isFalse(bobMap.has("not in map"));
});
});
describe("get", () => {
it("returns the value if the key is in the map", () => {
aliceMap.set("test", 7);
appGen.releaseAll();
assert.strictEqual(aliceMap.get("test"), 7);
assert.strictEqual(bobMap.get("test"), 7);
});
it("returns undefined if the key is not in the map", () => {
aliceMap.set("test", 7);
appGen.releaseAll();
assert.isUndefined(aliceMap.get("not in map"));
assert.isUndefined(bobMap.get("not in map"));
});
});
describe("delete", () => {
it("deletes existing elements", () => {
bobMap.set("test", 7);
appGen.releaseAll();
assert.deepStrictEqual(new Set(aliceMap.keys()), new Set(["test"]));
bobMap.delete("test");
appGen.releaseAll();
assert.deepStrictEqual(new Set(aliceMap.keys()), new Set([]));
assert.deepStrictEqual(new Set(bobMap.keys()), new Set([]));
assert.deepStrictEqual(new Set(aliceMap.values()), new Set([]));
assert.deepStrictEqual(new Set(bobMap.values()), new Set([]));
assert.deepStrictEqual(new Set(aliceMap.entries()), new Set([]));
assert.deepStrictEqual(new Set(bobMap.entries()), new Set([]));
assert.isUndefined(aliceMap.get("test"));
assert.isUndefined(bobMap.get("test"));
});
it("does not delete non-existing elements", () => {
bobMap.delete("test");
appGen.releaseAll();
assert.deepStrictEqual(new Set(aliceMap.keys()), new Set([]));
assert.deepStrictEqual(new Set(bobMap.keys()), new Set([]));
assert.deepStrictEqual(new Set(aliceMap.values()), new Set([]));
assert.deepStrictEqual(new Set(bobMap.values()), new Set([]));
assert.deepStrictEqual(new Set(aliceMap.entries()), new Set([]));
assert.deepStrictEqual(new Set(bobMap.entries()), new Set([]));
assert.isUndefined(aliceMap.get("test"));
assert.isUndefined(bobMap.get("test"));
});
// TODO: for future observed-remove semantics,
// this should no longer need the time interval
it("lets later set survive", () => {
aliceMap.set("variable", 7);
appGen.releaseAll();
assert.deepStrictEqual(new Set(aliceMap.keys()), new Set(["variable"]));
assert.deepStrictEqual(new Set(bobMap.keys()), new Set(["variable"]));
assert.strictEqual(bobMap.get("variable"), 7);
aliceMap.delete("variable");
let now = new Date().getTime();
while (new Date().getTime() <= now) {
// Loop; Bob will have a later time than now
}
bobMap.set("variable", 3);
appGen.releaseAll();
assert.deepStrictEqual(new Set(aliceMap.keys()), new Set(["variable"]));
assert.deepStrictEqual(new Set(bobMap.keys()), new Set(["variable"]));
assert.strictEqual(bobMap.get("variable"), 3);
assert.strictEqual(aliceMap.get("variable"), 3);
});
it("emits right events", async () => {
aliceMap.set("test", 7);
appGen.releaseAll();
const promise = Promise.all([
aliceMap.nextEvent("Delete"),
bobMap.nextEvent("Delete"),
]);
function checkKeyDelete(event: CMapDeleteEvent<string, number>) {
assert.strictEqual(event.key, "test");
// TODO: this depends on the value getting through,
// but it isn't set until after the add.
// Will work once events are async.
//assert.strictEqual(event.value, 7);
}
aliceMap.on("Delete", checkKeyDelete);
bobMap.on("Delete", checkKeyDelete);
aliceMap.on("Set", () =>
assert.fail("Did not expect Set event from Alice")
);
bobMap.on("Set", () => {
assert.fail("Did not expect Set event from Bob");
});
// aliceMap.on("KeyAdd", () =>
// assert.fail("Did not expect KeyAdd event from Alice")
// );
// bobMap.on("KeyAdd", () => {
// assert.fail("Did not expect KeyAdd event from Bob");
// });
aliceMap.delete("test");
appGen.releaseAll();
await promise;
});
});
describe("gc", () => {
it.skip("garbage collects deleted entries", async () => {
for (let i = 0; i < 100; i++) {
aliceMap.set(i + "", 10 * i);
}
appGen.releaseAll();
for (let i = 0; i < 100; i++) {
if (i < 50) aliceMap.delete(i + "");
else bobMap.delete(i + "");
}
appGen.releaseAll();
// TODO: use memtest to force gc
await new Promise((resolve) => setTimeout(resolve, 1000));
// @ts-ignore internalMap is private
assert.strictEqual(aliceMap.internalMap.size, 0);
// @ts-ignore internalMap is private
assert.strictEqual(bobMap.internalMap.size, 0);
});
it.skip("does not garbage collect non-deleted entries", async () => {
for (let i = 0; i < 100; i++) {
aliceMap.set(i + "", 10 * i);
}
appGen.releaseAll();
// Check nothing has happened synchronously
assert.strictEqual(aliceMap.size, 100);
assert.strictEqual(bobMap.size, 100);
// @ts-ignore internalMap is private
assert.strictEqual(aliceMap.internalMap.size, 100);
// @ts-ignore internalMap is private
assert.strictEqual(bobMap.internalMap.size, 100);
// TODO: Wait for GC to actually run
await new Promise((resolve) => setTimeout(resolve, 1000));
assert.strictEqual(aliceMap.size, 100);
assert.strictEqual(bobMap.size, 100);
// @ts-ignore internalMap is private
assert.strictEqual(aliceMap.internalMap.size, 100);
// @ts-ignore internalMap is private
assert.strictEqual(bobMap.internalMap.size, 100);
});
});
});
describe("DeletingMutCSet", () => {
let aliceSource: DeletingMutCSet<CNumber, []>;
let bobSource: DeletingMutCSet<CNumber, []>;
let aliceVariable: OptionalLWWCVariable<CollabID<CNumber>>;
let bobVariable: OptionalLWWCVariable<CollabID<CNumber>>;
beforeEach(() => {
aliceSource = alice.registerCollab(
"source",
Pre(DeletingMutCSet)((valueInitToken) => new CNumber(valueInitToken))
);
bobSource = bob.registerCollab(
"source",
Pre(DeletingMutCSet)((valueInitToken) => new CNumber(valueInitToken))
);
aliceVariable = alice.registerCollab(
"variable",
Pre(OptionalLWWCVariable)(new CollabIDSerializer(aliceSource))
);
bobVariable = bob.registerCollab(
"variable",
Pre(OptionalLWWCVariable)(new CollabIDSerializer(bobSource))
);
alice.load(Optional.empty());
bob.load(Optional.empty());
});
it("returns new Collab", () => {
let newCollab = aliceSource.add();
assert.strictEqual(newCollab.value, 0);
});
it("transfers new Collab via variable", () => {
aliceVariable.set(CollabID.fromCollab(aliceSource.add()));
aliceVariable.value.get().get(alice.runtime)!.add(7);
assert.strictEqual(
aliceVariable.value.get().get(alice.runtime)!.value,
7
);
appGen.releaseAll();
assert.strictEqual(bobVariable.value.get().get(bob.runtime)!.value, 7);
});
it("allows sequential creation", () => {
let new1 = aliceSource.add();
let new2 = aliceSource.add();
new1.add(7);
new2.add(-3);
assert.strictEqual(new1.value, 7);
assert.strictEqual(new2.value, -3);
});
it("allows concurrent creation", () => {
let new1 = aliceSource.add();
let new2 = bobSource.add();
new1.add(7);
new2.add(-3);
assert.strictEqual(new1.value, 7);
assert.strictEqual(new2.value, -3);
appGen.releaseAll();
assert.strictEqual(new1.value, 7);
assert.strictEqual(new2.value, -3);
aliceVariable.set(CollabID.fromCollab(new1));
appGen.releaseAll();
let new1Bob = bobVariable.value.get().get(bob.runtime)!;
bobVariable.set(CollabID.fromCollab(new2));
appGen.releaseAll();
let new2Alice = aliceVariable.value.get().get(alice.runtime)!;
assert.strictEqual(new1Bob.value, 7);
assert.strictEqual(new2Alice.value, -3);
});
// TODO: test deletion, freezing, getDescendant
});
}); | the_stack |
import * as React from 'react';
import { useState, useReducer, useEffect } from 'react';
import { sp } from '@pnp/sp';
import "@pnp/sp/webs";
import "@pnp/sp/folders";
import { HttpRequestError } from "@pnp/odata";
import { IFolder } from '@pnp/sp/folders';
import { ListViewCommandSetContext } from '@microsoft/sp-listview-extensibility';
import { Dialog, DialogType, DialogFooter, DefaultButton, PrimaryButton,
IContextualMenuProps, getId, IStackTokens,
KeyCodes, ITextFieldStyleProps, ITextFieldStyles, TooltipHost,
Spinner, SpinnerSize, Icon, ITextFieldProps, Stack, IconButton,
MessageBar, MessageBarType, Label, TextField, Toggle, Callout, DirectionalHint,
OverflowSet, Separator, Coachmark, TeachingBubbleContent
} from '@fluentui/react';
import { useBoolean } from '@uifabric/react-hooks';
import { FolderStatus } from '../../../constants/FolderStatus';
import { TaskState } from '../../../constants/TaskState';
import ICustomItem from '../../../interfaces/ICustomItem';
import { Constants } from '../../../constants/Constants';
import FolderButton from './FolderButton';
import IProcessFolder from '../../../interfaces/IProcessFolder';
import * as strings from 'AddFoldersCommandSetStrings';
import styles from './FolderHierarchyGenerator.module.scss';
interface IFolderControllerProps {
context: ListViewCommandSetContext;
currentLocation: string;
commandTitle: string;
hideDialog: boolean;
closeDialog: () => void;
}
const FolderController: React.FunctionComponent<IFolderControllerProps> = (props) => {
type FolderDispatchAction =
| { type: 'add'; value: any }
| { type: 'remove'; value: any }
| { type: 'replace'; value: any }
| { type: 'reset'; };
const _errorInfoId: string = getId('errorInfo');
const _folderTextFieldId: string = getId('folderTextField');
const _localStorageCoachmark: string = 'react-list-addfolders-coachmark';
const [isCoachmarkVisible, { setFalse: hideCoachmark, setTrue: showCoachmark }] = useBoolean(false);
const [batchFolders, setBatchFolders] = useState([]);
const [folderNameRegExInfo, {setFalse: hideFolderNameRegExInfo, setTrue: showFolderNameRegExInfo}] = useBoolean(false);
const [folderNameIsValid, setFolderNameIsValid] = useState(true);
const [taskStatus, setTaskStatus] = useState(TaskState.none);
const [folderName, setFolderName] = useState('');
const [folderLengthWarn, setFolderLengthWarn] = useState(false);
const [parallelFoldersWarn, setParallelFoldersWarn] = useState(false);
const [nestedFolders, setNestedFolders] = useState(true);
const [folders, dispatchFolders] = useReducer((fldrs, action: FolderDispatchAction) => {
switch (action.type) {
case "add":
return [...fldrs, action.value];
case "remove":
return fldrs.filter(_ => _ !== action.value);
case "replace":
return action.value;
case "reset":
return [];
default:
throw new Error();
}
}, [] as ICustomItem[]);
useEffect(() => {
if (!window.localStorage.getItem(_localStorageCoachmark)) {
showCoachmark();
}
return () => {
dispatchFolders({type: "reset"});
};
}, []);
useEffect(() => {
let keepLoading: boolean = true;
if (batchFolders.length > 0 && folders.length > 0) {
let _folders = [...folders];
let lastTask = batchFolders[batchFolders.length - 1];
let _folderToUpdate = _folders.filter(_fol => _fol.key === lastTask.key)[0];
let indexFolderToUpdate = _folders.indexOf(_folderToUpdate);
if (lastTask.created) {
_folders[indexFolderToUpdate].status = FolderStatus.created;
keepLoading = _folders.filter(fol => fol.status === FolderStatus.none).length > 0;
}
else {
if (nestedFolders) {
_folders = _folders.map((fol) => {
if (fol.status === FolderStatus.none) {
fol.status = FolderStatus.failed;
}
return fol;
});
keepLoading = false;
}
else {
_folders[indexFolderToUpdate].status = FolderStatus.failed;
keepLoading = _folders.filter(fol => fol.status === FolderStatus.none).length > 0;
}
}
dispatchFolders({type: "replace", value: _folders});
if (keepLoading) {
setTaskStatus(TaskState.progress);
}
else {
setTaskStatus(TaskState.done);
}
}
}, [batchFolders]);
useEffect(() => {
setFolderLengthWarn(isTotalUrlTooLong());
setParallelFoldersWarn(!nestedFolders && folders.length > Constants.maxParallelFolders);
}, [nestedFolders, folders]);
const calloutStackTokens: IStackTokens = {
childrenGap: 20,
maxWidth: 400
};
const foldersStackTokens: IStackTokens = {
childrenGap: 20
};
const btnCreateFoldersDisabled =
taskStatus === TaskState.progress
|| folderLengthWarn
|| parallelFoldersWarn
|| folders.length === 0;
const folderMenuProps: IContextualMenuProps = {
items: [
{
key: 'retryFailedTasks',
text: strings.FolderMenuRetry,
onClick: retryFailedFoldersClick
}
]
};
async function _addFolders(foldersToAdd: IProcessFolder[]) {
let currentFolderRelativeUrl = props.currentLocation;
let batchAddFolders = null;
let newFolder: IFolder;
if (!nestedFolders) {
batchAddFolders = sp.web.createBatch();
}
setBatchFolders([] as IProcessFolder[]);
try {
for (let fol of foldersToAdd) {
if (nestedFolders) {
try {
if (currentFolderRelativeUrl) {
newFolder = await sp.web.getFolderByServerRelativePath("!@p1::" + currentFolderRelativeUrl).addSubFolderUsingPath(fol.value);
currentFolderRelativeUrl = await newFolder.serverRelativeUrl.get();
setBatchFolders(oldBatchFolders => [...oldBatchFolders, { key: fol.key, value: fol.value, created: true }]);
}
else {
throw new Error("Current folder URL is empty");
}
} catch (nestedError) {
if(await raiseException(nestedError)) {
console.error(`Error during the creation of the folder [${fol.value}]`);
setBatchFolders(oldBatchFolders => [...oldBatchFolders, { key: fol.key, value: fol.value, created: false }]);
throw nestedError;
}
else {
currentFolderRelativeUrl += "/" + fol.value;
setBatchFolders(oldBatchFolders => [...oldBatchFolders, { key: fol.key, value: fol.value, created: true }]);
}
}
}
else {
sp.web.getFolderByServerRelativePath("!@p1::" + currentFolderRelativeUrl).inBatch(batchAddFolders).addSubFolderUsingPath(fol.value)
.then(_ => {
console.log(`Folder [${fol.value}] created`);
setBatchFolders(oldBatchFolders => [...oldBatchFolders, { key: fol.key, value: fol.value, created: true }]);
})
.catch(async(nestedError: HttpRequestError) => {
if(await raiseException(nestedError)) {
console.error(`Error during the creation of the folder [${fol.value}]`);
setBatchFolders(oldBatchFolders => [...oldBatchFolders, { key: fol.key, value: fol.value, created: false }]);
throw nestedError;
}
else {
currentFolderRelativeUrl += "/" + fol.value;
setBatchFolders(oldBatchFolders => [...oldBatchFolders, { key: fol.key, value: fol.value, created: true }]);
}
});
}
}
if (!nestedFolders) {
await batchAddFolders.execute();
}
} catch (globalError) {
console.log('Global error');
console.log(globalError);
}
}
async function raiseException(nestedError: HttpRequestError): Promise<boolean> {
let raiseError: boolean = true;
return new Promise<boolean>(async(resolve, reject) => {
if (nestedError.isHttpRequestError) {
try {
const errorJson = await (nestedError).response.json();
console.error(typeof errorJson["odata.error"] === "object" ? errorJson["odata.error"].message.value : nestedError.message);
if (nestedError.status === 500) {
// Don't raise an error if the folder already exists
if (nestedError.message.indexOf('exist') > 0) {
raiseError = false;
}
console.error(nestedError.statusText);
}
} catch (error) {
console.error(error);
}
} else {
console.log(nestedError.message);
}
resolve(raiseError);
});
}
function isTotalUrlTooLong() {
let _foldersPath = '';
let isUrlTooLong: boolean = false;
if (nestedFolders) {
folders.forEach((fol, i) => {
_foldersPath += fol.value + (i < folders.length - 1 ? '/' : '');
});
isUrlTooLong = props.context.pageContext.web.absoluteUrl.length + _foldersPath.length >= Constants.maxTotalUrlLength;
}
else {
isUrlTooLong = folders.some((fol) => props.context.pageContext.web.absoluteUrl.length + ('/' + fol.value).length >= Constants.maxTotalUrlLength);
}
return isUrlTooLong;
}
function addFolderToHierarchy() {
if (folderName.trim() != '' && folderNameIsValid) {
let folderToAdd: ICustomItem = {
key: folderName + '_' + Math.random().toString(36).substr(2, 9),
text: folderName,
onClick: selectFolderClick,
status: FolderStatus.none,
hidden: false,
value: folderName
};
dispatchFolders({type: "add", value: folderToAdd});
setFolderName('');
}
}
function selectFolderClick(ev: React.MouseEvent<any, MouseEvent>, selectedFolder: ICustomItem) {
if (taskStatus !== TaskState.progress) {
if (selectedFolder.status === FolderStatus.created) {
let newLocation: string = props.currentLocation;
if (nestedFolders) {
for (let folder of folders) {
newLocation += "/" + folder.value;
if (folder.key === selectedFolder.key) {
break;
}
}
}
else {
newLocation += "/" + selectedFolder.value;
}
if ('URLSearchParams' in window) {
let searchParams: URLSearchParams = new URLSearchParams(window.location.search);
if (searchParams.has('id')) {
searchParams.set('id', decodeURIComponent(newLocation));
}
else {
searchParams.append('id', decodeURIComponent(newLocation));
}
window.location.search = searchParams.toString();
}
}
else {
dispatchFolders({type: "remove", value: selectedFolder});
}
}
}
function folderTextFieldChange(ev: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, text: string) {
setFolderName(text);
return text;
}
function folderTextFieldKeyDown(ev: React.KeyboardEvent<HTMLElement>) {
const keyCode = ev.which;
switch (keyCode) {
case KeyCodes.tab:
case KeyCodes.enter:
addFolderToHierarchy();
ev.preventDefault();
ev.stopPropagation();
break;
}
}
function createFoldersClick() {
setTaskStatus(TaskState.progress);
let _folds = folders.map((fol) => {
return { key: fol.key, value: fol.value };
}) as IProcessFolder[];
_addFolders(_folds);
}
function eraseFoldersClick() {
dispatchFolders({type: "reset"});
setTaskStatus(TaskState.none);
}
function retryFailedFoldersClick() {
setTaskStatus(TaskState.progress);
let _folders = folders.map((fol) => {
if (fol.status === FolderStatus.failed) {
fol.status = FolderStatus.none;
}
return fol;
});
dispatchFolders({type: "replace", value: _folders});
_addFolders(_folders);
}
function changeFolderCreationDirectionClick(event: React.MouseEvent<HTMLElement>, checked?: boolean) {
setNestedFolders(checked);
}
function teachingBubbleButtonClick() {
window.localStorage.setItem(_localStorageCoachmark, 'hide');
hideCoachmark();
}
function getTextFieldStyles(stylesProps: ITextFieldStyleProps): Partial<ITextFieldStyles> {
let color = folderNameIsValid ? stylesProps.theme.semanticColors.inputText : stylesProps.theme.semanticColors.errorText;
let after = folderNameIsValid ? stylesProps.theme.semanticColors.inputBackgroundChecked : stylesProps.theme.semanticColors.errorText;
return {
fieldGroup: [
{
borderColor: stylesProps.disabled ? 'rgb(243, 242, 241)' : color,
selectors: {
'&:hover': {
borderColor: color
},
':after': {
borderColor: after
},
'[disabled]': {
backgroundColor: 'rgb(243, 242, 241)'
}
}
}
]
};
}
function folderNameErrorMessage(txtProps: ITextFieldProps) {
let matchFolderName: RegExpMatchArray = null;
if (txtProps.value != '') {
// usual folder name check
matchFolderName = txtProps.value.match(Constants.folderNameRegEx);
if (matchFolderName === null) {
const isLibraryContext = props.currentLocation.split('/').length === 2 && props.currentLocation.indexOf('/Lists/') < 0;
const isListContext = props.currentLocation.split('/').length === 3 && props.currentLocation.indexOf('/Lists/') >= 0;
// Reject if folder name submitted is "forms" if current location is root folder (library only)
// Reject if folder name submitted is "attachments" if current location is root folder (list only)
matchFolderName =
(isLibraryContext && txtProps.value.match(Constants.folderNameRootLibraryRegEx) || isListContext && txtProps.value.match(Constants.folderNameRootListRegEx))
|| null;
}
}
setFolderNameIsValid(matchFolderName === null || txtProps.value == '');
return (
<>
<Stack horizontal verticalAlign="center" className={styles.labelerror}>
<span>{txtProps.label}</span>
<div>
{matchFolderName !== null &&
<IconButton
id={_errorInfoId}
iconProps={{ iconName: 'Error' }}
title="Error"
onClick={showFolderNameRegExInfo}
className={styles.foldererror}
/>
}
</div>
</Stack>
</>);
}
function renderCustomBreadcrumb(item: ICustomItem, itemIndex: number) {
let tooltipItem: string = strings.TooltipFolderDelete;
let classIcon: string = '';
let icon: string = '';
let isInProgress: boolean = taskStatus === TaskState.progress && item.status === FolderStatus.none;
switch (item.status) {
case FolderStatus.created:
classIcon = styles.addsuccess;
icon = 'StatusCircleCheckmark';
tooltipItem = strings.TooltipFolderStatusSuccess;
break;
case FolderStatus.failed:
classIcon = styles.addfailure;
icon = 'StatusCircleErrorX';
tooltipItem = strings.TooltipFolderStatusFailure;
break;
}
if (isInProgress) {
tooltipItem = strings.TooltipFolderStatusProgress;
}
return (
<>
<TooltipHost content={tooltipItem}>
<FolderButton onClick={(ev) => selectFolderClick(ev, item)} isNested={nestedFolders}
render={
<>
{`${item.value} `}
{taskStatus === TaskState.none && item.status === FolderStatus.none &&
<div className={styles.blankarea}></div>
}
{isInProgress &&
<Spinner className={styles.addloading} size={SpinnerSize.xSmall} />
}
{item.status !== FolderStatus.none &&
<Icon className={classIcon} iconName={icon} />
}
</>
} />
</TooltipHost>
{itemIndex !== folders.length - 1 &&
<Icon iconName="ChevronRight" className={styles['folder-separator']} />
}
</>
);
}
function onRenderItem(item: ICustomItem) {
let tooltipItem: string = strings.TooltipFolderDelete;
let classIcon: string = '';
let icon: string = '';
let isInProgress: boolean = taskStatus === TaskState.progress && item.status === FolderStatus.none;
switch (item.status) {
case FolderStatus.created:
classIcon = styles.addsuccess;
icon = 'StatusCircleCheckmark';
tooltipItem = strings.TooltipFolderStatusSuccess;
break;
case FolderStatus.failed:
classIcon = styles.addfailure;
icon = 'StatusCircleErrorX';
tooltipItem = strings.TooltipFolderStatusFailure;
break;
}
if (isInProgress) {
tooltipItem = strings.TooltipFolderStatusProgress;
}
return (
<TooltipHost content={tooltipItem}>
<FolderButton onClick={(ev) => selectFolderClick(ev, item)} isNested={nestedFolders}
render={
<>
{`${item.value} `}
{taskStatus === TaskState.none && item.status === FolderStatus.none &&
<div className={styles.blankarea}></div>
}
{isInProgress &&
<Spinner className={styles.addloading} size={SpinnerSize.xSmall} />
}
{item.status !== FolderStatus.none &&
<Icon className={classIcon} iconName={icon} />
}
</>
} />
</TooltipHost>
);
}
function closeDialog(ev?: React.MouseEvent<HTMLButtonElement, MouseEvent>) {
if (taskStatus === TaskState.progress) {
// Prevent pop-up from closing during the creation process
return;
}
setFolderName('');
setNestedFolders(true);
eraseFoldersClick();
props.closeDialog();
}
return (
<Dialog
hidden={props.hideDialog}
minWidth={700}
dialogContentProps={{
type: DialogType.normal,
title: props.commandTitle
}}
modalProps={{
isBlocking: true,
}}
onDismiss={closeDialog}>
<div className={styles.folderHierarchyGenerator}>
<div className={styles.messages}>
{folderLengthWarn &&
<MessageBar messageBarType={MessageBarType.severeWarning}>{`${strings.MessageBarTooManyCharacters} ${Constants.maxTotalUrlLength}`}</MessageBar>
}
{parallelFoldersWarn &&
<MessageBar messageBarType={MessageBarType.severeWarning}>{`${strings.MessageBarMaxFoldersBatch} ${Constants.maxParallelFolders}`}</MessageBar>
}
</div>
<div className={styles.container}>
<Label className={styles.location}>{`${strings.LabelCurrentLocation} ${props.currentLocation.replace('/Lists', '')}`}</Label>
<Stack horizontal verticalAlign="end" tokens={foldersStackTokens}>
<TooltipHost content={strings.TextFieldDescription}>
<TextField
id={_folderTextFieldId}
label={strings.TextFieldLabel}
styles={getTextFieldStyles}
onRenderLabel={folderNameErrorMessage}
value={folderName}
onKeyDown={folderTextFieldKeyDown}
onChange={folderTextFieldChange}
disabled={taskStatus === TaskState.progress || taskStatus === TaskState.done && folders.filter(fol => fol.status === FolderStatus.failed).length === 0}
autoComplete='off'
maxLength={255} />
</TooltipHost>
<TooltipHost
content={strings.TooltipFolderAdd}>
<IconButton onClick={addFolderToHierarchy} iconProps={{iconName: "NewFolder"}} disabled={!folderNameIsValid || folderName == ''} />
</TooltipHost>
</Stack>
<Toggle
defaultChecked={nestedFolders}
inlineLabel
label={strings.ToggleSelectFoldersCreationMode}
onChange={changeFolderCreationDirectionClick}
disabled={taskStatus !== TaskState.none} />
{folderNameRegExInfo &&
<Callout
target={'#' + _errorInfoId}
setInitialFocus={true}
onDismiss={hideFolderNameRegExInfo}
role="alertdialog"
directionalHint={DirectionalHint.bottomCenter}>
<Stack tokens={calloutStackTokens} horizontalAlign='start' styles={{ root: { padding: 20 } }}>
<span>{strings.CalloutBannedCharacters} <b>«</b> <b>*</b> <b>:</b> <b><</b> <b>></b> <b>?</b> <b>/</b> <b>\</b> <b>|</b></span>
<span>{strings.CalloutBannedWords} <b>con</b>, <b>PRN</b>, <b>aux</b>, <b>nul</b>, <b>com0 - COM9</b>, <b>lpt0 - LPT9</b>, <b>_vti_</b></span>
<span>{strings.CalloutBannedPrefixCharacters} <b>~</b> <b>$</b></span>
<span>"<b>forms</b>" {strings.CalloutBannedFormsWordAtRoot}</span>
<span>"<b>attachments</b>" {strings.CalloutBannedAttachmentsWordAtRoot}</span>
<span>{strings.CalloutBannedCharactersUrlInfo} <a target='_blank' href={strings.CalloutBannedCharactersUrl}>{strings.CalloutBannedCharactersUrlLink}</a></span>
<DefaultButton onClick={hideFolderNameRegExInfo} text={strings.ButtonGlobalClose} />
</Stack>
</Callout>
}
{isCoachmarkVisible && (
<Coachmark
target={'#' + _folderTextFieldId}
positioningContainerProps={{
directionalHint: DirectionalHint.topRightEdge,
doNotLayer: false,
}}
>
<TeachingBubbleContent
headline={strings.TeachingBubbleHeadline}
hasCloseButton
primaryButtonProps={{
text: strings.TeachingBubblePrimaryButton,
onClick: teachingBubbleButtonClick
}}
onDismiss={hideCoachmark}
>
{strings.CoachmarkTutorial} <Icon iconName="NewFolder" />
</TeachingBubbleContent>
</Coachmark>
)}
<Separator />
<div className={styles.folderscontainer}>
{nestedFolders ?
<Stack horizontal wrap className={styles['folders-brdcrmb']}>
{folders.map((item, itemIndex) => {
return renderCustomBreadcrumb(item, itemIndex);
})}
</Stack>
:
<div className={styles.dialogContainer}>
<OverflowSet
vertical
items={folders}
onRenderItem={onRenderItem}
onRenderOverflowButton={null} />
</div>
}
</div>
</div>
</div>
<DialogFooter>
{taskStatus === TaskState.done &&
<PrimaryButton
split
menuProps={
folders.filter(fol => fol.status === FolderStatus.failed).length > 0 && folderMenuProps
}
text={strings.ButtonClearSelection}
onClick={eraseFoldersClick} />
}
{taskStatus !== TaskState.done &&
<PrimaryButton
text={strings.ButtonCreateFolders}
onClick={createFoldersClick}
disabled={btnCreateFoldersDisabled} />
}
<DefaultButton onClick={closeDialog} text={strings.ButtonGlobalClose} />
</DialogFooter>
</Dialog>
);
};
export default FolderController; | the_stack |
import { act, cleanup, render, waitFor } from '@testing-library/react'
import useEtherSWR, { etherJsFetcher } from '../src/'
import {
EventEmitterMock,
sleep,
mockFetcher,
mockMultipleFetch,
mockUseWeb3React,
mockContract
} from './util/utils'
import * as React from 'react'
import { useWeb3React } from '@web3-react/core'
import { Contract } from '@ethersproject/contracts'
import { ABINotFound } from '../src/Errors'
import { contracts } from '../src/utils'
import { BigNumber } from 'ethers'
import { DefaultContainer } from './util/components/DefaultContainer'
jest.mock('../src/ether-js-fetcher')
jest.mock('@web3-react/core')
jest.mock('@ethersproject/contracts')
const mockedEthFetcher = etherJsFetcher as jest.Mock
const mockeduseWeb3React = useWeb3React as jest.Mock
const mockedContract = (Contract as unknown) as jest.Mock
describe('useEtherSWR', () => {
describe('key', () => {
describe('web3Provider', () => {
beforeEach(() => {
mockedEthFetcher.mockReset()
mockUseWeb3React(mockeduseWeb3React)
})
afterEach(cleanup)
it('resolves using the fetcher passed', async () => {
const mockData = 10
const fetcher = mockFetcher(mockedEthFetcher, mockData)
const key: [string] = ['getBalance']
function Page() {
const { data } = useEtherSWR(key)
return <div>Balance, {data}</div>
}
const { container } = render(
<DefaultContainer fetcher={mockedEthFetcher}>
<Page />
</DefaultContainer>
)
await waitFor(() => {
expect(container.firstChild.textContent).toEqual(
`Balance, ${mockData}`
)
expect(fetcher).toBeCalledWith('getBalance')
})
})
it('uses a function to generate the key and resolves using the fetcher passed', async () => {
const mockData = 10
const fetcher = mockFetcher(mockedEthFetcher, mockData)
function Page() {
const { data, isValidating } = useEtherSWR(
() => ['0x111', 'balanceOf', '0x01'],
mockedEthFetcher()
)
if (isValidating) return <div>Loading</div>
return <div>Balance, {data}</div>
}
const { container } = render(
<DefaultContainer fetcher={mockedEthFetcher}>
<Page />
</DefaultContainer>
)
expect(container.textContent).toMatchInlineSnapshot(`"Loading"`)
// let's useEffect resolve
await act(() => sleep(110))
await waitFor(() => {
expect(container.textContent).toMatchInlineSnapshot(
`"Balance, ${mockData}"`
)
expect(fetcher).toBeCalledWith('0x111', 'balanceOf', '0x01')
})
})
it('resolves using an existing key', async () => {
const mockData = 10
const fetcher = mockFetcher(mockedEthFetcher, mockData)
function Page() {
const { data } = useEtherSWR(['getBalance'], mockedEthFetcher())
return <div>Balance, {data}</div>
}
const { container } = render(
<DefaultContainer fetcher={mockedEthFetcher}>
<Page />
</DefaultContainer>
)
await waitFor(() => {
expect(container.firstChild.textContent).toEqual(
`Balance, ${mockData}`
)
expect(fetcher).toBeCalledWith('getBalance')
})
})
it('resolves using the config', async () => {
const mockData = 51
const fetcher = mockFetcher(mockedEthFetcher, mockData)
function Page() {
const { data } = useEtherSWR(['getBlockByNumber', 'latest'], {
fetcher: mockedEthFetcher()
})
return <div>Block Number, {data}</div>
}
const { container } = render(
<DefaultContainer fetcher={mockedEthFetcher}>
<Page />
</DefaultContainer>
)
await waitFor(() => {
expect(container.firstChild.textContent).toEqual(
`Block Number, ${mockData}`
)
expect(fetcher).toBeCalledWith('getBlockByNumber', 'latest')
})
})
it('resolves multiple keys using the config', async () => {
const mockData = 51
const fetcher = mockFetcher(mockedEthFetcher, mockData)
function Page() {
const { data } = useEtherSWR([['getBlockByNumber', 'latest']], {
fetcher: mockedEthFetcher()
})
return <div>Block Number, {data}</div>
}
const { container } = render(
<DefaultContainer fetcher={mockedEthFetcher}>
<Page />
</DefaultContainer>
)
await waitFor(() => {
expect(container.firstChild.textContent).toEqual(
`Block Number, ${mockData}`
)
expect(fetcher).toBeCalledWith(
JSON.stringify([['getBlockByNumber', 'latest']])
)
})
})
it('resolves using the context with library', async () => {
const mockData = 11111
const fetcher = mockFetcher(mockedEthFetcher, mockData)
function Page() {
const { data } = useEtherSWR(['getBalance', 'pending'])
return <div>Balance, {data}</div>
}
const { container } = render(
<DefaultContainer fetcher={mockedEthFetcher}>
<Page />
</DefaultContainer>
)
await waitFor(() => {
expect(container.firstChild.textContent).toEqual(
`Balance, ${mockData}`
)
expect(fetcher).toBeCalledWith('getBalance', 'pending')
})
})
})
describe('contract', () => {
beforeEach(() => {
mockedEthFetcher.mockReset()
mockUseWeb3React(mockeduseWeb3React)
})
afterEach(cleanup)
it('throws ABI Missing', async () => {
jest.spyOn(console, 'error').mockImplementation()
function Page() {
const { library } = useWeb3React()
const { data } = useEtherSWR(
['0x6b175474e89094c44da98b954eedeac495271d0f', 'balanceOf', '0x01'],
{
ABIs: new Map(),
web3Provider: library,
subscribe: []
}
)
return <div>Balance, {data}</div>
}
expect(() => {
render(
<DefaultContainer fetcher={mockedEthFetcher}>
<Page />
</DefaultContainer>
)
}).toThrowError(
new ABINotFound(
'Missing ABI for 0x6b175474e89094c44da98b954eedeac495271d0f'
)
)
})
it('resolves using the fetcher passed', async () => {
const mockData = 10
const fetcher = mockFetcher(mockedEthFetcher, mockData)
function Page() {
const { data, isValidating } = useEtherSWR(
['0x111', 'balanceOf', '0x01'],
mockedEthFetcher()
)
if (isValidating) return <div>Loading</div>
return <div>Balance, {data}</div>
}
const { container } = render(
<DefaultContainer fetcher={mockedEthFetcher}>
<Page />
</DefaultContainer>
)
expect(container.textContent).toMatchInlineSnapshot(`"Loading"`)
await act(() => sleep(110))
await waitFor(() => {
expect(container.textContent).toMatchInlineSnapshot(
`"Balance, ${mockData}"`
)
expect(fetcher).toBeCalledWith('0x111', 'balanceOf', '0x01')
})
})
it('resolves multiple results', async () => {
const mockData = ['data']
const fetcher = mockFetcher(mockedEthFetcher, mockData)
const multiKeys = [
['0x111', 'balanceOf', '0x01'],
['0x111', 'balanceOf', '0x02']
]
function Page() {
const { data: balances, error, isValidating } = useEtherSWR<
BigNumber[]
>(multiKeys, mockedEthFetcher())
if (error) {
return <div>{error.message}</div>
}
if (isValidating) {
return <div>Loading</div>
}
return (
<div>
{balances &&
balances.map((balance, index) => {
return <p key={index}>Balance, {balance}</p>
})}
</div>
)
}
const { container } = render(
<DefaultContainer fetcher={mockedEthFetcher}>
<Page />
</DefaultContainer>
)
expect(container.textContent).toMatchInlineSnapshot(`"Loading"`)
await act(() => sleep(110))
await waitFor(() => {
expect(container.textContent).toMatchInlineSnapshot(`"Balance, data"`)
expect(fetcher).toBeCalledWith(JSON.stringify(multiKeys))
})
})
})
})
describe('subscribe', () => {
describe('base', () => {
let mockedLibrary: EventEmitterMock
beforeEach(() => {
mockedEthFetcher.mockReset()
mockedLibrary = mockUseWeb3React(mockeduseWeb3React)
})
afterEach(cleanup)
it('listens an event and update data', async () => {
const initialData = 10
const finalData = initialData + 10
const method = 'getBalance'
const fetcher = mockMultipleFetch(mockedEthFetcher, [
initialData,
finalData
])
function Page() {
const { data, isValidating } = useEtherSWR([method], {
subscribe: 'block'
})
if (isValidating) {
return <div>Loading</div>
}
return <div>Balance, {data}</div>
}
const { container } = render(
<DefaultContainer fetcher={mockedEthFetcher}>
<Page />
</DefaultContainer>
)
expect(container.textContent).toMatchInlineSnapshot(`"Loading"`)
act(() => {
mockedLibrary.emit('block', 1000)
})
await waitFor(() => {
expect(container.firstChild.textContent).toEqual(
`Balance, ${finalData}`
)
expect(fetcher).toHaveBeenNthCalledWith(1, method)
expect(fetcher).toHaveBeenNthCalledWith(2, method)
expect(mockedLibrary.listenerCount('block')).toEqual(1)
})
})
it('listens a list of events an update data', async () => {
const initialData = 10
const finalData = initialData + 10
const method = 'getBalance'
const fetcher = mockMultipleFetch(mockedEthFetcher, [
initialData,
finalData
])
function Page() {
const { data } = useEtherSWR(['getBalance'], {
subscribe: [
{
name: 'block'
}
]
})
return <div>Balance, {data}</div>
}
const { container } = render(
<DefaultContainer fetcher={mockedEthFetcher}>
<Page />
</DefaultContainer>
)
act(() => {
mockedLibrary.emit('block', 1000)
})
await waitFor(() => {
expect(container.firstChild.textContent).toEqual(
`Balance, ${finalData}`
)
expect(fetcher).toHaveBeenNthCalledWith(1, method)
expect(fetcher).toHaveBeenNthCalledWith(2, method)
expect(mockedLibrary.listenerCount('block')).toEqual(1)
})
})
it('listens a list of events and invoke the callback', async () => {
const initialData = 10
const finalData = initialData + 10
const callback = jest.fn()
const fetcher = mockMultipleFetch(mockedEthFetcher, [
initialData,
finalData
])
function Page() {
const { data, mutate } = useEtherSWR(['getBalance'], {
subscribe: [
{
name: 'block',
on: callback.mockImplementation(
// force a refresh of getBalance
() => {
mutate(undefined, true)
}
)
}
]
})
return <div>Balance, {data}</div>
}
const { container } = render(
<DefaultContainer fetcher={mockedEthFetcher}>
<Page />
</DefaultContainer>
)
await waitFor(() =>
expect(container.firstChild.textContent).toEqual(
`Balance, ${initialData}`
)
)
act(() => {
mockedLibrary.emit('block', 1000)
})
await waitFor(() => {
expect(container.firstChild.textContent).toEqual(
`Balance, ${finalData}`
)
expect(callback).toHaveBeenCalled()
expect(fetcher).toHaveBeenNthCalledWith(1, 'getBalance')
expect(fetcher).toHaveBeenNthCalledWith(2, 'getBalance')
expect(mockedLibrary.listenerCount('block')).toEqual(1)
})
})
})
describe('contract', () => {
let contractInstance
beforeEach(() => {
jest.clearAllMocks()
contractInstance = mockContract(mockedContract)
contracts.clear()
})
afterEach(() => {
// new EventEmitterMock().removeAllListeners()
})
it('listens an event and refresh data', async () => {
const initialData = 10
const finalData = initialData + 10
const contractAddr = '0x6126A4C0Eb7822C12Bea32327f1706F035b414bf'
const fetcher = mockMultipleFetch(mockedEthFetcher, [
initialData,
finalData
])
function Page() {
const { account } = useWeb3React()
const { data } = useEtherSWR([contractAddr, 'balanceOf', account], {
subscribe: 'Transfer'
})
return <div>Balance, {data}</div>
}
const { container } = render(
<DefaultContainer
contractAddr={contractAddr}
fetcher={mockedEthFetcher}
>
<Page />
</DefaultContainer>
)
await waitFor(() =>
expect(container.firstChild.textContent).toEqual(
`Balance, ${initialData}`
)
)
act(() => {
contractInstance.emit('Transfer')
})
await waitFor(() => {
expect(contractInstance.listenerCount('Transfer')).toEqual(1)
expect(container.firstChild.textContent).toEqual(
`Balance, ${finalData}`
)
expect(fetcher).toHaveBeenNthCalledWith(
1,
contractAddr,
'balanceOf',
'0x001'
)
expect(fetcher).toHaveBeenNthCalledWith(
2,
contractAddr,
'balanceOf',
'0x001'
)
})
})
it('listens an event and refresh multiple data', async () => {
const contractInstance = new EventEmitterMock()
const initialData = 10
const finalData = initialData + 10
const contractAddr = '0x6126A4C0Eb7822C12Bea32327f1706F035b414bf'
const fetcher = mockMultipleFetch(mockedEthFetcher, [
initialData,
finalData
])
function Page() {
const { account } = useWeb3React()
const { data } = useEtherSWR([[contractAddr, 'balanceOf', account]], {
subscribe: 'Transfer'
})
return <div>Balance, {data}</div>
}
const { container } = render(
<DefaultContainer
contractAddr={contractAddr}
fetcher={mockedEthFetcher}
>
<Page />
</DefaultContainer>
)
await waitFor(() =>
expect(container.firstChild.textContent).toEqual(
`Balance, ${initialData}`
)
)
const contract = mockedContract()
act(() => {
contract.emit('Transfer')
})
await waitFor(() => {
expect(contract.listenerCount('Transfer')).toEqual(1)
expect(container.firstChild.textContent).toEqual(
`Balance, ${initialData + 10}`
)
const key = JSON.stringify([[contractAddr, 'balanceOf', '0x001']])
expect(fetcher).toHaveBeenNthCalledWith(1, key)
expect(fetcher).toHaveBeenNthCalledWith(2, key)
})
})
it('listens an event with empty topics and refresh data', async () => {
const account = '0x001'
const initialData = 10
const finalData = initialData + 10
const contractAddr = '0x6126A4C0Eb7822C12Bea32327f1706F035b414bf'
const fetcher = mockMultipleFetch(mockedEthFetcher, [
initialData,
finalData
])
function Page() {
const { account } = useWeb3React()
const { data } = useEtherSWR(
[
'0x6126A4C0Eb7822C12Bea32327f1706F035b414bf',
'balanceOf',
account
],
{
// A filter from anyone to me
subscribe: { name: 'Transfer' }
}
)
return <div>Balance, {data}</div>
}
const { container } = render(
<DefaultContainer
contractAddr={contractAddr}
fetcher={mockedEthFetcher}
>
<Page />
</DefaultContainer>
)
await waitFor(() =>
expect(container.firstChild.textContent).toEqual(
`Balance, ${initialData}`
)
)
const contract = mockedContract()
act(() => contract.emit('Transfer'))
await waitFor(() => {
expect(container.firstChild.textContent).toEqual(
`Balance, ${initialData + 10}`
)
expect(contract.listenerCount('Transfer')).toEqual(1)
expect(fetcher).toHaveBeenNthCalledWith(
1,
contractAddr,
'balanceOf',
account
)
expect(fetcher).toHaveBeenNthCalledWith(
2,
contractAddr,
'balanceOf',
account
)
})
})
it('listens an event with topics and refresh data', async () => {
const account = '0x001'
const initialData = 10
const finalData = initialData + 10
const contractAddr = '0x6126A4C0Eb7822C12Bea32327f1706F035b414bf'
const fetcher = mockMultipleFetch(mockedEthFetcher, [
initialData,
finalData
])
function Page() {
const { account } = useWeb3React()
const { data } = useEtherSWR([contractAddr, 'balanceOf', account], {
// A filter from anyone to me
subscribe: { name: 'Transfer', topics: [null, account] }
})
return <div>Balance, {data}</div>
}
const { container } = render(
<DefaultContainer
contractAddr={contractAddr}
fetcher={mockedEthFetcher}
>
<Page />
</DefaultContainer>
)
await waitFor(() =>
expect(container.firstChild.textContent).toEqual(
`Balance, ${initialData}`
)
)
const contract = mockedContract()
act(() => contract.emit('Transfer'))
await waitFor(() => {
expect(container.firstChild.textContent).toEqual(
`Balance, ${finalData}`
)
expect(contract.listenerCount('Transfer')).toEqual(1)
expect(fetcher).toHaveBeenNthCalledWith(
1,
contractAddr,
'balanceOf',
account
)
expect(fetcher).toHaveBeenNthCalledWith(
2,
contractAddr,
'balanceOf',
account
)
})
})
it('listens an event with topics and invoke a callback', async () => {
const account = '0x001'
const initialData = 10
const finalData = initialData + 10
const contractAddr = '0x6126A4C0Eb7822C12Bea32327f1706F035b414bf'
const amount = 50
const callback = jest.fn()
const fetcher = mockMultipleFetch(mockedEthFetcher, [
initialData,
finalData
])
function Page() {
const { account } = useWeb3React()
const { data, mutate } = useEtherSWR(
[contractAddr, 'balanceOf', account],
{
// A filter from anyone to me
subscribe: {
name: 'Transfer',
topics: [null, account],
on: callback.mockImplementation(
(data, fromAddress, toAddress, amount, event) => {
const update = data + amount
mutate(update, false) // optimist update skip re-fetch
}
)
}
}
)
return <div>Balance, {data}</div>
}
const { container } = render(
<DefaultContainer
contractAddr={contractAddr}
fetcher={mockedEthFetcher}
>
<Page />
</DefaultContainer>
)
await waitFor(() =>
expect(container.firstChild.textContent).toEqual(
`Balance, ${initialData}`
)
)
const contract = mockedContract()
act(() => {
contract.emit('Transfer', null, account, amount, {})
// FIXME split in two act to receive two calls to the fetcher
contract.emit('Transfer', null, account, amount, {})
})
await waitFor(() => {
expect(container.firstChild.textContent).toEqual(
`Balance, ${initialData + amount + amount}`
)
expect(contract.listenerCount('Transfer')).toEqual(1)
expect(fetcher).toHaveBeenNthCalledWith(
1,
contractAddr,
'balanceOf',
account
)
//FIXME we should receive two calls
// expect(fetcher).toHaveBeenNthCalledWith(2, contractAddr, 'balanceOf', account)
})
})
it('listens a list of events with topics and invoke all the callbacks', async () => {
const account = '0x001'
const initialData = 10
const finalData = initialData + 10
const contractAddr = '0x6126A4C0Eb7822C12Bea32327f1706F035b414bf'
const amount = 50
const callback = jest.fn()
const fetcher = mockMultipleFetch(mockedEthFetcher, [
initialData,
finalData
])
function Page() {
const { account } = useWeb3React()
const { data, mutate } = useEtherSWR(
[
'0x6126A4C0Eb7822C12Bea32327f1706F035b414bf',
'balanceOf',
account
],
{
// A filter from anyone to me
subscribe: [
{
name: 'Transfer',
topics: [null, account],
on: callback.mockImplementation(
// currentData, all the props from the event
(data, fromAddress, toAddress, amount, event) => {
const update = data + amount
mutate(update, false) // optimistic update skip re-fetch
}
)
}
]
}
)
return <div>Balance, {data}</div>
}
const { container } = render(
<DefaultContainer
contractAddr={contractAddr}
fetcher={mockedEthFetcher}
>
<Page />
</DefaultContainer>
)
await waitFor(() =>
expect(container.firstChild.textContent).toEqual(
`Balance, ${initialData}`
)
)
act(() => {
contractInstance.emit('Transfer', null, account, amount, {})
contractInstance.emit('Transfer', null, account, amount, {})
})
await waitFor(() => {
expect(container.firstChild.textContent).toEqual(
`Balance, ${initialData + amount + amount}`
)
expect(contractInstance.listenerCount('Transfer')).toEqual(1)
expect(fetcher).toHaveBeenNthCalledWith(
1,
contractAddr,
'balanceOf',
account
)
})
})
})
})
}) | the_stack |
* @packageDocumentation
* @module gfx
*/
declare const gfx: any;
declare type RecursivePartial<T> = {
[P in keyof T]?:
T[P] extends Array<infer U> ? Array<RecursivePartial<U>> :
T[P] extends ReadonlyArray<infer V> ? ReadonlyArray<RecursivePartial<V>> : RecursivePartial<T[P]>;
};
import {
BlendFactor,
BlendOp,
ColorMask,
ComparisonFunc,
CullMode,
PolygonMode,
ShadeModel,
StencilOp,
Color,
} from './base/define';
export class RasterizerState {
protected _nativeObj;
protected _isDiscard: boolean = false;
protected _polygonMode: PolygonMode = PolygonMode.FILL;
protected _shadeModel: ShadeModel = ShadeModel.GOURAND;
protected _cullMode: CullMode = CullMode.BACK;
protected _isFrontFaceCCW: boolean = true;
protected _depthBiasEnabled: boolean = false;
protected _depthBias: number = 0;
protected _depthBiasClamp: number = 0.0;
protected _depthBiasSlop: number = 0.0;
protected _isDepthClip: boolean = true;
protected _isMultisample: boolean = false;
protected _lineWidth: number = 1.0;
constructor (
isDiscard: boolean = false,
polygonMode: PolygonMode = PolygonMode.FILL,
shadeModel: ShadeModel = ShadeModel.GOURAND,
cullMode: CullMode = CullMode.BACK,
isFrontFaceCCW: boolean = true,
depthBiasEnabled: boolean = false,
depthBias: number = 0,
depthBiasClamp: number = 0.0,
depthBiasSlop: number = 0.0,
isDepthClip: boolean = true,
isMultisample: boolean = false,
lineWidth: number = 1.0,
) {
this._nativeObj = new gfx.RasterizerState();
this.assignProperties(isDiscard, polygonMode, shadeModel, cullMode, isFrontFaceCCW,
depthBiasEnabled, depthBias, depthBiasClamp, depthBiasSlop, isDepthClip, isMultisample, lineWidth);
}
get native () {
return this._nativeObj;
}
get isDiscard (): boolean {
return this._isDiscard;
}
set isDiscard (val: boolean) {
this._isDiscard = val;
this._nativeObj.isDiscard = val;
}
get polygonMode (): PolygonMode { return this._polygonMode; }
set polygonMode (val: PolygonMode) {
this._polygonMode = val;
this._nativeObj.polygonMode = val;
}
get shadeModel (): ShadeModel { return this._shadeModel; }
set shadeModel (val: ShadeModel) {
this._shadeModel = val;
this._nativeObj.shadeModel = val;
}
get cullMode (): CullMode { return this._cullMode; }
set cullMode (val: CullMode) {
this._cullMode = val;
this._nativeObj.cullMode = val;
}
get isFrontFaceCCW (): boolean {
return this._isFrontFaceCCW;
}
set isFrontFaceCCW (val: boolean) {
this._isFrontFaceCCW = val;
this._nativeObj.isFrontFaceCCW = val;
}
get depthBiasEnabled (): boolean {
return this._depthBiasEnabled;
}
set depthBiasEnabled (val: boolean) {
this._depthBiasEnabled = val;
this._nativeObj.depthBiasEnabled = val;
}
get depthBias (): number { return this._depthBias; }
set depthBias (val: number) {
this._depthBias = val;
this._nativeObj.depthBias = val;
}
get depthBiasClamp (): number { return this._depthBiasClamp; }
set depthBiasClamp (val: number) {
this._depthBiasClamp = val;
this._nativeObj.depthBiasClamp = val;
}
get depthBiasSlop (): number { return this._depthBiasSlop; }
set depthBiasSlop (val: number) {
this._depthBiasSlop = val;
this._nativeObj.depthBiasSlop = val;
}
get isDepthClip (): boolean {
return this._isDepthClip;
}
set isDepthClip (val: boolean) {
this._isDepthClip = val;
this._nativeObj.isDepthClip = val;
}
get isMultisample (): boolean {
return this._isMultisample;
}
set isMultisample (val: boolean) {
this._isMultisample = val;
this._nativeObj.isMultisample = val;
}
get lineWidth (): number { return this._lineWidth; }
set lineWidth (val: number) {
this._lineWidth = val;
this._nativeObj.lineWidth = val;
}
public reset () {
this.assignProperties(false, PolygonMode.FILL, ShadeModel.GOURAND, CullMode.BACK, true, false, 0,
0.0, 0.0, true, false, 1.0);
}
public assign (rs: RecursivePartial<RasterizerState>) {
if (!rs) return;
this.assignProperties(rs.isDiscard, rs.polygonMode, rs.shadeModel, rs.cullMode, rs.isFrontFaceCCW,
rs.depthBiasEnabled, rs.depthBias, rs.depthBiasClamp, rs.depthBiasSlop, rs.isDepthClip, rs.isMultisample, rs.lineWidth);
}
public destroy () {
this._nativeObj = null;
}
private assignProperties (
isDiscard?: boolean,
polygonMode?: PolygonMode,
shadeModel?: ShadeModel,
cullMode?: CullMode,
isFrontFaceCCW?: boolean,
depthBiasEnabled?: boolean,
depthBias?: number,
depthBiasClamp?: number,
depthBiasSlop?: number,
isDepthClip?: boolean,
isMultisample?: boolean,
lineWidth?: number,
) {
if (isDiscard !== undefined) this.isDiscard = isDiscard;
if (polygonMode !== undefined) this.polygonMode = polygonMode;
if (shadeModel !== undefined) this.shadeModel = shadeModel;
if (cullMode !== undefined) this.cullMode = cullMode;
if (isFrontFaceCCW !== undefined) this.isFrontFaceCCW = isFrontFaceCCW;
if (depthBiasEnabled !== undefined) this.depthBiasEnabled = depthBiasEnabled;
if (depthBias !== undefined) this.depthBias = depthBias;
if (depthBiasClamp !== undefined) this.depthBiasClamp = depthBiasClamp;
if (depthBiasSlop !== undefined) this.depthBiasSlop = depthBiasSlop;
if (isDepthClip !== undefined) this.isDepthClip = isDepthClip;
if (isMultisample !== undefined) this.isMultisample = isMultisample;
if (lineWidth !== undefined) this.lineWidth = lineWidth;
}
}
/**
* @en GFX depth stencil state.
* @zh GFX 深度模板状态。
*/
export class DepthStencilState {
protected _nativeObj;
protected _depthTest: boolean = true;
protected _depthWrite: boolean = true;
protected _depthFunc: ComparisonFunc = ComparisonFunc.LESS;
protected _stencilTestFront: boolean = false;
protected _stencilFuncFront: ComparisonFunc = ComparisonFunc.ALWAYS;
protected _stencilReadMaskFront: number = 0xffff;
protected _stencilWriteMaskFront: number = 0xffff;
protected _stencilFailOpFront: StencilOp = StencilOp.KEEP;
protected _stencilZFailOpFront: StencilOp = StencilOp.KEEP;
protected _stencilPassOpFront: StencilOp = StencilOp.KEEP;
protected _stencilRefFront: number = 1;
protected _stencilTestBack: boolean = false;
protected _stencilFuncBack: ComparisonFunc = ComparisonFunc.ALWAYS;
protected _stencilReadMaskBack: number = 0xffff;
protected _stencilWriteMaskBack: number = 0xffff;
protected _stencilFailOpBack: StencilOp = StencilOp.KEEP;
protected _stencilZFailOpBack: StencilOp = StencilOp.KEEP;
protected _stencilPassOpBack: StencilOp = StencilOp.KEEP;
protected _stencilRefBack: number = 1;
constructor (
depthTest: boolean = true,
depthWrite: boolean = true,
depthFunc: ComparisonFunc = ComparisonFunc.LESS,
stencilTestFront: boolean = false,
stencilFuncFront: ComparisonFunc = ComparisonFunc.ALWAYS,
stencilReadMaskFront: number = 0xffff,
stencilWriteMaskFront: number = 0xffff,
stencilFailOpFront: StencilOp = StencilOp.KEEP,
stencilZFailOpFront: StencilOp = StencilOp.KEEP,
stencilPassOpFront: StencilOp = StencilOp.KEEP,
stencilRefFront: number = 1,
stencilTestBack: boolean = false,
stencilFuncBack: ComparisonFunc = ComparisonFunc.ALWAYS,
stencilReadMaskBack: number = 0xffff,
stencilWriteMaskBack: number = 0xffff,
stencilFailOpBack: StencilOp = StencilOp.KEEP,
stencilZFailOpBack: StencilOp = StencilOp.KEEP,
stencilPassOpBack: StencilOp = StencilOp.KEEP,
stencilRefBack: number = 1,
) {
this._nativeObj = new gfx.DepthStencilState();
this.assignProperties(depthTest, depthWrite, depthFunc, stencilTestFront, stencilFuncFront, stencilReadMaskFront,
stencilWriteMaskFront, stencilFailOpFront, stencilZFailOpFront, stencilPassOpFront, stencilRefFront,
stencilTestBack, stencilFuncBack, stencilReadMaskBack, stencilWriteMaskBack, stencilFailOpBack,
stencilZFailOpBack, stencilPassOpBack, stencilRefBack);
}
get native () {
return this._nativeObj;
}
get depthTest (): boolean {
return this._depthTest;
}
set depthTest (val: boolean) {
this._depthTest = val;
this._nativeObj.depthTest = val;
}
get depthWrite (): boolean {
return this._depthWrite;
}
set depthWrite (val: boolean) {
this._depthWrite = val;
this._nativeObj.depthWrite = val;
}
get depthFunc (): ComparisonFunc { return this._depthFunc; }
set depthFunc (val: ComparisonFunc) {
this._depthFunc = val;
this._nativeObj.depthFunc = val;
}
get stencilTestFront (): boolean {
return this._stencilTestFront;
}
set stencilTestFront (val: boolean) {
this._stencilTestFront = val;
this._nativeObj.stencilTestFront = val;
}
get stencilFuncFront (): ComparisonFunc { return this._stencilFuncFront; }
set stencilFuncFront (val: ComparisonFunc) {
this._stencilFuncFront = val;
this._nativeObj.stencilFuncFront = val;
}
get stencilReadMaskFront (): number { return this._stencilReadMaskFront; }
set stencilReadMaskFront (val: number) {
this._stencilReadMaskFront = val;
this._nativeObj.stencilReadMaskFront = val;
}
get stencilWriteMaskFront (): number { return this._stencilWriteMaskFront; }
set stencilWriteMaskFront (val: number) {
this._stencilWriteMaskFront = val;
this._nativeObj.stencilWriteMaskFront = val;
}
get stencilFailOpFront (): StencilOp { return this._stencilFailOpFront; }
set stencilFailOpFront (val: StencilOp) {
this._stencilFailOpFront = val;
this._nativeObj.stencilFailOpFront = val;
}
get stencilZFailOpFront (): StencilOp { return this._stencilZFailOpFront; }
set stencilZFailOpFront (val: StencilOp) {
this._stencilZFailOpFront = val;
this._nativeObj.stencilZFailOpFront = val;
}
get stencilPassOpFront (): StencilOp { return this._stencilPassOpFront; }
set stencilPassOpFront (val: StencilOp) {
this._stencilPassOpFront = val;
this._nativeObj.stencilPassOpFront = val;
}
get stencilRefFront (): number { return this._stencilRefFront; }
set stencilRefFront (val: number) {
this._stencilRefFront = val;
this._nativeObj.stencilRefFront = val;
}
get stencilTestBack (): boolean {
return this._stencilTestBack;
}
set stencilTestBack (val: boolean) {
this._stencilTestBack = val;
this._nativeObj.stencilTestBack = val;
}
get stencilFuncBack (): ComparisonFunc { return this._stencilFuncBack; }
set stencilFuncBack (val: ComparisonFunc) {
this._stencilFuncBack = val;
this._nativeObj.stencilFuncBack = val;
}
get stencilReadMaskBack (): number { return this._stencilReadMaskBack; }
set stencilReadMaskBack (val: number) {
this._stencilReadMaskBack = val;
this._nativeObj.stencilReadMaskBack = val;
}
get stencilWriteMaskBack (): number { return this._stencilWriteMaskBack; }
set stencilWriteMaskBack (val: number) {
this._stencilWriteMaskBack = val;
this._nativeObj.stencilWriteMaskBack = val;
}
get stencilFailOpBack (): StencilOp { return this._stencilFailOpBack; }
set stencilFailOpBack (val: StencilOp) {
this._stencilFailOpBack = val;
this._nativeObj.stencilFailOpBack = val;
}
get stencilZFailOpBack (): StencilOp { return this._stencilZFailOpBack; }
set stencilZFailOpBack (val: StencilOp) {
this._stencilZFailOpBack = val;
this._nativeObj.stencilZFailOpBack = val;
}
get stencilPassOpBack (): StencilOp { return this._stencilPassOpBack; }
set stencilPassOpBack (val: StencilOp) {
this._stencilPassOpBack = val;
this._nativeObj.stencilPassOpBack = val;
}
get stencilRefBack (): number { return this._stencilRefBack; }
set stencilRefBack (val: number) {
this._stencilRefBack = val;
this._nativeObj.stencilRefBack = val;
}
public reset () {
this.assignProperties(true, true, ComparisonFunc.LESS, false, ComparisonFunc.ALWAYS, 0xffff, 0xffff, StencilOp.KEEP,
StencilOp.KEEP, StencilOp.KEEP, 1, false, ComparisonFunc.ALWAYS, 0xffff, 0xffff, StencilOp.KEEP, StencilOp.KEEP, StencilOp.KEEP, 1);
}
public assign (dss: RecursivePartial<DepthStencilState>) {
if (!dss) return;
this.assignProperties(dss.depthTest, dss.depthWrite, dss.depthFunc, dss.stencilTestFront, dss.stencilFuncFront, dss.stencilReadMaskFront,
dss.stencilWriteMaskFront, dss.stencilFailOpFront, dss.stencilZFailOpFront, dss.stencilPassOpFront, dss.stencilRefFront,
dss.stencilTestBack, dss.stencilFuncBack, dss.stencilReadMaskBack, dss.stencilWriteMaskBack, dss.stencilFailOpBack,
dss.stencilZFailOpBack, dss.stencilPassOpBack, dss.stencilRefBack);
}
public destroy () {
this._nativeObj = null;
}
private assignProperties (
depthTest?: boolean,
depthWrite?: boolean,
depthFunc?: ComparisonFunc,
stencilTestFront?: boolean,
stencilFuncFront?: ComparisonFunc,
stencilReadMaskFront?: number,
stencilWriteMaskFront?: number,
stencilFailOpFront?: StencilOp,
stencilZFailOpFront?: StencilOp,
stencilPassOpFront?: StencilOp,
stencilRefFront?: number,
stencilTestBack?: boolean,
stencilFuncBack?: ComparisonFunc,
stencilReadMaskBack?: number,
stencilWriteMaskBack?: number,
stencilFailOpBack?: StencilOp,
stencilZFailOpBack?: StencilOp,
stencilPassOpBack?: StencilOp,
stencilRefBack?: number
) {
if (depthTest !== undefined) this.depthTest = depthTest;
if (depthWrite !== undefined) this.depthWrite = depthWrite;
if (depthFunc !== undefined) this.depthFunc = depthFunc;
if (stencilTestFront !== undefined) this.stencilTestFront = stencilTestFront;
if (stencilFuncFront !== undefined) this.stencilFuncFront = stencilFuncFront;
if (stencilReadMaskFront !== undefined) this.stencilReadMaskFront = stencilReadMaskFront;
if (stencilWriteMaskFront !== undefined) this.stencilWriteMaskFront = stencilWriteMaskFront;
if (stencilFailOpFront !== undefined) this.stencilFailOpFront = stencilFailOpFront;
if (stencilZFailOpFront !== undefined) this.stencilZFailOpFront = stencilZFailOpFront;
if (stencilPassOpFront !== undefined) this.stencilPassOpFront = stencilPassOpFront;
if (stencilRefFront !== undefined) this.stencilRefFront = stencilRefFront;
if (stencilTestBack !== undefined) this.stencilTestBack = stencilTestBack;
if (stencilFuncBack !== undefined) this.stencilFuncBack = stencilFuncBack;
if (stencilReadMaskBack !== undefined) this.stencilReadMaskBack = stencilReadMaskBack;
if (stencilWriteMaskBack !== undefined) this.stencilWriteMaskBack = stencilWriteMaskBack;
if (stencilFailOpBack !== undefined) this.stencilFailOpBack = stencilFailOpBack;
if (stencilZFailOpBack !== undefined) this.stencilZFailOpBack = stencilZFailOpBack;
if (stencilPassOpBack !== undefined) this.stencilPassOpBack = stencilPassOpBack;
if (stencilRefBack !== undefined) this.stencilRefBack = stencilRefBack;
}
}
/**
* @en GFX blend target.
* @zh GFX 混合目标。
*/
export class BlendTarget {
protected _nativeObj;
protected _blend: boolean = false;
protected _blendSrc: BlendFactor = BlendFactor.ONE;
protected _blendDst: BlendFactor = BlendFactor.ZERO;
protected _blendEq: BlendOp = BlendOp.ADD;
protected _blendSrcAlpha: BlendFactor = BlendFactor.ONE;
protected _blendDstAlpha: BlendFactor = BlendFactor.ZERO;
protected _blendAlphaEq: BlendOp = BlendOp.ADD;
protected _blendColorMask: ColorMask = ColorMask.ALL;
get native () {
return this._nativeObj;
}
constructor (
blend: boolean = false,
blendSrc: BlendFactor = BlendFactor.ONE,
blendDst: BlendFactor = BlendFactor.ZERO,
blendEq: BlendOp = BlendOp.ADD,
blendSrcAlpha: BlendFactor = BlendFactor.ONE,
blendDstAlpha: BlendFactor = BlendFactor.ZERO,
blendAlphaEq: BlendOp = BlendOp.ADD,
blendColorMask: ColorMask = ColorMask.ALL,
) {
this._nativeObj = new gfx.BlendTarget();
this.assignProperties(blend, blendSrc, blendDst, blendEq,
blendSrcAlpha, blendDstAlpha, blendAlphaEq, blendColorMask);
}
get blend (): boolean {
return this._blend;
}
set blend (val: boolean) {
this._blend = val;
this._nativeObj.blend = val;
}
get blendSrc (): BlendFactor { return this._blendSrc; }
set blendSrc (val: BlendFactor) {
this._blendSrc = val;
this._nativeObj.blendSrc = val;
}
get blendDst () { return this._blendDst; }
set blendDst (val: BlendFactor) {
this._blendDst = val;
this._nativeObj.blendDst = val;
}
get blendEq (): BlendOp { return this._blendEq; }
set blendEq (val: BlendOp) {
this._blendEq = val;
this._nativeObj.blendEq = val;
}
get blendSrcAlpha (): BlendFactor { return this._blendSrcAlpha; }
set blendSrcAlpha (val: BlendFactor) {
this._blendSrcAlpha = val;
this._nativeObj.blendSrcAlpha = val;
}
get blendDstAlpha (): BlendFactor { return this._blendDstAlpha; }
set blendDstAlpha (val: BlendFactor) {
this._blendDstAlpha = val;
this._nativeObj.blendDstAlpha = val;
}
get blendAlphaEq (): BlendOp { return this._blendAlphaEq; }
set blendAlphaEq (val: BlendOp) {
this._blendAlphaEq = val;
this._nativeObj.blendAlphaEq = val;
}
get blendColorMask (): ColorMask { return this._blendColorMask; }
set blendColorMask (val: ColorMask) {
this._blendColorMask = val;
this._nativeObj.blendColorMask = val;
}
public reset () {
this.assignProperties(false, BlendFactor.ONE, BlendFactor.ZERO, BlendOp.ADD,
BlendFactor.ONE, BlendFactor.ZERO, BlendOp.ADD, ColorMask.ALL);
}
public destroy () {
this._nativeObj = null;
}
public assign (target: RecursivePartial<BlendTarget>) {
if (!target) return;
this.assignProperties(target.blend, target.blendSrc, target.blendDst, target.blendEq,
target.blendSrcAlpha, target.blendDstAlpha, target.blendAlphaEq, target.blendColorMask);
}
private assignProperties (
blend?: boolean,
blendSrc?: BlendFactor,
blendDst?: BlendFactor,
blendEq?: BlendOp,
blendSrcAlpha?: BlendFactor,
blendDstAlpha?: BlendFactor,
blendAlphaEq?: BlendOp,
blendColorMask?: ColorMask
) {
if (blend !== undefined) this.blend = blend;
if (blendSrc !== undefined) this.blendSrc = blendSrc;
if (blendDst !== undefined) this.blendDst = blendDst;
if (blendEq !== undefined) this.blendEq = blendEq;
if (blendSrcAlpha !== undefined) this.blendSrcAlpha = blendSrcAlpha;
if (blendDstAlpha !== undefined) this.blendDstAlpha = blendDstAlpha;
if (blendAlphaEq !== undefined) this.blendAlphaEq = blendAlphaEq;
if (blendColorMask !== undefined) this.blendColorMask = blendColorMask;
}
}
function watchArrayElementsField<S, T> (self: S, list: T[], eleField: string, cachedFieldName: string, callback: (self: S, idx: number, originTarget: T, prop: symbol | string, value: any) => void) {
for (let i = 0, l = list.length; i < l; i++) {
let ele = list[i] as any;
let originField = ele[eleField][cachedFieldName] || ele[eleField];
// replace with Proxy
ele[eleField] = new Proxy(originField, {
get: (originTarget, key: string | symbol) => {
if (key === cachedFieldName) {
return originTarget;
}
return Reflect.get(originTarget, key);
},
set: (originTarget, prop, value) => {
Reflect.set(originTarget, prop, value);
callback(self, i, originTarget, prop, value);
return true;
}
});
}
}
export class BlendState {
private targets: BlendTarget[];
private _blendColor: Color;
protected _nativeObj;
protected _isA2C: boolean = false;
protected _isIndepend: boolean = false;
private _setTargets (targets: BlendTarget[]) {
this.targets = targets;
const CACHED_FIELD_NAME = `$__nativeObj`;
this._syncTargetsToNativeObj(CACHED_FIELD_NAME);
// watch target[i]._nativeObj fields update
watchArrayElementsField(this, this.targets, "_nativeObj", CACHED_FIELD_NAME, (self, _idx, _originTarget, _prop, _value) => {
self._syncTargetsToNativeObj(CACHED_FIELD_NAME);
});
}
private _syncTargetsToNativeObj (cachedFieldName: string) {
const nativeTars = this.targets.map(target => { return target.native[cachedFieldName] || target.native; });
this._nativeObj.targets = nativeTars;
}
get native () {
return this._nativeObj;
}
constructor (
isA2C: boolean = false,
isIndepend: boolean = false,
blendColor: Color = new Color(),
targets: BlendTarget[] = [new BlendTarget()],
) {
this._nativeObj = new gfx.BlendState();
this._setTargets(targets);
this.blendColor = blendColor;
this.isA2c = isA2C;
this.isIndepend = isIndepend;
}
get isA2c (): boolean {
return this._isA2C;
}
set isA2c (val: boolean) {
this._isA2C = val;
this._nativeObj.isA2C = val;
}
get isIndepend (): boolean {
return this._isIndepend;
}
set isIndepend (val: boolean) {
this._isIndepend = val;
this._nativeObj.isIndepend = val;
}
get blendColor (): Color { return this._blendColor; }
set blendColor (color: Color) {
this._blendColor = color;
this._nativeObj.blendColor = color;
}
/**
* @en Should use this function to set target, or it will not work
* on native platforms, as native can not support this feature,
* such as `blendState[i] = target;`.
*
* @param index The index to set target.
* @param target The target to be set.
*/
public setTarget (index: number, target: RecursivePartial<BlendTarget>) {
let tg = this.targets[index];
if (!tg) {
tg = this.targets[index] = new BlendTarget();
}
tg.assign(target);
// TODO: define setTarget function
this._setTargets(this.targets);
}
public reset () {
this.isA2c = false;
this.isIndepend = false;
this.blendColor = new Color(0, 0, 0, 0);
const targets = this.targets;
for (let i = 1, len = targets.length; i < len; ++i) {
targets[i].destroy();
}
targets.length = 1;
targets[0].reset();
this._setTargets(targets);
}
public destroy () {
for (let i = 0, len = this.targets.length; i < len; ++i) {
this.targets[i].destroy();
}
this.targets = null;
this._nativeObj = null;
}
}
export const PipelineState = gfx.PipelineState;
export const PipelineStateInfo = gfx.PipelineStateInfo; | the_stack |
import { getNetAddress } from "@homebridge/ciao/lib/util/domain-formatter";
import assert from "assert";
import createDebug from 'debug';
import { EventEmitter } from "events";
import { SrpServer } from "fast-srp-hap";
import http, { IncomingMessage, ServerResponse } from 'http';
import net, { AddressInfo, Socket } from 'net';
import os from "os";
import { CharacteristicEventNotification, EventNotification } from "../../internal-types";
import { CharacteristicValue, Nullable, SessionIdentifier } from '../../types';
import * as hapCrypto from "./hapCrypto";
import { getOSLoopbackAddressIfAvailable } from "./net-utils";
import * as uuid from './uuid';
import Timeout = NodeJS.Timeout;
const debug = createDebug('HAP-NodeJS:EventedHTTPServer');
const debugCon = createDebug("HAP-NodeJS:EventedHTTPServer:Connection")
export type HAPUsername = string;
export type EventName = string; // "<aid>.<iid>"
/**
* Simple struct to hold vars needed to support HAP encryption.
*/
export class HAPEncryption {
readonly clientPublicKey: Buffer;
readonly secretKey: Buffer;
readonly publicKey: Buffer;
readonly sharedSecret: Buffer;
readonly hkdfPairEncryptionKey: Buffer;
accessoryToControllerCount: number = 0;
controllerToAccessoryCount: number = 0;
accessoryToControllerKey: Buffer;
controllerToAccessoryKey: Buffer;
incompleteFrame?: Buffer;
public constructor(clientPublicKey: Buffer, secretKey: Buffer, publicKey: Buffer, sharedSecret: Buffer, hkdfPairEncryptionKey: Buffer) {
this.clientPublicKey = clientPublicKey;
this.secretKey = secretKey;
this.publicKey = publicKey;
this.sharedSecret = sharedSecret;
this.hkdfPairEncryptionKey = hkdfPairEncryptionKey;
this.accessoryToControllerKey = Buffer.alloc(0);
this.controllerToAccessoryKey = Buffer.alloc(0);
}
}
export const enum EventedHTTPServerEvent {
LISTENING = 'listening',
CONNECTION_OPENED = "connection-opened",
REQUEST = "request",
CONNECTION_CLOSED = "connection-closed",
}
export declare interface EventedHTTPServer {
on(event: "listening", listener: (port: number, address: string) => void): this;
on(event: "connection-opened", listener: (connection: HAPConnection) => void): this;
on(event: "request", listener: (connection: HAPConnection, request: IncomingMessage, response: ServerResponse) => void): this;
on(event: "connection-closed", listener: (connection: HAPConnection) => void): this;
emit(event: "listening", port: number, address: string): boolean;
emit(event: "connection-opened", connection: HAPConnection): boolean;
emit(event: "request", connection: HAPConnection, request: IncomingMessage, response: ServerResponse): boolean;
emit(event: "connection-closed", connection: HAPConnection): boolean;
}
/**
* EventedHTTPServer provides an HTTP-like server that supports HAP "extensions" for security and events.
*
* Implementation
* --------------
* In order to implement the "custom HTTP" server required by the HAP protocol (see HAPServer.js) without completely
* reinventing the wheel, we create both a generic TCP socket server as well as a standard Node HTTP server.
* The TCP socket server acts as a proxy, allowing users of this class to transform data (for encryption) as necessary
* and passing through bytes directly to the HTTP server for processing. This way we get Node to do all
* the "heavy lifting" of HTTP like parsing headers and formatting responses.
*
* Events are sent by simply waiting for current HTTP traffic to subside and then sending a custom response packet
* directly down the wire via the socket.
*
* Each connection to the main TCP server gets its own internal HTTP server, so we can track ongoing requests/responses
* for safe event insertion.
*/
export class EventedHTTPServer extends EventEmitter {
private static readonly CONNECTION_TIMEOUT_LIMIT = 16; // if we have more (or equal) # connections we start the timeout
private static readonly MAX_CONNECTION_IDLE_TIME = 60 * 60 * 1000; // 1h
private readonly tcpServer: net.Server;
/**
* Set of all currently connected HAP connections.
*/
private readonly connections: Set<HAPConnection> = new Set();
/**
* Session dictionary indexed by username/identifier. The username uniquely identifies every person added to the home.
* So there can be multiple sessions open for a single username (multiple devices connected to the same Apple ID).
*/
private readonly connectionsByUsername: Map<HAPUsername, HAPConnection[]> = new Map();
private connectionIdleTimeout?: Timeout;
constructor() {
super();
this.tcpServer = net.createServer();
const interval = setInterval(() => {
let connectionString = "";
for (const connection of this.connections) {
if (connectionString) {
connectionString += ", ";
}
connectionString += connection.remoteAddress + ":" + connection.remotePort;
}
debug("Currently " + this.connections.size + " hap connections open: " + connectionString);
}, 60000);
interval.unref();
}
private scheduleNextConnectionIdleTimeout(): void {
this.connectionIdleTimeout = undefined;
if (!this.tcpServer.listening) {
return;
}
debug("Running idle timeout timer...");
const currentTime = new Date().getTime();
let nextTimeout: number = -1;
for (const connection of this.connections) {
const timeDelta = currentTime - connection.lastSocketOperation;
if (timeDelta >= EventedHTTPServer.MAX_CONNECTION_IDLE_TIME) {
debug("[%s] Closing connection as it was inactive for " + timeDelta + "ms");
connection.close();
} else {
nextTimeout = Math.max(nextTimeout, EventedHTTPServer.MAX_CONNECTION_IDLE_TIME - timeDelta);
}
}
if (this.connections.size >= EventedHTTPServer.CONNECTION_TIMEOUT_LIMIT) {
this.connectionIdleTimeout = setTimeout(this.scheduleNextConnectionIdleTimeout.bind(this), nextTimeout);
}
}
public listen(targetPort: number, hostname?: string): void {
this.tcpServer.listen(targetPort, hostname, () => {
const address = this.tcpServer.address() as AddressInfo; // address() is only a string when listening to unix domain sockets
debug("Server listening on %s:%s", address.family === "IPv6"? `[${address.address}]`: address.address, address.port);
this.emit(EventedHTTPServerEvent.LISTENING, address.port, address.address);
});
this.tcpServer.on("connection", this.onConnection.bind(this));
}
public stop(): void {
this.tcpServer.close();
for (const connection of this.connections) {
connection.close();
}
}
public destroy(): void {
this.stop();
this.removeAllListeners();
}
/**
* Send a even notification for given characteristic and changed value to all connected clients.
* If {@param originator} is specified, the given {@link HAPConnection} will be excluded from the broadcast.
*
* @param aid - The accessory id of the updated characteristic.
* @param iid - The instance id of the updated characteristic.
* @param value - The newly set value of the characteristic.
* @param originator - If specified, the connection will not get a event message.
* @param immediateDelivery - The HAP spec requires some characteristics to be delivery immediately.
* Namely for the {@link ButtonEvent} and the {@link ProgrammableSwitchEvent} characteristics.
*/
public broadcastEvent(aid: number, iid: number, value: Nullable<CharacteristicValue>, originator?: HAPConnection, immediateDelivery?: boolean): void {
for (const connection of this.connections) {
if (connection === originator) {
debug("[%s] Muting event '%s' notification for this connection since it originated here.", connection.remoteAddress, aid + "." + iid);
continue;
}
connection.sendEvent(aid, iid, value, immediateDelivery);
}
}
private onConnection(socket: Socket): void {
const connection = new HAPConnection(this, socket);
connection.on(HAPConnectionEvent.REQUEST, (request, response) => {
this.emit(EventedHTTPServerEvent.REQUEST, connection, request, response);
});
connection.on(HAPConnectionEvent.AUTHENTICATED, this.handleConnectionAuthenticated.bind(this, connection));
connection.on(HAPConnectionEvent.CLOSED, this.handleConnectionClose.bind(this, connection));
this.connections.add(connection);
debug("[%s] New connection from client on interface %s (%s)", connection.remoteAddress, connection.networkInterface, connection.localAddress);
this.emit(EventedHTTPServerEvent.CONNECTION_OPENED, connection);
if (this.connections.size >= EventedHTTPServer.CONNECTION_TIMEOUT_LIMIT && !this.connectionIdleTimeout) {
this.scheduleNextConnectionIdleTimeout();
}
}
private handleConnectionAuthenticated(connection: HAPConnection, username: HAPUsername): void {
const connections: HAPConnection[] | undefined = this.connectionsByUsername.get(username);
if (!connections) {
this.connectionsByUsername.set(username, [connection]);
} else if (!connections.includes(connection)) { // ensure this doesn't get added more than one time
connections.push(connection);
}
}
private handleConnectionClose(connection: HAPConnection): void {
this.emit(EventedHTTPServerEvent.CONNECTION_CLOSED, connection);
this.connections.delete(connection);
if (connection.username) { // aka connection was authenticated
const connections = this.connectionsByUsername.get(connection.username);
if (connections) {
const index = connections.indexOf(connection);
if (index !== -1) {
connections.splice(index, 1);
}
if (connections.length === 0) {
this.connectionsByUsername.delete(connection.username);
}
}
}
}
public static destroyExistingConnectionsAfterUnpair(initiator: HAPConnection, username: string): void {
const connections: HAPConnection[] | undefined = initiator.server.connectionsByUsername.get(username);
if (connections) {
for (const connection of connections) {
connection.closeConnectionAsOfUnpair(initiator);
}
}
}
}
/**
* @private
*/
export const enum HAPConnectionState {
CONNECTING, // initial state, setup is going on
FULLY_SET_UP, // internal http server is running and connection is established
AUTHENTICATED, // encryption is set up
// above signals are represent a alive connection
// below states are considered "closed or soon closed"
TO_BE_TEARED_DOWN, // when in this state, connection should be closed down after response was sent out
CLOSING, // close was called
CLOSED, // dead
}
export const enum HAPConnectionEvent {
REQUEST = "request",
AUTHENTICATED = "authenticated",
CLOSED = "closed",
}
export declare interface HAPConnection {
on(event: "request", listener: (request: IncomingMessage, response: ServerResponse) => void): this;
on(event: "authenticated", listener: (username: HAPUsername) => void): this;
on(event: "closed", listener: () => void): this;
emit(event: "request", request: IncomingMessage, response: ServerResponse): boolean;
emit(event: "authenticated", username: HAPUsername): boolean;
emit(event: "closed"): boolean;
}
/**
* Manages a single iOS-initiated HTTP connection during its lifetime.
* @private
*/
export class HAPConnection extends EventEmitter {
readonly server: EventedHTTPServer;
readonly sessionID: SessionIdentifier; // uuid unique to every HAP connection
private state: HAPConnectionState = HAPConnectionState.CONNECTING;
readonly localAddress: string;
readonly remoteAddress: string; // cache because it becomes undefined in 'onClientSocketClose'
readonly remotePort: number;
readonly networkInterface: string;
private readonly tcpSocket: Socket;
private readonly internalHttpServer: http.Server;
private httpSocket?: Socket; // set when in state FULLY_SET_UP
private internalHttpServerPort?: number;
private internalHttpServerAddress?: string;
lastSocketOperation: number = new Date().getTime();
private pendingClientSocketData?: Buffer = Buffer.alloc(0); // data received from client before HTTP proxy is fully setup
private handlingRequest: boolean = false; // true while we are composing an HTTP response (so events can wait)
username?: HAPUsername; // username is unique to every user in the home, basically identifies an Apple Id
encryption?: HAPEncryption; // created in handlePairVerifyStepOne
srpServer?: SrpServer;
_pairSetupState?: number; // TODO ensure those two states are always correctly reset?
_pairVerifyState?: number;
private registeredEvents: Set<EventName> = new Set();
private eventsTimer?: Timeout;
private readonly queuedEvents: Map<EventName, CharacteristicEventNotification> = new Map();
private readonly pendingEventData: Buffer[] = []; // queue of unencrypted event data waiting to be sent until after an in-progress HTTP response is being written
timedWritePid?: number;
timedWriteTimeout?: NodeJS.Timeout;
constructor(server: EventedHTTPServer, clientSocket: Socket) {
super();
this.server = server;
this.sessionID = uuid.generate(clientSocket.remoteAddress + ':' + clientSocket.remotePort);
this.localAddress = clientSocket.localAddress;
this.remoteAddress = clientSocket.remoteAddress!; // cache because it becomes undefined in 'onClientSocketClose'
this.remotePort = clientSocket.remotePort!;
this.networkInterface = HAPConnection.getLocalNetworkInterface(clientSocket);
// clientSocket is the socket connected to the actual iOS device
this.tcpSocket = clientSocket;
this.tcpSocket.on('data', this.onTCPSocketData.bind(this));
this.tcpSocket.on('close', this.onTCPSocketClose.bind(this));
this.tcpSocket.on('error', this.onTCPSocketError.bind(this)); // we MUST register for this event, otherwise the error will bubble up to the top and crash the node process entirely.
this.tcpSocket.setNoDelay(true); // disable Nagle algorithm
// "HAP accessory servers must not use keepalive messages, which periodically wake up iOS devices".
// Thus we don't configure any tcp keepalive
// create our internal HTTP server for this connection that we will proxy data to and from
this.internalHttpServer = http.createServer();
this.internalHttpServer.timeout = 0; // clients expect to hold connections open as long as they want
this.internalHttpServer.keepAliveTimeout = 0; // workaround for https://github.com/nodejs/node/issues/13391
this.internalHttpServer.on("listening", this.onHttpServerListening.bind(this));
this.internalHttpServer.on('request', this.handleHttpServerRequest.bind(this));
this.internalHttpServer.on('error', this.onHttpServerError.bind(this));
// close event is added later on the "connect" event as possible listen retries would throw unnecessary close events
this.internalHttpServer.listen(0, this.internalHttpServerAddress = getOSLoopbackAddressIfAvailable());
}
/**
* This method is called once the connection has gone through pair-verify.
* As any HomeKit controller will initiate a pair-verify after the pair-setup procedure, this method gets
* not called on the initial pair-setup.
*
* Once this method has been called, the connection is authenticated and encryption is turned on.
*/
public connectionAuthenticated(username: HAPUsername): void {
this.state = HAPConnectionState.AUTHENTICATED;
this.username = username;
this.emit(HAPConnectionEvent.AUTHENTICATED, username);
}
public isAuthenticated(): boolean {
return this.state === HAPConnectionState.AUTHENTICATED;
}
public close(): void {
if (this.state >= HAPConnectionState.CLOSING) {
return; // already closed/closing
}
this.state = HAPConnectionState.CLOSING;
this.tcpSocket.destroy();
}
public closeConnectionAsOfUnpair(initiator: HAPConnection): void {
if (this === initiator) {
// the initiator of the unpair request is this connection, meaning it unpaired itself.
// we still need to send the response packet to the unpair request.
this.state = HAPConnectionState.TO_BE_TEARED_DOWN;
} else {
// as HomeKit requires it, destroy any active session which got unpaired
this.close();
}
}
public sendEvent(aid: number, iid: number, value: Nullable<CharacteristicValue>, immediateDelivery?: boolean): void {
assert(aid != undefined, "HAPConnection.sendEvent: aid must be defined!");
assert(iid != undefined, "HAPConnection.sendEvent: iid must be defined!");
const eventName = aid + "." + iid;
if (!this.registeredEvents.has(eventName)) {
return;
}
if (immediateDelivery) {
// some characteristics are required to deliver notifications immediately
this.writeEventNotification({
characteristics: [{
aid: aid,
iid: iid,
value: value,
}],
});
} else {
// TODO should a new event not remove a previous event (to support censor open -> censor closed :thinking:)
// any only remove previous events if the same value was set?
this.queuedEvents.set(eventName, {
aid: aid,
iid: iid,
value: value,
});
if (!this.handlingRequest && !this.eventsTimer) { // if we are handling a request or there is already a timer running we just add it in the queue
this.eventsTimer = setTimeout(this.handleEventsTimeout.bind(this), 250);
this.eventsTimer.unref();
}
}
}
private handleEventsTimeout(): void {
this.eventsTimer = undefined;
if (this.state > HAPConnectionState.AUTHENTICATED || this.handlingRequest) {
// connection is closed or about to be closed. no need to send any further events
// OR we are currently sending a response
return;
}
this.writeQueuedEventNotifications();
}
private writePendingEventNotifications(): void {
for (const buffer of this.pendingEventData) {
this.tcpSocket.write(this.encrypt(buffer));
}
this.pendingEventData.splice(0, this.pendingEventData.length);
}
private writeQueuedEventNotifications(): void {
if (this.queuedEvents.size === 0 || this.eventsTimer) {
return; // don't send empty event notifications or if there is a timeout running
}
const eventData: EventNotification = { characteristics: [] };
for (const [eventName, characteristic] of this.queuedEvents) {
if (!this.registeredEvents.has(eventName)) { // client unregistered events in the mean time
continue;
}
eventData.characteristics.push(characteristic);
}
this.queuedEvents.clear();
this.writeEventNotification(eventData);
}
/**
* This will create an EVENT/1.0 notification header with the provided event notification.
* If currently a HTTP request is in progress the assembled packet will be
* added to the pending events list.
*
* @param notification - The event which should be sent out
*/
private writeEventNotification(notification: EventNotification): void {
debugCon("[%s] Sending HAP event notifications %o", this.remoteAddress, notification.characteristics);
const dataBuffer = Buffer.from(JSON.stringify(notification), "utf8");
const header = Buffer.from(
"EVENT/1.0 200 OK\r\n" +
"Content-Type: application/hap+json\r\n" +
"Content-Length: " + dataBuffer.length + "\r\n" +
"\r\n",
"utf8" // buffer encoding
);
const buffer = Buffer.concat([header, dataBuffer]);
if (this.handlingRequest) {
// it is important that we not encrypt the pending event data. This would increment the nonce used in encryption
this.pendingEventData.push(buffer);
} else {
this.tcpSocket.write(this.encrypt(buffer), this.handleTCPSocketWriteFulfilled.bind(this));
}
}
public enableEventNotifications(aid: number, iid: number): void {
this.registeredEvents.add(aid + "." + iid);
}
public disableEventNotifications(aid: number, iid: number): void {
this.registeredEvents.delete(aid + "." + iid);
}
public hasEventNotifications(aid: number, iid: number): boolean {
return this.registeredEvents.has(aid + "." + iid);
}
public getRegisteredEvents(): Set<EventName> {
return this.registeredEvents;
}
public clearRegisteredEvents(): void {
this.registeredEvents.clear();
}
private encrypt(data: Buffer): Buffer {
// if accessoryToControllerKey is not empty, then encryption is enabled for this connection. However, we'll
// need to be careful to ensure that we don't encrypt the last few bytes of the response from handlePairVerifyStepTwo.
// Since all communication calls are asynchronous, we could easily receive this 'encrypt' event for those bytes.
// So we want to make sure that we aren't encrypting data until we have *received* some encrypted data from the client first.
if (this.encryption && this.encryption.accessoryToControllerKey.length > 0 && this.encryption.controllerToAccessoryCount > 0) {
return hapCrypto.layerEncrypt(data, this.encryption);
}
return data; // otherwise we don't encrypt and return plaintext
}
private decrypt(data: Buffer): Buffer {
if (this.encryption && this.encryption.controllerToAccessoryKey.length > 0) {
// below call may throw an error if decryption failed
return hapCrypto.layerDecrypt(data, this.encryption);
}
return data; // otherwise we don't decrypt and return plaintext
}
private onHttpServerListening() {
const addressInfo = this.internalHttpServer.address() as AddressInfo; // address() is only a string when listening to unix domain sockets
const addressString = addressInfo.family === "IPv6"? `[${addressInfo.address}]`: addressInfo.address;
this.internalHttpServerPort = addressInfo.port;
debugCon("[%s] Internal HTTP server listening on %s:%s", this.remoteAddress, addressString, addressInfo.port);
this.internalHttpServer.on('close', this.onHttpServerClose.bind(this));
// now we can establish a connection to this running HTTP server for proxying data
this.httpSocket = net.createConnection(this.internalHttpServerPort, this.internalHttpServerAddress); // previously we used addressInfo.address
this.httpSocket.setNoDelay(true); // disable Nagle algorithm
this.httpSocket.on('data', this.handleHttpServerResponse.bind(this));
this.httpSocket.on('error', this.onHttpSocketError.bind(this)); // we MUST register for this event, otherwise the error will bubble up to the top and crash the node process entirely.
this.httpSocket.on('close', this.onHttpSocketClose.bind(this));
this.httpSocket.on('connect', () => {
// we are now fully set up:
// - clientSocket is connected to the iOS device
// - serverSocket is connected to the httpServer
// - ready to proxy data!
this.state = HAPConnectionState.FULLY_SET_UP;
debugCon("[%s] Internal HTTP socket connected. HAPConnection now fully set up!", this.remoteAddress)
// start by flushing any pending buffered data received from the client while we were setting up
if (this.pendingClientSocketData && this.pendingClientSocketData.length > 0) {
this.httpSocket!.write(this.pendingClientSocketData);
}
this.pendingClientSocketData = undefined;
});
}
/**
* This event handler is called when we receive data from a HomeKit controller on our tcp socket.
* We store the data if the internal http server is not read yet, or forward it to the http server.
*/
private onTCPSocketData(data: Buffer): void {
if (this.state > HAPConnectionState.AUTHENTICATED) {
// don't accept data of a connection which is about to be closed or already closed
return;
}
this.handlingRequest = true; // reverted to false once response was sent out
this.lastSocketOperation = new Date().getTime();
try {
data = this.decrypt(data);
} catch (error) { // decryption and/or verification failed, disconnect the client
debugCon("[%s] Error occurred trying to decrypt incoming packet: %s", this.remoteAddress, error.message);
this.close();
return;
}
if (this.state < HAPConnectionState.FULLY_SET_UP) { // we're not setup yet, so add this data to our intermediate buffer
this.pendingClientSocketData = Buffer.concat([this.pendingClientSocketData!, data]);
} else {
this.httpSocket!.write(data); // proxy it along to the HTTP server
}
}
/**
* This event handler is called when the internal http server receives a request.
* Meaning we received data from the HomeKit controller in {@link onTCPSocketData}, which then send the
* data unencrypted to the internal http server. And now it landed here, fully parsed as a http request.
*/
private handleHttpServerRequest(request: IncomingMessage, response: ServerResponse): void {
if (this.state > HAPConnectionState.AUTHENTICATED) {
// don't accept data of a connection which is about to be closed or already closed
return;
}
request.socket.setNoDelay(true);
response.connection.setNoDelay(true); // deprecated since 13.0.0
debugCon("[%s] HTTP request: %s", this.remoteAddress, request.url);
this.emit(HAPConnectionEvent.REQUEST, request, response);
}
/**
* This event handler is called by the socket which is connected to our internal http server.
* It is called with the response returned from the http server.
* In this method we have to encrypt and forward the message back to the HomeKit controller.
*/
private handleHttpServerResponse(data: Buffer): void {
data = this.encrypt(data);
this.tcpSocket.write(data, this.handleTCPSocketWriteFulfilled.bind(this));
debugCon("[%s] HTTP Response is finished", this.remoteAddress);
this.handlingRequest = false;
if (this.state === HAPConnectionState.TO_BE_TEARED_DOWN) {
setTimeout(() => this.close(), 10);
} else if (this.state < HAPConnectionState.TO_BE_TEARED_DOWN) {
this.writePendingEventNotifications();
this.writeQueuedEventNotifications();
}
}
private handleTCPSocketWriteFulfilled(): void {
this.lastSocketOperation = new Date().getTime();
}
private onTCPSocketError(err: Error): void {
debugCon("[%s] Client connection error: %s", this.remoteAddress, err.message);
// onTCPSocketClose will be called next
}
private onTCPSocketClose(): void {
this.state = HAPConnectionState.CLOSED;
debugCon("[%s] Client connection closed", this.remoteAddress);
if (this.httpSocket) {
this.httpSocket.destroy();
}
this.internalHttpServer.close();
this.emit(HAPConnectionEvent.CLOSED); // sending final closed event
this.removeAllListeners(); // cleanup listeners, we are officially dead now
}
private onHttpServerError(err: Error & { code?: string }): void {
debugCon("[%s] HTTP server error: %s", this.remoteAddress, err.message);
if (err.code === 'EADDRINUSE') {
this.internalHttpServerPort = undefined;
this.internalHttpServer.close();
this.internalHttpServer.listen(0, this.internalHttpServerAddress = getOSLoopbackAddressIfAvailable());
}
}
private onHttpServerClose(): void {
debugCon("[%s] HTTP server was closed", this.remoteAddress);
// make sure the iOS side is closed as well
this.close();
}
private onHttpSocketError(err: Error): void {
debugCon("[%s] HTTP connection error: ", this.remoteAddress, err.message);
// onHttpSocketClose will be called next
}
private onHttpSocketClose(): void {
debugCon("[%s] HTTP connection was closed", this.remoteAddress);
// we only support a single long-lived connection to our internal HTTP server. Since it's closed,
// we'll need to shut it down entirely.
this.internalHttpServer.close();
}
public getLocalAddress(ipVersion: "ipv4" | "ipv6"): string {
const infos = os.networkInterfaces()[this.networkInterface];
if (ipVersion === "ipv4") {
for (const info of infos) {
if (info.family === "IPv4") {
return info.address;
}
}
throw new Error("Could not find " + ipVersion + " address for interface " + this.networkInterface);
} else {
let localUniqueAddress: string | undefined = undefined;
for (const info of infos) {
if (info.family === "IPv6") {
if (!info.scopeid) {
return info.address;
} else if (!localUniqueAddress) {
localUniqueAddress = info.address;
}
}
}
if (!localUniqueAddress) {
throw new Error("Could not find " + ipVersion + " address for interface " + this.networkInterface);
}
return localUniqueAddress;
}
}
private static getLocalNetworkInterface(socket: Socket): string {
let localAddress = socket.localAddress;
if (localAddress.startsWith("::ffff:")) { // IPv4-Mapped IPv6 Address https://tools.ietf.org/html/rfc4291#section-2.5.5.2
localAddress = localAddress.substring(7);
} else {
const index = localAddress.indexOf("%");
if (index !== -1) { // link-local ipv6
localAddress = localAddress.substring(0, index);
}
}
const interfaces = os.networkInterfaces();
for (const [name, infos] of Object.entries(interfaces)) {
for (const info of infos) {
if (info.address === localAddress) {
return name;
}
}
}
// we couldn't map the address from above, we try now to match subnets (see https://github.com/homebridge/HAP-NodeJS/issues/847)
const family = net.isIPv4(localAddress)? "IPv4": "IPv6";
for (const [name, infos] of Object.entries(interfaces)) {
for (const info of infos) {
if (info.family !== family) {
continue;
}
// check if the localAddress is in the same subnet
if (getNetAddress(localAddress, info.netmask) === getNetAddress(info.address, info.netmask)) {
return name;
}
}
}
console.log(`WARNING couldn't map socket coming from remote address ${socket.remoteAddress}:${socket.remotePort} at local address ${socket.localAddress} to a interface!`);
return Object.keys(interfaces)[1]; // just use the first interface after the loopback interface as fallback
}
} | the_stack |
import * as assert from 'assert';
import * as vscode from 'vscode';
import * as path from 'path';
import { PLSQLDefinitionProvider } from '../src/provider/plsqlDefinition.provider';
interface ICase {
curTextLine: string;
curText: string;
curChar: number;
expTextLine: string;
expChar: number;
expFile: string;
}
suite('PLSQL Definition', () => {
const provider = new PLSQLDefinitionProvider();
function runTest(file: string, cases: ICase[], done) {
const uri = vscode.Uri.file(path.join(vscode.workspace.rootPath, file));
vscode.workspace.openTextDocument(uri)
.then(textDocument => {
return Promise.all(cases.map( (test, index) => {
// found line index
const found = new RegExp(test.curTextLine, 'i').exec(textDocument.getText());
assert.notEqual(found, null, `curText: ${test.curTextLine} not found`);
const curPos = textDocument.positionAt(found.index+test.curChar);
// run test
const num = `(${index}) `;
let result;
return provider.provideDefinition(textDocument, curPos, null)
.then(r => {
result = r;
const text = textDocument.getText(textDocument.getWordRangeAtPosition(curPos));
assert.equal(text, test.curText, num+text);
assert.notEqual(result, null, num+'return is null');
assert.equal(path.basename(result.uri.fsPath), test.expFile, num+'uri: '+JSON.stringify(result.uri));
// OpenTextDocument to find offset...
return vscode.workspace.openTextDocument(result.uri);
})
.then(document => {
const match = new RegExp(test.expTextLine, 'i').exec(document.getText());
assert.notEqual(match, null, `expText: ${test.expTextLine} not found`);
const expPos = document.positionAt(match.index+test.expChar);
assert.equal(result.range.start.line, expPos.line, num+'line: '+JSON.stringify(result.range));
assert.equal(result.range.start.character, expPos.character, num+'char: '+JSON.stringify(result.range));
});
}));
}, err => assert.ok(false, `error in OpenTextDocument ${err}`))
.then(() => done(), done);
}
function buildCase(curTextLine: string, curChar: number, curText: string,
expTextLine: string, expChar: number, expFile: string): ICase {
return {
curChar: curChar,
curTextLine: curTextLine,
curText: curText,
expChar: expChar,
expTextLine: expTextLine,
expFile: expFile
};
}
test('Package I', (done) => {
let testCases: ICase[] = [
// body to spec
buildCase(
'function get_myValue\\(param1 in varchar2\\)\\s*return varchar2\\s*is', 14, 'get_myValue',
'function get_myValue\\(param1 in varchar2\\)\\s*return varchar2;', 0, 'xyz_myPackage.sql'),
// spec to body
buildCase(
'procedure set_myValue\\(param1 in varchar2\\);', 14, 'set_myValue',
'procedure set_myValue\\(param1 in varchar2\\)\\s*is', 0, 'xyz_myPackage.sql'),
// body to spec
buildCase(
'function get_myValue\\(param1 in varchar2\\)\\s*return varchar2\\s*is', 4, 'function',
'function get_myValue\\(param1 in varchar2\\)\\s*return varchar2;', 0, 'xyz_myPackage.sql'),
// spec to body
buildCase(
'procedure set_myValue\\(param1 in varchar2\\);', 4, 'procedure',
'procedure set_myValue\\(param1 in varchar2\\)\\s*is', 0, 'xyz_myPackage.sql'),
// body to body
buildCase(
'MyPackage.myCall\\(\'test\'\\);', 14, 'myCall',
'procedure myCall\\(param1 in varchar2\\)\\s*is', 0, 'xyz_myPackage.sql'),
// body to body
buildCase(
'schema.MyPackage.myCall\\(\'test2\'\\);', 22, 'myCall',
'procedure myCall\\(param1 in varchar2\\)\\s*is', 0, 'xyz_myPackage.sql'),
// body to body
buildCase(
'pCallInternal\\(\'test3\'\\);', 5, 'pCallInternal',
'procedure pCallInternal\\(param1 in varchar2\\)\\s*is', 0, 'xyz_myPackage.sql'),
// body to body in another package
buildCase(
'MyPackage2.myCall\\(\'Test\'\\);', 14, 'myCall',
'procedure myCall\\(param1 in varchar2\\)\\s*is', 0, 'xyz_myPackage2.pkb'),
// body to a function file
buildCase(
'MyFunc\\(\'Test\'\\);', 3, 'MyFunc',
'CREATE OR REPLACE FUNCTION MyFunc\\(param1 varchar2\\) return varchar2', 0, 'xyz_myFunc.sql'),
// constant in body to spec (+schema)
buildCase(
'if x = schema.MyPackage.myConst', 26, 'myConst',
'myConst constant char\\(2\\) := \'10\';', 0, 'xyz_myPackage.sql'),
// variable in body to spec
buildCase(
'if y = myGlobalVar', 15, 'myGlobalVar',
'myGlobalVar number := 10;', 0, 'xyz_myPackage.sql'),
// type in body to spec in another package
buildCase(
'xyz MyPackage2.txyz_myType;', 20, 'txyz_myType',
'type txyz_myType is record', 0, 'xyz_myPackage2.pks'),
// type in body to spec
buildCase('abc ttxyz_myType;', 13, 'ttxyz_myType',
'type ttxyz_myType is table of txyz_myType;', 0, 'xyz_myPackage.sql')
];
runTest('xyz_myPackage.sql', testCases, done);
});
test('Package II', (done) => {
let testCases: ICase[] = [
// forward declaration body to body declaration
buildCase(
'function pForward\\(param1 in varchar2\\)\\s*return varchar2\\s*is', 13, 'pForward',
'function pForward\\(param1 in varchar2\\)\\s*return varchar2;', 0, 'xyz_myPackage.sql'),
// forward declaration body declaration to body
buildCase(
'function pForward\\(param1 in varchar2\\)\\s*return varchar2;', 13, 'pForward',
'function pForward\\(param1 in varchar2\\)\\s*return varchar2\\s*is', 0, 'xyz_myPackage.sql'),
// forward declaration body to body declaration
buildCase(
'function pForward\\(param1 in varchar2\\)\\s*return varchar2\\s*is', 4, 'function',
'function pForward\\(param1 in varchar2\\)\\s*return varchar2;', 0, 'xyz_myPackage.sql'),
// forward declaration body declaration to body
buildCase(
'function pForward\\(param1 in varchar2\\)\\s*return varchar2;', 4, 'function',
'function pForward\\(param1 in varchar2\\)\\s*return varchar2\\s*is', 0, 'xyz_myPackage.sql'),
// call to forward declaration
buildCase(
'pForward\\(\'test3\'\\);', 5, 'pForward',
'function pForward\\(param1 in varchar2\\)\\s*return varchar2\\s*is', 0, 'xyz_myPackage.sql'),
// call to subFunctions
buildCase(
'x = pSubFunction\\(2\\);', 8, 'pSubFunction',
'function pSubFunction\\(param1 in number\\)\\s*is', 0, 'xyz_myPackage.sql'),
// constant in body to body declaration
buildCase(
'if x = myConst2', 12, 'myConst2',
'myConst2 constant char\\(2\\) := \'10\';', 0, 'xyz_myPackage.sql'),
// variable in body to body declaration
buildCase(
'if y = myGlobalVar2', 15, 'myGlobalVar2',
'myGlobalVar2 number := 10;', 0, 'xyz_myPackage.sql'),
// type in body to body declaration
buildCase(
'abc ttxyz_myType2;', 13, 'ttxyz_myType2',
'type ttxyz_myType2 is table of txyz_myType2;', 0, 'xyz_myPackage.sql')
];
runTest('xyz_myPackage.sql', testCases, done);
});
test('Separate package spec', (done) => {
let testCases: ICase[] = [
// spec to body
buildCase(
'procedure set_myValue\\(param1 in varchar2\\);', 14, 'set_myValue',
'procedure set_myValue\\(param1 in varchar2\\)\\s*is', 0, 'xyz_myPackage2.pkb'),
];
runTest('xyz_myPackage2.pks', testCases, done);
});
test('Separate package body I', (done) => {
let testCases: ICase[] = [
// body to spec
buildCase(
'function get_myValue\\(param1 in varchar2\\)\\s*return varchar2\\s*is', 13, 'get_myValue',
'function get_myValue\\(param1 in varchar2\\)\\s*return varchar2;', 0, 'xyz_myPackage2.pks'),
// body to body
buildCase(
'MyPackage2.myCall\\(\'test\'\\);', 13, 'myCall',
'procedure myCall\\(param1 in varchar2\\)\\s*is', 0, 'xyz_myPackage2.pkb'),
// body to body
buildCase(
'pCallInternal\\(\'test2\'\\);', 5, 'pCallInternal',
'procedure pCallInternal\\(param1 in varchar2\\)\\s*is', 0, 'xyz_myPackage2.pkb'),
// body to body in another package
buildCase(
'MyPackage.myCall\\(\'Test\'\\);', 12, 'myCall',
'procedure myCall\\(param1 in varchar2\\)\\s*is', 0, 'xyz_myPackage.sql'),
// body to a function file
buildCase(
'MyFunc\\(\'Test\'\\);', 2, 'MyFunc',
'CREATE OR REPLACE FUNCTION MyFunc\\(param1 varchar2\\) return varchar2\\s*is', 0, 'xyz_myFunc.sql'),
// body to a procedure file
buildCase(
'MyProc\\(\'Test\'\\);', 2, 'MyProc',
'CREATE OR REPLACE PROCEDURE "schema"."MyProc"\\(param1 varchar2\\)\\s*is', 0, 'xyz_myProc.sql'),
// body to a procedure file (+schema)
buildCase(
'schema.MyProc\\(\'Test\'\\);', 9, 'MyProc',
'CREATE OR REPLACE PROCEDURE "schema"."MyProc"\\(param1 varchar2\\)\\s*is', 0, 'xyz_myProc.sql'),
];
runTest('xyz_myPackage2.pkb', testCases, done);
});
test('Separate package body II', (done) => {
let testCases: ICase[] = [
// constant in body to spec (+schema)
buildCase(
'if x = schema.MyPackage2.myConst', 27, 'myConst',
'myConst constant char\\(2\\) := \'10\';', 0, 'xyz_myPackage2.pks'),
// variable in body to spec
buildCase(
'if y = myGlobalVar', 9, 'myGlobalVar',
'myGlobalVar number := 10;', 0, 'xyz_myPackage2.pks'),
// type in body to spec in another package
buildCase(
'xyz MyPackage.txyz_myType;', 18, 'txyz_myType',
'type txyz_myType is record\\(', 0, 'xyz_myPackage.sql'),
// type in body to spec
buildCase(
'abc ttxyz_myType;', 10, 'ttxyz_myType',
'type ttxyz_myType is table of txyz_myType;', 0, 'xyz_myPackage2.pks')
];
runTest('xyz_myPackage2.pkb', testCases, done);
});
test('Function', (done) => {
let testCases: ICase[] = [
// function to package
buildCase(
'myPackage.myCall\\(param1\\);', 12, 'myCall',
'procedure myCall\\(param1 in varchar2\\)\\s*is', 0, 'xyz_myPackage.sql'),
// function to procedure
buildCase(
'schema.MyProc\\(param1\\);', 9, 'MyProc',
'CREATE OR REPLACE PROCEDURE "schema"."MyProc"\\(param1 varchar2\\)', 0, 'xyz_myProc.sql'),
// function to nested function
buildCase(
'return myNestedFunc\\(param1\\);', 9, 'myNestedFunc',
'function myNestedFunc\\(param1 varchar2\\)', 0, 'xyz_myFunc.sql'),
// constant to spec (+schema)
buildCase(
'if x = schema.MyPackage.myConst', 26, 'myConst',
'myConst constant char\\(2\\) := \'10\';', 0, 'xyz_myPackage.sql'),
// variable to spec
buildCase(
'if y = MyPackage2.myGlobalVar', 20, 'myGlobalVar',
'myGlobalVar number := 10;', 0, 'xyz_myPackage2.pks'),
// type to spec
buildCase(
'xyz MyPackage2.txyz_myType;', 19, 'txyz_myType',
'type txyz_myType is record\\(', 0, 'xyz_myPackage2.pks'),
// type to spec
buildCase(
'abc MyPackage.ttxyz_myType;', 19, 'ttxyz_myType',
'type ttxyz_myType is table of txyz_myType;', 0, 'xyz_myPackage.sql')
];
runTest('xyz_myFunc.sql', testCases, done);
});
test('Procedure', (done) => {
let testCases: ICase[] = [
// procedure to package
buildCase(
'myPackage.myCall\\(param1\\);', 12, 'myCall',
'procedure myCall\\(param1 in varchar2\\)\\s*is', 0, 'xyz_myPackage.sql'),
// procedure to functiom
buildCase(
'x := schema.MyFunc\\(param1\\);', 14, 'MyFunc',
'CREATE OR REPLACE FUNCTION MyFunc\\(param1 varchar2\\) return varchar2', 0, 'xyz_myFunc.sql'),
// procedure to nested procedure
buildCase(
'myNestedProc\\(param1\\);', 2, 'myNestedProc',
'function myNestedProc\\(param1 varchar2\\)', 0, 'xyz_myProc.sql'),
];
runTest('xyz_myProc.sql', testCases, done);
});
test('Dml', (done) => {
let testCases: ICase[] = [
// dml to package
buildCase(
'set myField = MyPackage.set_myValue\\(\'toto\'\\)', 28, 'set_myValue',
'procedure set_myValue\\(param1 in varchar2\\)\\s*is', 0, 'xyz_myPackage.sql'),
// constant in dml to spec (+schema)
buildCase(
'if x = schema.MyPackage.myConst', 26, 'myConst',
'myConst constant char\\(2\\) := \'10\';', 0, 'xyz_myPackage.sql'),
// variable in dml to spec
buildCase(
'if y = MyPackage2.myGlobalVar', 20, 'myGlobalVar',
'myGlobalVar number := 10;', 0, 'xyz_myPackage2.pks'),
// type in dml to spec
buildCase(
'xyz MyPackage2.txyz_myType;', 20, 'txyz_myType',
'type txyz_myType is record\\(', 0, 'xyz_myPackage2.pks'),
// type in dml to spec
buildCase(
'abc MyPackage.ttxyz_myType;', 20, 'ttxyz_myType',
'type ttxyz_myType is table of txyz_myType;', 0, 'xyz_myPackage.sql')
];
runTest('xyz_myDml.sql', testCases, done);
});
}); | the_stack |
import { delay } from "./common";
import { Point } from "./structs/point";
import { BooleanArray2D } from "./structs/typedarrays";
import { FacetResult, PathPoint, OrientationEnum, Facet } from "./facetmanagement";
export class FacetBorderTracer {
/**
* Traces the border path of the facet from the facet border points.
* Imagine placing walls around the outer side of the border points.
*/
public static async buildFacetBorderPaths(facetResult: FacetResult, onUpdate: ((progress: number) => void) | null = null) {
let count = 0;
const borderMask = new BooleanArray2D(facetResult.width, facetResult.height);
// sort by biggest facets first
const facetProcessingOrder = facetResult.facets.filter((f) => f != null).slice(0).sort((a, b) => b!.pointCount > a!.pointCount ? 1 : (b!.pointCount < a!.pointCount ? -1 : 0)).map((f) => f!.id);
for (let fidx: number = 0; fidx < facetProcessingOrder.length; fidx++) {
const f = facetResult.facets[facetProcessingOrder[fidx]]!;
if (f != null) {
for (const bp of f.borderPoints) {
borderMask.set(bp.x, bp.y, true);
}
// keep track of which walls are already set on each pixel
// e.g. xWall.get(x,y) is the left wall of point x,y
// as the left wall of (x+1,y) and right wall of (x,y) is the same
// the right wall of x,y can be set with xWall.set(x+1,y).
// Analogous for the horizontal walls in yWall
const xWall = new BooleanArray2D(facetResult.width + 1, facetResult.height + 1);
const yWall = new BooleanArray2D(facetResult.width + 1, facetResult.height + 1);
// the first border point will guaranteed be one of the outer ones because
// it will be the first point that is encountered of the facet when building
// them in buildFacet with DFS.
// --> Or so I thought, which is apparently not the case in rare circumstances
// sooooo go look for a border that edges with the bounding box, this is definitely
// on the outer side then.
let borderStartIndex = -1;
for (let i: number = 0; i < f.borderPoints.length; i++) {
if ((f.borderPoints[i].x === f.bbox.minX || f.borderPoints[i].x === f.bbox.maxX) ||
(f.borderPoints[i].y === f.bbox.minY || f.borderPoints[i].y === f.bbox.maxY)) {
borderStartIndex = i;
break;
}
}
// determine the starting point orientation (the outside of facet)
const pt = new PathPoint(f.borderPoints[borderStartIndex], OrientationEnum.Left);
// L T R B
if (pt.x - 1 < 0 || facetResult.facetMap.get(pt.x - 1, pt.y) !== f.id) {
pt.orientation = OrientationEnum.Left;
}
else if (pt.y - 1 < 0 || facetResult.facetMap.get(pt.x, pt.y - 1) !== f.id) {
pt.orientation = OrientationEnum.Top;
}
else if (pt.x + 1 >= facetResult.width || facetResult.facetMap.get(pt.x + 1, pt.y) !== f.id) {
pt.orientation = OrientationEnum.Right;
}
else if (pt.y + 1 >= facetResult.height || facetResult.facetMap.get(pt.x, pt.y + 1) !== f.id) {
pt.orientation = OrientationEnum.Bottom;
}
// build a border path from that point
const path = FacetBorderTracer.getPath(pt, facetResult, f, borderMask, xWall, yWall);
f.borderPath = path;
if (count % 100 === 0) {
await delay(0);
if (onUpdate != null) {
onUpdate(fidx / facetProcessingOrder.length);
}
}
}
count++;
}
if (onUpdate != null) {
onUpdate(1);
}
}
/**
* Returns a border path starting from the given point
*/
private static getPath(pt: PathPoint, facetResult: FacetResult, f: Facet, borderMask: BooleanArray2D, xWall: BooleanArray2D, yWall: BooleanArray2D) {
const debug = false;
let finished = false;
const count = 0;
const path: PathPoint[] = [];
FacetBorderTracer.addPointToPath(path, pt, xWall, f, yWall);
// check rotations first, then straight along the ouside and finally diagonally
// this ensures that bends are always taken as tight as possible
// so it doesn't skip border points to later loop back to and get stuck (hopefully)
while (!finished) {
if (debug) {
console.log(pt.x + " " + pt.y + " " + pt.orientation);
}
// yes, technically i could do some trickery to only get the left/top cases
// by shifting the pixels but that means some more shenanigans in correct order of things
// so whatever. (And yes I tried it but it wasn't worth the debugging hell that ensued)
const possibleNextPoints: PathPoint[] = [];
// +---+---+
// | <| |
// +---+---+
if (pt.orientation === OrientationEnum.Left) {
// check rotate to top
// +---+---+
// | | |
// +---xnnnn (x = old wall, n = new wall, F = current facet x,y)
// | x F |
// +---x---+
if (((pt.y - 1 >= 0 && facetResult.facetMap.get(pt.x, pt.y - 1) !== f.id) // top exists and is a neighbour facet
|| pt.y - 1 < 0) // or top doesn't exist, which is the boundary of the image
&& !yWall.get(pt.x, pt.y)) { // and the wall isn't set yet
// can place top _ wall at x,y
if (debug) {
console.log("can place top _ wall at x,y");
}
const nextpt = new PathPoint(new Point(pt.x, pt.y), OrientationEnum.Top);
possibleNextPoints.push(nextpt);
}
// check rotate to bottom
// +---+---+
// | | |
// +---x---+ (x = old wall, n = new wall, F = current facet x,y)
// | x F |
// +---xnnnn
if (((pt.y + 1 < facetResult.height && facetResult.facetMap.get(pt.x, pt.y + 1) !== f.id) // bottom exists and is a neighbour facet
|| pt.y + 1 >= facetResult.height) // or bottom doesn't exist, which is the boundary of the image
&& !yWall.get(pt.x, pt.y + 1)) { // and the wall isn't set yet
// can place bottom _ wall at x,y
if (debug) {
console.log("can place bottom _ wall at x,y");
}
const nextpt = new PathPoint(new Point(pt.x, pt.y), OrientationEnum.Bottom);
possibleNextPoints.push(nextpt);
}
// check upwards
// +---n---+
// | n |
// +---x---+ (x = old wall, n = new wall, F = current facet x,y)
// | x F |
// +---x---+
if (pt.y - 1 >= 0 // top exists
&& facetResult.facetMap.get(pt.x, pt.y - 1) === f.id // and is part of the same facet
&& (pt.x - 1 < 0 || facetResult.facetMap.get(pt.x - 1, pt.y - 1) !== f.id) // and
&& borderMask.get(pt.x, pt.y - 1)
&& !xWall.get(pt.x, pt.y - 1)) {
// can place | wall at x,y-1
if (debug) {
console.log(`can place left | wall at x,y-1`);
}
const nextpt = new PathPoint(new Point(pt.x, pt.y - 1), OrientationEnum.Left);
possibleNextPoints.push(nextpt);
}
// check downwards
// +---x---+
// | x F |
// +---x---+ (x = old wall, n = new wall, F = current facet x,y)
// | n |
// +---n---+
if (pt.y + 1 < facetResult.height
&& facetResult.facetMap.get(pt.x, pt.y + 1) === f.id
&& (pt.x - 1 < 0 || facetResult.facetMap.get(pt.x - 1, pt.y + 1) !== f.id)
&& borderMask.get(pt.x, pt.y + 1)
&& !xWall.get(pt.x, pt.y + 1)) {
// can place | wall at x,y+1
if (debug) {
console.log("can place left | wall at x,y+1");
}
const nextpt = new PathPoint(new Point(pt.x, pt.y + 1), OrientationEnum.Left);
possibleNextPoints.push(nextpt);
}
// check left upwards
// +---+---+
// | | |
// nnnnx---+ (x = old wall, n = new wall, F = current facet x,y)
// | x F |
// +---x---+
if (pt.y - 1 >= 0 && pt.x - 1 >= 0 // there is a left upwards
&& facetResult.facetMap.get(pt.x - 1, pt.y - 1) === f.id // and it belongs to the same facet
&& borderMask.get(pt.x - 1, pt.y - 1) // and is on the border
&& !yWall.get(pt.x - 1, pt.y - 1 + 1) // and the bottom wall isn't set yet
&& !yWall.get(pt.x, pt.y) // and the path didn't come from the top of the current one to prevent getting a T shaped path (issue: https://i.imgur.com/ggUWuXi.png)
) {
// can place bottom _ wall at x-1,y-1
if (debug) {
console.log("can place bottom _ wall at x-1,y-1");
}
const nextpt = new PathPoint(new Point(pt.x - 1, pt.y - 1), OrientationEnum.Bottom);
possibleNextPoints.push(nextpt);
}
// check left downwards
// +---x---+
// | x F |
// nnnnx---+ (x = old wall, n = new wall, F = current facet x,y)
// | | |
// +---+---+
if (pt.y + 1 < facetResult.height && pt.x - 1 >= 0 // there is a left downwards
&& facetResult.facetMap.get(pt.x - 1, pt.y + 1) === f.id // and belongs to the same facet
&& borderMask.get(pt.x - 1, pt.y + 1) // and is on the border
&& !yWall.get(pt.x - 1, pt.y + 1) // and the top wall isn't set yet
&& !yWall.get(pt.x, pt.y + 1) // and the path didn't come from the bottom of the current point to prevent T shape
) {
// can place top _ wall at x-1,y+1
if (debug) {
console.log("can place top _ wall at x-1,y+1");
}
const nextpt = new PathPoint(new Point(pt.x - 1, pt.y + 1), OrientationEnum.Top);
possibleNextPoints.push(nextpt);
}
}
else if (pt.orientation === OrientationEnum.Top) {
// check rotate to left
if (((pt.x - 1 >= 0
&& facetResult.facetMap.get(pt.x - 1, pt.y) !== f.id)
|| pt.x - 1 < 0)
&& !xWall.get(pt.x, pt.y)) {
// can place left | wall at x,y
if (debug) {
console.log("can place left | wall at x,y");
}
const nextpt = new PathPoint(new Point(pt.x, pt.y), OrientationEnum.Left);
possibleNextPoints.push(nextpt);
}
// check rotate to right
if (((pt.x + 1 < facetResult.width
&& facetResult.facetMap.get(pt.x + 1, pt.y) !== f.id)
|| pt.x + 1 >= facetResult.width)
&& !xWall.get(pt.x + 1, pt.y)) {
// can place right | wall at x,y
if (debug) {
console.log("can place right | wall at x,y");
}
const nextpt = new PathPoint(new Point(pt.x, pt.y), OrientationEnum.Right);
possibleNextPoints.push(nextpt);
}
// check leftwards
if (pt.x - 1 >= 0
&& facetResult.facetMap.get(pt.x - 1, pt.y) === f.id
&& (pt.y - 1 < 0 || facetResult.facetMap.get(pt.x - 1, pt.y - 1) !== f.id)
&& borderMask.get(pt.x - 1, pt.y)
&& !yWall.get(pt.x - 1, pt.y)) {
// can place top _ wall at x-1,y
if (debug) {
console.log(`can place top _ wall at x-1,y`);
}
const nextpt = new PathPoint(new Point(pt.x - 1, pt.y), OrientationEnum.Top);
possibleNextPoints.push(nextpt);
}
// check rightwards
if (pt.x + 1 < facetResult.width
&& facetResult.facetMap.get(pt.x + 1, pt.y) === f.id
&& (pt.y - 1 < 0 || facetResult.facetMap.get(pt.x + 1, pt.y - 1) !== f.id)
&& borderMask.get(pt.x + 1, pt.y)
&& !yWall.get(pt.x + 1, pt.y)) {
// can place top _ wall at x+1,y
if (debug) {
console.log(`can place top _ wall at x+1,y`);
}
const nextpt = new PathPoint(new Point(pt.x + 1, pt.y), OrientationEnum.Top);
possibleNextPoints.push(nextpt);
}
// check left upwards
if (pt.y - 1 >= 0 && pt.x - 1 >= 0 // there is a left upwards
&& facetResult.facetMap.get(pt.x - 1, pt.y - 1) === f.id // and it belongs to the same facet
&& borderMask.get(pt.x - 1, pt.y - 1) // and it's part of the border
&& !xWall.get(pt.x - 1 + 1, pt.y - 1) // the right wall isn't set yet
&& !xWall.get(pt.x, pt.y) // and the left wall of the current point isn't set yet to prevent |- path
) {
// can place right | wall at x-1,y-1
if (debug) {
console.log("can place right | wall at x-1,y-1");
}
const nextpt = new PathPoint(new Point(pt.x - 1, pt.y - 1), OrientationEnum.Right);
possibleNextPoints.push(nextpt);
}
// check right upwards
if (pt.y - 1 >= 0 && pt.x + 1 < facetResult.width // there is a right upwards
&& facetResult.facetMap.get(pt.x + 1, pt.y - 1) === f.id // and it belongs to the same facet
&& borderMask.get(pt.x + 1, pt.y - 1) // and it's on the border
&& !xWall.get(pt.x + 1, pt.y - 1) // and the left wall isn't set yet
&& !xWall.get(pt.x + 1, pt.y) // and the right wall of the current point isn't set yet to prevent -| path
) {
// can place left | wall at x+1,y-1
if (debug) {
console.log("can place left | wall at x+1,y-1");
}
const nextpt = new PathPoint(new Point(pt.x + 1, pt.y - 1), OrientationEnum.Left);
possibleNextPoints.push(nextpt);
}
}
else if (pt.orientation === OrientationEnum.Right) {
// check rotate to top
if (((pt.y - 1 >= 0
&& facetResult.facetMap.get(pt.x, pt.y - 1) !== f.id)
|| pt.y - 1 < 0)
&& !yWall.get(pt.x, pt.y)) {
// can place top _ wall at x,y
if (debug) {
console.log("can place top _ wall at x,y");
}
const nextpt = new PathPoint(new Point(pt.x, pt.y), OrientationEnum.Top);
possibleNextPoints.push(nextpt);
}
// check rotate to bottom
if (((pt.y + 1 < facetResult.height
&& facetResult.facetMap.get(pt.x, pt.y + 1) !== f.id)
|| pt.y + 1 >= facetResult.height)
&& !yWall.get(pt.x, pt.y + 1)) {
// can place bottom _ wall at x,y
if (debug) {
console.log("can place bottom _ wall at x,y");
}
const nextpt = new PathPoint(new Point(pt.x, pt.y), OrientationEnum.Bottom);
possibleNextPoints.push(nextpt);
}
// check upwards
if (pt.y - 1 >= 0
&& facetResult.facetMap.get(pt.x, pt.y - 1) === f.id
&& (pt.x + 1 >= facetResult.width || facetResult.facetMap.get(pt.x + 1, pt.y - 1) !== f.id)
&& borderMask.get(pt.x, pt.y - 1)
&& !xWall.get(pt.x + 1, pt.y - 1)) {
// can place right | wall at x,y-1
if (debug) {
console.log(`can place right | wall at x,y-1`);
}
const nextpt = new PathPoint(new Point(pt.x, pt.y - 1), OrientationEnum.Right);
possibleNextPoints.push(nextpt);
}
// check downwards
if (pt.y + 1 < facetResult.height
&& facetResult.facetMap.get(pt.x, pt.y + 1) === f.id
&& (pt.x + 1 >= facetResult.width || facetResult.facetMap.get(pt.x + 1, pt.y + 1) !== f.id)
&& borderMask.get(pt.x, pt.y + 1)
&& !xWall.get(pt.x + 1, pt.y + 1)) {
// can place right | wall at x,y+1
if (debug) {
console.log("can place right | wall at x,y+1");
}
const nextpt = new PathPoint(new Point(pt.x, pt.y + 1), OrientationEnum.Right);
possibleNextPoints.push(nextpt);
}
// check right upwards
if (pt.y - 1 >= 0 && pt.x + 1 < facetResult.width // there is a right upwards
&& facetResult.facetMap.get(pt.x + 1, pt.y - 1) === f.id // and belongs to the same facet
&& borderMask.get(pt.x + 1, pt.y - 1) // and is on the border
&& !yWall.get(pt.x + 1, pt.y - 1 + 1) // and the bottom wall isn't set yet
&& !yWall.get(pt.x, pt.y) // and the top wall of the current point isn't set to prevent a T shape
) {
// can place bottom _ wall at x+1,y-1
if (debug) {
console.log("can place bottom _ wall at x+1,y-1");
}
const nextpt = new PathPoint(new Point(pt.x + 1, pt.y - 1), OrientationEnum.Bottom);
possibleNextPoints.push(nextpt);
}
// check right downwards
if (pt.y + 1 < facetResult.height && pt.x + 1 < facetResult.width // there is a right downwards
&& facetResult.facetMap.get(pt.x + 1, pt.y + 1) === f.id // and belongs to the same facet
&& borderMask.get(pt.x + 1, pt.y + 1) // and is on the border
&& !yWall.get(pt.x + 1, pt.y + 1) // and the top wall isn't visited yet
&& !yWall.get(pt.x, pt.y + 1) // and the bottom wall of the current point isn't set to prevent a T shape
) {
// can place top _ wall at x+1,y+1
if (debug) {
console.log("can place top _ wall at x+1,y+1");
}
const nextpt = new PathPoint(new Point(pt.x + 1, pt.y + 1), OrientationEnum.Top);
possibleNextPoints.push(nextpt);
}
}
else if (pt.orientation === OrientationEnum.Bottom) {
// check rotate to left
if (((pt.x - 1 >= 0
&& facetResult.facetMap.get(pt.x - 1, pt.y) !== f.id)
|| pt.x - 1 < 0)
&& !xWall.get(pt.x, pt.y)) {
// can place left | wall at x,y
if (debug) {
console.log("can place left | wall at x,y");
}
const nextpt = new PathPoint(new Point(pt.x, pt.y), OrientationEnum.Left);
possibleNextPoints.push(nextpt);
}
// check rotate to right
if (((pt.x + 1 < facetResult.width
&& facetResult.facetMap.get(pt.x + 1, pt.y) !== f.id)
|| pt.x + 1 >= facetResult.width)
&& !xWall.get(pt.x + 1, pt.y)) {
// can place right | wall at x,y
if (debug) {
console.log("can place right | wall at x,y");
}
const nextpt = new PathPoint(new Point(pt.x, pt.y), OrientationEnum.Right);
possibleNextPoints.push(nextpt);
}
// check leftwards
if (pt.x - 1 >= 0
&& facetResult.facetMap.get(pt.x - 1, pt.y) === f.id
&& (pt.y + 1 >= facetResult.height || facetResult.facetMap.get(pt.x - 1, pt.y + 1) !== f.id)
&& borderMask.get(pt.x - 1, pt.y)
&& !yWall.get(pt.x - 1, pt.y + 1)) {
// can place bottom _ wall at x-1,y
if (debug) {
console.log(`can place bottom _ wall at x-1,y`);
}
const nextpt = new PathPoint(new Point(pt.x - 1, pt.y), OrientationEnum.Bottom);
possibleNextPoints.push(nextpt);
}
// check rightwards
if (pt.x + 1 < facetResult.width
&& facetResult.facetMap.get(pt.x + 1, pt.y) === f.id
&& (pt.y + 1 >= facetResult.height || facetResult.facetMap.get(pt.x + 1, pt.y + 1) !== f.id)
&& borderMask.get(pt.x + 1, pt.y)
&& !yWall.get(pt.x + 1, pt.y + 1)) {
// can place top _ wall at x+1,y
if (debug) {
console.log(`can place bottom _ wall at x+1,y`);
}
const nextpt = new PathPoint(new Point(pt.x + 1, pt.y), OrientationEnum.Bottom);
possibleNextPoints.push(nextpt);
}
// check left downwards
if (pt.y + 1 < facetResult.height && pt.x - 1 >= 0 // there is a left downwards
&& facetResult.facetMap.get(pt.x - 1, pt.y + 1) === f.id // and it's the same facet
&& borderMask.get(pt.x - 1, pt.y + 1) // and it's on the border
&& !xWall.get(pt.x - 1 + 1, pt.y + 1) // and the right wall isn't set yet
&& !xWall.get(pt.x, pt.y) // and the left wall of the current point isn't set yet to prevent |- path
) {
// can place right | wall at x-1,y-1
if (debug) {
console.log("can place right | wall at x-1,y+1");
}
const nextpt = new PathPoint(new Point(pt.x - 1, pt.y + 1), OrientationEnum.Right);
possibleNextPoints.push(nextpt);
}
// check right downwards
if (pt.y + 1 < facetResult.height && pt.x + 1 < facetResult.width // there is a right downwards
&& facetResult.facetMap.get(pt.x + 1, pt.y + 1) === f.id // and it's the same facet
&& borderMask.get(pt.x + 1, pt.y + 1) // and it's on the border
&& !xWall.get(pt.x + 1, pt.y + 1) // and the left wall isn't set yet
&& !xWall.get(pt.x + 1, pt.y) // and the right wall of the current point isn't set yet to prevent -| path
) {
// can place left | wall at x+1,y+1
if (debug) {
console.log("can place left | wall at x+1,y+1");
}
const nextpt = new PathPoint(new Point(pt.x + 1, pt.y + 1), OrientationEnum.Left);
possibleNextPoints.push(nextpt);
}
}
if (possibleNextPoints.length > 1) {
// TODO it's now not necessary anymore to aggregate all possibilities, the first one is going to be the correct
// selection to trace the entire border, so the if checks above can include a skip once ssible point is found again
pt = possibleNextPoints[0];
FacetBorderTracer.addPointToPath(path, pt, xWall, f, yWall);
}
else if (possibleNextPoints.length === 1) {
pt = possibleNextPoints[0];
FacetBorderTracer.addPointToPath(path, pt, xWall, f, yWall);
}
else {
finished = true;
}
}
// clear up the walls set for the path so the array can be reused
for (const pathPoint of path) {
switch (pathPoint.orientation) {
case OrientationEnum.Left:
xWall.set(pathPoint.x, pathPoint.y, false);
break;
case OrientationEnum.Top:
yWall.set(pathPoint.x, pathPoint.y, false);
break;
case OrientationEnum.Right:
xWall.set(pathPoint.x + 1, pathPoint.y, false);
break;
case OrientationEnum.Bottom:
yWall.set(pathPoint.x, pathPoint.y + 1, false);
break;
}
}
return path;
}
/**
* Add a point to the border path and ensure the correct xWall/yWalls is set
*/
private static addPointToPath(path: PathPoint[], pt: PathPoint, xWall: BooleanArray2D, f: Facet, yWall: BooleanArray2D) {
path.push(pt);
switch (pt.orientation) {
case OrientationEnum.Left:
xWall.set(pt.x, pt.y, true);
break;
case OrientationEnum.Top:
yWall.set(pt.x, pt.y, true);
break;
case OrientationEnum.Right:
xWall.set(pt.x + 1, pt.y, true);
break;
case OrientationEnum.Bottom:
yWall.set(pt.x, pt.y + 1, true);
break;
}
}
} | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace Formmsdyn_scheduleboardsetting_Information {
interface Tabs {
}
interface Body {
msdyn_BookBasedOn: DevKit.Controls.Boolean;
msdyn_CustomTabName: DevKit.Controls.String;
msdyn_CustomTabWebResource: DevKit.Controls.String;
msdyn_FullyBookedColor: DevKit.Controls.String;
msdyn_HideCancelled: DevKit.Controls.Boolean;
msdyn_IsSynchronizeResources: DevKit.Controls.Boolean;
msdyn_MapViewTabPlacement: DevKit.Controls.Boolean;
msdyn_NotBookedColor: DevKit.Controls.String;
/** Tab index. */
msdyn_OrderNumber: DevKit.Controls.Integer;
msdyn_OrganizationalUnitTooltipsViewId: DevKit.Controls.String;
msdyn_OrganizationalUnitViewId: DevKit.Controls.String;
msdyn_OverbookedColor: DevKit.Controls.String;
msdyn_PartiallyBookedColor: DevKit.Controls.String;
msdyn_SAAvailableIcon: DevKit.Controls.String;
msdyn_SAPartiallyAvailableIcon: DevKit.Controls.String;
msdyn_SAUnavailableIcon: DevKit.Controls.String;
msdyn_SchedulerAlertsView: DevKit.Controls.String;
msdyn_SchedulerResourceDetailsView: DevKit.Controls.String;
msdyn_SchedulerResourceTooltipView: DevKit.Controls.String;
/** Shows the settings as a JSON string. */
msdyn_Settings: DevKit.Controls.String;
/** Field is used to determine if Schedule Board Tab are Private, Public or Shareable */
msdyn_ShareType: DevKit.Controls.OptionSet;
/** Enter the tab name. */
msdyn_TabName: DevKit.Controls.String;
msdyn_UnscheduledRequirementsViewId: DevKit.Controls.String;
/** Shows the number of records to be displayed per page in 'Resource Requirement' section. */
msdyn_UnscheduledWOPageRecCount: DevKit.Controls.Integer;
msdyn_WorkingHoursColor: DevKit.Controls.String;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
WebResource_FullyBookedColor: DevKit.Controls.WebResource;
WebResource_NotBookedColor: DevKit.Controls.WebResource;
WebResource_OverbookedColor: DevKit.Controls.WebResource;
WebResource_PartiallyBookedColor: DevKit.Controls.WebResource;
}
interface Footer extends DevKit.Controls.IFooter {
/** Status of the Schedule Board Setting */
statecode: DevKit.Controls.OptionSet;
}
interface Navigation {
navAsyncOperations: DevKit.Controls.NavigationItem,
navProcessSessions: DevKit.Controls.NavigationItem
}
}
class Formmsdyn_scheduleboardsetting_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form msdyn_scheduleboardsetting_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form msdyn_scheduleboardsetting_Information */
Body: DevKit.Formmsdyn_scheduleboardsetting_Information.Body;
/** The Footer section of form msdyn_scheduleboardsetting_Information */
Footer: DevKit.Formmsdyn_scheduleboardsetting_Information.Footer;
/** The Navigation of form msdyn_scheduleboardsetting_Information */
Navigation: DevKit.Formmsdyn_scheduleboardsetting_Information.Navigation;
}
class msdyn_scheduleboardsettingApi {
/**
* DynamicsCrm.DevKit msdyn_scheduleboardsettingApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Unique identifier of the user who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics CRM options. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who created the record on behalf of another user. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the user who modified the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics CRM options. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who last updated the record on behalf of another user. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
msdyn_BookBasedOn: DevKit.WebApi.BooleanValue;
msdyn_CustomTabName: DevKit.WebApi.StringValue;
msdyn_CustomTabWebResource: DevKit.WebApi.StringValue;
msdyn_FilterLayout: DevKit.WebApi.LookupValue;
/** Storing filter values as Json string. */
msdyn_FilterValues: DevKit.WebApi.StringValue;
msdyn_FullyBookedColor: DevKit.WebApi.StringValue;
msdyn_HideCancelled: DevKit.WebApi.BooleanValue;
msdyn_IsPublic: DevKit.WebApi.BooleanValue;
msdyn_IsSynchronizeResources: DevKit.WebApi.BooleanValue;
msdyn_MapViewTabPlacement: DevKit.WebApi.BooleanValue;
msdyn_NotBookedColor: DevKit.WebApi.StringValue;
/** Tab index. */
msdyn_OrderNumber: DevKit.WebApi.IntegerValue;
msdyn_OrganizationalUnitTooltipsViewId: DevKit.WebApi.StringValue;
msdyn_OrganizationalUnitViewId: DevKit.WebApi.StringValue;
msdyn_OverbookedColor: DevKit.WebApi.StringValue;
msdyn_PartiallyBookedColor: DevKit.WebApi.StringValue;
msdyn_ResourceCellTemplate: DevKit.WebApi.LookupValue;
msdyn_RetrieveResourcesQuery: DevKit.WebApi.LookupValue;
msdyn_SAAvailableColor: DevKit.WebApi.StringValue;
msdyn_SAAvailableIcon: DevKit.WebApi.StringValue;
/** Is available icon inheriting from default setting. */
msdyn_SAAvailableIconDefault: DevKit.WebApi.BooleanValue;
msdyn_SAPartiallyAvailableColor: DevKit.WebApi.StringValue;
msdyn_SAPartiallyAvailableIcon: DevKit.WebApi.StringValue;
/** Is partially available icon inheriting from default setting. */
msdyn_SAPartiallyAvailableIconDefault: DevKit.WebApi.BooleanValue;
msdyn_SAUnavailableColor: DevKit.WebApi.StringValue;
msdyn_SAUnavailableIcon: DevKit.WebApi.StringValue;
/** Is unavailable icon inheriting from default setting. */
msdyn_SAUnavailableIconDefault: DevKit.WebApi.BooleanValue;
/** Shows the entity instances. */
msdyn_scheduleboardsettingId: DevKit.WebApi.GuidValue;
msdyn_SchedulerAlertsView: DevKit.WebApi.StringValue;
msdyn_SchedulerBusinessUnitDetailsView: DevKit.WebApi.StringValue;
msdyn_SchedulerBusinessUnitTooltipView: DevKit.WebApi.StringValue;
msdyn_SchedulerCoreDetailsView: DevKit.WebApi.StringValue;
msdyn_SchedulerCoreSlotTextTemplate: DevKit.WebApi.StringValue;
msdyn_SchedulerCoreTooltipView: DevKit.WebApi.StringValue;
msdyn_SchedulerFieldServiceDetailsView: DevKit.WebApi.StringValue;
msdyn_SchedulerFieldServiceSlotTextTemplate: DevKit.WebApi.StringValue;
msdyn_SchedulerFieldServiceTooltipView: DevKit.WebApi.StringValue;
msdyn_SchedulerResourceDetailsView: DevKit.WebApi.StringValue;
msdyn_SchedulerResourceTooltipView: DevKit.WebApi.StringValue;
/** Shows the settings as a JSON string. */
msdyn_Settings: DevKit.WebApi.StringValue;
/** Field is used to determine if Schedule Board Tab are Private, Public or Shareable */
msdyn_ShareType: DevKit.WebApi.OptionSetValue;
/** Enter the tab name. */
msdyn_TabName: DevKit.WebApi.StringValue;
msdyn_UnscheduledRequirementsViewId: DevKit.WebApi.StringValue;
msdyn_UnscheduledViewId: DevKit.WebApi.StringValue;
/** Shows the number of records to be displayed per page in 'Resource Requirement' section. */
msdyn_UnscheduledWOPageRecCount: DevKit.WebApi.IntegerValue;
msdyn_UnscheduledWOTooltipsViewId: DevKit.WebApi.StringValue;
msdyn_WorkingHoursColor: DevKit.WebApi.StringValue;
/** Shows the date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Unique identifier for the business unit that owns the record */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the team that owns the record. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the user that owns the record. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Status of the Schedule Board Setting */
statecode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the Schedule Board Setting */
statuscode: DevKit.WebApi.OptionSetValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Shows the time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version Number */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
}
}
declare namespace OptionSet {
namespace msdyn_scheduleboardsetting {
enum msdyn_ShareType {
/** 192350000 */
Everyone,
/** 192350001 */
Just_me,
/** 192350002 */
Specific_people,
/** 192350003 */
System
}
enum statecode {
/** 0 */
Active,
/** 1 */
Inactive
}
enum statuscode {
/** 1 */
Active,
/** 2 */
Inactive
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import m from "mithril"
import Stream from "mithril/stream"
import AuthService from "_/AuthService"
import type { User } from "_/AuthService"
import { GIST_API_PREFIX, storageUrl } from "_/Env"
import ModalManager from "_/ModalManager"
import Button from "_/Button"
const STORAGE_URL_BASE = storageUrl()
export type Source =
LocalSource
| CloudSource
| GistSource
interface BaseSource {
type: string;
title: string;
}
interface LocalSource extends BaseSource {
type: "browser";
details: {
prefix: string;
};
}
interface CloudSource extends BaseSource {
type: "cloud";
}
interface GistSource extends BaseSource {
type: "gist";
}
type SheetPath = string
export const enum SaveState {
unchanged,
unsaved,
saving,
saved,
}
export class Sheet {
path: SheetPath
name: string
body: string
saveState: SaveState
constructor(path: SheetPath, body: string) {
this.path = path
this.name = path
this.body = body
this.saveState = SaveState.unchanged
}
}
type SheetEntry = Pick<Sheet, "path" | "name">
export abstract class Provider<S extends Source> {
key: string
source: S
entries: SheetEntry[]
isManualSave: boolean
constructor(key: string, source: S, isManualSave = false) {
this.key = key
this.source = source
this.entries = []
this.isManualSave = isManualSave
this.create = this.create.bind(this)
}
abstract loadRootListing(): Promise<void>
abstract load(sheetPath: SheetPath): Promise<Sheet>
abstract autoSave(sheet: Sheet): Promise<void>
manualSave(sheet: Sheet): Promise<void> {
return this.autoSave(sheet)
}
abstract create(): Promise<void>
abstract delete(path: string): Promise<void>
abstract render(): m.Children
}
class BrowserProvider extends Provider<LocalSource> {
get prefix() {
return this.source.details.prefix
}
async loadRootListing(): Promise<void> {
const paths: SheetEntry[] = []
for (let i = 0; i < localStorage.length; ++i) {
const key = localStorage.key(i)
if (key?.startsWith(this.prefix) && key.endsWith(":name")) {
const path = key.substring(this.prefix.length, key.length - ":name".length)
paths.push({ path, name: localStorage.getItem(key) ?? path })
}
}
this.entries = paths
}
async load(sheetPath: SheetPath): Promise<Sheet> {
const pathPrefix = this.prefix + sheetPath
const body = localStorage.getItem(pathPrefix + ":body") ?? ""
return new Sheet(sheetPath, body)
}
async autoSave({ path, name, body }: Sheet): Promise<void> {
localStorage.setItem(this.prefix + path + ":name", name)
localStorage.setItem(this.prefix + path + ":body", body)
}
async create(): Promise<void> {
const name = window.prompt("Sheet Name") ?? ""
if (name === "") {
return
}
const path = name
localStorage.setItem(this.prefix + path + ":name", name)
localStorage.setItem(this.prefix + path + ":body", "")
await this.loadRootListing()
}
delete(path: string): Promise<void> {
// TODO: Iterate over all of localStorage and delete all keys with path as prefix.
localStorage.removeItem(this.prefix + path + ":name")
localStorage.removeItem(this.prefix + path + ":body")
localStorage.removeItem(this.prefix + path + ":cookieJar")
return this.loadRootListing()
}
render(): m.Children {
return [
m(
"a.pv1.ph2.db",
{
onclick: this.create,
href: "#",
},
"+ Create new",
),
m("ul", [
this.entries.map(entry => {
const href = `/doc/${ this.key }/${ entry.path }`
return m(
"li",
[
m(
m.route.Link,
{
href,
class: window.location.hash.substr(2) === href ? "active" : "",
},
entry.name,
),
/* Deleting UI should be elsewhere.
m(
Button,
{
class: "compact danger-light",
onclick(event: Event) {
console.log("Deleting", entry)
provider.delete(entry.path)
event.preventDefault()
},
},
"Del",
),
//*/
],
)
}),
]),
]
}
}
class CloudProvider extends Provider<CloudSource> {
async loadRootListing(): Promise<void> {
const currentUser = AuthService.currentUser()
if (currentUser == null) {
throw new Error("Cannot browse sheets on cloud, since user not logged in.")
}
const response = await m.request<{ ok: boolean, entries: { name: string, slug: string }[] }>({
method: "GET",
url: STORAGE_URL_BASE,
withCredentials: true,
})
const entries = []
for (const item of response.entries) {
entries.push({ path: item.slug, name: item.name })
}
this.entries = entries
}
async load(sheetPath: SheetPath): Promise<Sheet> {
const currentUser = AuthService.currentUser()
if (currentUser == null) {
throw new Error("Cannot load sheets on cloud, since user not logged in.")
}
const response = await m.request<{ body: string }>({
method: "GET",
url: STORAGE_URL_BASE + sheetPath,
withCredentials: true,
})
return new Sheet(sheetPath, response.body)
}
async autoSave(sheet: Sheet): Promise<void> {
const currentUser = AuthService.currentUser()
if (currentUser == null) {
throw new Error("Cannot load sheets on cloud, since user not logged in.")
}
// TODO: Verify if the save was successful.
await m.request({
method: "PATCH",
url: STORAGE_URL_BASE + sheet.path,
withCredentials: true,
body: {
body: sheet.body,
},
})
}
async create(): Promise<void> {
const name = window.prompt("Sheet path:")
await m.request({
method: "POST",
url: STORAGE_URL_BASE + name,
withCredentials: true,
body: {
name,
},
})
await this.loadRootListing()
}
delete(path: string): Promise<void> {
return m.request({
method: "DELETE",
url: STORAGE_URL_BASE + path,
withCredentials: true,
})
.then(() => this.loadRootListing())
}
render(): m.Children {
return "Deprecated?"
}
}
interface Gist {
id: string
name: string
owner: string
description: string
path: string
readme: GistFile
files: GistFile[]
}
interface GistFile {
name: string
rawUrl: string
}
class GistProvider extends Provider<GistSource> {
private gists: Record<string, Gist>
constructor(key: string, source: GistSource) {
super(key, source, true)
this.gists = {}
}
verifyUser(): User {
const currentUser = AuthService.currentUser()
if (currentUser == null) {
throw new Error("User not logged in, cannot browse documents on Gist.")
}
if (!currentUser.isGitHubConnected) {
throw new Error("GitHub not connected for logged in user, cannot browse documents on Gist.")
}
return currentUser
}
async loadRootListing(): Promise<void> {
try {
this.verifyUser()
} catch (error) {
return
}
const response = await m.request<{ gists: Gist[] }>({
method: "GET",
url: GIST_API_PREFIX,
withCredentials: true,
})
this.entries = []
for (const gist of response.gists) {
if (gist.readme != null && gist.files?.length > 0) {
const path = `${ gist.owner }/${ gist.name }`
gist.path = path
this.gists[gist.name] = gist
}
}
}
async clearListing() {
this.gists = {}
}
async load(sheetPath: SheetPath): Promise<Sheet> {
const response = await m.request<string>({
method: "GET",
url: GIST_API_PREFIX + "get-file/" + sheetPath,
withCredentials: true,
responseType: "text",
deserialize(data) {
return data
},
})
return new Sheet(sheetPath, response)
}
autoSave(): Promise<void> {
return Promise.reject()
}
async manualSave(sheet: Sheet): Promise<void> {
this.verifyUser()
const gistName = sheet.path.split("/")[1]
const fileName = sheet.path.split("/")[2] ?? "main.prestige"
const gist = this.gists[gistName]
await m.request({
method: "PATCH",
url: GIST_API_PREFIX + "update/" + gistName,
withCredentials: true,
body: {
readmeName: gist.readme.name,
files: {
[fileName]: {
content: sheet.body,
},
},
},
})
}
async create(): Promise<void> {
let title = ""
let description = ""
ModalManager.show((control) => {
const onsubmit = (event: SubmitEvent) => {
if (title === "") {
return
}
event.preventDefault()
control.close()
m.request({
method: "POST",
url: GIST_API_PREFIX,
withCredentials: true,
body: {
title,
description,
isPublic: event.submitter?.classList.contains("public") ?? false,
},
}).then(() => {
console.log("Loading root listing after creating a gist.")
this.loadRootListing()
}).catch((error) => {
console.error("Error creating Gist", error)
})
}
return m(".pa2", [
m("h1", "Create a new Gist"),
m("form", { onsubmit }, [
m(".grid", [
m("label", { for: "gist-title" }, m("span", "Title*")),
m("input", {
id: "gist-title",
type: "text",
placeholder: "A title for the Gist",
value: title,
required: true,
oninput(event: InputEvent) {
title = (event.target as HTMLInputElement).value
},
}),
m("label", { for: "gist-description" }, m("span", "Description")),
m("input", {
id: "gist-description",
type: "text",
placeholder: "Optional, description for the Gist",
value: description,
oninput(event: InputEvent) {
description = (event.target as HTMLInputElement).value
},
}),
]),
m("p.tr", [
m(Button, { type: "submit", style: "primary" }, "Create Secret Gist"),
m(Button, { type: "submit", class: "ml2 public" }, "Create Public Gist"),
]),
]),
])
})
}
delete(path: string): Promise<void> {
return m.request({
method: "DELETE",
url: STORAGE_URL_BASE + path,
withCredentials: true,
})
.then(() => this.loadRootListing())
}
render(): m.Children {
const currentUser = AuthService.currentUser()
if (currentUser == null) {
return "Please login with GitHub to view your Gists."
}
if (!currentUser.isGitHubConnected) {
return "Please connect to GitHub to view your Gists."
}
const gists = Object.values(this.gists)
return [
gists.length === 0 && m("p", [
"No prestige gists found! Let's ",
m("a", { onclic: this.create, href: "#" }, "create one now"),
"!",
]),
gists.length > 0 && m(
"a.pv1.ph2.db",
{
onclick: this.create,
href: "#",
},
"+ Create new",
),
gists.length > 0 && m("ul", [
gists.map((gist: Gist) => {
const gistHref = `/doc/${ this.key }/${ gist.path }`
return m(
"li",
gist.files.length === 1 && [
m("li", m(
m.route.Link,
{
href: gistHref,
class: window.location.hash.substr(2) === gistHref ? "active" : "",
},
gist.readme.name.replace(/^_|(\.md$)/g, ""),
)),
],
gist.files.length > 1 && [
m(
m.route.Link,
{
href: gistHref,
class: window.location.hash.substr(2) === gistHref ? "active" : "",
},
gist.readme.name.replace(/^_|(\.md$)/g, ""),
),
m("ul", [
gist.files.map((file) => {
const fileHref = gistHref + "/" + file.name
return m("li", m(
m.route.Link,
{
href: fileHref,
class: window.location.hash.substr(2) === fileHref ? "active" : "",
},
file.name,
))
}),
]),
],
)
}),
]),
]
}
}
const availableSources: Stream<Source[]> = Stream()
AuthService.currentUser.map(recomputeAvailableSources)
async function recomputeAvailableSources(user: null | User): Promise<void> {
const sources: Source[] = [
{
type: "browser",
title: "Browser Storage",
details: {
prefix: "instance:",
},
},
]
if (STORAGE_URL_BASE && user != null) {
sources.push({
type: "cloud",
title: "Cloud",
})
}
// The Gist source is always available, since anonymous users should be able to load a Gist by URL.
sources.push({
type: "gist",
title: "GitHub Gist",
})
// If available sources didn't change, after auth checking is done, don't recompute stuff below.
if (JSON.stringify(availableSources()) !== JSON.stringify(sources)) {
availableSources(sources)
}
}
function createProviderForSource(key: string, source: Source): Provider<Source> {
if (source.type === "browser") {
return new BrowserProvider(key, source)
} else if (source.type === "cloud") {
return new CloudProvider(key, source)
} else if (source.type === "gist") {
return new GistProvider(key, source)
}
throw new Error(`Unrecognized persistence source type: '${ source != null && (source as BaseSource).type }'.`)
}
// TODO: Data in `currentProviders` and `providerRegistry` is the same, in different shapes. Remove one.
export const providerCache: Map<string, Provider<Source>> = new Map()
export const currentProviders: Stream<Provider<Source>[]> = Stream([])
export const currentSheetName: Stream<null | string> = Stream(null)
export const currentSheet: Stream<null | "loading" | Sheet> = Stream(null)
availableSources.map(async function(sources: Source[]): Promise<void> {
// Refresh available providers.
const providers: Provider<Source>[] = []
const typeCounts: Record<string, number> = {}
for (const source of sources) {
typeCounts[source.type] = 1 + (typeCounts[source.type] || -1)
const key = source.type + (typeCounts[source.type] > 0 ? ":" + typeCounts[source.type] : "")
let provider = providerCache.get(key)
if (provider == null) {
providerCache.set(key, provider = createProviderForSource(key, source))
}
providers.push(provider)
}
await Promise.all(providers.map(provider => provider.loadRootListing()))
currentProviders(providers)
})
Stream.lift((providers: Provider<Source>[], qualifiedName: string | null) => {
if (qualifiedName == null || providers == null || providers.length === 0) {
currentSheet(null)
return
}
const [providerKey, ...pathParts] = qualifiedName.split("/")
const path = pathParts.join("/")
console.log("Load sheet at", qualifiedName, "from", providerKey)
const provider = providerCache.get(providerKey)
if (provider == null) {
console.log("providerCache", providerCache)
throw new Error("Couldn't get provider for qualified name " + qualifiedName)
}
currentSheet("loading")
provider.load(path)
.then(currentSheet)
.finally(m.redraw)
}, currentProviders, currentSheetName)
// When auth status changes, reset or refresh Gist listing.
Stream.lift((providers: Provider<Source>[], user: null | User) => {
for (const provider of providers) {
if (provider.key === "gist") {
if (user == null) {
(provider as GistProvider).clearListing()
} else {
provider.loadRootListing()
}
}
}
}, currentProviders, AuthService.currentUser)
export async function openSheet(qualifiedName: string): Promise<Sheet> {
if (typeof currentProviders() === "undefined") {
throw new Error("Providers not initialized yet.")
}
const [providerKey, ...pathParts] = qualifiedName.split("/")
const path = pathParts.join("/")
const provider = providerCache.get(providerKey)
if (provider == null) {
console.log("providerCache", providerCache)
throw new Error("Couldn't get provider for qualified name " + qualifiedName)
}
return await provider.load(path)
}
function getProvider(qualifiedName: string): Provider<Source> {
if (typeof currentProviders() === "undefined") {
throw new Error("Providers not initialized yet.")
}
const providerKey = qualifiedName.split("/")[0]
const provider = providerCache.get(providerKey)
if (provider == null) {
console.log(providerCache)
throw new Error("Couldn't get provider for qualified name " + qualifiedName)
}
return provider
}
export async function saveSheetAuto(qualifiedName: string, sheet: Sheet): Promise<void> {
console.log("Save auto")
const provider = getProvider(qualifiedName)
if (!provider.isManualSave) {
const prevState = sheet.saveState
sheet.saveState = SaveState.saving
try {
await provider.autoSave(sheet)
sheet.saveState = SaveState.saved
} catch (error) {
console.error("Error saving automatically", error)
sheet.saveState = prevState
}
}
}
export async function saveSheetManual(qualifiedName: string, sheet: Sheet): Promise<void> {
console.log("Save manual")
const provider = getProvider(qualifiedName)
if (provider.isManualSave) {
const prevState = sheet.saveState
sheet.saveState = SaveState.saving
try {
await provider.manualSave(sheet)
sheet.saveState = SaveState.saved
} catch (error) {
console.error("Error saving manually", error)
sheet.saveState = prevState
}
}
}
export function isManualSaveAvailable(): boolean {
const sheetName = currentSheetName()
return sheetName != null && getProvider(sheetName).isManualSave
} | the_stack |
import QlogConnection from '@/data/Connection';
import * as d3 from 'd3';
import * as qlog from '@/data/QlogSchema';
export default class SequenceDiagramCanvasRenderer {
public containerID:string;
public rendering:boolean = false;
constructor(containerID:string){
this.containerID = containerID;
}
public render(traces:Array<QlogConnection>) {
if ( this.rendering ) {
return;
}
this.rendering = true;
this.renderTimeSliced(traces).then( () => {
this.rendering = false;
});
}
protected ensureMoreThanOneTrace(traces:Array<QlogConnection>) {
if ( traces.length > 1 ){
return;
}
if ( traces[0].parent.getConnections().length > 1 ){
return;
}
// we cannot just visualize a single trace on a sequence diagram...
// so we copy the trace and pretend like the copy is one from the other side
const newTrace = traces[0].clone();
newTrace.title = "Cloned trace : " + newTrace.title;
newTrace.description = "Cloned trace : " + newTrace.description;
// we have a single trace, we need to copy it so we can simulate client + server
if ( traces[0].vantagePoint.type === qlog.VantagePointType.server ||
traces[0].vantagePoint.flow === qlog.VantagePointType.server ){
newTrace.vantagePoint.type = qlog.VantagePointType.client;
traces.unshift( newTrace );
}
else if ( traces[0].vantagePoint.type === qlog.VantagePointType.client ||
traces[0].vantagePoint.flow === qlog.VantagePointType.client ){
newTrace.vantagePoint.type = qlog.VantagePointType.server;
traces.push( newTrace );
}
for ( const event of newTrace.getEvents() ){
const type = newTrace.parseEvent(event).name;
if ( type === qlog.TransportEventType.packet_sent ){
newTrace.parseEvent(event).name = qlog.TransportEventType.packet_received;
}
if ( type === qlog.TransportEventType.packet_received ){
newTrace.parseEvent(event).name = qlog.TransportEventType.packet_sent;
}
// TODO: are there other events that should be changed? probably some that should be filtered out? e.g., all non transport/H3-related things?
}
}
protected createPrivateNamespace(obj:any):void {
if ( obj.qvis === undefined ) {
Object.defineProperty(obj, "qvis", { enumerable: false, value: {} });
}
if ( obj.qvis.sequencediagram === undefined ) {
obj.qvis.sequencediagram = {};
}
}
protected calculateCoordinates(traces:Array<QlogConnection>):number {
const pixelsPerMillisecond = 2;
// we have n traces, each with their own timestamped events
// we want to map these on a single conceptual sequence diagram, so that the same timestamps line up correctly on the y-axis, but still have a single vertical timeline per-trace
// we also want to cut out long periods of inactivity and prevent overlaps (e.g., for many packets at the same timestamp)
// To do this, we have to calculate the y-coordinates as we go, accumulting to prevent overlaps, skipping large idle periods and keeping things in-sync between traces
// the simplest way to do this would be to merge all the traces into 1 big event log, ordered by timestamp
// However, since the traces can get quite big, we don't want to do this, as it would use -a lot- of memory
// So instead we perform a naive online k-way merge (so without actually moving to new memory) to process the events in their timestamp order
// https://en.wikipedia.org/wiki/K-way_merge_algorithm
const heads:Array<number> = new Array<number>( traces.length ).fill(0); // points to the current index of each trace we're looking at
let doneCount = 0;
let DEBUG_totalCount = 0;
let maxCoordinate = 0;
console.log( "CalculateCoordinates start" );
let done = false;
while ( !done ) {
let currentMinimumTrace:number = -1;
let currentMinimumValue:number = Number.MAX_VALUE;
// tslint:disable-next-line:no-unnecessary-initializer
let currentMinimumEvent:any = undefined;
for ( let t = 0; t < traces.length; ++t ){
if ( heads[t] === -1 ) { // means that array has been processed completely
continue;
}
const evt = traces[t].getEvents()[ heads[t] ];
const time = traces[t].parseEvent(evt).relativeTime;
if ( time < currentMinimumValue ){
currentMinimumTrace = t;
currentMinimumValue = time;
currentMinimumEvent = evt;
}
}
// TODO: make sure coordinates for the same timestamp are the same across traces (in the same trace, it should shift down, and also shift other traces down. What do you mean "complex"?)
// TODO: allow skipping of large periods of inactivity
this.createPrivateNamespace(currentMinimumEvent);
(currentMinimumEvent as any).qvis.sequencediagram.y = traces[currentMinimumTrace].parseEvent(currentMinimumEvent).relativeTime * pixelsPerMillisecond; // DEBUG_totalCount * pixelsPerMillisecond;
++DEBUG_totalCount;
maxCoordinate = (currentMinimumEvent as any).qvis.sequencediagram.y;
heads[ currentMinimumTrace ] += 1;
if ( heads[currentMinimumTrace] >= traces[currentMinimumTrace].getEvents().length ) {
heads[ currentMinimumTrace ] = -1;
++doneCount;
}
done = doneCount === traces.length;
}
return maxCoordinate;
}
protected async renderTimeSliced(tracesOriginal:Array<QlogConnection>){
const container:HTMLElement = document.getElementById(this.containerID)!;
if ( container === undefined ){
console.error("SequenceDiagramD3Renderer:renderTimeSliced : container element not found, cannot render!", this.containerID);
return;
}
// TODO: verify traces are left-to-right : i.e., arrows do not go UP!
const traces = tracesOriginal.slice(); // shallow copy since we might want to add a trace
this.ensureMoreThanOneTrace( traces );
const maxY = this.calculateCoordinates( traces );
console.log("SequenceDiagramD3Renderer:renderTimeSliced : rendering traces", traces, maxY);
const interactionLayer:HTMLElement = document.createElement("div");
interactionLayer.setAttribute("id", "sequencediagram-interaction");
const containerWidth:number = container.clientWidth;
const containerHeight:number = maxY;
// Note about performance: canvas is already much faster than SVG, but can still take a while
// TODO: explore options: rendering to double-buffered canvas first, use multipe on-screen canvases, rendering only parts and updating when scrolling,
// rendering in a web worker thread (potential problems with getting data there), ...
// To make canvas interactive, there really are no easy shortcuts...
// - Tried with Fabric.js : this just crashes the tab with even a moderately sized trace
// - Tried with overlaying DOM elements : event with visibility off, still invokes a long layout/styling/painting step, taking several seconds
// - Only option really: keep a custom pixels-to-element dictionary, similar to how chrome's devtools does it:
// https://github.com/ChromeDevTools/devtools-frontend/blob/8fb3ac5a4f56332900ddec43aeebb845759531ed/front_end/perf_ui/FlameChart.js#L740
let canvas:HTMLCanvasElement = document.getElementById("sequencediagram-canvas") as HTMLCanvasElement;
if ( !canvas ) {
canvas = document.createElement("canvas");
canvas.setAttribute("id", "sequencediagram-canvas");
container.appendChild( canvas );
}
const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
// changing width/height of a canvas empties it... so we calculate the maxY first (see above) so we can set it correctly from the start
// FIXME: TODO: canvases have a maximum size/surface area, need to make sure we don't exceed this
canvas.setAttribute("width", "" + containerWidth);
canvas.setAttribute("height", "" + containerHeight);
container.appendChild( interactionLayer );
container.setAttribute("style", "position: relative;");
interactionLayer.setAttribute("style", `position: absolute; left: 0px; top: 0px; width: ${containerWidth}px; height:${containerHeight}px; z-index: 1; border: 2px solid blue;`);
// interactionLayer.setAttribute("width", "" + containerWidth);
// interactionLayer.setAttribute("height", "" + containerHeight);
const bandWidth = (containerWidth / traces.length);
// draw the vertical timelines
for ( let i = 0; i < traces.length; ++i ){
const currentX = bandWidth * i + (bandWidth * 0.5);
ctx.fillStyle = 'black';
ctx.fillRect(currentX, 0, 2, containerHeight);
}
// draw the events
// TODO: if we want to properly time-slice this, we can't draw trace per trace
// we would need to e.g., draw 1000 events from trace 1, then 1000 from 2, then back to 1, etc.
for ( let i = 0; i < traces.length; ++i ){
const trace = traces[i];
const currentXline = bandWidth * i + (bandWidth * 0.5);
const events = trace.getEvents();
let currentY = 0;
for ( const evt of events ){
currentY = (evt as any).qvis.sequencediagram.y;
ctx.fillStyle = 'green';
let currentX = currentXline + (Math.random() * 50);
ctx.fillRect(currentX, currentY, 10, 10);
ctx.fillStyle = 'black';
ctx.font = "20px Arial";
ctx.fillText("" + currentY, currentX + 10, currentY);
let clicker = document.createElement("div");
clicker.setAttribute("style", `visibility: hidden; width: 10px; height: 10px; position: absolute; left: ${currentX}px; top: ${currentY}px;`);
clicker.onclick = (ev) => { alert("Clicked on event!" + (evt as any).qvis.sequencediagram.y); };
interactionLayer.appendChild(clicker);
}
}
if ( canvas.parentElement === null ) {
container.appendChild( canvas );
}
// fcanvas.renderAll();
}
} | the_stack |
import type * as BalenaSdk from '..';
import type { InferAssociatedResourceType } from '../typings/pinejs-client-core';
import type { AnyObject } from '../typings/utils';
import { Equals, EqualsTrue } from './utils';
// This file is in .prettierignore, since otherwise
// the @ts-expect-error comments would move to the wrong place
export const unkown$selectProps: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
// @ts-expect-error
$select: ['asdf', 'id', 'app_name', 'id'],
};
export const unkown$selectPropsFixed: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$select: ['id', 'app_name'],
};
export const unkown$selectPropsInside$expand: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
// @ts-expect-error
$expand: {
owns__device: {
$select: ['asdf', 'note', 'device_name', 'uuid'],
},
},
};
export const unkown$expandProps: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$expand: {
// @ts-expect-error
asdf: {},
owns__device: {
$select: ['note', 'device_name', 'uuid'],
},
},
};
export const unkownODataPropInside$expand: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$expand: {
owns__device: {
// @ts-expect-error
asdf: {},
$select: ['note', 'device_name', 'uuid'],
},
},
};
export const unkown$expandPropsFixed: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$expand: {
owns__device: {
$select: ['note', 'device_name', 'uuid'],
},
},
};
export const unkown$selectPropInsideNested$expandWith$select: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$expand: {
owns__device: {
$expand: {
// @ts-expect-error
asdf: {
$select: ['asdf'],
},
device_environment_variable: {
$select: ['name', 'value'],
},
},
},
},
};
export const unkown$selectPropInsideNested$expandWith$select2: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
// @ts-expect-error
$expand: {
owns__device: {
$select: ['note', 'device_name', 'uuid'],
$expand: {
device_environment_variable: {
$select: ['name', 'value', 'asdf'],
},
},
},
},
};
export const unkown$selectPropInsideNested$expandWith$select2Fixed: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$expand: {
owns__device: {
$select: ['note', 'device_name', 'uuid'],
$expand: {
device_environment_variable: {
$select: ['name', 'value'],
},
},
},
},
};
export const unkown$expandPropInArray$expands: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$expand: [
{
owns__device: {
$select: ['note', 'device_name', 'uuid'],
$expand: {
device_environment_variable: {
$select: ['name', 'value'],
},
},
},
},
'depends_on__application',
// @ts-expect-error
'asdf',
],
};
export const unkownODataPropInArray$expand: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$expand: [
{
owns__device: {
// @ts-expect-error
asdf: {},
$select: ['note', 'device_name', 'uuid'],
$expand: {
device_environment_variable: {
$select: ['name', 'value'],
},
},
},
},
'depends_on__application',
],
};
export const unkown$selectPropInArray$expand: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$expand: [
{
owns__device: {
// @ts-expect-error
$select: ['asdf', 'note', 'device_name', 'uuid'],
$expand: {
device_environment_variable: {
$select: ['name', 'value'],
},
},
},
},
'depends_on__application',
],
};
export const unkownNested$expandPropInsideArray$expand: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$expand: [
{
owns__device: {
$select: ['note', 'device_name', 'uuid'],
$expand: {
// @ts-expect-error
asdf: {},
device_environment_variable: {
$select: ['name', 'value'],
},
},
},
},
'depends_on__application',
],
};
export const unkownNested$expandWith$selectPropInsideArray$expand: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$expand: [
{
owns__device: {
$select: ['note', 'device_name', 'uuid'],
$expand: {
// @ts-expect-error
asdf: {
$select: ['id'],
},
device_environment_variable: {
$select: ['name', 'value'],
},
},
},
},
'depends_on__application',
],
};
export const unkown$selectPropInsideNestedArray$expand: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$expand: [
{
owns__device: {
$select: ['note', 'device_name', 'uuid'],
// @ts-expect-error
$expand: {
device_environment_variable: {
$select: ['name', 'value', 'asdf'],
},
},
},
},
'depends_on__application',
],
};
export const nestedArray$expandWithManyErrors1: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$expand: [
{
owns__device: {
// @ts-expect-error
$select: ['asdf', 'note', 'device_name', 'uuid'],
$expand: {
// @ts-expect-error
asdf: {
$select: ['asdf'],
},
device_environment_variable: {
$select: ['name', 'value', 'asdf'],
},
},
},
},
'depends_on__application',
],
};
export const nestedArray$expandWithManyErrors2: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$expand: [
{
owns__device: {
$select: ['note', 'device_name', 'uuid'],
$expand: {
// @ts-expect-error
asdf: {
$select: ['asdf'],
},
device_environment_variable: {
$select: ['name', 'value', 'asdf'],
},
},
},
},
'depends_on__application',
],
};
export const Nested$expandInArray$expandsFixed: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$expand: [
{
owns__device: {
$select: ['note', 'device_name', 'uuid'],
$expand: {
device_config_variable: {
$select: ['name', 'value'],
},
device_environment_variable: {
$select: ['name', 'value'],
},
},
},
application_tag: {
$select: 'id',
},
},
'depends_on__application',
],
};
// invalid filters
export const invalid$filterPropType: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$filter: {
// @ts-expect-error
id: 'asdf',
},
};
export const invalid$filterPropType2: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$filter: {
// @ts-expect-error
app_name: 5,
},
};
export const invalid$filterOfReverseNavigationProp: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$filter: {
app_name: 'test',
slug: null,
application_type: 5,
// TODO: The typings should prevent filtering RevenrseNavigationResources w/o $any
// skip-ts-expect-error
owns__device: 6,
},
};
export const unkownPropIn$filter: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$filter: {
id: 1,
app_name: 'test',
slug: null,
application_type: 5,
// @ts-expect-error
asdf: 'asdf',
},
};
export const unkownPropIn$filterFixed: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$filter: {
id: 1,
app_name: 'test',
slug: null,
application_type: 5,
},
};
export const unknown$any$filterPropInsideArray$expand: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$expand: [
{
owns__device: {
$filter: {
device_name: null,
note: 'note',
device_environment_variable: {
$any: {
$alias: 'dev',
$expr: {
dev: {
// @ts-expect-error
asdf: 'asdf',
},
},
},
},
},
},
},
'depends_on__application',
],
};
export const unknown$any$filterPropInsideArray$expandPlural: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$expand: [
{
owns__device: {
$filter: {
device_name: null,
note: 'note',
device_environment_variable: {
$any: {
$alias: 'dev',
$expr: {
dev: {
name: 'name',
// @ts-expect-error
asdf: 'asdf',
},
},
},
},
},
},
},
'depends_on__application',
],
};
export const unknown$any$filterPropInsideArray$expandFixed: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$expand: [
{
owns__device: {
$filter: {
device_name: null,
note: 'note',
device_environment_variable: {
$any: {
$alias: 'dev',
$expr: {
dev: {
name: 'name',
},
},
},
},
},
},
},
'depends_on__application',
],
};
export const unknown$filterPropInsideNested$expand: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$expand: [
{
owns__device: {
$filter: {
device_name: null,
note: 'note',
device_environment_variable: {
$any: {
$alias: 'dev',
$expr: {
dev: {
name: 'name',
},
},
},
},
},
$expand: {
device_environment_variable: {
$filter: {
name: 'name',
value: null,
// @ts-expect-error
asdf: 'asdf',
},
},
},
},
},
'depends_on__application',
],
};
// this check that even though the unknown$any$filterPropInsideArray$expandPlural case doesn't work
// it will at least not silence other errors
export const unknown$filterPropInsideNested$expandWithUnknown$any$filterProp: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$expand: [
{
owns__device: {
$filter: {
device_name: null,
note: 'note',
device_environment_variable: {
$any: {
$alias: 'dev',
$expr: {
dev: {
name: 'name',
// @ts-expect-error
asdf: 'asdf',
},
},
},
},
},
$expand: {
device_environment_variable: {
$filter: {
name: 'name',
value: null,
// @ts-expect-error
asdf: 'asdf',
},
},
},
},
},
'depends_on__application',
],
};
// valid selects
export const appOptionsEValid1: BalenaSdk.PineOptions<BalenaSdk.Application> = {
$select: ['app_name'],
};
export const deviceOptionsEValid2: BalenaSdk.PineOptions<BalenaSdk.Device> = {
$select: ['note', 'device_name', 'uuid'],
};
// valid expands
export const appOptionsEValid2: BalenaSdk.PineOptions<BalenaSdk.Application> = {
$expand: {
owns__device: {
$select: ['note', 'device_name', 'uuid'],
},
},
};
export const appOptionsEValid4: BalenaSdk.PineOptions<BalenaSdk.Application> = {
$expand: {
owns__device: {
$expand: {
device_environment_variable: {
$select: ['name', 'value'],
},
},
},
},
};
export const appOptionsEValid5: BalenaSdk.PineOptions<BalenaSdk.Application> = {
$expand: {
owns__device: {
$select: ['note', 'device_name', 'uuid'],
$expand: {
device_environment_variable: {
$select: ['name', 'value'],
},
},
},
},
};
export const appOptionsEValid20: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$expand: [
{
owns__device: {
$select: ['note', 'device_name', 'uuid'],
$expand: {
device_environment_variable: {
$select: ['name', 'value'],
},
},
},
},
'depends_on__application',
],
};
// valid OptionalNavigationResource $selects & $expands
type ReleaseExpandablePropsExpectation =
| 'is_created_by__user'
| 'belongs_to__application'
| 'contains__image'
| 'release_image'
| 'should_be_running_on__application'
| 'is_running_on__device'
| 'should_be_running_on__device'
| 'release_tag';
// @ts-expect-error
export const releaseExpandablePropsFailingTest1: Equals<
BalenaSdk.PineExpandableProps<BalenaSdk.Release>,
Exclude<ReleaseExpandablePropsExpectation, 'release_tag'>
> = EqualsTrue;
// @ts-expect-error
export const releaseExpandablePropsFailingTest2: Equals<
BalenaSdk.PineExpandableProps<BalenaSdk.Release>,
ReleaseExpandablePropsExpectation | 'id'
> = EqualsTrue;
export const releaseExpandablePropsTest: Equals<
BalenaSdk.PineExpandableProps<BalenaSdk.Release>,
ReleaseExpandablePropsExpectation
> = EqualsTrue;
export const deviceIsRunningReleaseAssociatedResourceType: Equals<
InferAssociatedResourceType<BalenaSdk.Device['is_running__release']>,
BalenaSdk.Release
> = EqualsTrue;
export const appOptionsEValid30: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$expand: [
{
owns__device: {
$select: ['note', 'device_name', 'uuid', 'is_running__release'],
$expand: {
device_environment_variable: {
$select: ['name', 'value'],
},
},
},
},
'depends_on__application',
],
};
export const appOptionsEValid31: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$expand: [
{
owns__device: {
$select: ['note', 'device_name', 'uuid'],
$expand: {
is_running__release: {
$select: ['id', 'commit'],
},
device_environment_variable: {
$select: ['name', 'value'],
},
},
},
},
'depends_on__application',
],
};
// valid filters
export const appOptionsEValidf1: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$filter: {
app_name: 'test',
slug: null,
application_type: 5,
},
};
export const appOptionsEValidf2: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$filter: {
app_name: 'test',
slug: null,
application_type: {
$any: {
$alias: 'o',
$expr: {
o: {
name: 'test',
},
},
},
},
owns__device: {
$any: {
$alias: 'd',
$expr: {
d: {
device_name: 'test',
},
},
},
},
owns__release: {
$any: {
$alias: 'r',
$expr: {
1: 1,
},
},
},
$not: {
owns__release: {
$any: {
$alias: 'r',
$expr: {
r: { commit: 'commit' },
},
},
},
},
},
};
export const appOptionsFNullIdValid1: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$filter: {
can_use__application_as_host: {
$any: {
$alias: 'cuaah',
$expr: {
cuaah: {
application: 5,
},
},
},
},
},
};
export const imageOptions$orValid1: BalenaSdk.PineOptions<BalenaSdk.Image> = {
$filter: {
status: 'success',
release_image: {
$any: {
$alias: 'ri',
$expr: {
ri: {
is_part_of__release: {
$any: {
$alias: 'ipor',
$expr: {
ipor: {
status: 'success',
belongs_to__application: {
$any: {
$alias: 'bta',
$expr: {
bta: {
slug: 'fleetSlug',
},
},
},
},
should_be_running_on__application: {
$any: {
$alias: 'sbroa',
$expr: {
sbroa: {
slug: 'fleetSlug',
},
},
},
},
},
$or: [
{ ipor: { commit: '50ff99284f6a4a36a70f9c4a2b37650f' } },
{ ipor: { semver: '1.2.3', is_final: true } },
{
ipor: { raw_version: '1.2.3-123456789', is_final: false },
},
],
},
},
},
},
},
},
},
is_a_build_of__service: {
$any: {
$alias: 'iabos',
$expr: {
iabos: {
service_name: 'main',
},
},
},
},
},
};
export const imageOptionsConditional$orValid1: BalenaSdk.PineOptions<BalenaSdk.Image> =
{
$filter: {
status: 'success',
release_image: {
$any: {
$alias: 'ri',
$expr: {
ri: {
is_part_of__release: {
$any: {
$alias: 'ipor',
$expr: {
ipor: {
status: 'success',
belongs_to__application: {
$any: {
$alias: 'bta',
$expr: {
bta: {
slug: 'fleetSlug',
},
},
},
},
should_be_running_on__application: {
$any: {
$alias: 'sbroa',
$expr: {
sbroa: {
slug: 'fleetSlug',
},
},
},
},
},
...(Math.random() > 0.5 && {
$or: [
{
ipor: { commit: '50ff99284f6a4a36a70f9c4a2b37650f' },
},
{ ipor: { semver: '1.2.3', is_final: true } },
{
ipor: {
raw_version: '1.2.3-123456789',
is_final: false,
},
},
],
}),
},
},
},
},
},
},
},
...(Math.random() > 0.5 && {
is_a_build_of__service: {
$any: {
$alias: 'iabos',
$expr: {
iabos: {
service_name: 'main',
},
},
},
},
}),
},
};
export const appOptionsEFValid1: BalenaSdk.PineOptions<BalenaSdk.Application> =
{
$expand: [
{
owns__device: {
$filter: {
device_name: null,
note: 'note',
device_environment_variable: {
$any: {
$alias: 'dev',
$expr: {
dev: {
name: 'name',
},
},
},
},
},
$expand: {
device_environment_variable: {
$filter: {
name: 'name',
value: null,
},
},
},
},
},
'depends_on__application',
],
};
export const anyObjectOptionsValid1: BalenaSdk.PineOptions<AnyObject> = {
$select: ['id', 'app_name'],
$expand: {
owns__device: {
$filter: {
device_name: null,
note: 'note',
device_environment_variable: {
$any: {
$alias: 'dev',
$expr: {
dev: {
name: 'name',
},
},
},
},
},
$expand: {
device_environment_variable: {
$filter: {
name: 'name',
value: null,
},
},
},
},
},
$filter: {
app_name: 'test',
application_type: {
$any: {
$alias: 'o',
$expr: {
o: {
name: 'test',
},
},
},
},
owns__device: {
$any: {
$alias: 'd',
$expr: {
d: {
device_name: 'test',
},
},
},
},
},
}; | the_stack |
import { EventInput } from "@fullcalendar/react";
import { appState, dispatch, store } from "./AppRedux";
import { AppState } from "./AppState";
import { Constants as C } from "./Constants";
import { ChangePasswordDlg } from "./dlg/ChangePasswordDlg";
import { ConfirmDlg } from "./dlg/ConfirmDlg";
import { EditNodeDlg } from "./dlg/EditNodeDlg";
import { ExportDlg } from "./dlg/ExportDlg";
import { ManageAccountDlg } from "./dlg/ManageAccountDlg";
import { PrefsDlg } from "./dlg/PrefsDlg";
import { UploadFromFileDropzoneDlg } from "./dlg/UploadFromFileDropzoneDlg";
import { EditIntf } from "./intf/EditIntf";
import { TabDataIntf } from "./intf/TabDataIntf";
import * as J from "./JavaIntf";
import { NodeHistoryItem } from "./NodeHistoryItem";
import { PubSub } from "./PubSub";
import { Singletons } from "./Singletons";
import { FeedView } from "./tabs/FeedView";
let S: Singletons;
PubSub.sub(C.PUBSUB_SingletonsReady, (s: Singletons) => {
S = s;
});
export class Edit implements EditIntf {
showReadOnlyProperties: boolean = false;
openChangePasswordDlg = (state: AppState): void => {
new ChangePasswordDlg(null, state).open();
}
openManageAccountDlg = (state: AppState): void => {
new ManageAccountDlg(state).open();
}
editPreferences = (state: AppState): void => {
new PrefsDlg(state).open();
}
openImportDlg = (state: AppState): void => {
const node: J.NodeInfo = S.quanta.getHighlightedNode(state);
if (!node) {
S.util.showMessage("No node is selected.", "Warning");
return;
}
const dlg = new UploadFromFileDropzoneDlg(node.id, "", false, null, true, true, state, () => {
S.view.jumpToId(node.id);
// S.quanta.refresh(state);
});
dlg.open();
}
openExportDlg = (state: AppState): void => {
let node = S.quanta.getHighlightedNode(state);
if (node) {
new ExportDlg(state, node).open();
}
}
private insertBookResponse = (res: J.InsertBookResponse, state: AppState): void => {
S.util.checkSuccess("Insert Book", res);
S.view.refreshTree(null, true, false, null, false, true, true, state);
S.view.scrollToSelectedNode(state);
}
private joinNodesResponse = (res: J.JoinNodesResponse, state: AppState): void => {
state = appState(state);
if (S.util.checkSuccess("Join node", res)) {
S.quanta.clearSelNodes(state);
S.view.refreshTree(state.node.id, false, false, null, false, true, true, state);
}
}
public initNodeEditResponse = (res: J.InitNodeEditResponse, forceUsePopup: boolean, encrypt: boolean, showJumpButton: boolean, replyToId: string, state: AppState): void => {
if (S.util.checkSuccess("Editing node", res)) {
/* NOTE: Removing 'editMode' check here is new 4/14/21, and without was stopping editing from calendar view which we
do need even when edit mode is technically off */
const editingAllowed = /* state.userPreferences.editMode && */ this.isEditAllowed(res.nodeInfo, state);
if (editingAllowed) {
S.quanta.tempDisableAutoScroll();
// these conditions determine if we want to run editing in popup, instead of inline in the page.
let editInPopup = forceUsePopup || state.mobileMode ||
// node not found on tree.
(!S.quanta.getDisplayingNode(state, res.nodeInfo.id) &&
!S.quanta.getDisplayingNode(state, S.quanta.newNodeTargetId)) ||
// not currently viewing tree
S.quanta.activeTab !== C.TAB_MAIN ||
S.quanta.fullscreenViewerActive(state);
/* If we're editing on the feed tab, we set the 'state.editNode' which makes the gui know to render
the editor at that place rather than opening a popup now */
if (!forceUsePopup && S.quanta.activeTab === C.TAB_FEED) {
dispatch("Action_startEditingInFeed", (s: AppState): AppState => {
s.editNodeReplyToId = replyToId;
s.editNodeOnTab = S.quanta.activeTab;
s.editNode = res.nodeInfo;
s.editShowJumpButton = showJumpButton;
s.editEncrypt = encrypt;
return s;
});
}
/* Either run the node editor as a popup or embedded, depending on whether we have a fullscreen
calendar up and wether we're on the main tab, etc */
else if (editInPopup) {
const dlg = new EditNodeDlg(res.nodeInfo, encrypt, showJumpButton, state);
dlg.open();
} else {
dispatch("Action_startEditing", (s: AppState): AppState => {
s.editNode = res.nodeInfo;
s.editNodeOnTab = S.quanta.activeTab;
s.editShowJumpButton = showJumpButton;
s.editEncrypt = encrypt;
return s;
});
}
} else {
S.util.showMessage("Editing not allowed on node.", "Warning");
}
}
}
/* nodeId is optional and represents what to highlight after the paste if anything */
private moveNodesResponse = (res: J.MoveNodesResponse, nodeId: string, pasting: boolean, state: AppState): void => {
if (S.util.checkSuccess("Move nodes", res)) {
dispatch("Action_SetNodesToMove", (s: AppState): AppState => {
s.nodesToMove = null;
return s;
});
S.quanta.tempDisableAutoScroll();
// if pasting do a kind of refresh which will maintain us at the same page parent.
if (pasting) {
S.view.refreshTree(null, false, false, nodeId, false, true, true, state);
}
else {
S.view.jumpToId(nodeId);
}
}
}
private setNodePositionResponse = (res: J.SetNodePositionResponse, id: string, state: AppState): void => {
if (S.util.checkSuccess("Change node position", res)) {
S.view.jumpToId(id);
}
}
/* returns true if we are admin or else the owner of the node */
isEditAllowed = (node: any, state: AppState): boolean => {
if (!node) return false;
let owner: string = node.owner;
// if we don't know who owns this node assume the admin owns it.
if (!owner) {
owner = "admin";
}
return state.isAdminUser || state.userName === owner;
}
isInsertAllowed = (node: J.NodeInfo, state: AppState): boolean => {
if (!node) return false;
if (state.homeNodeId === node.id) {
return true;
}
if (S.props.isPublicWritable(node)) {
return true;
}
let owner: string = node.owner;
// if we don't know who owns this node assume the admin owns it.
if (!owner) {
owner = "admin";
}
// if this node is admin owned, and we aren't the admin, then just disable editing. Admin himself is not even allowed to
// make nodes editable by any other user.
if (owner === "admin" && !state.isAdminUser) return false;
// right now, for logged in users, we enable the 'new' button because the CPU load for determining it's enablement is too much, so
// we throw an exception if they cannot. todo-2: need to make this work better.
// however we CAN check if this node is an "admin" node and at least disallow any inserts under admin-owned nodess
if (state.isAdminUser) return true;
if (state.isAnonUser) return false;
/* if we own the node we can edit it! */
if (state.userName === node.owner) {
// console.log("node owned by me: " + node.owner);
return true;
}
if (S.props.isPublicReadOnly(node)) {
return false;
}
// console.log("isInsertAllowed: node.owner="+node.owner+" nodeI="+node.id);
return node.owner !== "admin";
}
/*
* nodeInsertTarget holds the node that was clicked on at the time the insert was requested, and
* is sent to server for ordinal position assignment of new node. Also if this var is null, it indicates we are
* creating in a 'create under parent' mode, versus non-null meaning 'insert inline' type of insert.
*/
startEditingNewNode = async (typeName: string, createAtTop: boolean, parentNode: J.NodeInfo, nodeInsertTarget: J.NodeInfo, ordinalOffset: number, state: AppState): Promise<void> => {
if (!this.isInsertAllowed(parentNode, state)) {
// console.log("Rejecting request to edit. Not authorized");
return;
}
if (S.quanta.ctrlKeyCheck()) {
new ConfirmDlg("Paste your clipboard content into a new node?", "Create from Clipboard", //
async () => {
let clipboardText = await (navigator as any).clipboard.readText();
if (nodeInsertTarget) {
S.util.ajax<J.InsertNodeRequest, J.InsertNodeResponse>("insertNode", {
pendingEdit: false,
parentId: parentNode.id,
targetOrdinal: nodeInsertTarget.ordinal + ordinalOffset,
newNodeName: "",
typeName: typeName || "u",
initialValue: clipboardText
}, (res) => {
S.quanta.tempDisableAutoScroll();
S.quanta.refresh(state);
});
} else {
S.util.ajax<J.CreateSubNodeRequest, J.CreateSubNodeResponse>("createSubNode", {
pendingEdit: false,
nodeId: parentNode.id,
newNodeName: "",
typeName: typeName || "u",
createAtTop,
content: clipboardText,
typeLock: false,
properties: null,
shareToUserId: null
}, (res) => {
S.quanta.tempDisableAutoScroll();
S.quanta.refresh(state);
});
}
}, null, null, null, state
).open();
}
else {
if (nodeInsertTarget) {
S.util.ajax<J.InsertNodeRequest, J.InsertNodeResponse>("insertNode", {
pendingEdit: true,
parentId: parentNode.id,
targetOrdinal: nodeInsertTarget.ordinal + ordinalOffset,
newNodeName: "",
typeName: typeName || "u",
initialValue: ""
}, (res) => { this.insertNodeResponse(res, state); });
} else {
S.util.ajax<J.CreateSubNodeRequest, J.CreateSubNodeResponse>("createSubNode", {
pendingEdit: true,
nodeId: parentNode.id,
newNodeName: "",
typeName: typeName || "u",
createAtTop,
content: null,
typeLock: false,
properties: null,
shareToUserId: null
}, (res) => {
this.createSubNodeResponse(res, false, null, state);
});
}
}
}
insertNodeResponse = (res: J.InsertNodeResponse, state: AppState): void => {
if (S.util.checkSuccess("Insert node", res)) {
S.quanta.tempDisableAutoScroll();
S.quanta.updateNodeMap(res.newNode, state);
S.quanta.highlightNode(res.newNode, false, state);
this.runEditNode(null, res.newNode.id, false, false, false, null, state);
}
}
createSubNodeResponse = (res: J.CreateSubNodeResponse, forceUsePopup: boolean, replyToId: string, state: AppState): void => {
if (S.util.checkSuccess("Create subnode", res)) {
S.quanta.tempDisableAutoScroll();
if (!res.newNode) {
S.quanta.refresh(state);
}
else {
S.quanta.updateNodeMap(res.newNode, state);
this.runEditNode(null, res.newNode.id, forceUsePopup, res.encrypt, false, replyToId, state);
}
}
}
saveNodeResponse = async (node: J.NodeInfo, res: J.SaveNodeResponse, allowScroll: boolean, state: AppState): Promise<void> => {
if (S.util.checkSuccess("Save node", res)) {
await this.distributeKeys(node, res.aclEntries);
// if on feed tab, and it became dirty while we were editing then refresh it.
if (state.activeTab === C.TAB_FEED) {
let feedData: TabDataIntf = S.quanta.getTabDataById(null, C.TAB_FEED);
if (feedData?.props?.feedDirtyList) {
FeedView.updateFromFeedDirtyList(feedData, state);
}
}
// If we're on some tab other than MAIN (tree) we don't need to update anything.
if (state.activeTab !== C.TAB_MAIN) {
return;
}
// find and update the history item if it exists.
let histItem: NodeHistoryItem = S.quanta.nodeHistory.find(function (h: NodeHistoryItem) {
return h.id === node.id;
});
if (histItem) {
histItem.content = S.util.getShortContent(node);
}
// It's possible to end up editing a node that's not even on the page, or a child of a node on the page,
// and so before refreshing the screen we check for that edge case.
// console.log("saveNodeResponse: " + S.util.prettyPrint(node));
let parentPath = S.props.getParentPath(node);
if (!parentPath) return;
// I had expected the save to have already move into the non-pending folder by now,
// but i haven't investigated yet, this must be right.
if (parentPath.startsWith("/r/p")) {
parentPath = S.util.replaceAll(parentPath, "/r/p", "/r");
}
// if 'node.id' is not being displayed on the page we need to jump to it from scratch
if (!S.quanta.getDisplayingNode(state, node.id)) {
S.view.jumpToId(node.id);
}
// otherwise we just pull down the new node data and replace it into our 'state.node.children' (or page root) and we're done.
else {
this.refreshNodeFromServer(node.id);
}
if (state.fullScreenCalendarId) {
S.render.showCalendar(state.fullScreenCalendarId, state.fullScreenCalendarAllNodes, state);
}
}
}
refreshNodeFromServer = async (nodeId: string): Promise<J.NodeInfo> => {
// console.log("refreshNodeFromServer: " + nodeId);
return new Promise<J.NodeInfo>(async (resolve, reject) => {
S.util.ajax<J.RenderNodeRequest, J.RenderNodeResponse>("renderNode", {
nodeId,
upLevel: false,
siblingOffset: 0,
renderParentIfLeaf: false,
offset: 0,
goToLastPage: false,
forceIPFSRefresh: false,
singleNode: true
},
(res: J.RenderNodeResponse) => {
if (!res.node) {
resolve(null);
return;
}
dispatch("Action_RefreshNodeFromServer", (s: AppState): AppState => {
// if the node is our page parent (page root)
if (res.node.id === s.node.id) {
// preserve the children, when updating the root node, because they will not have been obtained
// due to the 'singleNode=true' in the request
res.node.children = s.node.children;
s.node = res.node;
}
// otherwise a child
else if (s.node && s.node.children) {
// replace the old node with the new node.
s.node.children.forEach((node, i) => {
if (node.id === res.node.id) {
s.node.children[i] = res.node;
}
});
}
S.quanta.updateNodeMap(res.node, s);
resolve(res.node);
return s;
});
}, // fail callback
(res: string) => {
console.log("failed to refresh node: " + res);
resolve(null);
});
});
}
distributeKeys = async (node: J.NodeInfo, aclEntries: J.AccessControlInfo[]): Promise<void> => {
if (!aclEntries || !S.props.isEncrypted(node)) {
return;
}
for (let ac of aclEntries) {
// console.log("Distribute Key to Principal: " + S.util.prettyPrint(ac));
await S.share.addCipherKeyToNode(node, ac.publicKey, ac.principalNodeId);
}
// console.log("Key distribution complete.");
}
setRssHeadlinesOnly = async (state: AppState, val: boolean): Promise<void> => {
state.userPreferences.rssHeadlinesOnly = val;
S.quanta.saveUserPreferences(state);
}
toggleEditMode = async (state: AppState): Promise<void> => {
state.userPreferences.editMode = !state.userPreferences.editMode;
S.quanta.saveUserPreferences(state);
/* scrolling is required because nodes will have scrolled out of view by the page just now updating */
S.view.scrollToSelectedNode(state);
}
setMetadataOption = (val: boolean): void => {
setTimeout(() => {
let state = store.getState();
state.userPreferences.showMetaData = val;
S.quanta.saveUserPreferences(state);
}, 100);
};
toggleShowMetaData = (state: AppState): void => {
state.userPreferences.showMetaData = !state.userPreferences.showMetaData;
S.quanta.saveUserPreferences(state);
/* scrolling is required because nodes will have scrolled out of view by the page just now updating */
S.view.scrollToSelectedNode(state);
}
moveNodeUp = (evt: Event, id: string, state?: AppState): void => {
id = S.util.allowIdFromEvent(evt, id);
state = appState(state);
if (!id) {
const selNode: J.NodeInfo = S.quanta.getHighlightedNode(state);
id = selNode.id;
}
const node: J.NodeInfo = state.idToNodeMap.get(id);
if (node) {
S.util.ajax<J.SetNodePositionRequest, J.SetNodePositionResponse>("setNodePosition", {
nodeId: node.id,
targetName: "up"
}, (res) => { this.setNodePositionResponse(res, id, state); });
}
}
moveNodeDown = (evt: Event, id: string, state: AppState): void => {
id = S.util.allowIdFromEvent(evt, id);
state = appState(state);
if (!id) {
const selNode: J.NodeInfo = S.quanta.getHighlightedNode(state);
id = selNode.id;
}
const node: J.NodeInfo = state.idToNodeMap.get(id);
if (node) {
S.util.ajax<J.SetNodePositionRequest, J.SetNodePositionResponse>("setNodePosition", {
nodeId: node.id,
targetName: "down"
}, (res) => { this.setNodePositionResponse(res, id, state); });
}
}
moveNodeToTop = (id: string = null, state: AppState = null): void => {
state = appState(state);
if (!id) {
const selNode: J.NodeInfo = S.quanta.getHighlightedNode(state);
id = selNode.id;
}
const node: J.NodeInfo = state.idToNodeMap.get(id);
if (node) {
S.util.ajax<J.SetNodePositionRequest, J.SetNodePositionResponse>("setNodePosition", {
nodeId: node.id,
targetName: "top"
}, (res) => { this.setNodePositionResponse(res, id, state); });
}
}
moveNodeToBottom = (id: string = null, state: AppState = null): void => {
state = appState(state);
if (!id) {
const selNode: J.NodeInfo = S.quanta.getHighlightedNode(state);
id = selNode.id;
}
const node: J.NodeInfo = state.idToNodeMap.get(id);
if (node) {
S.util.ajax<J.SetNodePositionRequest, J.SetNodePositionResponse>("setNodePosition", {
nodeId: node.id,
targetName: "bottom"
}, (res) => {
this.setNodePositionResponse(res, id, state);
});
}
}
getFirstChildNode = (state: AppState): any => {
if (!state.node || !state.node.children || state.node.children.length === 0) return null;
return state.node.children[0];
}
getLastChildNode = (state: AppState): any => {
if (!state.node || !state.node.children || state.node.children.length === 0) return null;
return state.node.children[state.node.children.length - 1];
}
runEditNodeByClick = (evt: Event, id: string, state?: AppState): void => {
id = S.util.allowIdFromEvent(evt, id);
// we set noScrollToId just to block the future attempt (one time) to
// scroll to this, because this is a hint telling us we are ALREADY
// scrolled to this ID so any scrolling will be unnecessary
S.quanta.noScrollToId = id;
this.runEditNode(null, id, false, false, false, null, state);
}
/* This can run as an actuall click event function in which only 'evt' is non-null here */
runEditNode = (evt: Event, id: string, forceUsePopup: boolean, encrypt: boolean, showJumpButton: boolean, replyToId: string, state?: AppState): void => {
id = S.util.allowIdFromEvent(evt, id);
state = appState(state);
if (!id) {
let node = S.quanta.getHighlightedNode(state);
if (node) {
id = node.id;
}
}
if (!id) {
S.util.showMessage("Unknown nodeId in editNodeClick: ", "Warning");
return;
}
S.util.ajax<J.InitNodeEditRequest, J.InitNodeEditResponse>("initNodeEdit", {
nodeId: id
}, (res) => {
this.initNodeEditResponse(res, forceUsePopup, encrypt, showJumpButton, replyToId, state);
});
}
toolbarInsertNode = (evt: Event, id: string): void => {
id = S.util.allowIdFromEvent(evt, id);
this.insertNode(id, null, 0);
}
insertNode = (id: string, typeName: string, ordinalOffset: number, state?: AppState): void => {
state = appState(state);
if (!state.node || !state.node.children) return;
/*
* We get the node selected for the insert position by using the uid if one was passed in or using the
* currently highlighted node if no uid was passed.
*/
let node: J.NodeInfo = null;
if (!id) {
node = S.quanta.getHighlightedNode(state);
} else {
node = state.idToNodeMap.get(id);
}
if (node) {
S.quanta.newNodeTargetId = id;
S.quanta.newNodeTargetOffset = ordinalOffset;
this.startEditingNewNode(typeName, false, state.node, node, ordinalOffset, state);
}
}
newSubNode = (evt: Event, id: string) => {
id = S.util.allowIdFromEvent(evt, id);
const state = store.getState();
if (S.quanta.ctrlKeyCheck()) {
new ConfirmDlg("Paste your clipboard content into a new node?", "Create from Clipboard", //
async () => {
// todo-2: document this feature under 'tips and tricks' in the user guide.
this.saveClipboardToChildNode(id);
}, null, null, null, state
).open();
}
else {
this.createSubNode(id, null, true, state.node, null);
}
}
createSubNode = (id: any, typeName: string, createAtTop: boolean, parentNode: J.NodeInfo, state: AppState): void => {
state = appState(state);
/*
* If no uid provided we deafult to creating a node under the currently viewed node (parent of current page), or any selected
* node if there is a selected node.
*/
if (!id) {
const node: J.NodeInfo = S.quanta.getHighlightedNode(state);
if (node) {
parentNode = node;
}
else {
if (!state.node || !state.node.children) return null;
parentNode = state.node;
}
} else {
parentNode = state.idToNodeMap.get(id);
if (!parentNode) {
// console.log("Unknown nodeId in createSubNode: " + id);
return;
}
}
this.startEditingNewNode(typeName, createAtTop, parentNode, null, 0, state);
}
selectAllNodes = async (state: AppState): Promise<void> => {
const highlightNode = S.quanta.getHighlightedNode(state);
S.util.ajax<J.SelectAllNodesRequest, J.SelectAllNodesResponse>("selectAllNodes", {
parentNodeId: highlightNode.id
}, async (res: J.SelectAllNodesResponse) => {
S.quanta.selectAllNodes(res.nodeIds);
});
}
clearInbox = (state: AppState): void => {
S.quanta.clearSelNodes(state);
new ConfirmDlg("Permanently delete the nodes in your Inbox", "Cleaer Inbox",
() => {
S.util.ajax<J.DeleteNodesRequest, J.DeleteNodesResponse>("deleteNodes", {
nodeIds: ["~" + J.NodeType.INBOX],
childrenOnly: true
}, (res: J.DeleteNodesResponse) => {
S.nav.openContentNode(state.homeNodePath, state);
});
}, null, "btn-danger", "alert alert-danger", state
).open();
}
joinNodes = (state?: AppState): void => {
state = appState(state);
const selNodesArray = S.quanta.getSelNodeIdsArray(state);
if (!selNodesArray || selNodesArray.length === 0) {
S.util.showMessage("Select some nodes to join.", "Warning");
return;
}
let confirmMsg = "Join " + selNodesArray.length + " node(s) ?";
new ConfirmDlg(confirmMsg, "Confirm Join " + selNodesArray.length,
() => {
S.util.ajax<J.JoinNodesRequest, J.JoinNodesResponse>("joinNodes", {
nodeIds: selNodesArray
}, (res: J.JoinNodesResponse) => {
this.joinNodesResponse(res, state);
});
},
null, "btn-danger", "alert alert-danger", state
).open();
}
/*
* Deletes the selNodesArray items, and if none are passed then we fall back to using whatever the user
* has currenly selected (via checkboxes)
*/
deleteSelNodes = (evt: Event = null, id: string = null): void => {
let state = store.getState();
id = S.util.allowIdFromEvent(evt, id);
// if a nodeId was specified we use it as the selected nodes to delete
if (id) {
// note we ARE updating 'state' here but it doesn't matter we can discard state, becasue
// all we needed is selNodesArray which we get and as long as selNodesArray is preserved
// we can let that change to 'state' get discarded in the next dispatch
S.nav.setNodeSel(true, id, state);
}
// note: the setNodeSel above isn't causing this to get anything here
const selNodesArray = S.quanta.getSelNodeIdsArray(state);
if (!selNodesArray || selNodesArray.length === 0) {
S.util.showMessage("Select some nodes to delete.", "Warning");
return;
}
if (selNodesArray.find(id => id === state.homeNodeId)) {
S.util.showMessage("You can't delete your account root node!", "Warning");
return;
}
if (selNodesArray.find(id => id === state.node.id)) {
S.util.showMessage("You can't delete your page node! Go up a level to do that.", "Warning");
return;
}
let confirmMsg = "Delete " + selNodesArray.length + " node(s) ?";
new ConfirmDlg(confirmMsg, "Confirm Delete " + selNodesArray.length,
() => {
S.util.ajax<J.DeleteNodesRequest, J.DeleteNodesResponse>("deleteNodes", {
nodeIds: selNodesArray,
childrenOnly: false
}, (res: J.DeleteNodesResponse) => {
S.quanta.tempDisableAutoScroll();
this.removeNodesFromHistory(selNodesArray, state);
this.removeNodesFromCalendarData(selNodesArray, state);
if (S.util.checkSuccess("Delete node", res)) {
if (state.node.children) {
state.node.children = state.node.children.filter(child => !selNodesArray.find(id => id === child.id));
}
if (state.node.children.length === 0) {
S.view.jumpToId(state.node.id);
}
else {
dispatch("Action_RefreshNodeFromServer", (s: AppState): AppState => {
s.node.children = state.node.children;
// remove this node from all data from all the tabs, so they all refresh without
// the deleted node without being queries from the server again.
selNodesArray.forEach(id => {
S.srch.removeNodeById(id, s);
});
s.selectedNodes.clear();
return s;
});
}
}
/* We waste a tiny bit of CPU/bandwidth here by just always updating the bookmarks in case
we just deleted some. This could be slightly improved to KNOW if we deleted any bookmarks, but
the added complexity to achieve that for recursive tree deletes doesn't pay off */
setTimeout(() => {
S.quanta.loadBookmarks();
}, 1000);
});
},
null, "btn-danger", "alert alert-danger", state
).open();
}
/* Updates 'nodeHistory' when nodes are deleted */
removeNodesFromHistory = (selNodesArray: string[], appState: AppState) => {
if (!selNodesArray) return;
selNodesArray.forEach((id: string) => {
// remove any top level history item that matches 'id'
S.quanta.nodeHistory = S.quanta.nodeHistory.filter(function (h: NodeHistoryItem) {
return h.id !== id;
});
// scan all top level history items, and remove 'id' from any subItems
S.quanta.nodeHistory.forEach(function (h: NodeHistoryItem) {
if (h.subItems) {
h.subItems = h.subItems.filter(function (hi: NodeHistoryItem) {
return hi.id !== id;
});
}
});
});
}
removeNodesFromCalendarData = (selNodesArray: string[], appState: AppState) => {
if (!appState.calendarData) return;
selNodesArray.forEach((id: string) => {
appState.calendarData = appState.calendarData.filter((item: EventInput) => item.id !== id);
});
// I'll leave this here commented until I actually TEST deleting calendar items again.
// dispatch("Action_UpdateCalendarData", (s: AppState): AppState => {
// return appState;
// });
}
undoCutSelNodes = (): void => {
dispatch("Action_SetNodesToMove", (s: AppState): AppState => {
s.nodesToMove = null;
return s;
});
}
cutSelNodes = (evt: Event, id: string): void => {
id = S.util.allowIdFromEvent(evt, null);
dispatch("Action_SetNodesToMove", (s: AppState): AppState => {
S.nav.setNodeSel(true, id, s);
let selNodesArray = S.quanta.getSelNodeIdsArray(s);
s.nodesToMove = selNodesArray;
s.selectedNodes.clear();
return s;
});
}
pasteSelNodesInside = (evt: Event, id: string) => {
id = S.util.allowIdFromEvent(evt, id);
const state = appState();
this.pasteSelNodes(id, "inside", state);
}
// location=inside | inline | inline-above (todo-2: put in java-aware enum)
pasteSelNodes = (nodeId: string, location: string, state?: AppState): void => {
state = appState(state);
/*
* For now, we will just cram the nodes onto the end of the children of the currently selected
* page. Later on we can get more specific about allowing precise destination location for moved
* nodes.
*/
S.util.ajax<J.MoveNodesRequest, J.MoveNodesResponse>("moveNodes", {
targetNodeId: nodeId,
nodeIds: state.nodesToMove,
location
}, (res) => {
this.moveNodesResponse(res, nodeId, true, state);
});
}
pasteSelNodes_InlineAbove = (evt: Event, id: string) => {
id = S.util.allowIdFromEvent(evt, id);
this.pasteSelNodes(id, "inline-above");
}
pasteSelNodes_Inline = (evt: Event, id: string) => {
id = S.util.allowIdFromEvent(evt, id);
this.pasteSelNodes(id, "inline");
}
insertBookWarAndPeace = (state: AppState): void => {
new ConfirmDlg("Warning: You should have an EMPTY node selected now, to serve as the root node of the book!",
"Confirm",
() => {
/* inserting under whatever node user has focused */
const node = S.quanta.getHighlightedNode(state);
if (!node) {
S.util.showMessage("No node is selected.", "Warning");
} else {
S.util.ajax<J.InsertBookRequest, J.InsertBookResponse>("insertBook", {
nodeId: node.id,
bookName: "War and Peace",
truncated: S.user.isTestUserAccount(state)
}, (res) => { this.insertBookResponse(res, state); });
}
}, null, null, null, state
).open();
}
saveClipboardToChildNode = async (parentId: string): Promise<void> => {
let clipText: string = await (navigator as any).clipboard.readText();
// DO NOT DELETE (yet)
// const items = await (navigator as any).clipboard.read();
// for (let item of items) {
// const blob = await item.getType("text/html");
// if (blob) {
// let html = await blob.text();
// clipText = "```html\n" + html + "\n```\n";
// break;
// }
// }
if (clipText) {
clipText = clipText.trim();
}
if (!clipText) {
S.util.flashMessage("Nothing saved clipboard is empty!", "Warning", true);
return;
}
S.util.ajax<J.CreateSubNodeRequest, J.CreateSubNodeResponse>("createSubNode", {
pendingEdit: false,
nodeId: parentId,
newNodeName: "",
typeName: "u",
createAtTop: true,
content: clipText,
typeLock: false,
properties: null,
shareToUserId: null
},
() => {
let message = parentId ? "Clipboard saved" : "Clipboard text saved under Notes node.";
S.util.flashMessage(message + "...\n\n" + clipText, "Note", true);
setTimeout(() => {
let state: AppState = store.getState();
S.view.refreshTree(null, true, false, null, false, true, true, state);
}, 4200);
});
}
splitNode = (node: J.NodeInfo, splitType: string, delimiter: string, state: AppState): void => {
if (!node) {
node = S.quanta.getHighlightedNode(state);
}
if (!node) {
S.util.showMessage("You didn't select a node to split.", "Warning");
return;
}
S.util.ajax<J.SplitNodeRequest, J.SplitNodeResponse>("splitNode", {
splitType: splitType,
nodeId: node.id,
delimiter
}, (res) => {
this.splitNodeResponse(res, state);
});
}
splitNodeResponse = (res: J.SplitNodeResponse, state: AppState): void => {
if (S.util.checkSuccess("Split content", res)) {
S.view.refreshTree(null, false, false, null, false, true, true, state);
S.view.scrollToSelectedNode(state);
}
}
addBookmark = (node: J.NodeInfo, state: AppState): void => {
this.createNode(node, J.NodeType.BOOKMARK, true, true, null, null, state);
}
addLinkBookmark = (content: any, state: AppState): void => {
state = appState(state);
this.createNode(null, J.NodeType.BOOKMARK, true, true, "linkBookmark", content, state);
}
/* If node is non-null that means this is a reply to that 'node' but if node is 'null' that means
this user just probably clicked "+" (new post button) on their Feed Tab and so we will let the server create some node
like "My Posts" in the root of the user's account to host this new 'reply' by creating the new node under that */
addNode = async (nodeId: string, content: string, shareToUserId: string, replyToId: string, state: AppState) => {
state = appState(state);
// auto-enable edit mode
if (!state.userPreferences.editMode) {
await S.edit.toggleEditMode(state);
}
S.util.ajax<J.CreateSubNodeRequest, J.CreateSubNodeResponse>("createSubNode", {
pendingEdit: true,
nodeId,
newNodeName: "",
typeName: J.NodeType.NONE,
createAtTop: false,
content,
typeLock: false,
properties: null,
shareToUserId
}, (res) => {
this.createSubNodeResponse(res, false, replyToId, state);
});
}
createNode = (node: J.NodeInfo, typeName: string, forceUsePopup: boolean, pendingEdit: boolean, payloadType: string, content: string, state: AppState) => {
state = appState(state);
S.util.ajax<J.CreateSubNodeRequest, J.CreateSubNodeResponse>("createSubNode", {
pendingEdit,
nodeId: node ? node.id : null,
newNodeName: "",
typeName,
createAtTop: true,
content,
typeLock: true,
properties: null,
payloadType,
shareToUserId: null
}, async (res) => {
// auto-enable edit mode
if (!state.userPreferences.editMode) {
await S.edit.toggleEditMode(state);
}
this.createSubNodeResponse(res, forceUsePopup, null, state);
return null;
});
}
addCalendarEntry = (initDate: number, state: AppState) => {
state = appState(state);
S.util.ajax<J.CreateSubNodeRequest, J.CreateSubNodeResponse>("createSubNode", {
pendingEdit: false,
nodeId: state.fullScreenCalendarId,
newNodeName: "",
typeName: J.NodeType.NONE,
createAtTop: true,
content: null,
typeLock: true,
properties: [{ name: J.NodeProp.DATE, value: "" + initDate }],
shareToUserId: null
}, (res) => {
this.createSubNodeResponse(res, false, null, state);
});
}
moveNodeByDrop = (targetNodeId: string, sourceNodeId: string, isFirst: boolean): void => {
/* if node being dropped on itself, then ignore */
if (targetNodeId === sourceNodeId) {
return;
}
// console.log("Moving node[" + targetNodeId + "] into position of node[" + sourceNodeId + "]");
const state = appState(null);
S.util.ajax<J.MoveNodesRequest, J.MoveNodesResponse>("moveNodes", {
targetNodeId,
nodeIds: [sourceNodeId],
location: isFirst ? "inline-above" : "inline"
}, (res) => {
S.render.fadeInId = sourceNodeId;
this.moveNodesResponse(res, sourceNodeId, false, state);
});
}
updateHeadings = (state: AppState): void => {
state = appState(state);
const node: J.NodeInfo = S.quanta.getHighlightedNode(state);
if (node) {
S.util.ajax<J.UpdateHeadingsRequest, J.UpdateHeadingsResponse>("updateHeadings", {
nodeId: node.id
}, (res) => {
S.quanta.refresh(state);
});
}
}
} | the_stack |
import { getAnimationFunction, ChartLocation, pathAnimation, getElement } from '../../common/utils/helper';
import { PathOption, Rect } from '@syncfusion/ej2-svg-base';
import { VisibleRangeModel, Axis } from '../axis/axis';
import { Series, Points } from './chart-series';
import { Chart } from '../chart';
import { AnimationModel } from '../../common/model/base-model';
import { Animation, AnimationOptions, isNullOrUndefined } from '@syncfusion/ej2-base';
/**
* Base for line type series.
*/
export class LineBase {
public chart: Chart;
/** @private */
constructor(chartModule?: Chart) {
this.chart = chartModule;
}
/**
* To improve the chart performance.
*
* @returns {void}
* @private
*/
public enableComplexProperty(series: Series): Points[] {
const tempPoints: Points[] = [];
const tempPoints2: Points[] = [];
const xVisibleRange: VisibleRangeModel = series.xAxis.visibleRange;
const yVisibleRange: VisibleRangeModel = series.yAxis.visibleRange;
const seriesPoints: Points[] = <Points[]>series.points;
const areaBounds: Rect = series.clipRect;
const xTolerance: number = Math.abs(xVisibleRange.delta / areaBounds.width);
const yTolerance: number = Math.abs(yVisibleRange.delta / areaBounds.height);
let prevXValue: number = (seriesPoints[0] && seriesPoints[0].x > xTolerance) ? 0 : xTolerance;
let prevYValue: number = (seriesPoints[0] && seriesPoints[0].y > yTolerance) ? 0 : yTolerance;
let xVal: number = 0;
let yVal: number = 0;
for (const currentPoint of seriesPoints) {
currentPoint.symbolLocations = [];
xVal = currentPoint.xValue ? currentPoint.xValue : xVisibleRange.min;
yVal = currentPoint.yValue ? currentPoint.yValue : yVisibleRange.min;
if (Math.abs(prevXValue - xVal) >= xTolerance || Math.abs(prevYValue - yVal) >= yTolerance) {
tempPoints.push(currentPoint);
prevXValue = xVal;
prevYValue = yVal;
}
}
let tempPoint: Points;
for (let i: number = 0; i < tempPoints.length; i++) {
tempPoint = tempPoints[i];
if (isNullOrUndefined(tempPoint.x) || tempPoint.x === '') {
continue;
} else {
tempPoints2.push(tempPoint);
}
}
return tempPoints2;
}
/**
* To generate the line path direction
*
* @param {Points} firstPoint firstPoint
* @param {Points} secondPoint secondPoint
* @param {Series} series series
* @param {boolean} isInverted isInverted
* @param {Function} getPointLocation getPointLocation
* @param {string} startPoint startPoint
*/
public getLineDirection(
firstPoint: Points, secondPoint: Points, series: Series,
isInverted: Boolean, getPointLocation: Function,
startPoint: string
): string {
let direction: string = '';
if (firstPoint != null) {
const point1: ChartLocation = getPointLocation(
firstPoint.xValue, firstPoint.yValue, series.xAxis, series.yAxis, isInverted, series
);
const point2: ChartLocation = getPointLocation(
secondPoint.xValue, secondPoint.yValue, series.xAxis, series.yAxis, isInverted, series
);
direction = startPoint + ' ' + (point1.x) + ' ' + (point1.y) + ' ' +
'L' + ' ' + (point2.x) + ' ' + (point2.y) + ' ';
}
return direction;
}
/**
* To append the line path.
*
* @returns {void}
* @private
*/
public appendLinePath(options: PathOption, series: Series, clipRect: string): void {
const element: Element = getElement(options.id);
const chart: Chart = series.chart;
const previousDirection: string = element ? element.getAttribute('d') : null;
const htmlObject: HTMLElement =
series.chart.renderer.drawPath(options, new Int32Array([series.clipRect.x, series.clipRect.y])) as HTMLElement;
if (htmlObject) {
htmlObject.setAttribute('clip-path', clipRect);
}
series.pathElement = htmlObject;
if (!series.chart.enableCanvas) {
series.seriesElement.appendChild(htmlObject);
}
series.isRectSeries = false;
pathAnimation(element, options.d, series.chart.redraw, previousDirection, chart.duration);
}
/**
* To render the marker for the series.
*
* @returns {void}
* @private
*/
public renderMarker(series: Series): void {
if (series.marker && series.marker.visible) {
series.chart.markerRender.render(series);
}
}
/**
* To do the progressive animation.
*
* @returns {void}
* @private
*/
public doProgressiveAnimation(series: Series, option: AnimationModel): void {
const animation: Animation = new Animation({});
const path: HTMLElement = <HTMLElement>series.pathElement;
const strokeDashArray: string = path.getAttribute('stroke-dasharray');
const pathLength: number = (<SVGPathElement>series.pathElement).getTotalLength();
let currentTime: number;
path.style.visibility = 'hidden';
animation.animate(path, {
duration: option.duration,
delay: option.delay,
progress: (args: AnimationOptions): void => {
if (args.timeStamp >= args.delay) {
path.style.visibility = 'visible';
currentTime = Math.abs(Math.round(((args.timeStamp - args.delay) * pathLength) / args.duration));
path.setAttribute('stroke-dasharray', currentTime + ',' + pathLength);
}
},
end: () => {
path.setAttribute('stroke-dasharray', strokeDashArray);
series.chart.trigger('animationComplete', { series: series.chart.isBlazor ? {} : series });
}
});
}
/**
* To store the symbol location and region
*
* @param {Points} point point
* @param {Series} series series
* @param {boolean} isInverted isInverted
* @param {Function} getLocation getLocation
*/
public storePointLocation(point: Points, series: Series, isInverted: boolean, getLocation: Function): void {
const markerWidth: number = (series.marker && series.marker.width) ? series.marker.width : 0;
const markerHeight: number = (series.marker && series.marker.height) ? series.marker.height : 0;
point.symbolLocations.push(
getLocation(
point.xValue, point.yValue,
series.xAxis, series.yAxis, isInverted, series
)
);
point.regions.push(
new Rect(
point.symbolLocations[0].x - markerWidth,
point.symbolLocations[0].y - markerHeight,
2 * markerWidth,
2 * markerHeight
)
);
}
/**
* To find point with in the visible range
*
* @param {Points} point point
* @param {Axis} yAxis yAxis
* @private
*/
public withinYRange(point: Points, yAxis: Axis): boolean {
return point.yValue >= yAxis.visibleRange.min && point.yValue <= yAxis.visibleRange.max;
}
/**
* To get first and last visible points
*
* @private
*/
public getFirstLastVisiblePoint(points: Points[]): { first: Points, last: Points } {
let first: Points = null; let last: Points = null;
for (const point of points) {
if (first === null && point.visible) {
first = last = point;
}
last = point.visible ? point : last;
}
return { first: first ? first : points[0], last: last ? last : points[points.length - 1] };
}
/**
* To do the linear animation.
*
* @returns {void}
* @private
*/
public doLinearAnimation(series: Series, animation: AnimationModel): void {
const clipRect: HTMLElement = <HTMLElement>series.clipRectElement.childNodes[0].childNodes[0];
const duration: number = series.chart.animated ? series.chart.duration : animation.duration;
const effect: Function = getAnimationFunction('Linear');
const elementHeight: number = +clipRect.getAttribute('height');
const elementWidth: number = +clipRect.getAttribute('width');
const xCenter: number = +clipRect.getAttribute('x');
const yCenter: number = series.chart.requireInvertedAxis ? +clipRect.getAttribute('height') + +clipRect.getAttribute('y') :
+clipRect.getAttribute('y');
let value: number;
clipRect.style.visibility = 'hidden';
new Animation({}).animate(clipRect, {
duration: duration,
delay: animation.delay,
progress: (args: AnimationOptions): void => {
if (args.timeStamp >= args.delay) {
clipRect.style.visibility = 'visible';
if (series.chart.requireInvertedAxis) {
value = effect(args.timeStamp - args.delay, 0, elementHeight, args.duration);
clipRect.setAttribute('transform', 'translate(' + xCenter + ' ' + yCenter +
') scale(1,' + (value / elementHeight) + ') translate(' + (-xCenter) + ' ' + (-yCenter) + ')');
} else {
value = effect(args.timeStamp - args.delay, 0, elementWidth, args.duration);
clipRect.setAttribute('transform', 'translate(' + xCenter + ' ' + yCenter +
') scale(' + (value / elementWidth) + ', 1) translate(' + (-xCenter) + ' ' + (-yCenter) + ')');
}
}
},
end: () => {
clipRect.setAttribute('transform', 'translate(0,0)');
series.chart.trigger('animationComplete', { series: series.chart.isBlazor ? {} : series });
}
});
}
} | the_stack |
import { DrawingElement } from '../core/elements/drawing-element';
import { PathElement } from '../core/elements/path-element';
import { TextElement } from '../core/elements/text-element';
import { Container } from '../core/containers/container';
import { wordBreakToString, whiteSpaceToString, textAlignToString } from '../utility/base-util';
import { getDiagramElement } from '../utility/dom-util';
import { PathAttributes, TextAttributes, ImageAttributes } from './canvas-interface';
import { RectAttributes, BaseAttributes } from './canvas-interface';
import { WhiteSpace, TextAlign, TextWrap } from '../enum/enum';
import { CanvasRenderer } from './canvas-renderer';
import { ImageElement } from '../core/elements/image-element';
/**
* Renderer module is used to render basic diagram elements
*/
/** @private */
export class DrawingRenderer {
/** @private */
public renderer: CanvasRenderer = null;
private diagramId: string;
/** @private */
public adornerSvgLayer: SVGSVGElement;
// private svgRenderer: SvgRenderer;
/** @private */
public isSvgMode: Boolean = true;
/** @private */
private element: HTMLElement;
constructor(name: string, isSvgMode: Boolean) {
this.diagramId = name;
this.element = getDiagramElement(this.diagramId);
this.isSvgMode = isSvgMode;
this.renderer = new CanvasRenderer();
// this.svgRenderer = new SvgRenderer();
}
// /** @private */
// public setLayers(): void {
// this.adornerSvgLayer = this.element.getElementsByClassName('e-adorner-layer')[0] as SVGSVGElement;
// }
/** @private */
public renderElement(
element: DrawingElement, canvas: HTMLCanvasElement | SVGElement, htmlLayer: HTMLElement, transform?: Transforms,
parentSvg?: SVGSVGElement, createParent?: boolean, fromPalette?: boolean, indexValue?: number):
void {
let isElement: boolean = true;
if (element instanceof Container) {
isElement = false;
this.renderContainer(element, canvas, htmlLayer, transform, parentSvg, createParent, fromPalette, indexValue);
} else if (element instanceof ImageElement) {
this.renderImageElement(element, canvas, transform, parentSvg, fromPalette);
} else if (element instanceof PathElement) {
this.renderPathElement(element, canvas, transform, parentSvg, fromPalette);
} else if (element instanceof TextElement) {
this.renderTextElement(element, canvas, transform, parentSvg, fromPalette);
} else {
this.renderRect(element, canvas, transform, parentSvg);
}
}
/** @private */
public renderImageElement(
element: ImageElement, canvas: HTMLCanvasElement | SVGElement,
transform?: Transforms, parentSvg?: SVGSVGElement, fromPalette?: boolean):
void {
let options: BaseAttributes = this.getBaseAttributes(element, transform);
(options as RectAttributes).cornerRadius = 0;
this.renderer.drawRectangle(canvas as HTMLCanvasElement, options as RectAttributes);
// let sx: number; let sy: number;
let imageWidth: number; let imageHeight: number;
let sourceWidth: number; let sourceHeight: number;
if (element.stretch === 'Stretch') {
imageWidth = element.actualSize.width;
imageHeight = element.actualSize.height;
} else {
let contentWidth: number = element.contentSize.width;
let contentHeight: number = element.contentSize.height;
let widthRatio: number = options.width / contentWidth;
let heightRatio: number = options.height / contentHeight;
let ratio: number;
switch (element.stretch) {
case 'Meet':
ratio = Math.min(widthRatio, heightRatio);
imageWidth = contentWidth * ratio;
imageHeight = contentHeight * ratio;
options.x += Math.abs(options.width - imageWidth) / 2;
options.y += Math.abs(options.height - imageHeight) / 2;
break;
case 'Slice':
widthRatio = options.width / contentWidth;
heightRatio = options.height / contentHeight;
ratio = Math.max(widthRatio, heightRatio);
imageWidth = contentWidth * ratio;
imageHeight = contentHeight * ratio;
sourceWidth = options.width / imageWidth * contentWidth;
sourceHeight = options.height / imageHeight * contentHeight;
break;
case 'None':
imageWidth = contentWidth;
imageHeight = contentHeight;
break;
}
}
options.width = imageWidth;
options.height = imageHeight;
//Commented for code coverage
//(options as ImageAttributes).sourceX = sx;
//(options as ImageAttrib utes).sourceY = sy;
(options as ImageAttributes).sourceWidth = sourceWidth;
(options as ImageAttributes).sourceHeight = sourceHeight;
(options as ImageAttributes).source = element.source;
(options as ImageAttributes).alignment = element.imageAlign;
(options as ImageAttributes).scale = element.imageScale;
this.renderer.drawImage(canvas as HTMLCanvasElement, options as ImageAttributes, parentSvg, fromPalette);
}
/** @private */
public renderPathElement(
element: PathElement, canvas: HTMLCanvasElement | SVGElement,
transform?: Transforms, parentSvg?: SVGSVGElement, fromPalette?: boolean):
void {
let options: BaseAttributes = this.getBaseAttributes(element, transform);
(options as PathAttributes).data = element.absolutePath;
(options as PathAttributes).data = element.absolutePath;
let ariaLabel: Object = element.id;
if (!this.isSvgMode) {
options.x = options.x;
options.y = options.y;
}
this.renderer.drawPath(canvas as HTMLCanvasElement, options as PathAttributes);
}
/** @private */
public renderTextElement(
element: TextElement, canvas: HTMLCanvasElement | SVGElement,
transform?: Transforms, parentSvg?: SVGSVGElement, fromPalette?: boolean):
void {
let options: BaseAttributes = this.getBaseAttributes(element, transform);
(options as RectAttributes).cornerRadius = 0;
(options as TextAttributes).whiteSpace = whiteSpaceToString(element.style.whiteSpace, element.style.textWrapping);
(options as TextAttributes).content = element.content;
(options as TextAttributes).breakWord = wordBreakToString(element.style.textWrapping);
(options as TextAttributes).textAlign = textAlignToString(element.style.textAlign);
(options as TextAttributes).color = element.style.color;
(options as TextAttributes).italic = element.style.italic;
(options as TextAttributes).bold = element.style.bold;
(options as TextAttributes).fontSize = element.style.fontSize;
(options as TextAttributes).fontFamily = element.style.fontFamily;
(options as TextAttributes).textOverflow = element.style.textOverflow;
(options as TextAttributes).textDecoration = element.style.textDecoration;
(options as TextAttributes).doWrap = element.doWrap;
(options as TextAttributes).wrapBounds = element.wrapBounds;
(options as TextAttributes).childNodes = element.childNodes;
options.dashArray = ''; options.strokeWidth = 0; options.fill = element.style.fill;
let ariaLabel: Object = element.content ? element.content : element.id;
this.renderer.drawRectangle(canvas as HTMLCanvasElement, options as RectAttributes);
this.renderer.drawText(canvas as HTMLCanvasElement, options as TextAttributes);
}
/** @private */
public renderContainer(
group: Container, canvas: HTMLCanvasElement | SVGElement, htmlLayer: HTMLElement,
transform?: Transforms, parentSvg?: SVGSVGElement, createParent?: boolean, fromPalette?: boolean, indexValue?: number):
void {
transform = { tx: 0, ty: 0, scale: 1 };
let svgParent: SvgParent = { svg: parentSvg, g: canvas };
if (this.diagramId) {
parentSvg = parentSvg;
}
this.renderRect(group, canvas, transform, parentSvg);
if (group.hasChildren()) {
let parentG: HTMLCanvasElement | SVGElement;
let svgParent: SvgParent;
for (let child of group.children) {
this.renderElement(child, parentG || canvas, htmlLayer, transform, parentSvg, true, fromPalette, indexValue);
}
}
}
/** @private */
public renderRect(element: DrawingElement, canvas: HTMLCanvasElement | SVGElement, transform?: Transforms, parentSvg?: SVGSVGElement):
void {
let options: RectAttributes = this.getBaseAttributes(element, transform);
options.cornerRadius = element.cornerRadius || 0;
let ariaLabel: Object = element.id;
this.renderer.drawRectangle(canvas as HTMLCanvasElement, options);
}
/** @private */
public getBaseAttributes(element: DrawingElement, transform?: Transforms): BaseAttributes {
let options: BaseAttributes = {
width: element.actualSize.width, height: element.actualSize.height,
x: element.offsetX - element.actualSize.width * element.pivot.x + 0.5,
y: element.offsetY - element.actualSize.height * element.pivot.y + 0.5,
fill: element.style.fill, stroke: element.style.strokeColor, angle: element.rotateAngle + element.parentTransform,
pivotX: element.pivot.x, pivotY: element.pivot.y, strokeWidth: element.style.strokeWidth,
dashArray: element.style.strokeDashArray || '', opacity: element.style.opacity,
visible: element.visible, id: element.id, gradient: element.style.gradient,
};
if (transform) {
options.x += transform.tx;
options.y += transform.ty;
}
return options;
}
}
interface SvgParent {
g: HTMLCanvasElement | SVGElement;
svg: SVGSVGElement;
}
interface TextStyle {
width: number;
height: number;
whiteSpace: WhiteSpace;
content: string;
breakWord: TextWrap;
fontSize: number;
fontFamily: string;
offsetX: number;
offsetY: number;
bold: boolean;
italic: boolean;
textAlign: TextAlign;
color: string;
pivotX: number;
pivotY: number;
fill: string;
}
interface Transforms {
tx: number;
ty: number;
scale: number;
} | the_stack |
import { Injectable } from '@angular/core';
import { CoreCourseActivityPrefetchHandlerBase } from '@features/course/classes/activity-prefetch-handler';
import { AddonModForum, AddonModForumData, AddonModForumPost, AddonModForumProvider } from '../forum';
import { CoreSitesReadingStrategy } from '@services/sites';
import { CoreFilepool } from '@services/filepool';
import { CoreWSFile } from '@services/ws';
import { CoreCourse, CoreCourseAnyModuleData, CoreCourseCommonModWSOptions } from '@features/course/services/course';
import { CoreUser } from '@features/user/services/user';
import { CoreGroups, CoreGroupsProvider } from '@services/groups';
import { CoreUtils } from '@services/utils/utils';
import { AddonModForumSync } from '../forum-sync';
import { makeSingleton } from '@singletons';
/**
* Handler to prefetch forums.
*/
@Injectable({ providedIn: 'root' })
export class AddonModForumPrefetchHandlerService extends CoreCourseActivityPrefetchHandlerBase {
name = 'AddonModForum';
modName = 'forum';
component = AddonModForumProvider.COMPONENT;
updatesNames = /^configuration$|^.*files$|^discussions$/;
/**
* Get list of files. If not defined, we'll assume they're in module.contents.
*
* @param module Module.
* @param courseId Course ID the module belongs to.
* @param single True if we're downloading a single module, false if we're downloading a whole section.
* @return Promise resolved with the list of files.
*/
async getFiles(module: CoreCourseAnyModuleData, courseId: number): Promise<CoreWSFile[]> {
try {
const forum = await AddonModForum.getForum(courseId, module.id);
let files = this.getIntroFilesFromInstance(module, forum);
// Get posts.
const posts = await this.getPostsForPrefetch(forum, { cmId: module.id });
// Add posts attachments and embedded files.
files = files.concat(this.getPostsFiles(posts));
return files;
} catch (error) {
// Forum not found, return empty list.
return [];
}
}
/**
* Given a list of forum posts, return a list with all the files (attachments and embedded files).
*
* @param posts Forum posts.
* @return Files.
*/
protected getPostsFiles(posts: AddonModForumPost[]): CoreWSFile[] {
let files: CoreWSFile[] = [];
posts.forEach((post) => {
if (post.attachments && post.attachments.length) {
files = files.concat(post.attachments as CoreWSFile[]);
}
if (post.messageinlinefiles) {
files = files.concat(post.messageinlinefiles);
} else if (post.message) {
files = files.concat(CoreFilepool.extractDownloadableFilesFromHtmlAsFakeFileObjects(post.message));
}
});
return files;
}
/**
* Get the posts to be prefetched.
*
* @param forum Forum instance.
* @param options Other options.
* @return Promise resolved with array of posts.
*/
protected getPostsForPrefetch(
forum: AddonModForumData,
options: CoreCourseCommonModWSOptions = {},
): Promise<AddonModForumPost[]> {
const promises = AddonModForum.getAvailableSortOrders().map((sortOrder) => {
// Get discussions in first 2 pages.
const discussionsOptions = {
sortOrder: sortOrder.value,
numPages: 2,
...options, // Include all options.
};
return AddonModForum.getDiscussionsInPages(forum.id, discussionsOptions).then((response) => {
if (response.error) {
throw new Error('Failed getting discussions');
}
const promises: Promise<{ posts: AddonModForumPost[] }>[] = [];
response.discussions.forEach((discussion) => {
promises.push(AddonModForum.getDiscussionPosts(discussion.discussion, options));
});
return Promise.all(promises);
});
});
return Promise.all(promises).then((results) => {
// Each order has returned its own list of posts. Merge all the lists, preventing duplicates.
const posts: AddonModForumPost[] = [];
const postIds = {}; // To make the array unique.
results.forEach((orderResults) => {
orderResults.forEach((orderResult) => {
orderResult.posts.forEach((post) => {
if (!postIds[post.id]) {
postIds[post.id] = true;
posts.push(post);
}
});
});
});
return posts;
});
}
/**
* Invalidate the prefetched content.
*
* @param moduleId The module ID.
* @param courseId The course ID the module belongs to.
* @return Promise resolved when the data is invalidated.
*/
invalidateContent(moduleId: number, courseId: number): Promise<void> {
return AddonModForum.invalidateContent(moduleId, courseId);
}
/**
* Invalidate WS calls needed to determine module status (usually, to check if module is downloadable).
* It doesn't need to invalidate check updates. It should NOT invalidate files nor all the prefetched data.
*
* @param module Module.
* @param courseId Course ID the module belongs to.
* @return Promise resolved when invalidated.
*/
async invalidateModule(module: CoreCourseAnyModuleData, courseId: number): Promise<void> {
// Invalidate forum data to recalculate unread message count badge.
const promises: Promise<unknown>[] = [];
promises.push(AddonModForum.invalidateForumData(courseId));
promises.push(CoreCourse.invalidateModule(module.id));
await Promise.all(promises);
}
/**
* @inheritdoc
*/
prefetch(module: CoreCourseAnyModuleData, courseId: number, single?: boolean): Promise<void> {
return this.prefetchPackage(module, courseId, this.prefetchForum.bind(this, module, courseId, single));
}
/**
* Prefetch a forum.
*
* @param module The module object returned by WS.
* @param courseId Course ID the module belongs to.
* @param single True if we're downloading a single module, false if we're downloading a whole section.
* @param siteId Site ID.
* @return Promise resolved when done.
*/
protected async prefetchForum(
module: CoreCourseAnyModuleData,
courseId: number,
single: boolean,
siteId: string,
): Promise<void> {
const commonOptions = {
readingStrategy: CoreSitesReadingStrategy.ONLY_NETWORK,
siteId,
};
const modOptions = {
cmId: module.id,
...commonOptions, // Include all common options.
};
// Get the forum data.
const forum = await AddonModForum.getForum(courseId, module.id, commonOptions);
const promises: Promise<unknown>[] = [];
// Prefetch the posts.
promises.push(this.getPostsForPrefetch(forum, modOptions).then((posts) => {
const promises: Promise<unknown>[] = [];
const files = this.getIntroFilesFromInstance(module, forum).concat(this.getPostsFiles(posts));
promises.push(CoreFilepool.addFilesToQueue(siteId, files, this.component, module.id));
// Prefetch groups data.
promises.push(this.prefetchGroupsInfo(forum, courseId, !!forum.cancreatediscussions, siteId));
// Prefetch avatars.
promises.push(CoreUser.prefetchUserAvatars(posts, 'userpictureurl', siteId));
return Promise.all(promises);
}));
// Prefetch access information.
promises.push(AddonModForum.getAccessInformation(forum.id, modOptions));
// Prefetch sort order preference.
if (AddonModForum.isDiscussionListSortingAvailable()) {
promises.push(CoreUser.getUserPreference(AddonModForumProvider.PREFERENCE_SORTORDER, siteId));
}
await Promise.all(promises);
}
/**
* Prefetch groups info for a forum.
*
* @param module The module object returned by WS.
* @param courseI Course ID the module belongs to.
* @param canCreateDiscussions Whether the user can create discussions in the forum.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when group data has been prefetched.
*/
protected async prefetchGroupsInfo(
forum: AddonModForumData,
courseId: number,
canCreateDiscussions: boolean,
siteId?: string,
): Promise<void> {
const options = {
cmId: forum.cmid,
siteId,
};
// Check group mode.
try {
const mode = await CoreGroups.getActivityGroupMode(forum.cmid, siteId);
if (mode !== CoreGroupsProvider.SEPARATEGROUPS && mode !== CoreGroupsProvider.VISIBLEGROUPS) {
// Activity doesn't use groups. Prefetch canAddDiscussionToAll to determine if user can pin/attach.
await CoreUtils.ignoreErrors(AddonModForum.canAddDiscussionToAll(forum.id, options));
return;
}
// Activity uses groups, prefetch allowed groups.
const result = await CoreGroups.getActivityAllowedGroups(forum.cmid, undefined, siteId);
if (mode === CoreGroupsProvider.SEPARATEGROUPS) {
// Groups are already filtered by WS. Prefetch canAddDiscussionToAll to determine if user can pin/attach.
await CoreUtils.ignoreErrors(AddonModForum.canAddDiscussionToAll(forum.id, options));
return;
}
if (canCreateDiscussions) {
// Prefetch data to check the visible groups when creating discussions.
const response = await CoreUtils.ignoreErrors(
AddonModForum.canAddDiscussionToAll(forum.id, options),
{ status: false },
);
if (response.status) {
// User can post to all groups, nothing else to prefetch.
return;
}
// The user can't post to all groups, let's check which groups he can post to.
await Promise.all(
result.groups.map(
async (group) => CoreUtils.ignoreErrors(
AddonModForum.canAddDiscussion(forum.id, group.id, options),
),
),
);
}
} catch (error) {
// Ignore errors if cannot create discussions.
if (canCreateDiscussions) {
throw error;
}
}
}
/**
* Sync a module.
*
* @param module Module.
* @param courseId Course ID the module belongs to
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when done.
*/
async sync(
module: CoreCourseAnyModuleData,
courseId: number,
siteId?: string,
): Promise<AddonModForumSyncResult> {
const promises: Promise<AddonModForumSyncResult>[] = [];
promises.push(AddonModForumSync.syncForumDiscussions(module.instance!, undefined, siteId));
promises.push(AddonModForumSync.syncForumReplies(module.instance!, undefined, siteId));
promises.push(AddonModForumSync.syncRatings(module.id, undefined, true, siteId));
const results = await Promise.all(promises);
return results.reduce(
(a, b) => ({
updated: a.updated || b.updated,
warnings: (a.warnings || []).concat(b.warnings || []),
}),
{
updated: false,
warnings: [],
},
);
}
}
export const AddonModForumPrefetchHandler = makeSingleton(AddonModForumPrefetchHandlerService);
/**
* Data returned by a forum sync.
*/
export type AddonModForumSyncResult = {
warnings: string[]; // List of warnings.
updated: boolean; // Whether some data was sent to the server or offline data was updated.
}; | the_stack |
import {SourceMapGenerator} from 'source-map';
import * as ts from 'typescript';
import {getDecoratorDeclarations} from './decorators';
import {getIdentifierText, Rewriter} from './rewriter';
import {SourceMapper} from './source_map_utils';
import {TypeTranslator} from './type-translator';
import {toArray} from './util';
/**
* ConstructorParameters are gathered from constructors, so that their type information and
* decorators can later be emitted as an annotation.
*/
interface ConstructorParameter {
/**
* The type declaration for the parameter. Only set if the type is a value (e.g. a class, not an
* interface).
*/
type: ts.TypeNode|null;
/** The list of decorators found on the parameter, null if none. */
decorators: ts.Decorator[]|null;
}
// DecoratorClassVisitor rewrites a single "class Foo {...}" declaration.
// It's its own object because we collect decorators on the class and the ctor
// separately for each class we encounter.
export class DecoratorClassVisitor {
/** Decorators on the class itself. */
decorators: ts.Decorator[];
/** The constructor parameter list and decorators on each param. */
private ctorParameters: ConstructorParameter[];
/** Per-method decorators. */
propDecorators: Map<string, ts.Decorator[]>;
constructor(
private typeChecker: ts.TypeChecker, private rewriter: Rewriter,
private classDecl: ts.ClassDeclaration,
private importedNames: Array<{name: ts.Identifier, declarationNames: ts.Identifier[]}>) {
if (classDecl.decorators) {
const toLower = this.decoratorsToLower(classDecl);
if (toLower.length > 0) this.decorators = toLower;
}
}
/**
* Determines whether the given decorator should be re-written as an annotation.
*/
private shouldLower(decorator: ts.Decorator) {
for (const d of getDecoratorDeclarations(decorator, this.typeChecker)) {
// Switch to the TS JSDoc parser in the future to avoid false positives here.
// For example using '@Annotation' in a true comment.
// However, a new TS API would be needed, track at
// https://github.com/Microsoft/TypeScript/issues/7393.
let commentNode: ts.Node = d;
// Not handling PropertyAccess expressions here, because they are
// filtered earlier.
if (commentNode.kind === ts.SyntaxKind.VariableDeclaration) {
if (!commentNode.parent) continue;
commentNode = commentNode.parent;
}
// Go up one more level to VariableDeclarationStatement, where usually
// the comment lives. If the declaration has an 'export', the
// VDList.getFullText will not contain the comment.
if (commentNode.kind === ts.SyntaxKind.VariableDeclarationList) {
if (!commentNode.parent) continue;
commentNode = commentNode.parent;
}
const range = ts.getLeadingCommentRanges(commentNode.getFullText(), 0);
if (!range) continue;
for (const {pos, end} of range) {
const jsDocText = commentNode.getFullText().substring(pos, end);
if (jsDocText.includes('@Annotation')) return true;
}
}
return false;
}
private decoratorsToLower(n: ts.Node): ts.Decorator[] {
if (n.decorators) {
return n.decorators.filter((d) => this.shouldLower(d));
}
return [];
}
/**
* gatherConstructor grabs the parameter list and decorators off the class
* constructor, and emits nothing.
*/
private gatherConstructor(ctor: ts.ConstructorDeclaration) {
const ctorParameters: ConstructorParameter[] = [];
let hasDecoratedParam = false;
for (const param of ctor.parameters) {
const ctorParam: ConstructorParameter = {type: null, decorators: null};
if (param.decorators) {
ctorParam.decorators = this.decoratorsToLower(param);
hasDecoratedParam = hasDecoratedParam || ctorParam.decorators.length > 0;
}
if (param.type) {
// param has a type provided, e.g. "foo: Bar".
// Verify that "Bar" is a value (e.g. a constructor) and not just a type.
const sym = this.typeChecker.getTypeAtLocation(param.type).getSymbol();
if (sym && (sym.flags & ts.SymbolFlags.Value)) {
ctorParam.type = param.type;
}
}
ctorParameters.push(ctorParam);
}
// Use the ctor parameter metadata only if the class or the ctor was decorated.
if (this.decorators || hasDecoratedParam) {
this.ctorParameters = ctorParameters;
}
}
/**
* gatherMethod grabs the decorators off a class method and emits nothing.
*/
private gatherMethodOrProperty(method: ts.NamedDeclaration) {
if (!method.decorators) return;
if (!method.name || method.name.kind !== ts.SyntaxKind.Identifier) {
// Method has a weird name, e.g.
// [Symbol.foo]() {...}
this.rewriter.error(method, 'cannot process decorators on strangely named method');
return;
}
const name = (method.name as ts.Identifier).text;
const decorators: ts.Decorator[] = this.decoratorsToLower(method);
if (decorators.length === 0) return;
if (!this.propDecorators) this.propDecorators = new Map<string, ts.Decorator[]>();
this.propDecorators.set(name, decorators);
}
/**
* For lowering decorators, we need to refer to constructor types.
* So we start with the identifiers that represent these types.
* However, TypeScript does not allow us to emit them in a value position
* as it associated different symbol information with it.
*
* This method looks for the place where the value that is associated to
* the type is defined and returns that identifier instead.
*
* This might be simplified when https://github.com/Microsoft/TypeScript/issues/17516 is solved.
*/
private getValueIdentifierForType(typeSymbol: ts.Symbol, typeNode: ts.TypeNode): ts.Identifier
|null {
const valueDeclaration = typeSymbol.valueDeclaration as ts.NamedDeclaration;
if (!valueDeclaration) return null;
const valueName = valueDeclaration.name;
if (!valueName || valueName.kind !== ts.SyntaxKind.Identifier) {
return null;
}
if (valueName.getSourceFile() === this.rewriter.file) {
return valueName;
}
// Need to look at the first identifier only
// to ignore generics.
const firstIdentifierInType = firstIdentifierInSubtree(typeNode);
if (firstIdentifierInType) {
for (const {name, declarationNames} of this.importedNames) {
if (firstIdentifierInType.text === name.text &&
declarationNames.some(d => d === valueName)) {
return name;
}
}
}
return null;
}
beforeProcessNode(node: ts.Node) {
switch (node.kind) {
case ts.SyntaxKind.Constructor:
this.gatherConstructor(node as ts.ConstructorDeclaration);
break;
case ts.SyntaxKind.PropertyDeclaration:
case ts.SyntaxKind.SetAccessor:
case ts.SyntaxKind.GetAccessor:
case ts.SyntaxKind.MethodDeclaration:
this.gatherMethodOrProperty(node as ts.Declaration);
break;
default:
}
}
maybeProcessDecorator(node: ts.Decorator, start?: number): boolean {
if (this.shouldLower(node)) {
// Return true to signal that this node should not be emitted,
// but still emit the whitespace *before* the node.
if (!start) {
start = node.getFullStart();
}
this.rewriter.writeRange(node, start, node.getStart());
return true;
}
return false;
}
foundDecorators(): boolean {
return !!(this.decorators || this.ctorParameters || this.propDecorators);
}
/**
* emits the types for the various gathered metadata to be used
* in the tsickle type annotations helper.
*/
emitMetadataTypeAnnotationsHelpers() {
if (!this.classDecl.name) return;
const className = getIdentifierText(this.classDecl.name);
if (this.decorators) {
this.rewriter.emit(`/** @type {!Array<{type: !Function, args: (undefined|!Array<?>)}>} */\n`);
this.rewriter.emit(`${className}.decorators;\n`);
}
if (this.decorators || this.ctorParameters) {
this.rewriter.emit(`/**\n`);
this.rewriter.emit(` * @nocollapse\n`);
this.rewriter.emit(
` * @type {function(): !Array<(null|{type: ?, decorators: (undefined|!Array<{type: !Function, args: (undefined|!Array<?>)}>)})>}\n`);
this.rewriter.emit(` */\n`);
this.rewriter.emit(`${className}.ctorParameters;\n`);
}
if (this.propDecorators) {
this.rewriter.emit(
`/** @type {!Object<string,!Array<{type: !Function, args: (undefined|!Array<?>)}>>} */\n`);
this.rewriter.emit(`${className}.propDecorators;\n`);
}
}
/**
* emitMetadata emits the various gathered metadata, as static fields.
*/
emitMetadataAsStaticProperties() {
const decoratorInvocations = '{type: Function, args?: any[]}[]';
if (this.decorators) {
this.rewriter.emit(`static decorators: ${decoratorInvocations} = [\n`);
for (const annotation of this.decorators) {
this.emitDecorator(annotation);
this.rewriter.emit(',\n');
}
this.rewriter.emit('];\n');
}
if (this.decorators || this.ctorParameters) {
this.rewriter.emit(`/** @nocollapse */\n`);
// ctorParameters may contain forward references in the type: field, so wrap in a function
// closure
this.rewriter.emit(
`static ctorParameters: () => ({type: any, decorators?: ` + decoratorInvocations +
`}|null)[] = () => [\n`);
for (const param of this.ctorParameters || []) {
if (!param.type && !param.decorators) {
this.rewriter.emit('null,\n');
continue;
}
this.rewriter.emit(`{type: `);
if (!param.type) {
this.rewriter.emit(`undefined`);
} else {
// For transformer mode, tsickle must emit not only the string referring to the type,
// but also create a source mapping, so that TypeScript can later recognize that the
// symbol is used in a value position, so that TypeScript emits an import for the
// symbol.
// The code below and in getValueIdentifierForType finds the value node corresponding to
// the type and emits that symbol if possible. This causes a source mapping to the value,
// which then allows later transformers in the pipeline to do the correct module
// rewriting. Note that we cannot use param.type as the emit node directly (not even just
// for mapping), because that is marked as a type use of the node, not a value use, so it
// doesn't get updated as an export.
const sym = this.typeChecker.getTypeAtLocation(param.type).getSymbol()!;
const emitNode = this.getValueIdentifierForType(sym, param.type);
if (emitNode) {
this.rewriter.writeRange(emitNode, emitNode.getStart(), emitNode.getEnd());
} else {
const typeStr = new TypeTranslator(this.typeChecker, param.type)
.symbolToString(sym, /* useFqn */ true);
this.rewriter.emit(typeStr);
}
}
this.rewriter.emit(`, `);
if (param.decorators) {
this.rewriter.emit('decorators: [');
for (const decorator of param.decorators) {
this.emitDecorator(decorator);
this.rewriter.emit(', ');
}
this.rewriter.emit(']');
}
this.rewriter.emit('},\n');
}
this.rewriter.emit(`];\n`);
}
if (this.propDecorators) {
this.rewriter.emit(
`static propDecorators: {[key: string]: ` + decoratorInvocations + `} = {\n`);
for (const name of toArray(this.propDecorators.keys())) {
this.rewriter.emit(`"${name}": [`);
for (const decorator of this.propDecorators.get(name)!) {
this.emitDecorator(decorator);
this.rewriter.emit(',');
}
this.rewriter.emit('],\n');
}
this.rewriter.emit('};\n');
}
}
private emitDecorator(decorator: ts.Decorator) {
this.rewriter.emit('{ type: ');
const expr = decorator.expression;
switch (expr.kind) {
case ts.SyntaxKind.Identifier:
// The decorator was a plain @Foo.
this.rewriter.visit(expr);
break;
case ts.SyntaxKind.CallExpression:
// The decorator was a call, like @Foo(bar).
const call = expr as ts.CallExpression;
this.rewriter.visit(call.expression);
if (call.arguments.length) {
this.rewriter.emit(', args: [');
for (const arg of call.arguments) {
this.rewriter.writeNodeFrom(arg, arg.getStart());
this.rewriter.emit(', ');
}
this.rewriter.emit(']');
}
break;
default:
this.rewriter.errorUnimplementedKind(expr, 'gathering metadata');
this.rewriter.emit('undefined');
}
this.rewriter.emit(' }');
}
}
class DecoratorRewriter extends Rewriter {
private currentDecoratorConverter: DecoratorClassVisitor;
private importedNames: Array<{name: ts.Identifier, declarationNames: ts.Identifier[]}> = [];
constructor(
private typeChecker: ts.TypeChecker, sourceFile: ts.SourceFile, sourceMapper?: SourceMapper) {
super(sourceFile, sourceMapper);
}
process(): {output: string, diagnostics: ts.Diagnostic[]} {
this.visit(this.file);
return this.getOutput();
}
protected maybeProcess(node: ts.Node): boolean {
if (this.currentDecoratorConverter) {
this.currentDecoratorConverter.beforeProcessNode(node);
}
switch (node.kind) {
case ts.SyntaxKind.ImportDeclaration:
this.importedNames.push(
...collectImportedNames(this.typeChecker, node as ts.ImportDeclaration));
return false;
case ts.SyntaxKind.Decorator:
return this.currentDecoratorConverter &&
this.currentDecoratorConverter.maybeProcessDecorator(node as ts.Decorator);
case ts.SyntaxKind.ClassDeclaration:
const oldDecoratorConverter = this.currentDecoratorConverter;
this.currentDecoratorConverter = new DecoratorClassVisitor(
this.typeChecker, this, node as ts.ClassDeclaration, this.importedNames);
this.writeLeadingTrivia(node);
visitClassContentIncludingDecorators(
node as ts.ClassDeclaration, this, this.currentDecoratorConverter);
this.currentDecoratorConverter = oldDecoratorConverter;
return true;
default:
return false;
}
}
}
/**
* Returns the first identifier in the node tree starting at node
* in a depth first order.
*
* @param node The node to start with
* @return The first identifier if one was found.
*/
function firstIdentifierInSubtree(node: ts.Node): ts.Identifier|undefined {
if (node.kind === ts.SyntaxKind.Identifier) {
return node as ts.Identifier;
}
return ts.forEachChild(node, firstIdentifierInSubtree);
}
/**
* Collect the Identifiers used as named bindings in the given import declaration
* with their Symbol.
* This is needed later on to find an identifier that represents the value
* of an imported type identifier.
*/
export function collectImportedNames(typeChecker: ts.TypeChecker, decl: ts.ImportDeclaration):
Array<{name: ts.Identifier, declarationNames: ts.Identifier[]}> {
const importedNames: Array<{name: ts.Identifier, declarationNames: ts.Identifier[]}> = [];
const importClause = decl.importClause;
if (!importClause) {
return importedNames;
}
const names: ts.Identifier[] = [];
if (importClause.name) {
names.push(importClause.name);
}
if (importClause.namedBindings &&
importClause.namedBindings.kind === ts.SyntaxKind.NamedImports) {
const namedImports = importClause.namedBindings as ts.NamedImports;
names.push(...namedImports.elements.map(e => e.name));
}
for (const name of names) {
let symbol = typeChecker.getSymbolAtLocation(name)!;
if (symbol.flags & ts.SymbolFlags.Alias) {
symbol = typeChecker.getAliasedSymbol(symbol);
}
const declarationNames: ts.Identifier[] = [];
if (symbol.declarations) {
for (const d of symbol.declarations) {
const decl = d as ts.NamedDeclaration;
if (decl.name && decl.name.kind === ts.SyntaxKind.Identifier) {
declarationNames.push(decl.name as ts.Identifier);
}
}
}
if (symbol.declarations) {
importedNames.push({name, declarationNames});
}
}
return importedNames;
}
export function visitClassContentIncludingDecorators(
classDecl: ts.ClassDeclaration, rewriter: Rewriter, decoratorVisitor?: DecoratorClassVisitor) {
if (rewriter.file.text[classDecl.getEnd() - 1] !== '}') {
rewriter.error(classDecl, 'unexpected class terminator');
return;
}
rewriter.writeNodeFrom(classDecl, classDecl.getStart(), classDecl.getEnd() - 1);
// At this point, we've emitted up through the final child of the class, so all that
// remains is the trailing whitespace and closing curly brace.
// The final character owned by the class node should always be a '}',
// or we somehow got the AST wrong and should report an error.
// (Any whitespace or semicolon following the '}' will be part of the next Node.)
if (decoratorVisitor) {
decoratorVisitor.emitMetadataAsStaticProperties();
}
rewriter.writeRange(classDecl, classDecl.getEnd() - 1, classDecl.getEnd());
}
export function convertDecorators(
typeChecker: ts.TypeChecker, sourceFile: ts.SourceFile,
sourceMapper?: SourceMapper): {output: string, diagnostics: ts.Diagnostic[]} {
return new DecoratorRewriter(typeChecker, sourceFile, sourceMapper).process();
} | the_stack |
import {CSS_PREFIX} from "./Utils.js";
import {Background, BasicLevel, CGChip, Config, ModelType, Phosphor, RamSize, ScanLines} from "trs80-emulator";
import {Trs80} from "trs80-emulator";
import {AUTHENTIC_BACKGROUND, BLACK_BACKGROUND, phosphorToRgb} from "./CanvasScreen.js";
const gCssPrefix = CSS_PREFIX + "-settings-panel";
const gScreenNodeCssClass = gCssPrefix + "-screen-node";
const gPanelCssClass = gCssPrefix + "-panel";
const gShownCssClass = gCssPrefix + "-shown";
const gAcceptButtonCssClass = gCssPrefix + "-accept";
const gRebootButtonCssClass = gCssPrefix + "-reboot";
const gOptionsClass = gCssPrefix + "-options";
const gButtonsClass = gCssPrefix + "-buttons";
const gColorButtonClass = gCssPrefix + "-color-button";
const gDarkColorButtonClass = gCssPrefix + "-dark-color-button";
const gAcceptButtonColor = "#449944";
const GLOBAL_CSS = `
.${gPanelCssClass} {
display: flex;
align-items: stretch;
justify-content: center;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
opacity: 0;
visibility: hidden;
transition: opacity .20s ease-in-out, visibility .20s ease-in-out;
}
.${gPanelCssClass}.${gShownCssClass} {
opacity: 1;
visibility: visible;
}
.${gPanelCssClass} > div {
display: flex;
flex-direction: column;
justify-content: space-between;
background-color: rgba(40, 40, 40, 0.8);
border-radius: 15px;
color: #ccc;
font-family: sans-serif;
font-size: 10pt;
line-height: normal;
margin: 20px 0;
padding: 10px 30px;
min-width: 200px;
}
.${gPanelCssClass} h1 {
text-transform: uppercase;
text-align: center;
letter-spacing: .5px;
font-size: 10pt;
margin: 0 0 10px 0;
}
.${gPanelCssClass} .${gOptionsClass} {
display: flex;
justify-content: center;
}
.${gPanelCssClass} input[type=radio] {
display: none;
}
.${gPanelCssClass} input[type=radio] + label {
display: block;
flex-grow: 1;
flex-basis: 0;
text-align: center;
padding: 4px 16px;
margin-left: 10px;
border-radius: 3px;
background-color: #44443A;
white-space: nowrap;
}
.${gPanelCssClass} input[type=radio] + label.${gColorButtonClass} {
flex-grow: 0;
flex-basis: auto;
width: 24px;
height: 24px;
padding: 0;
border-radius: 999px;
border: 2px solid transparent;
color: transparent;
transition: color .20s ease-in-out;
}
.${gPanelCssClass} input[type=radio] + label.${gColorButtonClass}.${gDarkColorButtonClass} {
border: solid 2px #ccc;
}
.${gPanelCssClass} input[type=radio]:checked + label.${gColorButtonClass}::after {
content: "✓";
font-size: 20px;
}
.${gPanelCssClass} input[type=radio]:checked + label.${gColorButtonClass} {
color: black;
}
.${gPanelCssClass} input[type=radio]:checked + label.${gColorButtonClass}.${gDarkColorButtonClass} {
color: #ccc;
}
.${gPanelCssClass} input[type=radio] + label:first-of-type {
margin-left: 0;
}
.${gPanelCssClass} input[type=radio]:enabled + label:hover {
background-color: #66665A;
}
.${gPanelCssClass} input[type=radio]:disabled + label {
color: #666;
}
.${gPanelCssClass} input[type=radio]:enabled:checked + label {
color: #444;
background-color: #ccc;
}
.${gPanelCssClass} .${gButtonsClass} {
display: flex;
}
.${gPanelCssClass} a {
display: block;
flex-grow: 1;
flex-basis: 0;
text-align: center;
padding: 4px 16px;
border-radius: 3px;
margin-left: 10px;
color: #ccc;
background-color: #44443A;
cursor: default;
}
.${gPanelCssClass} a:first-of-type {
margin-left: 0;
}
.${gPanelCssClass} a.${gAcceptButtonCssClass} {
font-weight: bold;
color: #eee;
background-color: ${gAcceptButtonColor};
}
.${gPanelCssClass} a.${gAcceptButtonCssClass}:hover {
background-color: #338833;
}
.${gPanelCssClass} a.${gRebootButtonCssClass} {
background-color: #D25F43;
}
.${gPanelCssClass} a:hover {
background-color: #66665A;
}
.${gPanelCssClass} a.${gRebootButtonCssClass}:hover {
background-color: #BD563C;
}
.${gScreenNodeCssClass} {
/* Force the screen node to relative positioning. Hope that doesn't screw anything up. */
position: relative;
}
`;
/**
* An option in the settings screen, like a specific model or RAM amount.
*/
interface Option {
label: string;
value: any;
}
/**
* A block of options that are mutually exclusive, like all the models.
*/
interface OptionBlock {
title: string;
/**
* Whether the option should be checked, based on this config.
*/
isChecked: (value: any, config: Config) => boolean;
/**
* Return a modified config, given that this option was selected by the user.
*/
updateConfig: (value: any, config: Config) => Config;
options: Option[];
}
/**
* An option that's currently displayed to the user.
*/
class DisplayedOption {
public readonly input: HTMLInputElement;
public readonly block: OptionBlock;
public readonly option: Option;
constructor(input: HTMLInputElement, block: OptionBlock, option: Option) {
this.input = input;
this.block = block;
this.option = option;
}
}
// Convert RGB array (0-255) to a CSS string.
function rgbToCss(color: number[]): string {
return "#" + color.map(c => c.toString(16).padStart(2, "0").toUpperCase()).join("");
}
// Multiplies an RGB (0-255) color by a factor.
function adjustColor(color: number[], factor: number): number[] {
return color.map(c => Math.max(0, Math.min(255, Math.round(c*factor))));
}
/**
* Our full configuration options.
*/
const HARDWARE_OPTION_BLOCKS: OptionBlock[] = [
{
title: "Model",
isChecked: (modelType: ModelType, config: Config) => modelType === config.modelType,
updateConfig: (modelType: ModelType, config: Config) => config.withModelType(modelType),
options: [
{
label: "Model I",
value: ModelType.MODEL1,
},
{
label: "Model III",
value: ModelType.MODEL3,
},
{
label: "Model 4",
value: ModelType.MODEL4,
},
]
},
{
title: "Basic",
isChecked: (basicLevel: BasicLevel, config: Config) => basicLevel === config.basicLevel,
updateConfig: (basicLevel: BasicLevel, config: Config) => config.withBasicLevel(basicLevel),
options: [
{
label: "Level 1",
value: BasicLevel.LEVEL1,
},
{
label: "Level 2",
value: BasicLevel.LEVEL2,
},
]
},
{
title: "Characters",
isChecked: (cgChip: CGChip, config: Config) => cgChip === config.cgChip,
updateConfig: (cgChip: CGChip, config: Config) => config.withCGChip(cgChip),
options: [
{
label: "Original",
value: CGChip.ORIGINAL,
},
{
label: "Lower case",
value: CGChip.LOWER_CASE,
},
]
},
{
title: "RAM",
isChecked: (ramSize: RamSize, config: Config) => ramSize === config.ramSize,
updateConfig: (ramSize: RamSize, config: Config) => config.withRamSize(ramSize),
options: [
{
label: "4 kB",
value: RamSize.RAM_4_KB,
},
{
label: "16 kB",
value: RamSize.RAM_16_KB,
},
{
label: "32 kB",
value: RamSize.RAM_32_KB,
},
{
label: "48 kB",
value: RamSize.RAM_48_KB,
},
]
},
];
const VIEW_OPTION_BLOCKS: OptionBlock[] = [
{
title: "Phosphor",
isChecked: (phosphor: Phosphor, config: Config) => phosphor === config.phosphor,
updateConfig: (phosphor: Phosphor, config: Config) => config.withPhosphor(phosphor),
options: [
{
label: rgbToCss(adjustColor(phosphorToRgb(Phosphor.WHITE), 0.8)),
value: Phosphor.WHITE,
},
{
// Cheat and use the green from the OK button so that the two greens don't clash.
label: gAcceptButtonColor,
value: Phosphor.GREEN,
},
{
label: rgbToCss(adjustColor(phosphorToRgb(Phosphor.AMBER), 0.8)),
value: Phosphor.AMBER,
},
]
},
{
title: "Background",
isChecked: (background: Background, config: Config) => background === config.background,
updateConfig: (background: Background, config: Config) => config.withBackground(background),
options: [
{
label: BLACK_BACKGROUND,
value: Background.BLACK,
},
{
label: AUTHENTIC_BACKGROUND,
value: Background.AUTHENTIC,
},
]
},
{
title: "Scan Lines",
isChecked: (scanLines: ScanLines, config: Config) => scanLines === config.scanLines,
updateConfig: (scanLines: ScanLines, config: Config) => config.withScanLines(scanLines),
options: [
{
label: "Off",
value: ScanLines.OFF,
},
{
label: "On",
value: ScanLines.ON,
},
]
},
];
// Type of panel to show.
export enum PanelType {
// Model, RAM, etc.
HARDWARE,
// Phosphor color, background, etc.
VIEW,
}
// Get the right options blocks for the panel type.
function optionBlocksForPanelType(panelType: PanelType): OptionBlock[] {
switch (panelType) {
case PanelType.HARDWARE:
default:
return HARDWARE_OPTION_BLOCKS;
case PanelType.VIEW:
return VIEW_OPTION_BLOCKS;
}
}
/**
* Whether the given CSS color is dark.
*
* @param color an CSS color in the form "#rrggbb".
*/
function isDarkColor(color: string): boolean {
if (!color.startsWith("#") || color.length !== 7) {
throw new Error("isDarkColor: not a color (" + color + ")");
}
const red = parseInt(color.substr(1, 2), 16);
const grn = parseInt(color.substr(3, 2), 16);
const blu = parseInt(color.substr(5, 2), 16);
const gray = red*0.3 + grn*0.6 + blu*0.1;
return gray < 110;
}
let gRadioButtonCounter = 1;
/**
* A full-screen control panel for configuring the emulator.
*/
export class SettingsPanel {
public onOpen: (() => void) | undefined;
public onClose: (() => void) | undefined;
public readonly panelType: PanelType;
private readonly trs80: Trs80;
private readonly panelNode: HTMLElement;
private readonly displayedOptions: DisplayedOption[] = [];
private readonly acceptButton: HTMLElement;
constructor(screenNode: HTMLElement, trs80: Trs80, panelType: PanelType) {
this.panelType = panelType;
this.trs80 = trs80;
// Make global CSS if necessary.
SettingsPanel.configureStyle();
screenNode.classList.add(gScreenNodeCssClass);
this.panelNode = document.createElement("div");
this.panelNode.classList.add(gPanelCssClass);
screenNode.appendChild(this.panelNode);
const div = document.createElement("div");
this.panelNode.appendChild(div);
for (const block of optionBlocksForPanelType(panelType)) {
const name = gCssPrefix + "-" + gRadioButtonCounter++;
const blockDiv = document.createElement("div");
div.appendChild(blockDiv);
const h1 = document.createElement("h1");
h1.innerText = block.title;
blockDiv.appendChild(h1);
const optionsDiv = document.createElement("div");
optionsDiv.classList.add(gOptionsClass);
blockDiv.appendChild(optionsDiv);
for (const option of block.options) {
const id = gCssPrefix + "-" + gRadioButtonCounter++;
const input = document.createElement("input");
input.id = id;
input.type = "radio";
input.name = name;
input.addEventListener("change", () => this.updateEnabledOptions());
optionsDiv.appendChild(input);
const label = document.createElement("label");
label.htmlFor = id;
if (option.label.startsWith("#")) {
// It's a color, show a swatch.
label.classList.add(gColorButtonClass);
label.style.backgroundColor = option.label;
if (isDarkColor(option.label)) {
label.classList.add(gDarkColorButtonClass);
}
} else {
label.innerText = option.label;
}
optionsDiv.appendChild(label);
this.displayedOptions.push(new DisplayedOption(input, block, option));
}
}
const buttonsDiv = document.createElement("div");
buttonsDiv.classList.add(gButtonsClass);
div.appendChild(buttonsDiv);
this.acceptButton = document.createElement("a");
this.acceptButton.classList.add(gAcceptButtonCssClass);
this.acceptButton.addEventListener("click", (event) => {
event.preventDefault();
this.accept();
});
buttonsDiv.appendChild(this.acceptButton);
this.configureAcceptButton(this.trs80.getConfig());
const cancelButton = document.createElement("a");
cancelButton.innerText = "Cancel";
cancelButton.addEventListener("click", (event) => {
event.preventDefault();
this.close();
});
buttonsDiv.appendChild(cancelButton);
}
/**
* Open the settings panel.
*/
public open(): void {
if (this.onOpen !== undefined) {
this.onOpen();
}
// Configure options.
for (const displayedOption of this.displayedOptions) {
displayedOption.input.checked = displayedOption.block.isChecked(displayedOption.option.value, this.trs80.getConfig());
}
this.updateEnabledOptions();
this.panelNode.classList.add(gShownCssClass);
}
/**
* Accept the changes, configure the machine, and close the dialog box.
*/
private accept(): void {
this.trs80.setConfig(this.getConfig());
this.close();
}
/**
* Close the settings panel.
*/
private close(): void {
this.panelNode.classList.remove(gShownCssClass);
if (this.onClose !== undefined) {
this.onClose();
}
}
/**
* Update which options are enabled based on the current selection.
*/
private updateEnabledOptions(): void {
const config = this.getConfig();
for (const displayedOption of this.displayedOptions) {
const enabled = displayedOption.block.updateConfig(displayedOption.option.value, config).isValid();
displayedOption.input.disabled = !enabled;
}
this.configureAcceptButton(config);
}
/**
* Set the accept button to be OK or Reboot.
*/
private configureAcceptButton(config: Config) {
if (config.needsReboot(this.trs80.getConfig())) {
this.acceptButton.classList.add(gRebootButtonCssClass);
this.acceptButton.innerText = "Reboot";
} else {
this.acceptButton.classList.remove(gRebootButtonCssClass);
this.acceptButton.innerText = "OK";
}
}
/**
* Make a new config from the user's currently selected options.
*/
private getConfig(): Config {
let config = this.trs80.getConfig();
for (const displayedOption of this.displayedOptions) {
if (displayedOption.input.checked) {
config = displayedOption.block.updateConfig(displayedOption.option.value, config);
}
}
return config;
}
/**
* Make a global stylesheet for all TRS-80 emulators on this page.
*/
private static configureStyle(): void {
const styleId = gCssPrefix;
if (document.getElementById(styleId) !== null) {
// Already created.
return;
}
const node = document.createElement("style");
node.id = styleId;
node.innerHTML = GLOBAL_CSS;
document.head.appendChild(node);
}
} | the_stack |
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js";
import * as msRest from "@azure/ms-rest-js";
export { BaseResource, CloudError };
/**
* Creator resource properties
*/
export interface CreatorProperties {
/**
* The state of the resource provisioning, terminal states: Succeeded, Failed, Canceled
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
/**
* The storage units to be allocated. Integer values from 1 to 100, inclusive.
*/
storageUnits: number;
}
/**
* An Azure resource which represents Maps Creator product and provides ability to manage private
* location data.
*/
export interface Creator extends BaseResource {
/**
* The Creator resource properties.
*/
properties: CreatorProperties;
}
/**
* The SKU of the Maps Account.
*/
export interface Sku {
/**
* The name of the SKU, in standard format (such as S0). Possible values include: 'S0', 'S1',
* 'G2'
*/
name: Name;
/**
* Gets the sku tier. This is based on the SKU name.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly tier?: string;
}
/**
* Metadata pertaining to creation and last modification of the resource.
*/
export interface SystemData {
/**
* The identity that created the resource.
*/
createdBy?: string;
/**
* The type of identity that created the resource. Possible values include: 'User',
* 'Application', 'ManagedIdentity', 'Key'
*/
createdByType?: CreatedByType;
/**
* The timestamp of resource creation (UTC).
*/
createdAt?: Date;
/**
* The identity that last modified the resource.
*/
lastModifiedBy?: string;
/**
* The type of identity that last modified the resource. Possible values include: 'User',
* 'Application', 'ManagedIdentity', 'Key'
*/
lastModifiedByType?: CreatedByType;
/**
* The timestamp of resource last modification (UTC)
*/
lastModifiedAt?: Date;
}
/**
* Additional Map account properties
*/
export interface MapsAccountProperties {
/**
* A unique identifier for the maps account
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly uniqueId?: string;
/**
* Allows toggle functionality on Azure Policy to disable Azure Maps local authentication
* support. This will disable Shared Keys authentication from any usage. Default value: false.
*/
disableLocalAuth?: boolean;
/**
* the state of the provisioning.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
}
/**
* An Azure resource which represents access to a suite of Maps REST APIs.
*/
export interface MapsAccount extends BaseResource {
/**
* The SKU of this account.
*/
sku: Sku;
/**
* Get or Set Kind property. Possible values include: 'Gen1', 'Gen2'. Default value: 'Gen1'.
*/
kind?: Kind;
/**
* The system meta data relating to this resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly systemData?: SystemData;
/**
* The map account properties.
*/
properties?: MapsAccountProperties;
}
/**
* Parameters used to update an existing Maps Account.
*/
export interface MapsAccountUpdateParameters {
/**
* Gets or sets a list of key value pairs that describe the resource. These tags can be used in
* viewing and grouping this resource (across resource groups). A maximum of 15 tags can be
* provided for a resource. Each tag must have a key no greater than 128 characters and value no
* greater than 256 characters.
*/
tags?: { [propertyName: string]: string };
/**
* Get or Set Kind property. Possible values include: 'Gen1', 'Gen2'. Default value: 'Gen1'.
*/
kind?: Kind;
/**
* The SKU of this account.
*/
sku?: Sku;
/**
* A unique identifier for the maps account
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly uniqueId?: string;
/**
* Allows toggle functionality on Azure Policy to disable Azure Maps local authentication
* support. This will disable Shared Keys authentication from any usage. Default value: false.
*/
disableLocalAuth?: boolean;
/**
* the state of the provisioning.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
}
/**
* Parameters used to update an existing Creator resource.
*/
export interface CreatorUpdateParameters {
/**
* Gets or sets a list of key value pairs that describe the resource. These tags can be used in
* viewing and grouping this resource (across resource groups). A maximum of 15 tags can be
* provided for a resource. Each tag must have a key no greater than 128 characters and value no
* greater than 256 characters.
*/
tags?: { [propertyName: string]: string };
/**
* The state of the resource provisioning, terminal states: Succeeded, Failed, Canceled
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
/**
* The storage units to be allocated. Integer values from 1 to 100, inclusive.
*/
storageUnits: number;
}
/**
* Whether the operation refers to the primary or secondary key.
*/
export interface MapsKeySpecification {
/**
* Whether the operation refers to the primary or secondary key. Possible values include:
* 'primary', 'secondary'
*/
keyType: KeyType;
}
/**
* The set of keys which can be used to access the Maps REST APIs. Two keys are provided for key
* rotation without interruption.
*/
export interface MapsAccountKeys {
/**
* The last updated date and time of the primary key.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly primaryKeyLastUpdated?: string;
/**
* The primary key for accessing the Maps REST APIs.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly primaryKey?: string;
/**
* The secondary key for accessing the Maps REST APIs.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly secondaryKey?: string;
/**
* The last updated date and time of the secondary key.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly secondaryKeyLastUpdated?: string;
}
/**
* Operation display payload
*/
export interface OperationDisplay {
/**
* Resource provider of the operation
*/
provider?: string;
/**
* Resource of the operation
*/
resource?: string;
/**
* Localized friendly name for the operation
*/
operation?: string;
/**
* Localized friendly description for the operation
*/
description?: string;
}
/**
* Dimension of map account, for example API Category, Api Name, Result Type, and Response Code.
*/
export interface Dimension {
/**
* Display name of dimension.
*/
name?: string;
/**
* Display name of dimension.
*/
displayName?: string;
}
/**
* Metric specification of operation.
*/
export interface MetricSpecification {
/**
* Name of metric specification.
*/
name?: string;
/**
* Display name of metric specification.
*/
displayName?: string;
/**
* Display description of metric specification.
*/
displayDescription?: string;
/**
* Unit could be Count.
*/
unit?: string;
/**
* Dimensions of map account.
*/
dimensions?: Dimension[];
/**
* Aggregation type could be Average.
*/
aggregationType?: string;
/**
* The property to decide fill gap with zero or not.
*/
fillGapWithZero?: boolean;
/**
* The category this metric specification belong to, could be Capacity.
*/
category?: string;
/**
* Account Resource Id.
*/
resourceIdDimensionNameOverride?: string;
}
/**
* One property of operation, include metric specifications.
*/
export interface ServiceSpecification {
/**
* Metric specifications of operation.
*/
metricSpecifications?: MetricSpecification[];
}
/**
* Operation detail payload
*/
export interface OperationDetail {
/**
* Name of the operation
*/
name?: string;
/**
* Indicates whether the operation is a data action
*/
isDataAction?: boolean;
/**
* Display of the operation
*/
display?: OperationDisplay;
/**
* Origin of the operation
*/
origin?: string;
/**
* One property of operation, include metric specifications.
*/
serviceSpecification?: ServiceSpecification;
}
/**
* Common fields that are returned in the response for all Azure Resource Manager resources
* @summary Resource
*/
export interface Resource extends BaseResource {
/**
* Fully qualified resource ID for the resource. Ex -
* /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* The name of the resource
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
* "Microsoft.Storage/storageAccounts"
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
}
/**
* The resource model definition for a Azure Resource Manager proxy resource. It will not have tags
* and a location
* @summary Proxy Resource
*/
export interface ProxyResource extends Resource {}
/**
* The resource model definition for an Azure Resource Manager resource with an etag.
* @summary Entity Resource
*/
export interface AzureEntityResource extends Resource {
/**
* Resource Etag.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly etag?: string;
}
/**
* The resource model definition for an Azure Resource Manager tracked top level resource which has
* 'tags' and a 'location'
* @summary Tracked Resource
*/
export interface TrackedResource extends Resource {
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
/**
* The geo-location where the resource lives
*/
location: string;
}
/**
* The resource management error additional info.
*/
export interface ErrorAdditionalInfo {
/**
* The additional info type.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
/**
* The additional info.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly info?: any;
}
/**
* The error detail.
*/
export interface ErrorDetail {
/**
* The error code.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly code?: string;
/**
* The error message.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly message?: string;
/**
* The error target.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly target?: string;
/**
* The error details.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly details?: ErrorDetail[];
/**
* The error additional info.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly additionalInfo?: ErrorAdditionalInfo[];
}
/**
* Common error response for all Azure Resource Manager APIs to return error details for failed
* operations. (This also follows the OData error response format.).
* @summary Error response
*/
export interface ErrorResponse {
/**
* The error object.
*/
error?: ErrorDetail;
}
/**
* An interface representing AzureMapsManagementClientOptions.
*/
export interface AzureMapsManagementClientOptions extends AzureServiceClientOptions {
baseUri?: string;
}
/**
* @interface
* A list of Maps Accounts.
* @extends Array<MapsAccount>
*/
export interface MapsAccounts extends Array<MapsAccount> {
/**
* URL client should use to fetch the next page (per server side paging).
* It's null for now, added for future use.
*/
nextLink?: string;
}
/**
* @interface
* The set of operations available for Maps.
* @extends Array<OperationDetail>
*/
export interface MapsOperations extends Array<OperationDetail> {
/**
* URL client should use to fetch the next page (per server side paging).
* It's null for now, added for future use.
*/
nextLink?: string;
}
/**
* @interface
* A list of Creator resources.
* @extends Array<Creator>
*/
export interface CreatorList extends Array<Creator> {
/**
* URL client should use to fetch the next page (per server side paging).
* It's null for now, added for future use.
*/
nextLink?: string;
}
/**
* Defines values for Name.
* Possible values include: 'S0', 'S1', 'G2'
* @readonly
* @enum {string}
*/
export type Name = "S0" | "S1" | "G2";
/**
* Defines values for Kind.
* Possible values include: 'Gen1', 'Gen2'
* @readonly
* @enum {string}
*/
export type Kind = "Gen1" | "Gen2";
/**
* Defines values for CreatedByType.
* Possible values include: 'User', 'Application', 'ManagedIdentity', 'Key'
* @readonly
* @enum {string}
*/
export type CreatedByType = "User" | "Application" | "ManagedIdentity" | "Key";
/**
* Defines values for KeyType.
* Possible values include: 'primary', 'secondary'
* @readonly
* @enum {string}
*/
export type KeyType = "primary" | "secondary";
/**
* Contains response data for the createOrUpdate operation.
*/
export type AccountsCreateOrUpdateResponse = MapsAccount & {
/**
* 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: MapsAccount;
};
};
/**
* Contains response data for the update operation.
*/
export type AccountsUpdateResponse = MapsAccount & {
/**
* 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: MapsAccount;
};
};
/**
* Contains response data for the get operation.
*/
export type AccountsGetResponse = MapsAccount & {
/**
* 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: MapsAccount;
};
};
/**
* Contains response data for the listByResourceGroup operation.
*/
export type AccountsListByResourceGroupResponse = MapsAccounts & {
/**
* 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: MapsAccounts;
};
};
/**
* Contains response data for the listBySubscription operation.
*/
export type AccountsListBySubscriptionResponse = MapsAccounts & {
/**
* 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: MapsAccounts;
};
};
/**
* Contains response data for the listKeys operation.
*/
export type AccountsListKeysResponse = MapsAccountKeys & {
/**
* 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: MapsAccountKeys;
};
};
/**
* Contains response data for the regenerateKeys operation.
*/
export type AccountsRegenerateKeysResponse = MapsAccountKeys & {
/**
* 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: MapsAccountKeys;
};
};
/**
* Contains response data for the listByResourceGroupNext operation.
*/
export type AccountsListByResourceGroupNextResponse = MapsAccounts & {
/**
* 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: MapsAccounts;
};
};
/**
* Contains response data for the listBySubscriptionNext operation.
*/
export type AccountsListBySubscriptionNextResponse = MapsAccounts & {
/**
* 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: MapsAccounts;
};
};
/**
* Contains response data for the listOperations operation.
*/
export type MapsListOperationsResponse = MapsOperations & {
/**
* 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: MapsOperations;
};
};
/**
* Contains response data for the listOperationsNext operation.
*/
export type MapsListOperationsNextResponse = MapsOperations & {
/**
* 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: MapsOperations;
};
};
/**
* Contains response data for the listByAccount operation.
*/
export type CreatorsListByAccountResponse = CreatorList & {
/**
* 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: CreatorList;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type CreatorsCreateOrUpdateResponse = Creator & {
/**
* 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: Creator;
};
};
/**
* Contains response data for the update operation.
*/
export type CreatorsUpdateResponse = Creator & {
/**
* 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: Creator;
};
};
/**
* Contains response data for the get operation.
*/
export type CreatorsGetResponse = Creator & {
/**
* 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: Creator;
};
};
/**
* Contains response data for the listByAccountNext operation.
*/
export type CreatorsListByAccountNextResponse = CreatorList & {
/**
* 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: CreatorList;
};
}; | the_stack |
import * as R from 'ramda';
import {Size, RGBColor} from '@compiler/core/types';
import {VGA} from './VGA';
import {VGAFontPack} from './VGAConstants';
/**
* @see {@link https://files.osdev.org/mirrors/geezer/osd/graphics/modes.c}
*/
/**
* Due to function size it is here
*
* @export
* @param {VGA} vga
* @param {number[]} preset
*/
export function assignPresetToVGA(vga: VGA, preset: number[]): void {
const {
externalRegs,
crtcRegs,
attrRegs,
graphicsRegs: gRegs,
sequencerRegs: seqRegs,
} = vga;
let regIndex: number = 0;
const nextReg = () => preset[regIndex++];
/* MISC */
externalRegs.miscReg.number = nextReg();
/* SEQ */
seqRegs.resetReg.number = nextReg();
seqRegs.clockingModeReg.number = nextReg();
seqRegs.mapMaskReg.number = nextReg();
seqRegs.charMapSelectReg.number = nextReg();
seqRegs.memModeReg.number = nextReg();
/* CRTC */
crtcRegs.horizontalTotalReg = nextReg();
crtcRegs.endHorizontalDisplayReg = nextReg();
crtcRegs.startHorizontalBlankingReg = nextReg();
crtcRegs.endHorizontalBlankingReg.number = nextReg();
crtcRegs.startHorizontalRetraceReg = nextReg();
crtcRegs.endHorizontalRetraceReg.number = nextReg();
crtcRegs.verticalTotalReg = nextReg();
crtcRegs.overflowReg.number = nextReg();
crtcRegs.presetRowScanReg.number = nextReg();
crtcRegs.maxScanLineReg.number = nextReg();
crtcRegs.cursorStartReg.number = nextReg();
crtcRegs.cursorEndReg.number = nextReg();
crtcRegs.startAddress.high = nextReg();
crtcRegs.startAddress.low = nextReg();
crtcRegs.cursorLocation.high = nextReg();
crtcRegs.cursorLocation.low = nextReg();
crtcRegs.verticalRetraceStartReg = nextReg();
crtcRegs.verticalRetraceEndReg = nextReg();
crtcRegs.verticalDisplayEndReg = nextReg();
crtcRegs.offsetReg = nextReg();
crtcRegs.underlineLocation.number = nextReg();
crtcRegs.startVerticalBlankingReg = nextReg();
crtcRegs.endVerticalBlankingReg = nextReg();
crtcRegs.crtcModeControlReg.number = nextReg();
crtcRegs.lineCompareReg = nextReg();
/* GC */
gRegs.setResetReg.number = nextReg();
gRegs.enableSetResetReg.number = nextReg();
gRegs.colorCompareReg.number = nextReg();
gRegs.dataRotateReg.number = nextReg();
gRegs.readMapSelectReg.number = nextReg();
gRegs.graphicsModeReg.number = nextReg();
gRegs.miscGraphicsReg.number = nextReg();
gRegs.colorDontCareReg.number = nextReg();
gRegs.colorBitmaskReg.number = nextReg();
/* AC */
attrRegs.paletteRegs = R.times(nextReg, 16);
attrRegs.attrModeControlReg.number = nextReg();
attrRegs.overscanColorReg = nextReg();
attrRegs.colorPlaneEnableReg.number = nextReg();
attrRegs.horizontalPixelPanningReg.number = nextReg();
attrRegs.colorSelectReg.number = nextReg();
}
/**
* See vgaColorsScrapper.js, it might be not accurate
*/
export const VGA256Palette: RGBColor[] = R.map(
RGBColor.fromNumber,
[
0x000000, 0x0000aa, 0x00aa00, 0x00aaaa, 0xaa0000, 0xaa00aa, 0xaa5500, 0xaaaaaa, 0x555555, 0x5555ff,
0x55ff55, 0x55ffff, 0xff5555, 0xff55ff, 0xffff55, 0xffffff, 0x000000, 0x101010, 0x202020, 0x353535,
0x454545, 0x555555, 0x656565, 0x757575, 0x8a8a8a, 0x9a9a9a, 0xaaaaaa, 0xbababa, 0xcacaca, 0xdfdfdf,
0xefefef, 0xffffff, 0x0000ff, 0x4100ff, 0x8200ff, 0xbe00ff, 0xff00ff, 0xff00be, 0xff0082, 0xff0041,
0xff0000, 0xff4100, 0xff8200, 0xffbe00, 0xffff00, 0xbeff00, 0x82ff00, 0x41ff00, 0x00ff00, 0x00ff41,
0x00ff82, 0x00ffbe, 0x00ffff, 0x00beff, 0x0082ff, 0x0041ff, 0x8282ff, 0x9e82ff, 0xbe82ff, 0xdf82ff,
0xff82ff, 0xff82df, 0xff82be, 0xff829e, 0xff8282, 0xff9e82, 0xffbe82, 0xffdf82, 0xffff82, 0xdfff82,
0xbeff82, 0x9eff82, 0x82ff82, 0x82ff9e, 0x82ffbe, 0x82ffdf, 0x82ffff, 0x82dfff, 0x82beff, 0x829eff,
0xbabaff, 0xcabaff, 0xdfbaff, 0xefbaff, 0xffbaff, 0xffbaef, 0xffbadf, 0xffbaca, 0xffbaba, 0xffcaba,
0xffdfba, 0xffefba, 0xffffba, 0xefffba, 0xdfffba, 0xcaffba, 0xbaffba, 0xbaffca, 0xbaffdf, 0xbaffef,
0xbaffff, 0xbaefff, 0xbadfff, 0xbacaff, 0x000071, 0x1c0071, 0x390071, 0x550071, 0x710071, 0x710055,
0x710039, 0x71001c, 0x710000, 0x711c00, 0x713900, 0x715500, 0x717100, 0x557100, 0x397100, 0x1c7100,
0x007100, 0x00711c, 0x007139, 0x007155, 0x007171, 0x005571, 0x003971, 0x001c71, 0x393971, 0x453971,
0x553971, 0x613971, 0x713971, 0x713961, 0x713955, 0x713945, 0x713939, 0x714539, 0x715539, 0x716139,
0x717139, 0x617139, 0x557139, 0x457139, 0x397139, 0x397145, 0x397155, 0x397161, 0x397171, 0x396171,
0x395571, 0x394571, 0x515171, 0x595171, 0x615171, 0x695171, 0x715171, 0x715169, 0x715161, 0x715159,
0x715151, 0x715951, 0x716151, 0x716951, 0x717151, 0x697151, 0x617151, 0x597151, 0x517151, 0x517159,
0x517161, 0x517169, 0x517171, 0x516971, 0x516171, 0x515971, 0x000041, 0x100041, 0x200041, 0x310041,
0x410041, 0x410031, 0x410020, 0x410010, 0x410000, 0x411000, 0x412000, 0x413100, 0x414100, 0x314100,
0x204100, 0x104100, 0x004100, 0x004110, 0x004120, 0x004131, 0x004141, 0x003141, 0x002041, 0x001041,
0x202041, 0x282041, 0x312041, 0x392041, 0x412041, 0x412039, 0x412031, 0x412028, 0x412020, 0x412820,
0x413120, 0x413920, 0x414120, 0x394120, 0x314120, 0x284120, 0x204120, 0x204128, 0x204131, 0x204139,
0x204141, 0x203941, 0x203141, 0x202841, 0x2d2d41, 0x312d41, 0x352d41, 0x3d2d41, 0x412d41, 0x412d3d,
0x412d35, 0x412d31, 0x412d2d, 0x41312d, 0x41352d, 0x413d2d, 0x41412d, 0x3d412d, 0x35412d, 0x31412d,
0x2d412d, 0x2d4131, 0x2d4135, 0x2d413d, 0x2d4141, 0x2d3d41, 0x2d3541, 0x2d3141, 0x000000, 0x000000,
0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000,
],
);
export const VGA_TEXT_MODES_PRESET = {
'40x25': [
/* MISC */
0x67,
/* SEQ */
0x03, 0x08, 0x03, 0x00, 0x02,
/* CRTC */
0x2D, 0x27, 0x28, 0x90, 0x2B, 0xA0, 0xBF, 0x1F,
0x00, 0x4F, 0x0D, 0x0E, 0x00, 0x00, 0x00, 0xA0,
0x9C, 0x8E, 0x8F, 0x14, 0x1F, 0x96, 0xB9, 0xA3,
0xFF,
/* GC */
0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00,
0xFF,
/* AC */
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x0C, 0x00, 0x0F, 0x08, 0x00,
],
'40x50': [
/* MISC */
0x67,
/* SEQ */
0x03, 0x08, 0x03, 0x00, 0x02,
/* CRTC */
0x2D, 0x27, 0x28, 0x90, 0x2B, 0xA0, 0xBF, 0x1F,
0x00, 0x47, 0x06, 0x07, 0x00, 0x00, 0x04, 0x60,
0x9C, 0x8E, 0x8F, 0x14, 0x1F, 0x96, 0xB9, 0xA3,
0xFF,
/* GC */
0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00,
0xFF,
/* AC */
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x0C, 0x00, 0x0F, 0x08, 0x00,
],
'80x25': [
/* MISC */
0x67,
/* SEQ */
0x03, 0x00, 0x03, 0x00, 0x02,
/* CRTC */
0x5F, 0x4F, 0x50, 0x82, 0x55, 0x81, 0xBF, 0x1F,
0x00, 0x4F, 0x0D, 0x0E, 0x00, 0x00, 0x00, 0x50,
0x9C, 0x0E, 0x8F, 0x28, 0x1F, 0x96, 0xB9, 0xA3,
0xFF,
/* GC */
0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00,
0xFF,
/* AC */
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x0C, 0x00, 0x0F, 0x08, 0x00,
],
'80x50': [
/* MISC */
0x67,
/* SEQ */
0x03, 0x00, 0x03, 0x00, 0x02,
/* CRTC */
0x5F, 0x4F, 0x50, 0x82, 0x55, 0x81, 0xBF, 0x1F,
0x00, 0x47, 0x06, 0x07, 0x00, 0x00, 0x01, 0x40,
0x9C, 0x8E, 0x8F, 0x28, 0x1F, 0x96, 0xB9, 0xA3,
0xFF,
/* GC */
0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00,
0xFF,
/* AC */
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x0C, 0x00, 0x0F, 0x08, 0x00,
],
'90x30': [
/* MISC */
0xE7,
/* SEQ */
0x03, 0x01, 0x03, 0x00, 0x02,
/* CRTC */
0x6B, 0x59, 0x5A, 0x82, 0x60, 0x8D, 0x0B, 0x3E,
0x00, 0x4F, 0x0D, 0x0E, 0x00, 0x00, 0x00, 0x00,
0xEA, 0x0C, 0xDF, 0x2D, 0x10, 0xE8, 0x05, 0xA3,
0xFF,
/* GC */
0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00,
0xFF,
/* AC */
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x0C, 0x00, 0x0F, 0x08, 0x00,
],
'90x60': [
/* MISC */
0xE7,
/* SEQ */
0x03, 0x01, 0x03, 0x00, 0x02,
/* CRTC */
0x6B, 0x59, 0x5A, 0x82, 0x60, 0x8D, 0x0B, 0x3E,
0x00, 0x47, 0x06, 0x07, 0x00, 0x00, 0x00, 0x00,
0xEA, 0x0C, 0xDF, 0x2D, 0x08, 0xE8, 0x05, 0xA3,
0xFF,
/* GC */
0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00,
0xFF,
/* AC */
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x0C, 0x00, 0x0F, 0x08, 0x00,
],
};
export const VGA_GRAPHICS_MODES_PRESET = {
'640x480x2': [
/* MISC */
0xE3,
/* SEQ */
0x03, 0x01, 0x0F, 0x00, 0x06,
/* CRTC */
0x5F, 0x4F, 0x50, 0x82, 0x54, 0x80, 0x0B, 0x3E,
0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xEA, 0x0C, 0xDF, 0x28, 0x00, 0xE7, 0x04, 0xE3,
0xFF,
/* GC */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x0F,
0xFF,
/* AC */
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x01, 0x00, 0x0F, 0x00, 0x00,
],
/**
* NOTE: the mode described by g_320x200x4[]
* is different from BIOS mode 05h in two ways:
* - Framebuffer is at A000:0000 instead of B800:0000
* - Framebuffer is linear (no screwy line-by-line CGA addressing)
*/
'320x200x4': [
/* MISC */
0x63,
/* SEQ */
0x03, 0x09, 0x03, 0x00, 0x02,
/* CRTC */
0x2D, 0x27, 0x28, 0x90, 0x2B, 0x80, 0xBF, 0x1F,
0x00, 0x41, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x9C, 0x0E, 0x8F, 0x14, 0x00, 0x96, 0xB9, 0xA3,
0xFF,
/* GC */
0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x02, 0x00,
0xFF,
/* AC */
0x00, 0x13, 0x15, 0x17, 0x02, 0x04, 0x06, 0x07,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x01, 0x00, 0x03, 0x00, 0x00,
],
'640x480x16': [
/* MISC */
0xE3,
/* SEQ */
0x03, 0x01, 0x08, 0x00, 0x06,
/* CRTC */
0x5F, 0x4F, 0x50, 0x82, 0x54, 0x80, 0x0B, 0x3E,
0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xEA, 0x0C, 0xDF, 0x28, 0x00, 0xE7, 0x04, 0xE3,
0xFF,
/* GC */
0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x05, 0x0F,
0xFF,
/* AC */
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x01, 0x00, 0x0F, 0x00, 0x00,
],
'720x480x16': [
/* MISC */
0xE7,
/* SEQ */
0x03, 0x01, 0x08, 0x00, 0x06,
/* CRTC */
0x6B, 0x59, 0x5A, 0x82, 0x60, 0x8D, 0x0B, 0x3E,
0x00, 0x40, 0x06, 0x07, 0x00, 0x00, 0x00, 0x00,
0xEA, 0x0C, 0xDF, 0x2D, 0x08, 0xE8, 0x05, 0xE3,
0xFF,
/* GC */
0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x05, 0x0F,
0xFF,
/* AC */
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x01, 0x00, 0x0F, 0x00, 0x00,
],
'320x200x256': [
/* MISC */
0x63,
/* SEQ */
0x03, 0x01, 0x0F, 0x00, 0x0E,
/* CRTC */
0x5F, 0x4F, 0x50, 0x82, 0x54, 0x80, 0xBF, 0x1F,
0x00, 0x41, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x9C, 0x0E, 0x8F, 0x28, 0x40, 0x96, 0xB9, 0xA3,
0xFF,
/* GC */
0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x05, 0x0F,
0xFF,
/* AC */
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x41, 0x00, 0x0F, 0x00, 0x00,
],
'320x200x26_modex': [
/* MISC */
0x63,
/* SEQ */
0x03, 0x01, 0x0F, 0x00, 0x06,
/* CRTC */
0x5F, 0x4F, 0x50, 0x82, 0x54, 0x80, 0xBF, 0x1F,
0x00, 0x41, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x9C, 0x0E, 0x8F, 0x28, 0x00, 0x96, 0xB9, 0xE3,
0xFF,
/* GC */
0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x05, 0x0F,
0xFF,
/* AC */
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x41, 0x00, 0x0F, 0x00, 0x00,
],
};
/* FONTS */
export const VGA_8X8_FONT = new VGAFontPack(
new Size(8, 8),
[
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x7E, 0x81, 0xA5, 0x81, 0xBD, 0x99, 0x81, 0x7E,
0x7E, 0xFF, 0xDB, 0xFF, 0xC3, 0xE7, 0xFF, 0x7E,
0x6C, 0xFE, 0xFE, 0xFE, 0x7C, 0x38, 0x10, 0x00,
0x10, 0x38, 0x7C, 0xFE, 0x7C, 0x38, 0x10, 0x00,
0x38, 0x7C, 0x38, 0xFE, 0xFE, 0x92, 0x10, 0x7C,
0x00, 0x10, 0x38, 0x7C, 0xFE, 0x7C, 0x38, 0x7C,
0x00, 0x00, 0x18, 0x3C, 0x3C, 0x18, 0x00, 0x00,
0xFF, 0xFF, 0xE7, 0xC3, 0xC3, 0xE7, 0xFF, 0xFF,
0x00, 0x3C, 0x66, 0x42, 0x42, 0x66, 0x3C, 0x00,
0xFF, 0xC3, 0x99, 0xBD, 0xBD, 0x99, 0xC3, 0xFF,
0x0F, 0x07, 0x0F, 0x7D, 0xCC, 0xCC, 0xCC, 0x78,
0x3C, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x7E, 0x18,
0x3F, 0x33, 0x3F, 0x30, 0x30, 0x70, 0xF0, 0xE0,
0x7F, 0x63, 0x7F, 0x63, 0x63, 0x67, 0xE6, 0xC0,
0x99, 0x5A, 0x3C, 0xE7, 0xE7, 0x3C, 0x5A, 0x99,
0x80, 0xE0, 0xF8, 0xFE, 0xF8, 0xE0, 0x80, 0x00,
0x02, 0x0E, 0x3E, 0xFE, 0x3E, 0x0E, 0x02, 0x00,
0x18, 0x3C, 0x7E, 0x18, 0x18, 0x7E, 0x3C, 0x18,
0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x66, 0x00,
0x7F, 0xDB, 0xDB, 0x7B, 0x1B, 0x1B, 0x1B, 0x00,
0x3E, 0x63, 0x38, 0x6C, 0x6C, 0x38, 0x86, 0xFC,
0x00, 0x00, 0x00, 0x00, 0x7E, 0x7E, 0x7E, 0x00,
0x18, 0x3C, 0x7E, 0x18, 0x7E, 0x3C, 0x18, 0xFF,
0x18, 0x3C, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x00,
0x18, 0x18, 0x18, 0x18, 0x7E, 0x3C, 0x18, 0x00,
0x00, 0x18, 0x0C, 0xFE, 0x0C, 0x18, 0x00, 0x00,
0x00, 0x30, 0x60, 0xFE, 0x60, 0x30, 0x00, 0x00,
0x00, 0x00, 0xC0, 0xC0, 0xC0, 0xFE, 0x00, 0x00,
0x00, 0x24, 0x66, 0xFF, 0x66, 0x24, 0x00, 0x00,
0x00, 0x18, 0x3C, 0x7E, 0xFF, 0xFF, 0x00, 0x00,
0x00, 0xFF, 0xFF, 0x7E, 0x3C, 0x18, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x18, 0x3C, 0x3C, 0x18, 0x18, 0x00, 0x18, 0x00,
0x6C, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00,
0x6C, 0x6C, 0xFE, 0x6C, 0xFE, 0x6C, 0x6C, 0x00,
0x18, 0x7E, 0xC0, 0x7C, 0x06, 0xFC, 0x18, 0x00,
0x00, 0xC6, 0xCC, 0x18, 0x30, 0x66, 0xC6, 0x00,
0x38, 0x6C, 0x38, 0x76, 0xDC, 0xCC, 0x76, 0x00,
0x30, 0x30, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00,
0x18, 0x30, 0x60, 0x60, 0x60, 0x30, 0x18, 0x00,
0x60, 0x30, 0x18, 0x18, 0x18, 0x30, 0x60, 0x00,
0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00,
0x00, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x30,
0x00, 0x00, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00,
0x06, 0x0C, 0x18, 0x30, 0x60, 0xC0, 0x80, 0x00,
0x7C, 0xCE, 0xDE, 0xF6, 0xE6, 0xC6, 0x7C, 0x00,
0x30, 0x70, 0x30, 0x30, 0x30, 0x30, 0xFC, 0x00,
0x78, 0xCC, 0x0C, 0x38, 0x60, 0xCC, 0xFC, 0x00,
0x78, 0xCC, 0x0C, 0x38, 0x0C, 0xCC, 0x78, 0x00,
0x1C, 0x3C, 0x6C, 0xCC, 0xFE, 0x0C, 0x1E, 0x00,
0xFC, 0xC0, 0xF8, 0x0C, 0x0C, 0xCC, 0x78, 0x00,
0x38, 0x60, 0xC0, 0xF8, 0xCC, 0xCC, 0x78, 0x00,
0xFC, 0xCC, 0x0C, 0x18, 0x30, 0x30, 0x30, 0x00,
0x78, 0xCC, 0xCC, 0x78, 0xCC, 0xCC, 0x78, 0x00,
0x78, 0xCC, 0xCC, 0x7C, 0x0C, 0x18, 0x70, 0x00,
0x00, 0x18, 0x18, 0x00, 0x00, 0x18, 0x18, 0x00,
0x00, 0x18, 0x18, 0x00, 0x00, 0x18, 0x18, 0x30,
0x18, 0x30, 0x60, 0xC0, 0x60, 0x30, 0x18, 0x00,
0x00, 0x00, 0x7E, 0x00, 0x7E, 0x00, 0x00, 0x00,
0x60, 0x30, 0x18, 0x0C, 0x18, 0x30, 0x60, 0x00,
0x3C, 0x66, 0x0C, 0x18, 0x18, 0x00, 0x18, 0x00,
0x7C, 0xC6, 0xDE, 0xDE, 0xDC, 0xC0, 0x7C, 0x00,
0x30, 0x78, 0xCC, 0xCC, 0xFC, 0xCC, 0xCC, 0x00,
0xFC, 0x66, 0x66, 0x7C, 0x66, 0x66, 0xFC, 0x00,
0x3C, 0x66, 0xC0, 0xC0, 0xC0, 0x66, 0x3C, 0x00,
0xF8, 0x6C, 0x66, 0x66, 0x66, 0x6C, 0xF8, 0x00,
0xFE, 0x62, 0x68, 0x78, 0x68, 0x62, 0xFE, 0x00,
0xFE, 0x62, 0x68, 0x78, 0x68, 0x60, 0xF0, 0x00,
0x3C, 0x66, 0xC0, 0xC0, 0xCE, 0x66, 0x3A, 0x00,
0xCC, 0xCC, 0xCC, 0xFC, 0xCC, 0xCC, 0xCC, 0x00,
0x78, 0x30, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00,
0x1E, 0x0C, 0x0C, 0x0C, 0xCC, 0xCC, 0x78, 0x00,
0xE6, 0x66, 0x6C, 0x78, 0x6C, 0x66, 0xE6, 0x00,
0xF0, 0x60, 0x60, 0x60, 0x62, 0x66, 0xFE, 0x00,
0xC6, 0xEE, 0xFE, 0xFE, 0xD6, 0xC6, 0xC6, 0x00,
0xC6, 0xE6, 0xF6, 0xDE, 0xCE, 0xC6, 0xC6, 0x00,
0x38, 0x6C, 0xC6, 0xC6, 0xC6, 0x6C, 0x38, 0x00,
0xFC, 0x66, 0x66, 0x7C, 0x60, 0x60, 0xF0, 0x00,
0x7C, 0xC6, 0xC6, 0xC6, 0xD6, 0x7C, 0x0E, 0x00,
0xFC, 0x66, 0x66, 0x7C, 0x6C, 0x66, 0xE6, 0x00,
0x7C, 0xC6, 0xE0, 0x78, 0x0E, 0xC6, 0x7C, 0x00,
0xFC, 0xB4, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00,
0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xFC, 0x00,
0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x78, 0x30, 0x00,
0xC6, 0xC6, 0xC6, 0xC6, 0xD6, 0xFE, 0x6C, 0x00,
0xC6, 0xC6, 0x6C, 0x38, 0x6C, 0xC6, 0xC6, 0x00,
0xCC, 0xCC, 0xCC, 0x78, 0x30, 0x30, 0x78, 0x00,
0xFE, 0xC6, 0x8C, 0x18, 0x32, 0x66, 0xFE, 0x00,
0x78, 0x60, 0x60, 0x60, 0x60, 0x60, 0x78, 0x00,
0xC0, 0x60, 0x30, 0x18, 0x0C, 0x06, 0x02, 0x00,
0x78, 0x18, 0x18, 0x18, 0x18, 0x18, 0x78, 0x00,
0x10, 0x38, 0x6C, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF,
0x30, 0x30, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0x76, 0x00,
0xE0, 0x60, 0x60, 0x7C, 0x66, 0x66, 0xDC, 0x00,
0x00, 0x00, 0x78, 0xCC, 0xC0, 0xCC, 0x78, 0x00,
0x1C, 0x0C, 0x0C, 0x7C, 0xCC, 0xCC, 0x76, 0x00,
0x00, 0x00, 0x78, 0xCC, 0xFC, 0xC0, 0x78, 0x00,
0x38, 0x6C, 0x64, 0xF0, 0x60, 0x60, 0xF0, 0x00,
0x00, 0x00, 0x76, 0xCC, 0xCC, 0x7C, 0x0C, 0xF8,
0xE0, 0x60, 0x6C, 0x76, 0x66, 0x66, 0xE6, 0x00,
0x30, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00,
0x0C, 0x00, 0x1C, 0x0C, 0x0C, 0xCC, 0xCC, 0x78,
0xE0, 0x60, 0x66, 0x6C, 0x78, 0x6C, 0xE6, 0x00,
0x70, 0x30, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00,
0x00, 0x00, 0xCC, 0xFE, 0xFE, 0xD6, 0xD6, 0x00,
0x00, 0x00, 0xB8, 0xCC, 0xCC, 0xCC, 0xCC, 0x00,
0x00, 0x00, 0x78, 0xCC, 0xCC, 0xCC, 0x78, 0x00,
0x00, 0x00, 0xDC, 0x66, 0x66, 0x7C, 0x60, 0xF0,
0x00, 0x00, 0x76, 0xCC, 0xCC, 0x7C, 0x0C, 0x1E,
0x00, 0x00, 0xDC, 0x76, 0x62, 0x60, 0xF0, 0x00,
0x00, 0x00, 0x7C, 0xC0, 0x70, 0x1C, 0xF8, 0x00,
0x10, 0x30, 0xFC, 0x30, 0x30, 0x34, 0x18, 0x00,
0x00, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00,
0x00, 0x00, 0xCC, 0xCC, 0xCC, 0x78, 0x30, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0xD6, 0xFE, 0x6C, 0x00,
0x00, 0x00, 0xC6, 0x6C, 0x38, 0x6C, 0xC6, 0x00,
0x00, 0x00, 0xCC, 0xCC, 0xCC, 0x7C, 0x0C, 0xF8,
0x00, 0x00, 0xFC, 0x98, 0x30, 0x64, 0xFC, 0x00,
0x1C, 0x30, 0x30, 0xE0, 0x30, 0x30, 0x1C, 0x00,
0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x00,
0xE0, 0x30, 0x30, 0x1C, 0x30, 0x30, 0xE0, 0x00,
0x76, 0xDC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x10, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0x00,
0x7C, 0xC6, 0xC0, 0xC6, 0x7C, 0x0C, 0x06, 0x7C,
0x00, 0xCC, 0x00, 0xCC, 0xCC, 0xCC, 0x76, 0x00,
0x1C, 0x00, 0x78, 0xCC, 0xFC, 0xC0, 0x78, 0x00,
0x7E, 0x81, 0x3C, 0x06, 0x3E, 0x66, 0x3B, 0x00,
0xCC, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0x76, 0x00,
0xE0, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0x76, 0x00,
0x30, 0x30, 0x78, 0x0C, 0x7C, 0xCC, 0x76, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0xC0, 0x78, 0x0C, 0x38,
0x7E, 0x81, 0x3C, 0x66, 0x7E, 0x60, 0x3C, 0x00,
0xCC, 0x00, 0x78, 0xCC, 0xFC, 0xC0, 0x78, 0x00,
0xE0, 0x00, 0x78, 0xCC, 0xFC, 0xC0, 0x78, 0x00,
0xCC, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00,
0x7C, 0x82, 0x38, 0x18, 0x18, 0x18, 0x3C, 0x00,
0xE0, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00,
0xC6, 0x10, 0x7C, 0xC6, 0xFE, 0xC6, 0xC6, 0x00,
0x30, 0x30, 0x00, 0x78, 0xCC, 0xFC, 0xCC, 0x00,
0x1C, 0x00, 0xFC, 0x60, 0x78, 0x60, 0xFC, 0x00,
0x00, 0x00, 0x7F, 0x0C, 0x7F, 0xCC, 0x7F, 0x00,
0x3E, 0x6C, 0xCC, 0xFE, 0xCC, 0xCC, 0xCE, 0x00,
0x78, 0x84, 0x00, 0x78, 0xCC, 0xCC, 0x78, 0x00,
0x00, 0xCC, 0x00, 0x78, 0xCC, 0xCC, 0x78, 0x00,
0x00, 0xE0, 0x00, 0x78, 0xCC, 0xCC, 0x78, 0x00,
0x78, 0x84, 0x00, 0xCC, 0xCC, 0xCC, 0x76, 0x00,
0x00, 0xE0, 0x00, 0xCC, 0xCC, 0xCC, 0x76, 0x00,
0x00, 0xCC, 0x00, 0xCC, 0xCC, 0x7C, 0x0C, 0xF8,
0xC3, 0x18, 0x3C, 0x66, 0x66, 0x3C, 0x18, 0x00,
0xCC, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0x78, 0x00,
0x18, 0x18, 0x7E, 0xC0, 0xC0, 0x7E, 0x18, 0x18,
0x38, 0x6C, 0x64, 0xF0, 0x60, 0xE6, 0xFC, 0x00,
0xCC, 0xCC, 0x78, 0x30, 0xFC, 0x30, 0xFC, 0x30,
0xF8, 0xCC, 0xCC, 0xFA, 0xC6, 0xCF, 0xC6, 0xC3,
0x0E, 0x1B, 0x18, 0x3C, 0x18, 0x18, 0xD8, 0x70,
0x1C, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0x76, 0x00,
0x38, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00,
0x00, 0x1C, 0x00, 0x78, 0xCC, 0xCC, 0x78, 0x00,
0x00, 0x1C, 0x00, 0xCC, 0xCC, 0xCC, 0x76, 0x00,
0x00, 0xF8, 0x00, 0xB8, 0xCC, 0xCC, 0xCC, 0x00,
0xFC, 0x00, 0xCC, 0xEC, 0xFC, 0xDC, 0xCC, 0x00,
0x3C, 0x6C, 0x6C, 0x3E, 0x00, 0x7E, 0x00, 0x00,
0x38, 0x6C, 0x6C, 0x38, 0x00, 0x7C, 0x00, 0x00,
0x18, 0x00, 0x18, 0x18, 0x30, 0x66, 0x3C, 0x00,
0x00, 0x00, 0x00, 0xFC, 0xC0, 0xC0, 0x00, 0x00,
0x00, 0x00, 0x00, 0xFC, 0x0C, 0x0C, 0x00, 0x00,
0xC6, 0xCC, 0xD8, 0x36, 0x6B, 0xC2, 0x84, 0x0F,
0xC3, 0xC6, 0xCC, 0xDB, 0x37, 0x6D, 0xCF, 0x03,
0x18, 0x00, 0x18, 0x18, 0x3C, 0x3C, 0x18, 0x00,
0x00, 0x33, 0x66, 0xCC, 0x66, 0x33, 0x00, 0x00,
0x00, 0xCC, 0x66, 0x33, 0x66, 0xCC, 0x00, 0x00,
0x22, 0x88, 0x22, 0x88, 0x22, 0x88, 0x22, 0x88,
0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA,
0xDB, 0xF6, 0xDB, 0x6F, 0xDB, 0x7E, 0xD7, 0xED,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0xF8, 0x18, 0x18, 0x18,
0x18, 0x18, 0xF8, 0x18, 0xF8, 0x18, 0x18, 0x18,
0x36, 0x36, 0x36, 0x36, 0xF6, 0x36, 0x36, 0x36,
0x00, 0x00, 0x00, 0x00, 0xFE, 0x36, 0x36, 0x36,
0x00, 0x00, 0xF8, 0x18, 0xF8, 0x18, 0x18, 0x18,
0x36, 0x36, 0xF6, 0x06, 0xF6, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x00, 0x00, 0xFE, 0x06, 0xF6, 0x36, 0x36, 0x36,
0x36, 0x36, 0xF6, 0x06, 0xFE, 0x00, 0x00, 0x00,
0x36, 0x36, 0x36, 0x36, 0xFE, 0x00, 0x00, 0x00,
0x18, 0x18, 0xF8, 0x18, 0xF8, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xF8, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x1F, 0x00, 0x00, 0x00,
0x18, 0x18, 0x18, 0x18, 0xFF, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xFF, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x1F, 0x18, 0x18, 0x18,
0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00,
0x18, 0x18, 0x18, 0x18, 0xFF, 0x18, 0x18, 0x18,
0x18, 0x18, 0x1F, 0x18, 0x1F, 0x18, 0x18, 0x18,
0x36, 0x36, 0x36, 0x36, 0x37, 0x36, 0x36, 0x36,
0x36, 0x36, 0x37, 0x30, 0x3F, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3F, 0x30, 0x37, 0x36, 0x36, 0x36,
0x36, 0x36, 0xF7, 0x00, 0xFF, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFF, 0x00, 0xF7, 0x36, 0x36, 0x36,
0x36, 0x36, 0x37, 0x30, 0x37, 0x36, 0x36, 0x36,
0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00,
0x36, 0x36, 0xF7, 0x00, 0xF7, 0x36, 0x36, 0x36,
0x18, 0x18, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00,
0x36, 0x36, 0x36, 0x36, 0xFF, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFF, 0x00, 0xFF, 0x18, 0x18, 0x18,
0x00, 0x00, 0x00, 0x00, 0xFF, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x3F, 0x00, 0x00, 0x00,
0x18, 0x18, 0x1F, 0x18, 0x1F, 0x00, 0x00, 0x00,
0x00, 0x00, 0x1F, 0x18, 0x1F, 0x18, 0x18, 0x18,
0x00, 0x00, 0x00, 0x00, 0x3F, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0xFF, 0x36, 0x36, 0x36,
0x18, 0x18, 0xFF, 0x18, 0xFF, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0xF8, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x1F, 0x18, 0x18, 0x18,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F,
0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x76, 0xDC, 0xC8, 0xDC, 0x76, 0x00,
0x00, 0x78, 0xCC, 0xF8, 0xCC, 0xF8, 0xC0, 0xC0,
0x00, 0xFC, 0xCC, 0xC0, 0xC0, 0xC0, 0xC0, 0x00,
0x00, 0x00, 0xFE, 0x6C, 0x6C, 0x6C, 0x6C, 0x00,
0xFC, 0xCC, 0x60, 0x30, 0x60, 0xCC, 0xFC, 0x00,
0x00, 0x00, 0x7E, 0xD8, 0xD8, 0xD8, 0x70, 0x00,
0x00, 0x66, 0x66, 0x66, 0x66, 0x7C, 0x60, 0xC0,
0x00, 0x76, 0xDC, 0x18, 0x18, 0x18, 0x18, 0x00,
0xFC, 0x30, 0x78, 0xCC, 0xCC, 0x78, 0x30, 0xFC,
0x38, 0x6C, 0xC6, 0xFE, 0xC6, 0x6C, 0x38, 0x00,
0x38, 0x6C, 0xC6, 0xC6, 0x6C, 0x6C, 0xEE, 0x00,
0x1C, 0x30, 0x18, 0x7C, 0xCC, 0xCC, 0x78, 0x00,
0x00, 0x00, 0x7E, 0xDB, 0xDB, 0x7E, 0x00, 0x00,
0x06, 0x0C, 0x7E, 0xDB, 0xDB, 0x7E, 0x60, 0xC0,
0x38, 0x60, 0xC0, 0xF8, 0xC0, 0x60, 0x38, 0x00,
0x78, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x00,
0x00, 0x7E, 0x00, 0x7E, 0x00, 0x7E, 0x00, 0x00,
0x18, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x7E, 0x00,
0x60, 0x30, 0x18, 0x30, 0x60, 0x00, 0xFC, 0x00,
0x18, 0x30, 0x60, 0x30, 0x18, 0x00, 0xFC, 0x00,
0x0E, 0x1B, 0x1B, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0xD8, 0xD8, 0x70,
0x18, 0x18, 0x00, 0x7E, 0x00, 0x18, 0x18, 0x00,
0x00, 0x76, 0xDC, 0x00, 0x76, 0xDC, 0x00, 0x00,
0x38, 0x6C, 0x6C, 0x38, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00,
0x0F, 0x0C, 0x0C, 0x0C, 0xEC, 0x6C, 0x3C, 0x1C,
0x58, 0x6C, 0x6C, 0x6C, 0x6C, 0x00, 0x00, 0x00,
0x70, 0x98, 0x30, 0x60, 0xF8, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x3C, 0x3C, 0x3C, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
],
);
export const VGA_8X16_FONT = new VGAFontPack(
new Size(8, 16),
[
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7E, 0x81, 0xA5, 0x81, 0x81, 0xBD, 0x99, 0x81, 0x81, 0x7E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7E, 0xFF, 0xDB, 0xFF, 0xFF, 0xC3, 0xE7, 0xFF, 0xFF, 0x7E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x6C, 0xFE, 0xFE, 0xFE, 0xFE, 0x7C, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x7C, 0xFE, 0x7C, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x18, 0x3C, 0x3C, 0xE7, 0xE7, 0xE7, 0x99, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x18, 0x3C, 0x7E, 0xFF, 0xFF, 0x7E, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3C, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE7, 0xC3, 0xC3, 0xE7, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x66, 0x42, 0x42, 0x66, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC3, 0x99, 0xBD, 0xBD, 0x99, 0xC3, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x1E, 0x0E, 0x1A, 0x32, 0x78, 0xCC, 0xCC, 0xCC, 0xCC, 0x78, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3F, 0x33, 0x3F, 0x30, 0x30, 0x30, 0x30, 0x70, 0xF0, 0xE0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7F, 0x63, 0x7F, 0x63, 0x63, 0x63, 0x63, 0x67, 0xE7, 0xE6, 0xC0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x18, 0x18, 0xDB, 0x3C, 0xE7, 0x3C, 0xDB, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x80, 0xC0, 0xE0, 0xF0, 0xF8, 0xFE, 0xF8, 0xF0, 0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00,
0x00, 0x02, 0x06, 0x0E, 0x1E, 0x3E, 0xFE, 0x3E, 0x1E, 0x0E, 0x06, 0x02, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x18, 0x3C, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7F, 0xDB, 0xDB, 0xDB, 0x7B, 0x1B, 0x1B, 0x1B, 0x1B, 0x1B, 0x00, 0x00, 0x00, 0x00,
0x00, 0x7C, 0xC6, 0x60, 0x38, 0x6C, 0xC6, 0xC6, 0x6C, 0x38, 0x0C, 0xC6, 0x7C, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x18, 0x3C, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x3C, 0x18, 0x7E, 0x00, 0x00, 0x00,
0x00, 0x00, 0x18, 0x3C, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x0C, 0xFE, 0x0C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x60, 0xFE, 0x60, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xC0, 0xC0, 0xC0, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0x6C, 0xFE, 0x6C, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x38, 0x7C, 0x7C, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0x7C, 0x7C, 0x38, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x18, 0x3C, 0x3C, 0x3C, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x66, 0x66, 0x66, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x6C, 0x6C, 0xFE, 0x6C, 0x6C, 0x6C, 0xFE, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00,
0x18, 0x18, 0x7C, 0xC6, 0xC2, 0xC0, 0x7C, 0x06, 0x86, 0xC6, 0x7C, 0x18, 0x18, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xC2, 0xC6, 0x0C, 0x18, 0x30, 0x60, 0xC6, 0x86, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x38, 0x6C, 0x6C, 0x38, 0x76, 0xDC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x30, 0x30, 0x30, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0C, 0x18, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x18, 0x0C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x30, 0x18, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x18, 0x30, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x30, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x02, 0x06, 0x0C, 0x18, 0x30, 0x60, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xCE, 0xD6, 0xD6, 0xE6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x18, 0x38, 0x78, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0x06, 0x0C, 0x18, 0x30, 0x60, 0xC0, 0xC6, 0xFE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0x06, 0x06, 0x3C, 0x06, 0x06, 0x06, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0C, 0x1C, 0x3C, 0x6C, 0xCC, 0xFE, 0x0C, 0x0C, 0x0C, 0x1E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFE, 0xC0, 0xC0, 0xC0, 0xFC, 0x0E, 0x06, 0x06, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x38, 0x60, 0xC0, 0xC0, 0xFC, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFE, 0xC6, 0x06, 0x06, 0x0C, 0x18, 0x30, 0x30, 0x30, 0x30, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0x7E, 0x06, 0x06, 0x06, 0x0C, 0x78, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x18, 0x18, 0x30, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x30, 0x18, 0x0C, 0x06, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x00, 0x00, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x0C, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0xC6, 0x0C, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xDE, 0xDE, 0xDE, 0xDC, 0xC0, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x10, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFC, 0x66, 0x66, 0x66, 0x7C, 0x66, 0x66, 0x66, 0x66, 0xFC, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x66, 0xC2, 0xC0, 0xC0, 0xC0, 0xC0, 0xC2, 0x66, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xF8, 0x6C, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x6C, 0xF8, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFE, 0x66, 0x62, 0x68, 0x78, 0x68, 0x60, 0x62, 0x66, 0xFE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFE, 0x66, 0x62, 0x68, 0x78, 0x68, 0x60, 0x60, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x66, 0xC2, 0xC0, 0xC0, 0xDE, 0xC6, 0xC6, 0x66, 0x3A, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x1E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0xCC, 0xCC, 0xCC, 0x78, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xE6, 0x66, 0x6C, 0x6C, 0x78, 0x78, 0x6C, 0x66, 0x66, 0xE6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xF0, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x62, 0x66, 0xFE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xEE, 0xFE, 0xFE, 0xD6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xE6, 0xF6, 0xFE, 0xDE, 0xCE, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x6C, 0x38, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFC, 0x66, 0x66, 0x66, 0x7C, 0x60, 0x60, 0x60, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xD6, 0xDE, 0x7C, 0x0C, 0x0E, 0x00, 0x00,
0x00, 0x00, 0xFC, 0x66, 0x66, 0x66, 0x7C, 0x6C, 0x66, 0x66, 0x66, 0xE6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0xC6, 0x60, 0x38, 0x0C, 0x06, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7E, 0x7E, 0x5A, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x6C, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xD6, 0xD6, 0xFE, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0x6C, 0x6C, 0x38, 0x38, 0x6C, 0x6C, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFE, 0xC6, 0x86, 0x0C, 0x18, 0x30, 0x60, 0xC2, 0xC6, 0xFE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0x70, 0x38, 0x1C, 0x0E, 0x06, 0x02, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x10, 0x38, 0x6C, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00,
0x30, 0x30, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xE0, 0x60, 0x60, 0x78, 0x6C, 0x66, 0x66, 0x66, 0x66, 0xDC, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC0, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x1C, 0x0C, 0x0C, 0x3C, 0x6C, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x38, 0x6C, 0x64, 0x60, 0xF0, 0x60, 0x60, 0x60, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x7C, 0x0C, 0xCC, 0x78, 0x00,
0x00, 0x00, 0xE0, 0x60, 0x60, 0x6C, 0x76, 0x66, 0x66, 0x66, 0x66, 0xE6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x18, 0x18, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x06, 0x00, 0x0E, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x66, 0x66, 0x3C, 0x00,
0x00, 0x00, 0xE0, 0x60, 0x60, 0x66, 0x6C, 0x78, 0x78, 0x6C, 0x66, 0xE6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xEC, 0xFE, 0xD6, 0xD6, 0xD6, 0xD6, 0xD6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xDC, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xDC, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7C, 0x60, 0x60, 0xF0, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x7C, 0x0C, 0x0C, 0x1E, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xDC, 0x76, 0x62, 0x60, 0x60, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0x60, 0x38, 0x0C, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x10, 0x30, 0x30, 0xFC, 0x30, 0x30, 0x30, 0x30, 0x36, 0x1C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xD6, 0xD6, 0xFE, 0x6C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0x6C, 0x38, 0x38, 0x38, 0x6C, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7E, 0x06, 0x0C, 0xF8, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xCC, 0x18, 0x30, 0x60, 0xC6, 0xFE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0E, 0x18, 0x18, 0x18, 0x70, 0x18, 0x18, 0x18, 0x18, 0x0E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x70, 0x18, 0x18, 0x18, 0x0E, 0x18, 0x18, 0x18, 0x18, 0x70, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x76, 0xDC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6C, 0xC6, 0xC6, 0xC6, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x66, 0xC2, 0xC0, 0xC0, 0xC0, 0xC2, 0x66, 0x3C, 0x0C, 0x06, 0x7C, 0x00, 0x00,
0x00, 0x00, 0xCC, 0xCC, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x0C, 0x18, 0x30, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x10, 0x38, 0x6C, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xCC, 0xCC, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x60, 0x30, 0x18, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x38, 0x6C, 0x38, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x3C, 0x66, 0x60, 0x60, 0x66, 0x3C, 0x0C, 0x06, 0x3C, 0x00, 0x00, 0x00,
0x00, 0x10, 0x38, 0x6C, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x60, 0x30, 0x18, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x66, 0x66, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x18, 0x3C, 0x66, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x60, 0x30, 0x18, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0xC6, 0xC6, 0x10, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x38, 0x6C, 0x38, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x18, 0x30, 0x60, 0x00, 0xFE, 0x66, 0x60, 0x7C, 0x60, 0x60, 0x66, 0xFE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xCC, 0x76, 0x36, 0x7E, 0xD8, 0xD8, 0x6E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3E, 0x6C, 0xCC, 0xCC, 0xFE, 0xCC, 0xCC, 0xCC, 0xCC, 0xCE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x10, 0x38, 0x6C, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x60, 0x30, 0x18, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x30, 0x78, 0xCC, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x60, 0x30, 0x18, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7E, 0x06, 0x0C, 0x78, 0x00,
0x00, 0xC6, 0xC6, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xC6, 0xC6, 0x6C, 0x38, 0x00, 0x00, 0x00, 0x00,
0x00, 0xC6, 0xC6, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x18, 0x18, 0x3C, 0x66, 0x60, 0x60, 0x60, 0x66, 0x3C, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x38, 0x6C, 0x64, 0x60, 0xF0, 0x60, 0x60, 0x60, 0x60, 0xE6, 0xFC, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x66, 0x66, 0x3C, 0x18, 0x7E, 0x18, 0x7E, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0xF8, 0xCC, 0xCC, 0xF8, 0xC4, 0xCC, 0xDE, 0xCC, 0xCC, 0xCC, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x0E, 0x1B, 0x18, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x18, 0xD8, 0x70, 0x00, 0x00,
0x00, 0x18, 0x30, 0x60, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x0C, 0x18, 0x30, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x18, 0x30, 0x60, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x18, 0x30, 0x60, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x76, 0xDC, 0x00, 0xDC, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00,
0x76, 0xDC, 0x00, 0xC6, 0xE6, 0xF6, 0xFE, 0xDE, 0xCE, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x3C, 0x6C, 0x6C, 0x3E, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x38, 0x6C, 0x6C, 0x38, 0x00, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x30, 0x30, 0x00, 0x30, 0x30, 0x60, 0xC0, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xC0, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x06, 0x06, 0x06, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xC0, 0xC0, 0xC2, 0xC6, 0xCC, 0x18, 0x30, 0x60, 0xCE, 0x93, 0x06, 0x0C, 0x1F, 0x00, 0x00,
0x00, 0xC0, 0xC0, 0xC2, 0xC6, 0xCC, 0x18, 0x30, 0x66, 0xCE, 0x9A, 0x3F, 0x06, 0x0F, 0x00, 0x00,
0x00, 0x00, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x3C, 0x3C, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x33, 0x66, 0xCC, 0x66, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xCC, 0x66, 0x33, 0x66, 0xCC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44,
0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA,
0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x18, 0xF8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xF6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x18, 0xF8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x36, 0x36, 0x36, 0x36, 0x36, 0xF6, 0x06, 0xF6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x06, 0xF6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0xF6, 0x06, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x18, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x18, 0x1F, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x30, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x30, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0xF7, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xF7, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x30, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x36, 0x36, 0x36, 0x36, 0x36, 0xF7, 0x00, 0xF7, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x18, 0x18, 0x18, 0x18, 0x18, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x18, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x18, 0x1F, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xFF, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x18, 0x18, 0x18, 0x18, 0x18, 0xFF, 0x18, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xDC, 0xD8, 0xD8, 0xD8, 0xDC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xC6, 0xFC, 0xC6, 0xC6, 0xFC, 0xC0, 0xC0, 0xC0, 0x00, 0x00,
0x00, 0x00, 0xFE, 0xC6, 0xC6, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x80, 0xFE, 0x6C, 0x6C, 0x6C, 0x6C, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xFE, 0xC6, 0x60, 0x30, 0x18, 0x30, 0x60, 0xC6, 0xFE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0xD8, 0xD8, 0xD8, 0xD8, 0xD8, 0x70, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7C, 0x60, 0x60, 0xC0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x76, 0xDC, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x7E, 0x18, 0x3C, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x7E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0x6C, 0x38, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xC6, 0x6C, 0x6C, 0x6C, 0x6C, 0xEE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x1E, 0x30, 0x18, 0x0C, 0x3E, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0xDB, 0xDB, 0xDB, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x03, 0x06, 0x7E, 0xCF, 0xDB, 0xF3, 0x7E, 0x60, 0xC0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x1C, 0x30, 0x60, 0x60, 0x7C, 0x60, 0x60, 0x60, 0x30, 0x1C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xFE, 0x00, 0x00, 0xFE, 0x00, 0x00, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x30, 0x18, 0x0C, 0x06, 0x0C, 0x18, 0x30, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0C, 0x18, 0x30, 0x60, 0x30, 0x18, 0x0C, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0E, 0x1B, 0x1B, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xD8, 0xD8, 0xD8, 0x70, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x7E, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xDC, 0x00, 0x76, 0xDC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x38, 0x6C, 0x6C, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x0F, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0xEC, 0x6C, 0x6C, 0x3C, 0x1C, 0x00, 0x00, 0x00, 0x00,
0x00, 0xD8, 0x6C, 0x6C, 0x6C, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x70, 0x98, 0x30, 0x60, 0xC8, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x7C, 0x7C, 0x7C, 0x7C, 0x7C, 0x7C, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
],
); | the_stack |
import React, {CSSProperties, PointerEventHandler} from "react";
import {DockContext, DockContextType, DockMode, PanelData, TabData, TabGroup} from "./DockData";
import {DockTabs} from "./DockTabs";
import {AbstractPointerEvent, DragDropDiv} from "./dragdrop/DragDropDiv";
import {DragState} from "./dragdrop/DragManager";
import {DockDropLayer} from "./DockDropLayer";
import {getFloatPanelSize, nextZIndex} from "./Algorithm";
import {DockDropEdge} from "./DockDropEdge";
interface Props {
panelData: PanelData;
size: number;
}
interface State {
dropFromPanel: PanelData;
draggingHeader: boolean;
}
export class DockPanel extends React.PureComponent<Props, State> {
static contextType = DockContextType;
context!: DockContext;
_ref: HTMLDivElement;
getRef = (r: HTMLDivElement) => {
this._ref = r;
};
static _droppingPanel: DockPanel;
static set droppingPanel(panel: DockPanel) {
if (DockPanel._droppingPanel === panel) {
return;
}
if (DockPanel._droppingPanel) {
DockPanel._droppingPanel.onDragOverOtherPanel();
}
DockPanel._droppingPanel = panel;
}
state: State = {dropFromPanel: null, draggingHeader: false};
onDragOver = (e: DragState) => {
if (DockPanel._droppingPanel === this) {
return;
}
let {panelData} = this.props;
let dockId = this.context.getDockId();
let tab: TabData = DragState.getData('tab', dockId);
let panel: PanelData = DragState.getData('panel', dockId);
if (tab || panel) {
DockPanel.droppingPanel = this;
}
if (tab) {
if (tab.parent) {
this.setState({dropFromPanel: tab.parent});
} else {
// add a fake panel
this.setState({dropFromPanel: {activeId: '', tabs: [], group: tab.group}});
}
} else if (panel) {
this.setState({dropFromPanel: panel});
}
};
onDragOverOtherPanel() {
if (this.state.dropFromPanel) {
this.setState({dropFromPanel: null});
}
}
// used both by dragging head and corner
_movingX: number;
_movingY: number;
// drop to move in float mode
onPanelHeaderDragStart = (event: DragState) => {
let {panelData} = this.props;
let {parent, x, y, z} = panelData;
let dockId = this.context.getDockId();
if (parent && parent.mode === 'float') {
this._movingX = x;
this._movingY = y;
// hide the panel, but not create drag layer element
event.setData({panel: this.props.panelData}, dockId);
event.startDrag(null, null);
this.onFloatPointerDown();
} else {
let tabGroup = this.context.getGroup(panelData.group);
let [panelWidth, panelHeight] = getFloatPanelSize(this._ref, tabGroup);
event.setData({panel: panelData, panelSize: [panelWidth, panelHeight]}, dockId);
event.startDrag(null);
}
this.setState({draggingHeader: true});
};
onPanelHeaderDragMove = (e: DragState) => {
let {width, height} = this.context.getLayoutSize();
let {panelData} = this.props;
panelData.x = this._movingX + e.dx;
panelData.y = this._movingY + e.dy;
if (width > 200 && height > 200) {
if (panelData.y < 0) {
panelData.y = 0;
} else if (panelData.y > height - 16) {
panelData.y = height - 16;
}
if (panelData.x + panelData.w < 16) {
panelData.x = 16 - panelData.w;
} else if (panelData.x > width - 16) {
panelData.x = width - 16;
}
}
this.forceUpdate();
};
onPanelHeaderDragEnd = (e: DragState) => {
if (!this._unmounted) {
this.setState({draggingHeader: false});
this.context.onSilentChange(this.props.panelData.activeId, 'move');
}
};
_movingW: number;
_movingH: number;
_movingCorner: string;
onPanelCornerDragTL = (e: DragState) => {
this.onPanelCornerDrag(e, 'tl');
};
onPanelCornerDragTR = (e: DragState) => {
this.onPanelCornerDrag(e, 'tr');
};
onPanelCornerDragBL = (e: DragState) => {
this.onPanelCornerDrag(e, 'bl');
};
onPanelCornerDragBR = (e: DragState) => {
this.onPanelCornerDrag(e, 'br');
};
onPanelCornerDrag(e: DragState, corner: string) {
let {parent, x, y, w, h} = this.props.panelData;
if (parent && parent.mode === 'float') {
this._movingCorner = corner;
this._movingX = x;
this._movingY = y;
this._movingW = w;
this._movingH = h;
e.startDrag(null, null);
}
}
onPanelCornerDragMove = (e: DragState) => {
let {panelData} = this.props;
let {dx, dy} = e;
if (this._movingCorner.startsWith('t')) {
// when moving top corners, dont let it move header out of screen
let {width, height} = this.context.getLayoutSize();
if (this._movingY + dy < 0) {
dy = -this._movingY;
} else if (this._movingY + dy > height - 16) {
dy = height - 16 - this._movingY;
}
}
switch (this._movingCorner) {
case 'tl': {
panelData.x = this._movingX + dx;
panelData.w = this._movingW - dx;
panelData.y = this._movingY + dy;
panelData.h = this._movingH - dy;
break;
}
case 'tr': {
panelData.w = this._movingW + dx;
panelData.y = this._movingY + dy;
panelData.h = this._movingH - dy;
break;
}
case 'bl': {
panelData.x = this._movingX + dx;
panelData.w = this._movingW - dx;
panelData.h = this._movingH + dy;
break;
}
case 'br': {
panelData.w = this._movingW + dx;
panelData.h = this._movingH + dy;
break;
}
}
this.forceUpdate();
};
onPanelCornerDragEnd = (e: DragState) => {
this.context.onSilentChange(this.props.panelData.activeId, 'move');
};
onFloatPointerDown = () => {
let {panelData} = this.props;
let {z} = panelData;
let newZ = nextZIndex(z);
if (newZ !== z) {
panelData.z = newZ;
this.forceUpdate();
}
};
onPanelClicked = (e: React.MouseEvent) => {
const target = e.nativeEvent.target;
if (!this._ref.contains(this._ref.ownerDocument.activeElement) && target instanceof Node && this._ref.contains(target)) {
(this._ref.querySelector('.dock-bar') as HTMLElement).focus();
}
};
render(): React.ReactNode {
let {dropFromPanel, draggingHeader} = this.state;
let {panelData, size} = this.props;
let {minWidth, minHeight, group, id, parent, panelLock} = panelData;
let styleName = group;
let tabGroup = this.context.getGroup(group);
let {widthFlex, heightFlex} = tabGroup;
if (panelLock) {
let {panelStyle, widthFlex: panelWidthFlex, heightFlex: panelHeightFlex} = panelLock;
if (panelStyle) {
styleName = panelStyle;
}
if (typeof panelWidthFlex === 'number') {
widthFlex = panelWidthFlex;
}
if (typeof panelHeightFlex === 'number') {
heightFlex = panelHeightFlex;
}
}
let panelClass: string;
if (styleName) {
panelClass = styleName
.split(' ')
.map((name) => `dock-style-${name}`)
.join(' ');
}
let isMax = parent?.mode === 'maximize';
let isFloat = parent?.mode === 'float';
let isHBox = parent?.mode === 'horizontal';
let isVBox = parent?.mode === 'vertical';
let pointerDownCallback = this.onFloatPointerDown;
let onPanelHeaderDragStart = this.onPanelHeaderDragStart;
if (!isFloat || isMax) {
pointerDownCallback = null;
}
if (isMax) {
dropFromPanel = null;
onPanelHeaderDragStart = null;
}
let cls = `dock-panel ${
panelClass ? panelClass : ''}${
dropFromPanel ? ' dock-panel-dropping' : ''}${
draggingHeader ? ' dragging' : ''
}`;
let flex = 1;
if (isHBox && widthFlex != null) {
flex = widthFlex;
} else if (isVBox && heightFlex != null) {
flex = heightFlex;
}
let flexGrow = flex * size;
let flexShrink = flex * 1000000;
if (flexShrink < 1) {
flexShrink = 1;
}
let style: React.CSSProperties = {minWidth, minHeight, flex: `${flexGrow} ${flexShrink} ${size}px`};
if (isFloat) {
style.left = panelData.x;
style.top = panelData.y;
style.width = panelData.w;
style.height = panelData.h;
style.zIndex = panelData.z;
}
let droppingLayer: React.ReactNode;
if (dropFromPanel) {
let dropFromGroup = this.context.getGroup(dropFromPanel.group);
let dockId = this.context.getDockId();
if (!dropFromGroup.tabLocked || DragState.getData('tab', dockId) == null) {
// not allowed locked tab to create new panel
let DockDropClass = this.context.useEdgeDrop() ? DockDropEdge : DockDropLayer;
droppingLayer = <DockDropClass panelData={panelData} panelElement={this._ref} dropFromPanel={dropFromPanel}/>;
}
}
return (
<DragDropDiv getRef={this.getRef} className={cls} style={style} data-dockid={id}
onMouseDownCapture={pointerDownCallback} onTouchStartCapture={pointerDownCallback}
onDragOverT={isFloat ? null : this.onDragOver} onClick={this.onPanelClicked}>
<DockTabs panelData={panelData} onPanelDragStart={onPanelHeaderDragStart}
onPanelDragMove={this.onPanelHeaderDragMove} onPanelDragEnd={this.onPanelHeaderDragEnd}/>
{isFloat ?
[
<DragDropDiv key="drag-size-t-l" className="dock-panel-drag-size dock-panel-drag-size-t-l"
onDragStartT={this.onPanelCornerDragTL} onDragMoveT={this.onPanelCornerDragMove}
onDragEndT={this.onPanelCornerDragEnd}/>,
<DragDropDiv key="drag-size-t-r" className="dock-panel-drag-size dock-panel-drag-size-t-r"
onDragStartT={this.onPanelCornerDragTR} onDragMoveT={this.onPanelCornerDragMove}
onDragEndT={this.onPanelCornerDragEnd}/>,
<DragDropDiv key="drag-size-b-l" className="dock-panel-drag-size dock-panel-drag-size-b-l"
onDragStartT={this.onPanelCornerDragBL} onDragMoveT={this.onPanelCornerDragMove}
onDragEndT={this.onPanelCornerDragEnd}/>,
<DragDropDiv key="drag-size-b-r" className="dock-panel-drag-size dock-panel-drag-size-b-r"
onDragStartT={this.onPanelCornerDragBR} onDragMoveT={this.onPanelCornerDragMove}
onDragEndT={this.onPanelCornerDragEnd}/>
]
: null
}
{droppingLayer}
</DragDropDiv>
);
}
_unmounted = false;
componentWillUnmount(): void {
if (DockPanel._droppingPanel === this) {
DockPanel.droppingPanel = null;
}
this._unmounted = true;
}
} | the_stack |
import * as coreClient from "@azure/core-client";
/** Result of the request to list REST API operations. It contains a list of operations. */
export interface OperationList {
/** List of operations supported by the resource provider. */
value?: Operation[];
/**
* The URL the client should use to fetch the next page (per server side paging).
* It's null for now, added for future use.
*/
nextLink?: string;
}
/** REST API operation supported by resource provider. */
export interface Operation {
/** Name of the operation with format: {provider}/{resource}/{operation} */
name?: string;
/** If the operation is a data action. (for data plane rbac) */
isDataAction?: boolean;
/** The object that describes a operation. */
display?: OperationDisplay;
/** Optional. The intended executor of the operation; governs the display of the operation in the RBAC UX and the audit logs UX. */
origin?: string;
/** Extra Operation properties. */
properties?: OperationProperties;
}
/** The object that describes a operation. */
export interface OperationDisplay {
/** Friendly name of the resource provider */
provider?: string;
/** Resource type on which the operation is performed. */
resource?: string;
/** The localized friendly name for the operation. */
operation?: string;
/** The localized friendly description for the operation */
description?: string;
}
/** Extra Operation properties. */
export interface OperationProperties {
/** An object that describes a specification. */
serviceSpecification?: ServiceSpecification;
}
/** An object that describes a specification. */
export interface ServiceSpecification {
/** Specifications of the Metrics for Azure Monitoring. */
metricSpecifications?: MetricSpecification[];
/** Specifications of the Logs for Azure Monitoring. */
logSpecifications?: LogSpecification[];
}
/** Specifications of the Metrics for Azure Monitoring. */
export interface MetricSpecification {
/** Name of the metric. */
name?: string;
/** Localized friendly display name of the metric. */
displayName?: string;
/** Localized friendly description of the metric. */
displayDescription?: string;
/** The unit that makes sense for the metric. */
unit?: string;
/** Only provide one value for this field. Valid values: Average, Minimum, Maximum, Total, Count. */
aggregationType?: string;
/**
* Optional. If set to true, then zero will be returned for time duration where no metric is emitted/published.
* Ex. a metric that returns the number of times a particular error code was emitted. The error code may not appear
* often, instead of the RP publishing 0, Shoebox can auto fill in 0s for time periods where nothing was emitted.
*/
fillGapWithZero?: string;
/** The name of the metric category that the metric belongs to. A metric can only belong to a single category. */
category?: string;
/** The dimensions of the metrics. */
dimensions?: Dimension[];
}
/** Specifications of the Dimension of metrics. */
export interface Dimension {
/** The public facing name of the dimension. */
name?: string;
/** Localized friendly display name of the dimension. */
displayName?: string;
/** Name of the dimension as it appears in MDM. */
internalName?: string;
/** A Boolean flag indicating whether this dimension should be included for the shoebox export scenario. */
toBeExportedForShoebox?: boolean;
}
/** Specifications of the Logs for Azure Monitoring. */
export interface LogSpecification {
/** Name of the log. */
name?: string;
/** Localized friendly display name of the log. */
displayName?: string;
}
/** Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). */
export interface ErrorResponse {
/** The error object. */
error?: ErrorDetail;
}
/** The error detail. */
export interface ErrorDetail {
/**
* The error code.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly code?: string;
/**
* The error message.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly message?: string;
/**
* The error target.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly target?: string;
/**
* The error details.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly details?: ErrorDetail[];
/**
* The error additional info.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly additionalInfo?: ErrorAdditionalInfo[];
}
/** The resource management error additional info. */
export interface ErrorAdditionalInfo {
/**
* The additional info type.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: string;
/**
* The additional info.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly info?: Record<string, unknown>;
}
/** Data POST-ed to the nameAvailability action */
export interface NameAvailabilityParameters {
/** The resource type. Can be "Microsoft.SignalRService/SignalR" or "Microsoft.SignalRService/webPubSub" */
type: string;
/** The resource name to validate. e.g."my-resource-name" */
name: string;
}
/** Result of the request to check name availability. It contains a flag and possible reason of failure. */
export interface NameAvailability {
/** Indicates whether the name is available or not. */
nameAvailable?: boolean;
/** The reason of the availability. Required if name is not available. */
reason?: string;
/** The message of the operation. */
message?: string;
}
/** Object that includes an array of the resource usages and a possible link for next set. */
export interface SignalRServiceUsageList {
/** List of the resource usages */
value?: SignalRServiceUsage[];
/**
* The URL the client should use to fetch the next page (per server side paging).
* It's null for now, added for future use.
*/
nextLink?: string;
}
/** Object that describes a specific usage of the resources. */
export interface SignalRServiceUsage {
/** Fully qualified ARM resource id */
id?: string;
/** Current value for the usage quota. */
currentValue?: number;
/** The maximum permitted value for the usage quota. If there is no limit, this value will be -1. */
limit?: number;
/** Localizable String object containing the name and a localized value. */
name?: SignalRServiceUsageName;
/** Representing the units of the usage quota. Possible values are: Count, Bytes, Seconds, Percent, CountPerSecond, BytesPerSecond. */
unit?: string;
}
/** Localizable String object containing the name and a localized value. */
export interface SignalRServiceUsageName {
/** The identifier of the usage. */
value?: string;
/** Localized name of the usage. */
localizedValue?: string;
}
/** Object that includes an array of resources and a possible link for next set. */
export interface WebPubSubResourceList {
/** List of the resources */
value?: WebPubSubResource[];
/**
* The URL the client should use to fetch the next page (per server side paging).
* It's null for now, added for future use.
*/
nextLink?: string;
}
/** The billing information of the resource. */
export interface ResourceSku {
/**
* The name of the SKU. Required.
*
* Allowed values: Standard_S1, Free_F1
*/
name: string;
/**
* Optional tier of this particular SKU. 'Standard' or 'Free'.
*
* `Basic` is deprecated, use `Standard` instead.
*/
tier?: WebPubSubSkuTier;
/**
* Not used. Retained for future use.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly size?: string;
/**
* Not used. Retained for future use.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly family?: string;
/**
* Optional, integer. The unit count of the resource. 1 by default.
*
* If present, following values are allowed:
* Free: 1
* Standard: 1,2,5,10,20,50,100
*/
capacity?: number;
}
/** Metadata pertaining to creation and last modification of the resource. */
export interface SystemData {
/** The identity that created the resource. */
createdBy?: string;
/** The type of identity that created the resource. */
createdByType?: CreatedByType;
/** The timestamp of resource creation (UTC). */
createdAt?: Date;
/** The identity that last modified the resource. */
lastModifiedBy?: string;
/** The type of identity that last modified the resource. */
lastModifiedByType?: CreatedByType;
/** The timestamp of resource last modification (UTC) */
lastModifiedAt?: Date;
}
/** Private endpoint */
export interface PrivateEndpoint {
/** Full qualified Id of the private endpoint */
id?: string;
}
/** Connection state of the private endpoint connection */
export interface PrivateLinkServiceConnectionState {
/** Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. */
status?: PrivateLinkServiceConnectionStatus;
/** The reason for approval/rejection of the connection. */
description?: string;
/** A message indicating if changes on the service provider require any updates on the consumer. */
actionsRequired?: string;
}
/** The core properties of ARM resources. */
export interface Resource {
/**
* Fully qualified resource Id for the resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly id?: string;
/**
* The name of the resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/**
* The type of the resource - e.g. "Microsoft.SignalRService/SignalR"
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: string;
}
/** TLS settings for the resource */
export interface WebPubSubTlsSettings {
/** Request client certificate during TLS handshake if enabled */
clientCertEnabled?: boolean;
}
/** Live trace configuration of a Microsoft.SignalRService resource. */
export interface LiveTraceConfiguration {
/**
* Indicates whether or not enable live trace.
* When it's set to true, live trace client can connect to the service.
* Otherwise, live trace client can't connect to the service, so that you are unable to receive any log, no matter what you configure in "categories".
* Available values: true, false.
* Case insensitive.
*/
enabled?: string;
/** Gets or sets the list of category configurations. */
categories?: LiveTraceCategory[];
}
/** Live trace category configuration of a Microsoft.SignalRService resource. */
export interface LiveTraceCategory {
/**
* Gets or sets the live trace category's name.
* Available values: ConnectivityLogs, MessagingLogs.
* Case insensitive.
*/
name?: string;
/**
* Indicates whether or the live trace category is enabled.
* Available values: true, false.
* Case insensitive.
*/
enabled?: string;
}
/** Resource log configuration of a Microsoft.SignalRService resource. */
export interface ResourceLogConfiguration {
/** Gets or sets the list of category configurations. */
categories?: ResourceLogCategory[];
}
/** Resource log category configuration of a Microsoft.SignalRService resource. */
export interface ResourceLogCategory {
/**
* Gets or sets the resource log category's name.
* Available values: ConnectivityLogs, MessagingLogs.
* Case insensitive.
*/
name?: string;
/**
* Indicates whether or the resource log category is enabled.
* Available values: true, false.
* Case insensitive.
*/
enabled?: string;
}
/** Network ACLs for the resource */
export interface WebPubSubNetworkACLs {
/** Azure Networking ACL Action. */
defaultAction?: ACLAction;
/** Network ACL */
publicNetwork?: NetworkACL;
/** ACLs for requests from private endpoints */
privateEndpoints?: PrivateEndpointACL[];
}
/** Network ACL */
export interface NetworkACL {
/** Allowed request types. The value can be one or more of: ClientConnection, ServerConnection, RESTAPI. */
allow?: WebPubSubRequestType[];
/** Denied request types. The value can be one or more of: ClientConnection, ServerConnection, RESTAPI. */
deny?: WebPubSubRequestType[];
}
/** A class represent managed identities used for request and response */
export interface ManagedIdentity {
/** Represents the identity type: systemAssigned, userAssigned, None */
type?: ManagedIdentityType;
/** Get or set the user assigned identities */
userAssignedIdentities?: {
[propertyName: string]: UserAssignedIdentityProperty;
};
/**
* Get the principal id for the system assigned identity.
* Only be used in response.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly principalId?: string;
/**
* Get the tenant id for the system assigned identity.
* Only be used in response
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly tenantId?: string;
}
/** Properties of user assigned identity. */
export interface UserAssignedIdentityProperty {
/**
* Get the principal id for the user assigned identity
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly principalId?: string;
/**
* Get the client id for the user assigned identity
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly clientId?: string;
}
/** Hub setting list */
export interface WebPubSubHubList {
/** List of hub settings to this resource. */
value?: WebPubSubHub[];
/**
* The URL the client should use to fetch the next page (per server side paging).
* It's null for now, added for future use.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly nextLink?: string;
}
/** Properties of a hub. */
export interface WebPubSubHubProperties {
/** Event handler of a hub. */
eventHandlers?: EventHandler[];
/** The settings for configuring if anonymous connections are allowed for this hub: "allow" or "deny". Default to "deny". */
anonymousConnectPolicy?: string;
}
/** Properties of event handler. */
export interface EventHandler {
/**
* Gets or sets the EventHandler URL template. You can use a predefined parameter {hub} and {event} inside the template, the value of the EventHandler URL is dynamically calculated when the client request comes in.
* For example, UrlTemplate can be `http://example.com/api/{hub}/{event}`. The host part can't contains parameters.
*/
urlTemplate: string;
/**
* Gets or sets the matching pattern for event names.
* There are 3 kind of patterns supported:
* 1. "*", it to matches any event name
* 2. Combine multiple events with ",", for example "event1,event2", it matches event "event1" and "event2"
* 3. The single event name, for example, "event1", it matches "event1"
*/
userEventPattern?: string;
/** Gets ot sets the list of system events. */
systemEvents?: string[];
/** Upstream auth settings. If not set, no auth is used for upstream messages. */
auth?: UpstreamAuthSettings;
}
/** Upstream auth settings. If not set, no auth is used for upstream messages. */
export interface UpstreamAuthSettings {
/** Upstream auth type enum. */
type?: UpstreamAuthType;
/** Managed identity settings for upstream. */
managedIdentity?: ManagedIdentitySettings;
}
/** Managed identity settings for upstream. */
export interface ManagedIdentitySettings {
/**
* The Resource indicating the App ID URI of the target resource.
* It also appears in the aud (audience) claim of the issued token.
*/
resource?: string;
}
/** A class represents the access keys of the resource. */
export interface WebPubSubKeys {
/** The primary access key. */
primaryKey?: string;
/** The secondary access key. */
secondaryKey?: string;
/** Connection string constructed via the primaryKey */
primaryConnectionString?: string;
/** Connection string constructed via the secondaryKey */
secondaryConnectionString?: string;
}
/** A list of private endpoint connections */
export interface PrivateEndpointConnectionList {
/** The list of the private endpoint connections */
value?: PrivateEndpointConnection[];
/** Request URL that can be used to query next page of private endpoint connections. Returned when the total number of requested private endpoint connections exceed maximum page size. */
nextLink?: string;
}
/** Contains a list of PrivateLinkResource and a possible link to query more results */
export interface PrivateLinkResourceList {
/** List of PrivateLinkResource */
value?: PrivateLinkResource[];
/**
* The URL the client should use to fetch the next page (per server side paging).
* It's null for now, added for future use.
*/
nextLink?: string;
}
/** Describes a resource type that has been onboarded to private link service */
export interface ShareablePrivateLinkResourceType {
/** The name of the resource type that has been onboarded to private link service */
name?: string;
/** Describes the properties of a resource type that has been onboarded to private link service */
properties?: ShareablePrivateLinkResourceProperties;
}
/** Describes the properties of a resource type that has been onboarded to private link service */
export interface ShareablePrivateLinkResourceProperties {
/** The description of the resource type that has been onboarded to private link service */
description?: string;
/** The resource provider group id for the resource that has been onboarded to private link service */
groupId?: string;
/** The resource provider type for the resource that has been onboarded to private link service */
type?: string;
}
/** Parameters describes the request to regenerate access keys */
export interface RegenerateKeyParameters {
/** The type of access key. */
keyType?: KeyType;
}
/** A list of shared private link resources */
export interface SharedPrivateLinkResourceList {
/** The list of the shared private link resources */
value?: SharedPrivateLinkResource[];
/** Request URL that can be used to query next page of private endpoint connections. Returned when the total number of requested private endpoint connections exceed maximum page size. */
nextLink?: string;
}
/** The list skus operation response */
export interface SkuList {
/**
* The list of skus available for the resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly value?: Sku[];
/**
* The URL the client should use to fetch the next page (per server side paging).
* It's null for now, added for future use.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly nextLink?: string;
}
/** Describes an available sku." */
export interface Sku {
/**
* The resource type that this object applies to
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly resourceType?: string;
/**
* The billing information of the resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly sku?: ResourceSku;
/**
* Describes scaling information of a sku.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly capacity?: SkuCapacity;
}
/** Describes scaling information of a sku. */
export interface SkuCapacity {
/**
* The lowest permitted capacity for this resource
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly minimum?: number;
/**
* The highest permitted capacity for this resource
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly maximum?: number;
/**
* The default capacity.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly default?: number;
/**
* Allows capacity value list.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly allowedValues?: number[];
/**
* The scale type applicable to the sku.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly scaleType?: ScaleType;
}
/** The resource model definition for a ARM proxy resource. It will have everything other than required location and tags */
export type ProxyResource = Resource & {};
/** The resource model definition for a ARM tracked top level resource. */
export type TrackedResource = Resource & {
/** The GEO location of the resource. e.g. West US | East US | North Central US | South Central US. */
location?: string;
/** Tags of the service which is a list of key value pairs that describe the resource. */
tags?: { [propertyName: string]: string };
};
/** ACL for a private endpoint */
export type PrivateEndpointACL = NetworkACL & {
/** Name of the private endpoint connection */
name: string;
};
/** A private endpoint connection to an azure resource */
export type PrivateEndpointConnection = ProxyResource & {
/**
* Metadata pertaining to creation and last modification of the resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly systemData?: SystemData;
/**
* Provisioning state of the resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly provisioningState?: ProvisioningState;
/** Private endpoint */
privateEndpoint?: PrivateEndpoint;
/**
* Group IDs
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly groupIds?: string[];
/** Connection state of the private endpoint connection */
privateLinkServiceConnectionState?: PrivateLinkServiceConnectionState;
};
/** Describes a Shared Private Link Resource */
export type SharedPrivateLinkResource = ProxyResource & {
/**
* Metadata pertaining to creation and last modification of the resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly systemData?: SystemData;
/** The group id from the provider of resource the shared private link resource is for */
groupId?: string;
/** The resource id of the resource the shared private link resource is for */
privateLinkResourceId?: string;
/**
* Provisioning state of the resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly provisioningState?: ProvisioningState;
/** The request message for requesting approval of the shared private link resource */
requestMessage?: string;
/**
* Status of the shared private link resource
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly status?: SharedPrivateLinkResourceStatus;
};
/** A hub setting */
export type WebPubSubHub = ProxyResource & {
/**
* Metadata pertaining to creation and last modification of the resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly systemData?: SystemData;
/** Properties of a hub. */
properties: WebPubSubHubProperties;
};
/** Private link resource */
export type PrivateLinkResource = ProxyResource & {
/** Group Id of the private link resource */
groupId?: string;
/** Required members of the private link resource */
requiredMembers?: string[];
/** Required private DNS zone names */
requiredZoneNames?: string[];
/** The list of resources that are onboarded to private link service */
shareablePrivateLinkResourceTypes?: ShareablePrivateLinkResourceType[];
};
/** A class represent a resource. */
export type WebPubSubResource = TrackedResource & {
/** The billing information of the resource. */
sku?: ResourceSku;
/** A class represent managed identities used for request and response */
identity?: ManagedIdentity;
/**
* Metadata pertaining to creation and last modification of the resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly systemData?: SystemData;
/**
* Provisioning state of the resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly provisioningState?: ProvisioningState;
/**
* The publicly accessible IP of the resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly externalIP?: string;
/**
* FQDN of the service instance.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly hostName?: string;
/**
* The publicly accessible port of the resource which is designed for browser/client side usage.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly publicPort?: number;
/**
* The publicly accessible port of the resource which is designed for customer server side usage.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly serverPort?: number;
/**
* Version of the resource. Probably you need the same or higher version of client SDKs.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly version?: string;
/**
* Private endpoint connections to the resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly privateEndpointConnections?: PrivateEndpointConnection[];
/**
* The list of shared private link resources.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly sharedPrivateLinkResources?: SharedPrivateLinkResource[];
/** TLS settings for the resource */
tls?: WebPubSubTlsSettings;
/**
* Deprecated.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly hostNamePrefix?: string;
/** Live trace configuration of a Microsoft.SignalRService resource. */
liveTraceConfiguration?: LiveTraceConfiguration;
/** Resource log configuration of a Microsoft.SignalRService resource. */
resourceLogConfiguration?: ResourceLogConfiguration;
/** Network ACLs for the resource */
networkACLs?: WebPubSubNetworkACLs;
/**
* Enable or disable public network access. Default to "Enabled".
* When it's Enabled, network ACLs still apply.
* When it's Disabled, public network access is always disabled no matter what you set in network ACLs.
*/
publicNetworkAccess?: string;
/**
* DisableLocalAuth
* Enable or disable local auth with AccessKey
* When set as true, connection with AccessKey=xxx won't work.
*/
disableLocalAuth?: boolean;
/**
* DisableLocalAuth
* Enable or disable aad auth
* When set as true, connection with AuthType=aad won't work.
*/
disableAadAuth?: boolean;
};
/** Known values of {@link WebPubSubSkuTier} that the service accepts. */
export enum KnownWebPubSubSkuTier {
Free = "Free",
Basic = "Basic",
Standard = "Standard",
Premium = "Premium"
}
/**
* Defines values for WebPubSubSkuTier. \
* {@link KnownWebPubSubSkuTier} can be used interchangeably with WebPubSubSkuTier,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Free** \
* **Basic** \
* **Standard** \
* **Premium**
*/
export type WebPubSubSkuTier = string;
/** Known values of {@link ProvisioningState} that the service accepts. */
export enum KnownProvisioningState {
Unknown = "Unknown",
Succeeded = "Succeeded",
Failed = "Failed",
Canceled = "Canceled",
Running = "Running",
Creating = "Creating",
Updating = "Updating",
Deleting = "Deleting",
Moving = "Moving"
}
/**
* Defines values for ProvisioningState. \
* {@link KnownProvisioningState} can be used interchangeably with ProvisioningState,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Unknown** \
* **Succeeded** \
* **Failed** \
* **Canceled** \
* **Running** \
* **Creating** \
* **Updating** \
* **Deleting** \
* **Moving**
*/
export type ProvisioningState = string;
/** Known values of {@link CreatedByType} that the service accepts. */
export enum KnownCreatedByType {
User = "User",
Application = "Application",
ManagedIdentity = "ManagedIdentity",
Key = "Key"
}
/**
* Defines values for CreatedByType. \
* {@link KnownCreatedByType} can be used interchangeably with CreatedByType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **User** \
* **Application** \
* **ManagedIdentity** \
* **Key**
*/
export type CreatedByType = string;
/** Known values of {@link PrivateLinkServiceConnectionStatus} that the service accepts. */
export enum KnownPrivateLinkServiceConnectionStatus {
Pending = "Pending",
Approved = "Approved",
Rejected = "Rejected",
Disconnected = "Disconnected"
}
/**
* Defines values for PrivateLinkServiceConnectionStatus. \
* {@link KnownPrivateLinkServiceConnectionStatus} can be used interchangeably with PrivateLinkServiceConnectionStatus,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Pending** \
* **Approved** \
* **Rejected** \
* **Disconnected**
*/
export type PrivateLinkServiceConnectionStatus = string;
/** Known values of {@link SharedPrivateLinkResourceStatus} that the service accepts. */
export enum KnownSharedPrivateLinkResourceStatus {
Pending = "Pending",
Approved = "Approved",
Rejected = "Rejected",
Disconnected = "Disconnected",
Timeout = "Timeout"
}
/**
* Defines values for SharedPrivateLinkResourceStatus. \
* {@link KnownSharedPrivateLinkResourceStatus} can be used interchangeably with SharedPrivateLinkResourceStatus,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Pending** \
* **Approved** \
* **Rejected** \
* **Disconnected** \
* **Timeout**
*/
export type SharedPrivateLinkResourceStatus = string;
/** Known values of {@link ACLAction} that the service accepts. */
export enum KnownACLAction {
Allow = "Allow",
Deny = "Deny"
}
/**
* Defines values for ACLAction. \
* {@link KnownACLAction} can be used interchangeably with ACLAction,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Allow** \
* **Deny**
*/
export type ACLAction = string;
/** Known values of {@link WebPubSubRequestType} that the service accepts. */
export enum KnownWebPubSubRequestType {
ClientConnection = "ClientConnection",
ServerConnection = "ServerConnection",
Restapi = "RESTAPI",
Trace = "Trace"
}
/**
* Defines values for WebPubSubRequestType. \
* {@link KnownWebPubSubRequestType} can be used interchangeably with WebPubSubRequestType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **ClientConnection** \
* **ServerConnection** \
* **RESTAPI** \
* **Trace**
*/
export type WebPubSubRequestType = string;
/** Known values of {@link ManagedIdentityType} that the service accepts. */
export enum KnownManagedIdentityType {
None = "None",
SystemAssigned = "SystemAssigned",
UserAssigned = "UserAssigned"
}
/**
* Defines values for ManagedIdentityType. \
* {@link KnownManagedIdentityType} can be used interchangeably with ManagedIdentityType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **None** \
* **SystemAssigned** \
* **UserAssigned**
*/
export type ManagedIdentityType = string;
/** Known values of {@link UpstreamAuthType} that the service accepts. */
export enum KnownUpstreamAuthType {
None = "None",
ManagedIdentity = "ManagedIdentity"
}
/**
* Defines values for UpstreamAuthType. \
* {@link KnownUpstreamAuthType} can be used interchangeably with UpstreamAuthType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **None** \
* **ManagedIdentity**
*/
export type UpstreamAuthType = string;
/** Known values of {@link KeyType} that the service accepts. */
export enum KnownKeyType {
Primary = "Primary",
Secondary = "Secondary",
Salt = "Salt"
}
/**
* Defines values for KeyType. \
* {@link KnownKeyType} can be used interchangeably with KeyType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Primary** \
* **Secondary** \
* **Salt**
*/
export type KeyType = string;
/** Known values of {@link ScaleType} that the service accepts. */
export enum KnownScaleType {
None = "None",
Manual = "Manual",
Automatic = "Automatic"
}
/**
* Defines values for ScaleType. \
* {@link KnownScaleType} can be used interchangeably with ScaleType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **None** \
* **Manual** \
* **Automatic**
*/
export type ScaleType = string;
/** Optional parameters. */
export interface OperationsListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type OperationsListResponse = OperationList;
/** Optional parameters. */
export interface OperationsListNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listNext operation. */
export type OperationsListNextResponse = OperationList;
/** Optional parameters. */
export interface WebPubSubCheckNameAvailabilityOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the checkNameAvailability operation. */
export type WebPubSubCheckNameAvailabilityResponse = NameAvailability;
/** Optional parameters. */
export interface WebPubSubListBySubscriptionOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listBySubscription operation. */
export type WebPubSubListBySubscriptionResponse = WebPubSubResourceList;
/** Optional parameters. */
export interface WebPubSubListByResourceGroupOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listByResourceGroup operation. */
export type WebPubSubListByResourceGroupResponse = WebPubSubResourceList;
/** Optional parameters. */
export interface WebPubSubGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type WebPubSubGetResponse = WebPubSubResource;
/** Optional parameters. */
export interface WebPubSubCreateOrUpdateOptionalParams
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 WebPubSubCreateOrUpdateResponse = WebPubSubResource;
/** Optional parameters. */
export interface WebPubSubDeleteOptionalParams
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 WebPubSubUpdateOptionalParams
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 WebPubSubUpdateResponse = WebPubSubResource;
/** Optional parameters. */
export interface WebPubSubListKeysOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listKeys operation. */
export type WebPubSubListKeysResponse = WebPubSubKeys;
/** Optional parameters. */
export interface WebPubSubRegenerateKeyOptionalParams
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 regenerateKey operation. */
export type WebPubSubRegenerateKeyResponse = WebPubSubKeys;
/** Optional parameters. */
export interface WebPubSubRestartOptionalParams
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 WebPubSubListSkusOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listSkus operation. */
export type WebPubSubListSkusResponse = SkuList;
/** Optional parameters. */
export interface WebPubSubListBySubscriptionNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listBySubscriptionNext operation. */
export type WebPubSubListBySubscriptionNextResponse = WebPubSubResourceList;
/** Optional parameters. */
export interface WebPubSubListByResourceGroupNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listByResourceGroupNext operation. */
export type WebPubSubListByResourceGroupNextResponse = WebPubSubResourceList;
/** Optional parameters. */
export interface UsagesListOptionalParams extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type UsagesListResponse = SignalRServiceUsageList;
/** Optional parameters. */
export interface UsagesListNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listNext operation. */
export type UsagesListNextResponse = SignalRServiceUsageList;
/** Optional parameters. */
export interface WebPubSubHubsListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type WebPubSubHubsListResponse = WebPubSubHubList;
/** Optional parameters. */
export interface WebPubSubHubsGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type WebPubSubHubsGetResponse = WebPubSubHub;
/** Optional parameters. */
export interface WebPubSubHubsCreateOrUpdateOptionalParams
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 WebPubSubHubsCreateOrUpdateResponse = WebPubSubHub;
/** Optional parameters. */
export interface WebPubSubHubsDeleteOptionalParams
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 WebPubSubHubsListNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listNext operation. */
export type WebPubSubHubsListNextResponse = WebPubSubHubList;
/** Optional parameters. */
export interface WebPubSubPrivateEndpointConnectionsListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type WebPubSubPrivateEndpointConnectionsListResponse = PrivateEndpointConnectionList;
/** Optional parameters. */
export interface WebPubSubPrivateEndpointConnectionsGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type WebPubSubPrivateEndpointConnectionsGetResponse = PrivateEndpointConnection;
/** Optional parameters. */
export interface WebPubSubPrivateEndpointConnectionsUpdateOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the update operation. */
export type WebPubSubPrivateEndpointConnectionsUpdateResponse = PrivateEndpointConnection;
/** Optional parameters. */
export interface WebPubSubPrivateEndpointConnectionsDeleteOptionalParams
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 WebPubSubPrivateEndpointConnectionsListNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listNext operation. */
export type WebPubSubPrivateEndpointConnectionsListNextResponse = PrivateEndpointConnectionList;
/** Optional parameters. */
export interface WebPubSubPrivateLinkResourcesListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type WebPubSubPrivateLinkResourcesListResponse = PrivateLinkResourceList;
/** Optional parameters. */
export interface WebPubSubPrivateLinkResourcesListNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listNext operation. */
export type WebPubSubPrivateLinkResourcesListNextResponse = PrivateLinkResourceList;
/** Optional parameters. */
export interface WebPubSubSharedPrivateLinkResourcesListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type WebPubSubSharedPrivateLinkResourcesListResponse = SharedPrivateLinkResourceList;
/** Optional parameters. */
export interface WebPubSubSharedPrivateLinkResourcesGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type WebPubSubSharedPrivateLinkResourcesGetResponse = SharedPrivateLinkResource;
/** Optional parameters. */
export interface WebPubSubSharedPrivateLinkResourcesCreateOrUpdateOptionalParams
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 WebPubSubSharedPrivateLinkResourcesCreateOrUpdateResponse = SharedPrivateLinkResource;
/** Optional parameters. */
export interface WebPubSubSharedPrivateLinkResourcesDeleteOptionalParams
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 WebPubSubSharedPrivateLinkResourcesListNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listNext operation. */
export type WebPubSubSharedPrivateLinkResourcesListNextResponse = SharedPrivateLinkResourceList;
/** Optional parameters. */
export interface WebPubSubManagementClientOptionalParams
extends coreClient.ServiceClientOptions {
/** server parameter */
$host?: string;
/** Api Version */
apiVersion?: string;
/** Overrides client endpoint. */
endpoint?: string;
} | the_stack |
import { expect } from 'chai';
import * as sinon from 'sinon';
import { StatusCodeError, UpdatesLockedError } from '../src/lib/errors';
import * as dockerUtils from '../src/lib/docker-utils';
import * as config from '../src/config';
import * as imageManager from '../src/compose/images';
import { ConfigTxt } from '../src/config/backends/config-txt';
import * as deviceState from '../src/device-state';
import * as deviceConfig from '../src/device-config';
import {
loadTargetFromFile,
appsJsonBackup,
} from '../src/device-state/preload';
import Service from '../src/compose/service';
import { intialiseContractRequirements } from '../src/lib/contracts';
import * as updateLock from '../src/lib/update-lock';
import * as fsUtils from '../src/lib/fs-utils';
import { TargetState } from '../src/types';
import * as dbHelper from './lib/db-helper';
import log from '../src/lib/supervisor-console';
const mockedInitialConfig = {
RESIN_SUPERVISOR_CONNECTIVITY_CHECK: 'true',
RESIN_SUPERVISOR_DELTA: 'false',
RESIN_SUPERVISOR_DELTA_APPLY_TIMEOUT: '0',
RESIN_SUPERVISOR_DELTA_REQUEST_TIMEOUT: '30000',
RESIN_SUPERVISOR_DELTA_RETRY_COUNT: '30',
RESIN_SUPERVISOR_DELTA_RETRY_INTERVAL: '10000',
RESIN_SUPERVISOR_DELTA_VERSION: '2',
RESIN_SUPERVISOR_INSTANT_UPDATE_TRIGGER: 'true',
RESIN_SUPERVISOR_LOCAL_MODE: 'false',
RESIN_SUPERVISOR_LOG_CONTROL: 'true',
RESIN_SUPERVISOR_OVERRIDE_LOCK: 'false',
RESIN_SUPERVISOR_POLL_INTERVAL: '60000',
RESIN_SUPERVISOR_VPN_CONTROL: 'true',
};
describe('device-state', () => {
const originalImagesSave = imageManager.save;
const originalImagesInspect = imageManager.inspectByName;
const originalGetCurrent = deviceConfig.getCurrent;
let testDb: dbHelper.TestDatabase;
before(async () => {
testDb = await dbHelper.createDB();
await config.initialized;
// Prevent side effects from changes in config
sinon.stub(config, 'on');
// Set the device uuid
await config.set({ uuid: 'local' });
await deviceState.initialized;
// disable log output during testing
sinon.stub(log, 'debug');
sinon.stub(log, 'warn');
sinon.stub(log, 'info');
sinon.stub(log, 'event');
sinon.stub(log, 'success');
// TODO: all these stubs are internal implementation details of
// deviceState, we should refactor deviceState to use dependency
// injection instead of initializing everything in memory
sinon.stub(Service as any, 'extendEnvVars').callsFake((env: any) => {
env['ADDITIONAL_ENV_VAR'] = 'foo';
return env;
});
intialiseContractRequirements({
supervisorVersion: '11.0.0',
deviceType: 'intel-nuc',
});
sinon
.stub(dockerUtils, 'getNetworkGateway')
.returns(Promise.resolve('172.17.0.1'));
// @ts-expect-error Assigning to a RO property
imageManager.cleanImageData = () => {
console.log('Cleanup database called');
};
// @ts-expect-error Assigning to a RO property
imageManager.save = () => Promise.resolve();
// @ts-expect-error Assigning to a RO property
imageManager.inspectByName = () => {
const err: StatusCodeError = new Error();
err.statusCode = 404;
return Promise.reject(err);
};
// @ts-expect-error Assigning to a RO property
deviceConfig.configBackend = new ConfigTxt();
// @ts-expect-error Assigning to a RO property
deviceConfig.getCurrent = async () => mockedInitialConfig;
});
after(async () => {
(Service as any).extendEnvVars.restore();
(dockerUtils.getNetworkGateway as sinon.SinonStub).restore();
// @ts-expect-error Assigning to a RO property
imageManager.save = originalImagesSave;
// @ts-expect-error Assigning to a RO property
imageManager.inspectByName = originalImagesInspect;
// @ts-expect-error Assigning to a RO property
deviceConfig.getCurrent = originalGetCurrent;
try {
await testDb.destroy();
} catch (e) {
/* noop */
}
sinon.restore();
});
afterEach(async () => {
await testDb.reset();
});
it('loads a target state from an apps.json file and saves it as target state, then returns it', async () => {
const appsJson = process.env.ROOT_MOUNTPOINT + '/apps.json';
await loadTargetFromFile(appsJson);
const targetState = await deviceState.getTarget();
expect(await fsUtils.exists(appsJsonBackup(appsJson))).to.be.true;
expect(targetState)
.to.have.property('local')
.that.has.property('config')
.that.has.property('HOST_CONFIG_gpu_mem')
.that.equals('256');
expect(targetState)
.to.have.property('local')
.that.has.property('apps')
.that.has.property('1234')
.that.is.an('object');
const app = targetState.local.apps[1234];
expect(app).to.have.property('appName').that.equals('superapp');
expect(app).to.have.property('services').that.is.an('array').with.length(1);
expect(app.services[0])
.to.have.property('config')
.that.has.property('image')
.that.equals('registry2.resin.io/superapp/abcdef:latest');
expect(app.services[0].config)
.to.have.property('labels')
.that.has.property('io.balena.something')
.that.equals('bar');
expect(app).to.have.property('appName').that.equals('superapp');
expect(app).to.have.property('services').that.is.an('array').with.length(1);
expect(app.services[0])
.to.have.property('config')
.that.has.property('image')
.that.equals('registry2.resin.io/superapp/abcdef:latest');
expect(app.services[0].config)
.to.have.property('labels')
.that.has.property('io.balena.something')
.that.equals('bar');
expect(app).to.have.property('appName').that.equals('superapp');
expect(app).to.have.property('services').that.is.an('array').with.length(1);
expect(app.services[0])
.to.have.property('config')
.that.has.property('image')
.that.equals('registry2.resin.io/superapp/abcdef:latest');
expect(app.services[0].config)
.to.have.property('labels')
.that.has.property('io.balena.something')
.that.equals('bar');
expect(app).to.have.property('appName').that.equals('superapp');
expect(app).to.have.property('services').that.is.an('array').with.length(1);
expect(app.services[0])
.to.have.property('config')
.that.has.property('image')
.that.equals('registry2.resin.io/superapp/abcdef:latest');
expect(app.services[0].config)
.to.have.property('labels')
.that.has.property('io.balena.something')
.that.equals('bar');
expect(app).to.have.property('appName').that.equals('superapp');
expect(app).to.have.property('services').that.is.an('array').with.length(1);
expect(app.services[0])
.to.have.property('config')
.that.has.property('image')
.that.equals('registry2.resin.io/superapp/abcdef:latest');
expect(app.services[0].config)
.to.have.property('labels')
.that.has.property('io.balena.something')
.that.equals('bar');
// Restore renamed apps.json
await fsUtils.safeRename(appsJsonBackup(appsJson), appsJson);
});
it('stores info for pinning a device after loading an apps.json with a pinDevice field', async () => {
const appsJson = process.env.ROOT_MOUNTPOINT + '/apps-pin.json';
await loadTargetFromFile(appsJson);
const pinned = await config.get('pinDevice');
expect(pinned).to.have.property('app').that.equals(1234);
expect(pinned).to.have.property('commit').that.equals('abcdef');
expect(await fsUtils.exists(appsJsonBackup(appsJson))).to.be.true;
// Restore renamed apps.json
await fsUtils.safeRename(appsJsonBackup(appsJson), appsJson);
});
it('emits a change event when a new state is reported', (done) => {
// TODO: where is the test on this test?
deviceState.once('change', done);
deviceState.reportCurrentState({ someStateDiff: 'someValue' } as any);
});
it('writes the target state to the db with some extra defaults', async () => {
await deviceState.setTarget({
local: {
name: 'aDeviceWithDifferentName',
config: {
RESIN_HOST_CONFIG_gpu_mem: '512',
},
apps: {
myapp: {
id: 1234,
name: 'superapp',
class: 'fleet',
releases: {
afafafa: {
id: 2,
services: {
aservice: {
id: 23,
image_id: 12345,
image: 'registry2.resin.io/superapp/edfabc',
environment: {
FOO: 'bar',
},
labels: {},
},
anotherService: {
id: 24,
image_id: 12346,
image: 'registry2.resin.io/superapp/afaff',
environment: {
FOO: 'bro',
},
labels: {},
},
},
volumes: {},
networks: {},
},
},
},
},
},
} as TargetState);
const targetState = await deviceState.getTarget();
expect(targetState)
.to.have.property('local')
.that.has.property('config')
.that.has.property('HOST_CONFIG_gpu_mem')
.that.equals('512');
expect(targetState)
.to.have.property('local')
.that.has.property('apps')
.that.has.property('1234')
.that.is.an('object');
const app = targetState.local.apps[1234];
expect(app).to.have.property('appName').that.equals('superapp');
expect(app).to.have.property('commit').that.equals('afafafa');
expect(app).to.have.property('services').that.is.an('array').with.length(2);
expect(app.services[0])
.to.have.property('config')
.that.has.property('image')
.that.equals('registry2.resin.io/superapp/edfabc:latest');
expect(app.services[0].config)
.to.have.property('environment')
.that.has.property('FOO')
.that.equals('bar');
expect(app.services[1])
.to.have.property('config')
.that.has.property('image')
.that.equals('registry2.resin.io/superapp/afaff:latest');
expect(app.services[1].config)
.to.have.property('environment')
.that.has.property('FOO')
.that.equals('bro');
});
it('does not allow setting an invalid target state', () => {
// v2 state should be rejected
expect(
deviceState.setTarget({
local: {
name: 'aDeviceWithDifferentName',
config: {
RESIN_HOST_CONFIG_gpu_mem: '512',
},
apps: {
1234: {
appId: '1234',
name: 'superapp',
commit: 'afafafa',
releaseId: '2',
config: {},
services: {
23: {
serviceId: '23',
serviceName: 'aservice',
imageId: '12345',
image: 'registry2.resin.io/superapp/edfabc',
environment: {
' FOO': 'bar',
},
labels: {},
},
24: {
serviceId: '24',
serviceName: 'anotherService',
imageId: '12346',
image: 'registry2.resin.io/superapp/afaff',
environment: {
FOO: 'bro',
},
labels: {},
},
},
},
},
},
dependent: { apps: {}, devices: {} },
} as any),
).to.be.rejected;
});
it('allows triggering applying the target state', (done) => {
const applyTargetStub = sinon
.stub(deviceState, 'applyTarget')
.returns(Promise.resolve());
deviceState.triggerApplyTarget({ force: true });
expect(applyTargetStub).to.not.be.called;
setTimeout(() => {
expect(applyTargetStub).to.be.calledWith({
force: true,
initial: false,
});
applyTargetStub.restore();
done();
}, 1000);
});
it('accepts a target state with an valid contract', async () => {
await deviceState.setTarget({
local: {
name: 'aDeviceWithDifferentName',
config: {},
apps: {
myapp: {
id: 1234,
name: 'superapp',
class: 'fleet',
releases: {
one: {
id: 2,
services: {
valid: {
id: 23,
image_id: 12345,
image: 'registry2.resin.io/superapp/valid',
environment: {},
labels: {},
},
alsoValid: {
id: 24,
image_id: 12346,
image: 'registry2.resin.io/superapp/afaff',
contract: {
type: 'sw.container',
slug: 'supervisor-version',
name: 'Enforce supervisor version',
requires: [
{
type: 'sw.supervisor',
version: '>=11.0.0',
},
],
},
environment: {},
labels: {},
},
},
volumes: {},
networks: {},
},
},
},
},
},
} as TargetState);
const targetState = await deviceState.getTarget();
const app = targetState.local.apps[1234];
expect(app).to.have.property('appName').that.equals('superapp');
expect(app).to.have.property('commit').that.equals('one');
// Only a single service should be on the target state
expect(app).to.have.property('services').that.is.an('array').with.length(2);
expect(app.services[1])
.that.has.property('serviceName')
.that.equals('alsoValid');
});
it('accepts a target state with an invalid contract for an optional container', async () => {
await deviceState.setTarget({
local: {
name: 'aDeviceWithDifferentName',
config: {},
apps: {
myapp: {
id: 1234,
name: 'superapp',
class: 'fleet',
releases: {
one: {
id: 2,
services: {
valid: {
id: 23,
image_id: 12345,
image: 'registry2.resin.io/superapp/valid',
environment: {},
labels: {},
},
invalidButOptional: {
id: 24,
image_id: 12346,
image: 'registry2.resin.io/superapp/afaff',
contract: {
type: 'sw.container',
slug: 'supervisor-version',
name: 'Enforce supervisor version',
requires: [
{
type: 'sw.supervisor',
version: '>=12.0.0',
},
],
},
environment: {},
labels: {
'io.balena.features.optional': 'true',
},
},
},
volumes: {},
networks: {},
},
},
},
},
},
} as TargetState);
const targetState = await deviceState.getTarget();
const app = targetState.local.apps[1234];
expect(app).to.have.property('appName').that.equals('superapp');
expect(app).to.have.property('commit').that.equals('one');
// Only a single service should be on the target state
expect(app).to.have.property('services').that.is.an('array').with.length(1);
expect(app.services[0])
.that.has.property('serviceName')
.that.equals('valid');
});
it('rejects a target state with invalid contract and non optional service', async () => {
await expect(
deviceState.setTarget({
local: {
name: 'aDeviceWithDifferentName',
config: {},
apps: {
myapp: {
id: 1234,
name: 'superapp',
class: 'fleet',
releases: {
one: {
id: 2,
services: {
valid: {
id: 23,
image_id: 12345,
image: 'registry2.resin.io/superapp/valid',
environment: {},
labels: {},
},
invalid: {
id: 24,
image_id: 12346,
image: 'registry2.resin.io/superapp/afaff',
contract: {
type: 'sw.container',
slug: 'supervisor-version',
name: 'Enforce supervisor version',
requires: [
{
type: 'sw.supervisor',
version: '>=12.0.0',
},
],
},
environment: {},
labels: {},
},
},
volumes: {},
networks: {},
},
},
},
},
},
} as TargetState),
).to.be.rejected;
});
// TODO: There is no easy way to test this behaviour with the current
// interface of device-state. We should really think about the device-state
// interface to allow this flexibility (and to avoid having to change module
// internal variables)
it.skip('cancels current promise applying the target state');
it.skip('applies the target state for device config');
it.skip('applies the target state for applications');
it('prevents reboot or shutdown when HUP rollback breadcrumbs are present', async () => {
const testErrMsg = 'Waiting for Host OS updates to finish';
sinon
.stub(updateLock, 'abortIfHUPInProgress')
.throws(new UpdatesLockedError(testErrMsg));
await expect(deviceState.reboot())
.to.eventually.be.rejectedWith(testErrMsg)
.and.be.an.instanceOf(UpdatesLockedError);
await expect(deviceState.shutdown())
.to.eventually.be.rejectedWith(testErrMsg)
.and.be.an.instanceOf(UpdatesLockedError);
(updateLock.abortIfHUPInProgress as sinon.SinonStub).restore();
});
}); | the_stack |
import 'chrome://profile-picker/profile_picker.js';
import {loadTimeData, ManageProfilesBrowserProxyImpl, NavigationMixin, ProfileCardElement, ProfilePickerMainViewElement, ProfileState, Routes} from 'chrome://profile-picker/profile_picker.js';
import {webUIListenerCallback} from 'chrome://resources/js/cr.m.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {assertEquals, assertTrue} from 'chrome://webui-test/chai_assert.js';
import {flushTasks, waitBeforeNextRender} from 'chrome://webui-test/test_util.js';
import {TestManageProfilesBrowserProxy} from './test_manage_profiles_browser_proxy.js';
class NavigationElement extends NavigationMixin
(PolymerElement) {
static get is() {
return 'navigation-element';
}
changeCalled: boolean = false;
route: string = '';
ready() {
super.ready();
this.reset();
}
onRouteChange(route: Routes, _step: string) {
this.changeCalled = true;
this.route = route;
}
reset() {
this.changeCalled = false;
this.route = '';
}
}
declare global {
interface HTMLElementTagNameMap {
'navigation-element': NavigationElement;
}
}
customElements.define(NavigationElement.is, NavigationElement);
suite('ProfilePickerMainViewTest', function() {
let mainViewElement: ProfilePickerMainViewElement;
let browserProxy: TestManageProfilesBrowserProxy;
let navigationElement: NavigationElement;
function resetTest() {
document.body.innerHTML = '';
navigationElement = document.createElement('navigation-element');
document.body.appendChild(navigationElement);
mainViewElement = document.createElement('profile-picker-main-view');
document.body.appendChild(mainViewElement);
return waitBeforeNextRender(mainViewElement);
}
function resetPolicies() {
// This is necessary as |loadTimeData| state leaks between tests.
// Any load time data manipulated by the tests needs to be reset here.
loadTimeData.overrideValues({
isGuestModeEnabled: true,
isProfileCreationAllowed: true,
isAskOnStartupAllowed: true
});
}
setup(function() {
browserProxy = new TestManageProfilesBrowserProxy();
ManageProfilesBrowserProxyImpl.setInstance(browserProxy);
resetPolicies();
return resetTest();
});
/**
* @param n Indicates the desired number of profiles.
*/
function generateProfilesList(n: number): ProfileState[] {
return Array(n)
.fill(0)
.map((_x, i) => i % 2 === 0)
.map((sync, i) => ({
profilePath: `profilePath${i}`,
localProfileName: `profile${i}`,
isSyncing: sync,
needsSignin: false,
gaiaName: sync ? `User${i}` : '',
userName: sync ? `User${i}@gmail.com` : '',
isManaged: i % 4 === 0,
avatarIcon: `AvatarUrl-${i}`,
// <if expr="lacros">
isPrimaryLacrosProfile: false,
// </if>
}));
}
async function verifyProfileCard(
expectedProfiles: ProfileState[],
profiles: NodeListOf<ProfileCardElement>) {
assertEquals(expectedProfiles.length, profiles.length);
for (let i = 0; i < expectedProfiles.length; i++) {
const profile = profiles[i]!;
const expectedProfile = expectedProfiles[i]!;
assertTrue(!!profile.shadowRoot!.querySelector('profile-card-menu'));
profile.shadowRoot!.querySelector('cr-button')!.click();
await browserProxy.whenCalled('launchSelectedProfile');
assertEquals(
profile.shadowRoot!
.querySelector<HTMLElement>('#forceSigninContainer')!.hidden,
!expectedProfile.needsSignin);
const gaiaName = profile.$.gaiaName;
assertEquals(gaiaName.hidden, expectedProfile.needsSignin);
assertEquals(gaiaName.innerText.trim(), expectedProfile.gaiaName);
assertEquals(profile.$.nameInput.value, expectedProfile.localProfileName);
assertEquals(
profile.shadowRoot!.querySelector<HTMLElement>(
'#iconContainer')!.hidden,
!expectedProfile.isManaged);
assertEquals(
(profile.shadowRoot!
.querySelector<HTMLImageElement>('.profile-avatar')!.src)
.split('/')
.pop(),
expectedProfile.avatarIcon);
}
}
test('MainViewWithDefaultPolicies', async function() {
assertTrue(navigationElement.changeCalled);
assertEquals(navigationElement.route, Routes.MAIN);
await browserProxy.whenCalled('initializeMainView');
// Hidden while profiles list is not yet defined.
assertTrue(mainViewElement.$.wrapper.hidden);
assertTrue(mainViewElement.$.askOnStartup.hidden);
const profiles = generateProfilesList(6);
webUIListenerCallback('profiles-list-changed', [...profiles]);
flushTasks();
// Profiles list defined.
assertTrue(!mainViewElement.$.wrapper.hidden);
assertTrue(!mainViewElement.$.askOnStartup.hidden);
assertTrue(mainViewElement.$.askOnStartup.checked);
// Verify profile card.
await verifyProfileCard(
profiles, mainViewElement.shadowRoot!.querySelectorAll('profile-card'));
// Browse as guest.
assertTrue(!!mainViewElement.$.browseAsGuestButton);
mainViewElement.$.browseAsGuestButton.click();
await browserProxy.whenCalled('launchGuestProfile');
// Ask when chrome opens.
mainViewElement.$.askOnStartup.click();
await browserProxy.whenCalled('askOnStartupChanged');
assertTrue(!mainViewElement.$.askOnStartup.checked);
// Update profile data.
profiles[1] = profiles[4]!;
webUIListenerCallback('profiles-list-changed', [...profiles]);
flushTasks();
await verifyProfileCard(
profiles, mainViewElement.shadowRoot!.querySelectorAll('profile-card'));
// Profiles update on remove.
webUIListenerCallback('profile-removed', profiles[3]!.profilePath);
profiles.splice(3, 1);
flushTasks();
await verifyProfileCard(
profiles, mainViewElement.shadowRoot!.querySelectorAll('profile-card'));
});
test('EditLocalProfileName', async function() {
await browserProxy.whenCalled('initializeMainView');
const profiles = generateProfilesList(1);
webUIListenerCallback('profiles-list-changed', [...profiles]);
flushTasks();
const localProfileName =
mainViewElement.shadowRoot!.querySelector('profile-card')!.$.nameInput;
assertEquals(localProfileName.value, profiles[0]!.localProfileName);
// Set to valid profile name.
localProfileName.value = 'Alice';
localProfileName.dispatchEvent(
new CustomEvent('change', {bubbles: true, composed: true}));
const args = await browserProxy.whenCalled('setProfileName');
assertEquals(args[0], profiles[0]!.profilePath);
assertEquals(args[1], 'Alice');
assertEquals(localProfileName.value, 'Alice');
// Set to invalid profile name
localProfileName.value = '';
assertTrue(localProfileName.invalid);
});
test('GuestModeDisabled', async function() {
loadTimeData.overrideValues({
isGuestModeEnabled: false,
});
resetTest();
assertEquals(mainViewElement.$.browseAsGuestButton.style.display, 'none');
await browserProxy.whenCalled('initializeMainView');
webUIListenerCallback('profiles-list-changed', generateProfilesList(2));
flushTasks();
assertEquals(mainViewElement.$.browseAsGuestButton.style.display, 'none');
});
test('ProfileCreationNotAllowed', async function() {
loadTimeData.overrideValues({
isProfileCreationAllowed: false,
});
resetTest();
const addProfile =
mainViewElement.shadowRoot!.querySelector<HTMLElement>('#addProfile')!;
assertEquals(addProfile.style.display, 'none');
await browserProxy.whenCalled('initializeMainView');
webUIListenerCallback('profiles-list-changed', generateProfilesList(2));
flushTasks();
navigationElement.reset();
assertEquals(addProfile.style.display, 'none');
addProfile.click();
flushTasks();
assertTrue(!navigationElement.changeCalled);
});
test('AskOnStartupSingleToMultipleProfiles', async function() {
await browserProxy.whenCalled('initializeMainView');
// Hidden while profiles list is not yet defined.
assertTrue(mainViewElement.$.wrapper.hidden);
assertTrue(mainViewElement.$.askOnStartup.hidden);
let profiles = generateProfilesList(1);
webUIListenerCallback('profiles-list-changed', [...profiles]);
flushTasks();
await verifyProfileCard(
profiles, mainViewElement.shadowRoot!.querySelectorAll('profile-card'));
// The checkbox 'Ask when chrome opens' should only be visible to
// multi-profile users.
assertTrue(mainViewElement.$.askOnStartup.hidden);
// Add a second profile.
profiles = generateProfilesList(2);
webUIListenerCallback('profiles-list-changed', [...profiles]);
flushTasks();
await verifyProfileCard(
profiles, mainViewElement.shadowRoot!.querySelectorAll('profile-card'));
assertTrue(!mainViewElement.$.askOnStartup.hidden);
assertTrue(mainViewElement.$.askOnStartup.checked);
mainViewElement.$.askOnStartup.click();
await browserProxy.whenCalled('askOnStartupChanged');
assertTrue(!mainViewElement.$.askOnStartup.checked);
});
test('AskOnStartupMultipleToSingleProfile', async function() {
await browserProxy.whenCalled('initializeMainView');
// Hidden while profiles list is not yet defined.
assertTrue(mainViewElement.$.wrapper.hidden);
assertTrue(mainViewElement.$.askOnStartup.hidden);
const profiles = generateProfilesList(2);
webUIListenerCallback('profiles-list-changed', [...profiles]);
flushTasks();
await verifyProfileCard(
profiles, mainViewElement.shadowRoot!.querySelectorAll('profile-card'));
assertTrue(!mainViewElement.$.askOnStartup.hidden);
// Remove profile.
webUIListenerCallback('profile-removed', profiles[0]!.profilePath);
flushTasks();
await verifyProfileCard(
[profiles[1]!],
mainViewElement.shadowRoot!.querySelectorAll('profile-card'));
assertTrue(mainViewElement.$.askOnStartup.hidden);
});
test('AskOnStartupMulipleProfiles', async function() {
// Disable AskOnStartup
loadTimeData.overrideValues({isAskOnStartupAllowed: false});
resetTest();
await browserProxy.whenCalled('initializeMainView');
// Hidden while profiles list is not yet defined.
assertTrue(mainViewElement.$.wrapper.hidden);
assertTrue(mainViewElement.$.askOnStartup.hidden);
const profiles = generateProfilesList(2);
webUIListenerCallback('profiles-list-changed', [...profiles]);
flushTasks();
await verifyProfileCard(
profiles, mainViewElement.shadowRoot!.querySelectorAll('profile-card'));
// Checkbox hidden even if there are multiple profiles.
assertTrue(mainViewElement.$.askOnStartup.hidden);
});
test('ForceSigninIsEnabled', async function() {
loadTimeData.overrideValues({isForceSigninEnabled: true});
resetTest();
await browserProxy.whenCalled('initializeMainView');
const profiles = generateProfilesList(2);
profiles[0]!.needsSignin = true;
webUIListenerCallback('profiles-list-changed', [...profiles]);
flushTasks();
await verifyProfileCard(
profiles, mainViewElement.shadowRoot!.querySelectorAll('profile-card'));
});
}); | the_stack |
import {ua} from 'griffith-utils'
import FragmentFetch from '../fetch'
import MP4Parse from '../mp4/mp4Parse'
import MP4Probe from '../mp4/mp4Probe'
import FMP4 from '../fmp4/fmp4Generator'
import {concatTypedArray} from '../fmp4/utils'
import {abortPolyfill} from './polyfill'
import {Mp4BoxTree} from '../mp4/types'
const MAGIC_NUMBER = 20000
type SourceBufferKey = 'audio' | 'video'
export default class MSE {
audioQueue: BufferSource[]
mediaSource!: MediaSource
mimeTypes: any
mp4BoxTreeObject: any
mp4Probe?: MP4Probe
needUpdateTime?: boolean
qualityChangeFlag: boolean
sourceBuffers: {
[key in SourceBufferKey]: SourceBuffer | null
}
src: string
video: HTMLVideoElement
videoQueue: BufferSource[]
constructor(video: any, src: any) {
this.video = video
this.src = src
this.qualityChangeFlag = false
this.videoQueue = []
this.audioQueue = []
this.sourceBuffers = {
video: null,
audio: null,
}
this.mimeTypes = {
video: 'video/mp4; codecs="avc1.42E01E"',
audio: 'audio/mp4; codecs="mp4a.40.2"',
}
this.installSrc()
}
installSrc = () => {
this.mediaSource = new MediaSource()
this.mediaSource.addEventListener('sourceopen', this.handleSourceOpen)
this.video.src = URL.createObjectURL(this.mediaSource)
}
handleSourceOpen = () => {
this.sourceBuffers.video = this.mediaSource.addSourceBuffer(
this.mimeTypes.video
)
this.sourceBuffers.audio = this.mediaSource.addSourceBuffer(
this.mimeTypes.audio
)
this.sourceBuffers.video.addEventListener('updateend', () => {
const buffer = this.videoQueue.shift()
if (buffer && this.mediaSource.readyState === 'open') {
this.handleAppendBuffer(buffer, 'video')
}
if (this.needUpdateTime) {
this.needUpdateTime = false
this.handleTimeUpdate()
}
})
this.sourceBuffers.audio.addEventListener('updateend', () => {
const buffer = this.audioQueue.shift()
if (buffer && this.mediaSource.readyState === 'open') {
this.handleAppendBuffer(buffer, 'audio')
}
})
}
handleAppendBuffer = (buffer: BufferSource, type: SourceBufferKey) => {
if (this.mediaSource.readyState === 'open') {
try {
if (this.sourceBuffers[type]) {
this.sourceBuffers[type]!.appendBuffer(buffer)
}
} catch (error) {
// see https://developers.google.com/web/updates/2017/10/quotaexceedederror
// @ts-expect-error any
if (error.code === 22) {
this.handleQuotaExceededError(buffer, type)
} else {
throw error
}
}
} else {
this[`${type}Queue`].push(buffer)
}
}
init() {
// 获取 mdat 外的数据
return this.loadData()
.then((res) => {
// @ts-expect-error No overload matches this call.
return new MP4Parse(new Uint8Array(res)).mp4BoxTreeObject
})
.then((mp4BoxTreeObject) => {
// 有可能 moov 在最后一个 box,导致我们第一次请求 0~MAGIC_NUMBER 没有请求到 moov。
const {moov, ftyp} = mp4BoxTreeObject
if (!moov) {
let moovStart = 0
for (const box in mp4BoxTreeObject) {
// @ts-expect-error Property 'size' does not exist
moovStart += mp4BoxTreeObject[box as keyof Mp4BoxTree].size
}
// @ts-expect-error ts-migrate(2345) FIXME: Argument of type '""' is not assignable to paramet... Remove this comment to see the full error message
return this.loadData(moovStart, '').then((res) => {
// @ts-expect-error ts-migrate(2769) FIXME: No overload matches this call.
const {moov} = new MP4Parse(new Uint8Array(res)).mp4BoxTreeObject
if (moov) {
mp4BoxTreeObject.moov = moov
return mp4BoxTreeObject
}
})
} else {
// 有可能视频较大,第一次请求没有请求到完整的 moov box
// @ts-expect-error Operands of '+' operation must either be both strings or both numbers
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
const ftypAndMoovSize = moov.size + ftyp.size
if (ftypAndMoovSize > MAGIC_NUMBER) {
// @ts-expect-error Property 'size' does not exist on type
return this.loadData(ftyp.size, ftypAndMoovSize).then((res) => {
// @ts-expect-error ts-migrate(2769) FIXME: No overload matches this call.
const {moov} = new MP4Parse(new Uint8Array(res)).mp4BoxTreeObject
if (moov) {
mp4BoxTreeObject.moov = moov
return mp4BoxTreeObject
}
})
}
}
return mp4BoxTreeObject
})
.then((mp4BoxTreeObject) => {
this.mp4Probe = new MP4Probe(mp4BoxTreeObject!)
this.mp4BoxTreeObject = mp4BoxTreeObject
const videoRawData = concatTypedArray(
FMP4.ftyp(),
FMP4.moov(this.mp4Probe.mp4Data, 'video')
)
const audioRawData = concatTypedArray(
FMP4.ftyp(),
FMP4.moov(this.mp4Probe.mp4Data, 'audio')
)
// 如果是切换清晰度,mediaSource 的 readyState 已经 open 了,可以直接 append 数据。
// mediaSource is already open when we switch video quality.
if (this.qualityChangeFlag) {
this.handleAppendBuffer(videoRawData, 'video')
this.handleAppendBuffer(audioRawData, 'audio')
} else {
this.mediaSource.addEventListener('sourceopen', () => {
this.handleAppendBuffer(videoRawData, 'video')
this.handleAppendBuffer(audioRawData, 'audio')
})
}
})
}
hasBufferedCache = (isSeek: any) => {
const {
timeRange: [start, end],
} = this.mp4Probe!
// handle seek case and normal case
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
const time = isSeek ? this.video.currentTime : Math.floor((start + end) / 2)
const buffered = this.video.buffered
if (buffered && buffered.length > 0) {
for (let i = 0; i < buffered.length; i++) {
if (time >= buffered.start(i) && time <= buffered.end(i)) {
return true
}
}
}
return false
}
seek = (time: any) => {
FragmentFetch.clear()
const [start, end] = this.mp4Probe!.getFragmentPosition(time)
// 对于已经请求的数据不再重复请求
// No need to repeat request video data
if (this.hasBufferedCache(time) && !this.qualityChangeFlag) {
return
}
this.handleReplayCase()
void this.loadData(start as number, end as number).then((mdatBuffer) => {
if (!mdatBuffer) {
return
}
const {videoTrackInfo, audioTrackInfo} =
this.mp4Probe!.getTrackInfo(mdatBuffer)
const {videoInterval, audioInterval} = this.mp4Probe!
const videoBaseMediaDecodeTime = videoInterval!.timeInterVal[0]
const audioBaseMediaDecodeTime = audioInterval!.timeInterVal[0]
const videoRawData = concatTypedArray(
FMP4.moof(videoTrackInfo, videoBaseMediaDecodeTime),
FMP4.mdat(videoTrackInfo)
)
// maybe the last GOP dont have audio track
// 最后一个 GOP 序列可能没有音频轨
if (audioTrackInfo.samples.length !== 0) {
const audioRawData = concatTypedArray(
FMP4.moof(audioTrackInfo, audioBaseMediaDecodeTime),
FMP4.mdat(audioTrackInfo)
)
this.handleAppendBuffer(audioRawData, 'audio')
}
this.handleAppendBuffer(videoRawData, 'video')
if (time) {
this.needUpdateTime = true
}
this.qualityChangeFlag = false
})
}
changeQuality(newSrc: string) {
this.src = newSrc
this.qualityChangeFlag = true
// remove old quality buffer before append new quality buffer
for (const key in this.sourceBuffers) {
const track = this.sourceBuffers[key as SourceBufferKey] as SourceBuffer
const length = track.buffered.length
if (length > 0) {
this.removeBuffer(
track.buffered.start(0),
track.buffered.end(length - 1),
key as SourceBufferKey
)
}
}
void this.init().then(() => {
// eslint-disable-next-line no-self-assign
this.video.currentTime = this.video.currentTime
})
}
removeBuffer(start: number, end: number, type: SourceBufferKey) {
const track = this.sourceBuffers[type] as SourceBuffer
if (track.updating) {
const {isSafari} = ua
if (isSafari) {
// Safari 9/10/11/12 does not correctly implement abort() on SourceBuffer.
// Calling abort() before appending a segment causes that segment to be
// incomplete in buffer.
// Bug filed: https://bugs.webkit.org/show_bug.cgi?id=165342
abortPolyfill()
}
track.abort()
}
track.remove(start, end)
}
loadData(start = 0, end = MAGIC_NUMBER) {
return new Promise<ArrayBuffer>((resolve) => {
new FragmentFetch(this.src, start, end, resolve)
}).catch(() => {
// catch cancel error
})
}
handleTimeUpdate = () => {
if (!this.mp4Probe) {
return
}
const {
// @ts-expect-error Property 'offsetInterVal' does not exist on type 'never[] | TimeOffsetInterval'
videoInterval: {offsetInterVal = []} = [],
mp4Data: {videoSamplesLength},
timeRange = [],
} = this.mp4Probe
if (this.mediaSource.readyState !== 'closed') {
if (
offsetInterVal[1] === videoSamplesLength &&
this.video.currentTime > timeRange[0]!
) {
this.destroy()
} else if (this.shouldFetchNextSegment()) {
// @ts-expect-error ts-migrate(2554) FIXME: Expected 1 arguments, but got 0.
this.seek()
}
}
}
handleReplayCase = () => {
if (this.mediaSource.readyState === 'ended') {
// If MediaSource.readyState value is ended,
// setting SourceBuffer.timestampOffset will cause this value to transition to open.
this.sourceBuffers.video!.timestampOffset = 0
}
}
shouldFetchNextSegment = () => {
this.handleReplayCase()
if (this.mp4Probe!.isDraining(this.video.currentTime)) {
return true
}
return false
}
destroy = () => {
this.mediaSource.removeEventListener('sourceopen', this.handleSourceOpen)
URL.revokeObjectURL(this.video.src)
if (
this.mediaSource.readyState === 'open' &&
!this.sourceBuffers.video!.updating &&
!this.sourceBuffers.audio!.updating
) {
this.mediaSource.endOfStream()
}
}
handleQuotaExceededError = (buffer: BufferSource, type: SourceBufferKey) => {
for (const key in this.sourceBuffers) {
const track = this.sourceBuffers[key as SourceBufferKey] as SourceBuffer
const currentTime = this.video.currentTime
let removeStart = 0
if (track.buffered.length > 0) {
removeStart = track.buffered.start(0) + 10
}
this.removeBuffer(removeStart, currentTime - 10, key as SourceBufferKey)
}
// re-append(maybe should lower the playback resolution)
this.handleAppendBuffer(buffer, type)
}
} | the_stack |
export type MatchRange = [number, number];
/**
* Match encapsulates information about a match between a certain
* user input and a string.
*/
export interface Match {
/** Subject to match. */
readonly subject: string;
/** Character ranges inside subject that triggered the match. */
readonly matchRanges: ReadonlyArray<MatchRange>;
}
/**
* Find longest common prefix of 2 strings. For example: for
* 'foo1' and 'foo bar', the longest common prefix will be 'foo'.
*/
function findLongestCommonPrefix(s1: string, s2: string): string {
let i = 0;
while (i < s1.length && i < s2.length && s1[i] === s2[i]) {
i++;
}
return s1.substring(0, i);
}
/**
* Recursive match helper function.
*
* @param currentComponent Current string component being matched.
* currentComponent === undefined means there are no more string
* components to check.
* @param currentComponentOffset Offset of the currentComponent within
* the string. Used to calculate matched character ranges.
* @param otherComponents String components that should be checked
* for a match after the currentComponent.
* @param userInput A string containing a yet unmatched part of the user
* input.
* @param matchedRanges Current list of matched ranges.
*/
function recursiveMatch(
currentComponent: string|undefined, currentComponentOffset: number,
otherComponents: string[], userInput: string,
matchedRanges: MatchRange[]): MatchRange[]|undefined {
// Empty user input means that all parts of it were removed when they
// matched string components, meaning we have a successful match.
if (!userInput) {
return matchedRanges;
}
// Non-empty userInput and no more string components means a failed match.
if (currentComponent === undefined) {
return undefined;
}
const commonPrefix = findLongestCommonPrefix(currentComponent, userInput);
// Generate all possible prefixes from the longest common prefix and
// match them recursively.
for (let j = commonPrefix.length; j > 0; --j) {
const result = recursiveMatch(
// Shift components by 1.
otherComponents[0],
currentComponentOffset + currentComponent.length + 1,
otherComponents.slice(1),
// Shift user input by the size of matched string and remove
// trailing whitespace, if there's any.
userInput.substring(j).trim(),
// Update ranges with a newfound match.
matchedRanges.concat(
[[currentComponentOffset, currentComponentOffset + j]]));
if (result !== undefined) {
return result;
}
}
// This code is reached only if all of the possible currentComponent's
// prefixes didn't match the current userInput. In this case, try to
// match same userInput to the next component.
return recursiveMatch(
otherComponents[0], currentComponentOffset + currentComponent.length + 1,
otherComponents.slice(1), userInput, matchedRanges);
}
/**
* Helper class for finding matching strings using prefix-based matching
* algorithm.
*/
class PrefixMatchData {
/* String components (done by splitting the title with ' '). */
private readonly components: string[];
/** A string containing first letter of every title component. */
readonly firstLetters: string;
constructor(subject: string) {
this.components = subject.toLowerCase().split(' ');
this.firstLetters = this.components.map(x => x[0]).join('');
}
/**
* Matches a user input against the subject string.
*
* @return A list of MatchRanges if there's a match or undefined
* otherwise.
*/
match(input: string): MatchRange[]|undefined {
return recursiveMatch(
this.components[0], 0, this.components.slice(1), input.trim(), []);
}
}
/**
* An implementation of a fuzzy matching algorithm used to filter the list
* of strings by fuzzy matching them to user input. See the
* match() method documentation for more details.
*/
export class FuzzyMatcher {
private readonly prefixMatchMap = new Map<PrefixMatchData, string>();
constructor(/** A list of strings to be checked against user input. */
private readonly subjects: ReadonlyArray<string>) {
for (const subject of this.subjects) {
this.prefixMatchMap.set(new PrefixMatchData(subject), subject);
}
}
/**
* Matches user input against the list of strings using a simple substring
* match. I.e. 'o b' will trigger a match against a string 'foo bar',
* since 'o b' is a substring of 'foo bar'.
*/
private matchAsSubstring(input: string): Match[] {
const results: Match[] = [];
for (const subject of this.subjects) {
const index = subject.toLowerCase().indexOf(input);
if (index !== -1) {
results.push({
subject,
matchRanges: [
[index, index + input.length],
]
});
}
}
return results;
}
/**
* Does a preliminary filtering of PrefixMatchData - only the ones that
* have at least one first letter mathching the first letter of the user
* input are left. This is a minor optimization that limits the number
* of PrefixMatchDatas used to do the full recursive matching.
*
* For example: if there's a string 'foo bar wah', then
* its corresponding PrefixMatchData will have firstLetter set to 'fbw'.
* Consequently, user input of 'abc' won't match such string, whereas
* user input of 'black' will.
*/
private matchByFirstInputLetter(input: string): PrefixMatchData[] {
return Array.from(this.prefixMatchMap.keys())
.filter(matchData => matchData.firstLetters.includes(input[0]));
}
/**
* Matches user input against the list of strings using a prefix matching
* algorithm.
*
* @param input is a user input string.
* @param stringsToIgnore contains a set of strings that shouldn't be
* included into the results map. This argument is used to not waste
* cycles on checking strings that were already matched with a
* simple substring match.
* @return A list of Match objects.
*/
private matchAsPrefixes(input: string, stringsToIgnore: Set<string>):
Match[] {
const results: Match[] = [];
const filtered = this.matchByFirstInputLetter(input).filter(matchData => {
const subject = this.prefixMatchMap.get(matchData);
if (subject === undefined) {
throw new Error('subject can\'t be undefined at this point');
}
return !stringsToIgnore.has(subject);
});
for (const prefixMatchData of filtered) {
const matchRanges = prefixMatchData.match(input);
if (matchRanges) {
const subject = this.prefixMatchMap.get(prefixMatchData);
if (subject === undefined) {
throw new Error('subject can\'t be undefined at this point');
}
results.push({
subject,
matchRanges,
});
}
}
return results;
}
/**
* Matches the user input against the list of strings using a simple
* substring-based matching approach and more complicated prefix-based
* matching approach. If a string triggers both a substring-based match and a
* prefix-based match, a substring one is preferred (this affects the
* MatchRange list containing the indices of matched characters
* returned in Match object).
*
* For every string, the matching algorithm is this:
* 1. If the input is a substring of the string, report it as a
* match. I.e. 'bar' triggers the match for a string 'foo bar
* The reported matching range then is [4, 7].
*
* 2. If there's no direct substring match, do a prefix-based fuzzy match.
* User input is then treated as a list of prefixes. For example:
*
* a. 'bw' matches 'black and white' because of `*b*lack and *w*hite`.
*
* b. 'blaawh' matches 'black and white' because of
* `*bla*ck *a*nd *wh*ite`.
*
* c. 'bl a' matched 'black and white' because of `*bl* *a*`. I.e. a
* space within user's input means that characters on the left and right
* side of it should prefix-match different string components.
*
* @return A list of Match objects sorted alphabetically, according
* to subject strings.
*/
match(input: string): Match[] {
const lowerInput = input.toLowerCase();
const substringMatches = this.matchAsSubstring(lowerInput);
const prefixMatches = this.matchAsPrefixes(
lowerInput, new Set(substringMatches.map(m => m.subject)));
const results = [...substringMatches, ...prefixMatches];
results.sort((a: Match, b: Match) => {
return a.subject.localeCompare(b.subject);
});
return results;
}
}
/**
* StringWithHighlightsPart is a part of a string with highlights. Such a string
* is comprised of multiple parts, each either highlighted or not.
*/
export interface StringWithHighlightsPart {
readonly value: string;
readonly highlight: boolean;
}
/**
* StringWithHighlights is a string comprised of multiple parts, each either
* highlighted or not.
*/
export interface StringWithHighlights {
readonly value: string;
readonly parts: ReadonlyArray<StringWithHighlightsPart>;
}
/**
* Converts a given match produced by the FuzzyMatcher into a string with
* highlights.
*/
export function stringWithHighlightsFromMatch(match: Match):
StringWithHighlights {
const parts: StringWithHighlightsPart[] = [];
let i = 0;
let currentRangeIndex = 0;
while (i < match.subject.length) {
// If all the match ranges were checked, add the rest of the string as
// the last part and exit the loop.
if (currentRangeIndex >= match.matchRanges.length) {
parts.push({
value: match.subject.substring(i),
highlight: false,
});
break;
}
const currentRange = match.matchRanges[currentRangeIndex];
if (currentRange[0] === i) {
// If i equals to a beginning of a range, add it as a new part and
// mark it as highlighted.
parts.push({
value: match.subject.substring(currentRange[0], currentRange[1]),
highlight: true,
});
i = currentRange[1];
currentRangeIndex += 1;
} else {
// If i doesn't equal to a beginning of a range, add a part that spans
// from i to the beginning of next range.
parts.push({
value: match.subject.substring(i, currentRange[0]),
highlight: false,
});
i = currentRange[0];
}
}
return {
value: match.subject,
parts,
};
} | the_stack |
import { ParserRuleContext } from "antlr4ts";
import { SymbolTable, Symbol, ScopedSymbol, SymbolTableOptions } from "antlr4-c3";
import { SymbolKind, SymbolGroupKind, SymbolInfo, CodeActionType } from "../backend/facade";
import { SourceContext } from "./SourceContext";
import { ParseTree } from "antlr4ts/tree";
export class ContextSymbolTable extends SymbolTable {
public tree: ParserRuleContext; // Set by the owning source context after each parse run.
private symbolReferences = new Map<string, number>();
// Caches with reverse lookup for indexed symbols.
private namedActions: Symbol[] = [];
private parserActions: Symbol[] = [];
private lexerActions: Symbol[] = [];
private parserPredicates: Symbol[] = [];
private lexerPredicates: Symbol[] = [];
public constructor(name: string, options: SymbolTableOptions, public owner?: SourceContext) {
super(name, options);
}
public clear(): void {
// Before clearing the dependencies make sure the owners are updated.
if (this.owner) {
for (const dep of this.dependencies) {
if ((dep as ContextSymbolTable).owner) {
this.owner.removeDependency((dep as ContextSymbolTable).owner!);
}
}
}
this.symbolReferences.clear();
this.namedActions = [];
this.parserActions = [];
this.lexerActions = [];
this.parserPredicates = [];
this.lexerPredicates = [];
super.clear();
}
public symbolExists(name: string, kind: SymbolKind, localOnly: boolean): boolean {
return this.getSymbolOfType(name, kind, localOnly) !== undefined;
}
public symbolExistsInGroup(symbol: string, kind: SymbolGroupKind, localOnly: boolean): boolean {
// Group of lookups.
switch (kind) {
case SymbolGroupKind.TokenRef: {
if (this.symbolExists(symbol, SymbolKind.BuiltInLexerToken, localOnly)) {
return true;
}
if (this.symbolExists(symbol, SymbolKind.VirtualLexerToken, localOnly)) {
return true;
}
if (this.symbolExists(symbol, SymbolKind.FragmentLexerToken, localOnly)) {
return true;
}
if (this.symbolExists(symbol, SymbolKind.LexerRule, localOnly)) {
return true;
}
break;
}
case SymbolGroupKind.LexerMode: {
if (this.symbolExists(symbol, SymbolKind.BuiltInMode, localOnly)) {
return true;
}
if (this.symbolExists(symbol, SymbolKind.LexerMode, localOnly)) {
return true;
}
break;
}
case SymbolGroupKind.TokenChannel: {
if (this.symbolExists(symbol, SymbolKind.BuiltInChannel, localOnly)) {
return true;
}
if (this.symbolExists(symbol, SymbolKind.TokenChannel, localOnly)) {
return true;
}
break;
}
case SymbolGroupKind.RuleRef: {
if (this.symbolExists(symbol, SymbolKind.ParserRule, localOnly)) {
return true;
}
break;
}
default: {
break;
}
}
return false;
}
public contextForSymbol(symbolName: string, kind: SymbolKind, localOnly: boolean): ParseTree | undefined {
const symbol = this.getSymbolOfType(symbolName, kind, localOnly);
if (!symbol) {
return undefined;
}
return symbol.context;
}
public getSymbolInfo(symbol: string | Symbol): SymbolInfo | undefined {
if (!(symbol instanceof Symbol)) {
const temp = this.resolve(symbol);
if (!temp) {
return undefined;
}
symbol = temp;
}
let kind = SourceContext.getKindFromSymbol(symbol);
const name = symbol.name;
// Special handling for certain symbols.
switch (kind) {
case SymbolKind.TokenVocab:
case SymbolKind.Import: {
// Get the source id from a dependent module.
this.dependencies.forEach((table: ContextSymbolTable) => {
if (table.owner && table.owner.sourceId.includes(name)) {
return { // TODO: implement a best match search.
kind,
name,
source: table.owner.fileName,
definition: SourceContext.definitionForContext(table.tree, true),
};
}
});
break;
}
case SymbolKind.Operator:
case SymbolKind.Terminal: {
// These are references to a depending grammar.
this.dependencies.forEach((table: ContextSymbolTable) => {
const actualSymbol = table.resolve(name);
if (actualSymbol) {
symbol = actualSymbol;
kind = SourceContext.getKindFromSymbol(actualSymbol);
}
});
break;
}
default: {
break;
}
}
const symbolTable = symbol.symbolTable as ContextSymbolTable;
return {
kind,
name,
source: (symbol.context && symbolTable && symbolTable.owner) ? symbolTable.owner.fileName : "ANTLR runtime",
definition: SourceContext.definitionForContext(symbol.context, true),
description: undefined,
};
}
public listTopLevelSymbols(localOnly: boolean): SymbolInfo[] {
const result: SymbolInfo[] = [];
const options = this.resolve("options", true);
if (options) {
const tokenVocab = options.resolve("tokenVocab", true);
if (tokenVocab) {
result.push(this.getSymbolInfo(tokenVocab)!);
}
}
result.push(...this.symbolsOfType(ImportSymbol, localOnly));
result.push(...this.symbolsOfType(BuiltInTokenSymbol, localOnly));
result.push(...this.symbolsOfType(VirtualTokenSymbol, localOnly));
result.push(...this.symbolsOfType(FragmentTokenSymbol, localOnly));
result.push(...this.symbolsOfType(TokenSymbol, localOnly));
result.push(...this.symbolsOfType(BuiltInModeSymbol, localOnly));
result.push(...this.symbolsOfType(LexerModeSymbol, localOnly));
result.push(...this.symbolsOfType(BuiltInChannelSymbol, localOnly));
result.push(...this.symbolsOfType(TokenChannelSymbol, localOnly));
result.push(...this.symbolsOfType(RuleSymbol, localOnly));
return result;
}
/**
* Collects a list of action symbols.
*
* @param type The type of actions to return.
*
* @returns Symbol information for each defined action.
*/
public listActions(type: CodeActionType): SymbolInfo[] {
const result: SymbolInfo[] = [];
try {
const list = this.actionListOfType(type);
for (const entry of list) {
const definition = SourceContext.definitionForContext(entry.context, true);
if (definition && entry.name.toLowerCase() === "skip") {
// Seems there's a bug for the skip action where the parse tree indicates a
// single letter source range.
definition.range.end.column = definition.range.start.column + 3;
}
result.push({
kind: SourceContext.getKindFromSymbol(entry),
name: entry.name,
source: this.owner ? this.owner.fileName : "",
definition,
description: entry.context!.text,
});
}
} catch (e) {
result.push({
kind: SymbolKind.Unknown,
name: "Error getting actions list",
description: "Internal error occurred while collecting the list of defined actions",
source: "",
});
}
return result;
}
public getActionCounts(): Map<CodeActionType, number> {
const result = new Map<CodeActionType, number>();
let list = this.namedActions.filter((symbol) => symbol instanceof LocalNamedActionSymbol);
result.set(CodeActionType.LocalNamed, list.length);
list = this.namedActions.filter((symbol) => symbol instanceof GlobalNamedActionSymbol);
result.set(CodeActionType.GlobalNamed, list.length);
result.set(CodeActionType.ParserAction, this.parserActions.length);
result.set(CodeActionType.LexerAction, this.lexerActions.length);
result.set(CodeActionType.ParserPredicate, this.parserPredicates.length);
result.set(CodeActionType.LexerPredicate, this.lexerPredicates.length);
return result;
}
public getReferenceCount(symbolName: string): number {
const reference = this.symbolReferences.get(symbolName);
if (reference) {
return reference;
} else {
return 0;
}
}
public getUnreferencedSymbols(): string[] {
const result: string[] = [];
for (const entry of this.symbolReferences) {
if (entry[1] === 0) {
result.push(entry[0]);
}
}
return result;
}
public incrementSymbolRefCount(symbolName: string): void {
const reference = this.symbolReferences.get(symbolName);
if (reference) {
this.symbolReferences.set(symbolName, reference + 1);
} else {
this.symbolReferences.set(symbolName, 1);
}
}
public getSymbolOccurrences(symbolName: string, localOnly: boolean): SymbolInfo[] {
const result: SymbolInfo[] = [];
const symbols = this.getAllSymbols(Symbol, localOnly);
for (const symbol of symbols) {
const owner = (symbol.root as ContextSymbolTable).owner;
if (owner) {
if (symbol.context && symbol.name === symbolName) {
let context = symbol.context;
if (symbol instanceof FragmentTokenSymbol) {
context = (symbol.context as ParserRuleContext).children![1];
} else if (symbol instanceof TokenSymbol || symbol instanceof RuleSymbol) {
context = (symbol.context as ParserRuleContext).children![0];
}
result.push({
kind: SourceContext.getKindFromSymbol(symbol),
name: symbolName,
source: owner.fileName,
definition: SourceContext.definitionForContext(context, true),
description: undefined,
});
}
if (symbol instanceof ScopedSymbol) {
const references = symbol.getAllNestedSymbols(symbolName);
for (const reference of references) {
result.push({
kind: SourceContext.getKindFromSymbol(reference),
name: symbolName,
source: owner.fileName,
definition: SourceContext.definitionForContext(reference.context, true),
description: undefined,
});
}
}
}
}
return result;
}
/**
* Stores the given symbol in the named action cache.
*
* @param action The symbol representing the action.
*/
public defineNamedAction(action: Symbol): void {
this.namedActions.push(action);
}
/**
* Stores the given symbol in the parser action cache.
*
* @param action The symbol representing the action.
*/
public defineParserAction(action: Symbol): void {
this.parserActions.push(action);
}
/**
* Stores the given symbol in the lexer action cache.
*
* @param action The symbol representing the action.
*/
public defineLexerAction(action: Symbol): void {
this.lexerActions.push(action);
}
/**
* Stores the given symbol in the predicate cache. The current size of the cache
* defines its index, as used in predicate evaluation.
*
* @param predicate The symbol representing the predicate.
*/
public definePredicate(predicate: Symbol): void {
if (predicate instanceof LexerPredicateSymbol) {
this.lexerPredicates.push(predicate);
} else {
this.parserPredicates.push(predicate);
}
}
/**
* Does a depth-first search in the table for a symbol which contains the given context.
* The search is based on the token indices which the context covers and goes down as much as possible to find
* the closes covering symbol.
*
* @param context The context to search for.
*
* @returns The symbol covering the given context or undefined if nothing was found.
*/
public symbolContainingContext(context: ParseTree): Symbol | undefined {
const findRecursive = (parent: ScopedSymbol): Symbol | undefined => {
for (const symbol of parent.children) {
if (!symbol.context) {
continue;
}
if (symbol.context.sourceInterval.properlyContains(context.sourceInterval)) {
let child;
if (symbol instanceof ScopedSymbol) {
child = findRecursive(symbol);
}
if (child) {
return child;
} else {
return symbol;
}
}
}
};
return findRecursive(this);
}
/**
* Collects a list of action symbols.
*
* @param type The type of actions to return.
*
* @returns Symbol information for each defined action.
*/
private actionListOfType(type: CodeActionType): Symbol[] {
switch (type) {
case CodeActionType.LocalNamed: {
return this.namedActions.filter((symbol) => symbol instanceof LocalNamedActionSymbol);
}
case CodeActionType.ParserAction: {
return this.parserActions;
}
case CodeActionType.LexerAction: {
return this.lexerActions;
}
case CodeActionType.ParserPredicate: {
return this.parserPredicates;
}
case CodeActionType.LexerPredicate: {
return this.lexerPredicates;
}
default: {
return this.namedActions.filter((symbol) => symbol instanceof GlobalNamedActionSymbol);
}
}
}
private symbolsOfType<T extends Symbol>(t: new (...args: any[]) => T, localOnly = false): SymbolInfo[] {
const result: SymbolInfo[] = [];
const symbols = this.getAllSymbols(t, localOnly);
for (const symbol of symbols) {
const root = symbol.root as ContextSymbolTable;
result.push({
kind: SourceContext.getKindFromSymbol(symbol),
name: symbol.name,
source: root.owner ? root.owner.fileName : "ANTLR runtime",
definition: SourceContext.definitionForContext(symbol.context, true),
description: undefined,
});
}
return result;
}
private getSymbolOfType(name: string, kind: SymbolKind, localOnly: boolean): Symbol | undefined {
switch (kind) {
case SymbolKind.TokenVocab: {
const options = this.resolve("options", true);
if (options) {
return options.resolve(name, localOnly);
}
}
case SymbolKind.Import: {
return this.resolve(name, localOnly) as ImportSymbol;
}
case SymbolKind.BuiltInLexerToken: {
return this.resolve(name, localOnly) as BuiltInTokenSymbol;
}
case SymbolKind.VirtualLexerToken: {
return this.resolve(name, localOnly) as VirtualTokenSymbol;
}
case SymbolKind.FragmentLexerToken: {
return this.resolve(name, localOnly) as FragmentTokenSymbol;
}
case SymbolKind.LexerRule: {
return this.resolve(name, localOnly) as TokenSymbol;
}
case SymbolKind.BuiltInMode: {
return this.resolve(name, localOnly) as BuiltInModeSymbol;
}
case SymbolKind.LexerMode: {
return this.resolve(name, localOnly) as LexerModeSymbol;
}
case SymbolKind.BuiltInChannel: {
return this.resolve(name, localOnly) as BuiltInChannelSymbol;
}
case SymbolKind.TokenChannel: {
return this.resolve(name, localOnly) as TokenChannelSymbol;
}
case SymbolKind.ParserRule: {
return this.resolve(name, localOnly) as RuleSymbol;
}
default: {
break;
}
}
return undefined;
}
}
export class OptionSymbol extends Symbol {
public value: string;
}
export class ImportSymbol extends Symbol { }
export class BuiltInTokenSymbol extends Symbol { }
export class VirtualTokenSymbol extends Symbol { }
export class FragmentTokenSymbol extends ScopedSymbol { }
export class TokenSymbol extends ScopedSymbol { }
export class TokenReferenceSymbol extends Symbol { }
export class BuiltInModeSymbol extends Symbol { }
export class LexerModeSymbol extends Symbol { }
export class BuiltInChannelSymbol extends Symbol { }
export class TokenChannelSymbol extends Symbol { }
export class RuleSymbol extends ScopedSymbol { }
export class RuleReferenceSymbol extends Symbol { }
export class AlternativeSymbol extends ScopedSymbol { }
export class EbnfSuffixSymbol extends Symbol { }
export class OptionsSymbol extends ScopedSymbol { }
export class ArgumentSymbol extends ScopedSymbol { }
export class OperatorSymbol extends Symbol { }
export class TerminalSymbol extends Symbol { } // Any other terminal but operators.
export class LexerCommandSymbol extends Symbol { } // Commands in lexer rules after the -> introducer.
// Symbols for all kind of native code blocks in a grammar.
export class GlobalNamedActionSymbol extends Symbol { } // Top level actions prefixed with @.
export class LocalNamedActionSymbol extends Symbol { } // Rule level actions prefixed with @.
export class ExceptionActionSymbol extends Symbol { } // Action code in exception blocks.
export class FinallyActionSymbol extends Symbol { } // Ditto for finally clauses.
export class ParserActionSymbol extends Symbol { } // Simple code blocks in rule alts for a parser rule.
export class LexerActionSymbol extends Symbol { } // Ditto for lexer rules.
export class ParserPredicateSymbol extends Symbol { } // Predicate code in a parser rule.
export class LexerPredicateSymbol extends Symbol { } // Ditto for lexer rules.
export class ArgumentsSymbol extends Symbol { } // Native code for argument blocks and local variables. | the_stack |
import { ipcRenderer } from "electron";
import { writeJson } from "fs-extra";
import { extname, basename } from "path";
import { Nullable, IStringDictionary, Undefinable } from "../../../shared/types";
import * as React from "react";
import { Button, Divider, ButtonGroup, Popover, Position, Menu, MenuItem, MenuDivider, Toaster, Intent, ContextMenu, Classes } from "@blueprintjs/core";
import GoldenLayout from "golden-layout";
import { ISize } from "babylonjs";
import { Icon } from "../../editor/gui/icon";
import { Code } from "../../editor/gui/code";
import { Alert } from "../../editor/gui/alert";
import { Confirm } from "../../editor/gui/confirm";
import { Tools } from "../../editor/tools/tools";
import { IPCTools } from "../../editor/tools/ipc";
import { undoRedo } from "../../editor/tools/undo-redo";
import { LayoutUtils } from "../../editor/tools/layout-utils";
import { TouchBarHelper, ITouchBarButton } from "../../editor/tools/touch-bar";
import { GraphCode } from "../../editor/graph/graph";
import { GraphCodeGenerator } from "../../editor/graph/generate";
import { Logs } from "./components/logs";
import { Graph } from "./components/graph";
import { Preview } from "./components/preview";
import { Inspector } from "./components/inspector";
import { CallStack } from "./components/call-stack";
import { GraphEditorTemplate } from "./template";
import "./augmentations";
export const title = "Graph Editor";
export interface IGraphEditorTemplate {
/**
* Defines the name of the template.
*/
name: string;
/**
* Defines the path to the file.
*/
file: string;
}
export interface IGraphEditorWindowProps {
}
export interface IGraphEditorWindowState {
/**
* Defines wether or not the graph is plaging.
*/
playing: boolean;
/**
* Defines wether or not the graph is played in standalone mode.
*/
standalone: boolean;
/**
* Defines the list of all existing templates.
*/
templates: IGraphEditorTemplate[];
}
export default class GraphEditorWindow extends React.Component<IGraphEditorWindowProps, IGraphEditorWindowState> {
/**
* Reference to the layout used to create the editor's sections.
*/
public layout: GoldenLayout;
/**
* Defines the reference to the graph.
*/
public graph: Graph;
/**
* Defines the reference to the preview.
*/
public preview: Preview;
/**
* Defines the reference to the logs.
*/
public logs: Logs;
/**
* Defines the reference to the call stack.
*/
public callStack: CallStack;
/**
* Defines the reference to the inspector.
*/
public inspector: Inspector;
private _layoutDiv: Nullable<HTMLDivElement> = null;
private _toaster: Nullable<Toaster> = null;
private _refHandler = {
getLayoutDiv: (ref: HTMLDivElement) => this._layoutDiv = ref,
getToaster: (ref: Toaster) => (this._toaster = ref),
};
private _path: Nullable<string> = null;
private _linkPath: Nullable<string> = null;
private _components: IStringDictionary<any> = { };
private _isSaving: boolean = false;
private _closing: boolean = false;
/**
* Defines the current version of the layout.
*/
public static readonly LayoutVersion = "3.0.0";
/**
* Constructor
* @param props the component's props.
*/
public constructor(props: any) {
super(props);
this.state = {
playing: false,
standalone: false,
templates: [],
};
GraphCode.Init();
}
/**
* Renders the component.
*/
public render(): React.ReactNode {
const file = (
<Menu>
<MenuItem text="Load From..." icon={<Icon src="folder-open.svg" />} onClick={() => this._handleLoadFrom()} />
<MenuDivider />
<MenuItem text="Save (CTRL + S)" icon={<Icon src="copy.svg" />} onClick={() => this._handleSave()} />
<MenuItem text="Save As... (CTRL + SHIFT + S)" icon={<Icon src="copy.svg" />} onClick={() => this._handleSaveAs()} />
</Menu>
);
const edit = (
<Menu>
<MenuItem text="Undo (CTRL + Z)" icon={<Icon src="undo.svg" />} onClick={() => undoRedo.undo()} />
<MenuItem text="Redo (CTRL + Y)" icon={<Icon src="redo.svg" />} onClick={() => undoRedo.redo()} />
<MenuDivider />
<MenuItem text="Clear..." icon={<Icon src="recycle.svg" />} onClick={() => this._handleClearGraph()} />
</Menu>
);
const view = (
<Menu>
<MenuItem text="Show Generated Code..." icon="code" onClick={() => this._handleShowGeneratedCode()} />
<MenuDivider />
<MenuItem text="Show Infos" icon={this._getCheckedIcon(this.graph?.graphCanvas?.show_info ?? true)} onClick={() => this._handleGraphCanvasOption("show_info")} />
<MenuItem text="Render Execution Order" icon={this._getCheckedIcon(this.graph?.graphCanvas?.render_execution_order ?? true)} onClick={() => this._handleGraphCanvasOption("render_execution_order")} />
<MenuItem text="Render Collapsed Slots" icon={this._getCheckedIcon(this.graph?.graphCanvas?.render_collapsed_slots ?? true)} onClick={() => this._handleGraphCanvasOption("render_collapsed_slots")} />
</Menu>
);
const snippets = (
<Menu>
<MenuItem text="Refresh..." icon="refresh" onClick={() => this._loadTemplates()} />
<MenuDivider />
{this.state.templates.length ? this.state.templates.map((t) => (
<MenuItem text={t.name} onClick={() => GraphEditorTemplate.ApplyTemplate(t, this.graph)} />
)) : undefined}
</Menu>
);
return (
<>
<div className="bp3-dark" style={{ width: "100%", height: "80px", backgroundColor: "#444444" }}>
<ButtonGroup style={{ paddingTop: "4px" }}>
<Popover content={file} position={Position.BOTTOM_LEFT}>
<Button icon={<Icon src="folder-open.svg"/>} rightIcon="caret-down" text="File"/>
</Popover>
<Popover content={edit} position={Position.BOTTOM_LEFT}>
<Button icon={<Icon src="edit.svg"/>} rightIcon="caret-down" text="Edit"/>
</Popover>
<Popover content={view} position={Position.BOTTOM_LEFT}>
<Button icon={<Icon src="eye.svg"/>} rightIcon="caret-down" text="View"/>
</Popover>
<Popover content={snippets} position={Position.BOTTOM_LEFT}>
<Button icon={<Icon src="grip-lines.svg"/>} rightIcon="caret-down" text="Snippets"/>
</Popover>
</ButtonGroup>
<Divider />
<ButtonGroup style={{ position: "relative", left: "50%", transform: "translate(-50%)" }}>
<Button disabled={this.state.playing} icon={<Icon src="play.svg"/>} rightIcon="caret-down" text="Play" onContextMenu={(e) => this._handlePlayContextMenu(e)} onClick={() => this.start(false)} />
<Button disabled={!this.state.playing} icon={<Icon src="square-full.svg" />} text="Stop" onClick={() => this.stop()} />
<Button disabled={!this.state.playing} icon="reset" text="Restart" onClick={() => {
this.stop();
this.start(this.state.standalone);
}} />
</ButtonGroup>
<Divider />
</div>
<div ref={this._refHandler.getLayoutDiv} className="bp3-dark" style={{ width: "100%", height: "calc(100% - 80px)" }}></div>
<Toaster canEscapeKeyClear={true} position={Position.TOP_RIGHT} ref={this._refHandler.getToaster}></Toaster>
</>
);
}
/**
* Called on the component did mount.
*/
public async componentDidMount(): Promise<void> {
if (!this._layoutDiv) { return; }
// Window configuration
const windowDimensions = JSON.parse(localStorage.getItem("babylonjs-editor-graph-window-dimensions") ?? "null");
if (windowDimensions) {
window.resizeTo(windowDimensions.width, windowDimensions.height);
const x = windowDimensions.x ?? screenLeft;
const y = windowDimensions.y ?? screenTop;
window.moveTo(x, y);
}
// Layout configuration
const layoutVersion = localStorage.getItem('babylonjs-editor-graph-layout-version');
const layoutStateItem = (layoutVersion === GraphEditorWindow.LayoutVersion) ? localStorage.getItem('babylonjs-editor-graph-layout-state') : null;
const layoutState = layoutStateItem ? JSON.parse(layoutStateItem) : null;
if (layoutState) { LayoutUtils.ConfigureLayoutContent(this, layoutState.content); }
// Create layout
this.layout = new GoldenLayout(layoutState ?? {
settings: { showPopoutIcon: false, showCloseIcon: false, showMaximiseIcon: false },
dimensions: { minItemWidth: 240, minItemHeight: 50 },
labels: { close: "Close", maximise: "Maximize", minimise: "Minimize" },
content: [{
type: "row", content: [
{ type: "column", width: 1, content: [
{ type: "react-component", id: "inspector", component: "inspector", componentName: "Inspector", title: "Inspector", isClosable: false, props: {
editor: this,
} },
{ type: "react-component", id: "preview", component: "preview", componentName: "Preview", title: "Preview", isClosable: false, props: {
editor: this,
} },
{ type: "react-component", id: "logs", component: "logs", componentName: "Logs", title: "Logs", isClosable: false, props: {
editor: this,
} },
{ type: "react-component", id: "call-stack", component: "call-stack", componentName: "Call Stack", title: "Call Stack", isClosable: false, props: {
editor: this,
} },
]},
{ type: "react-component", id: "graph", component: "graph", componentName: "graph", title: "Graph", width: 1, isClosable: false, props: {
editor: this,
} },
],
}],
}, this._layoutDiv);
// Register layout events
this.layout.on("componentCreated", (c) => {
this._components[c.config.component] = c;
c.container.on("resize", () => this.resize());
c.container.on("show", () => this.resize());
});
this.layout.registerComponent("inspector", Inspector);
this.layout.registerComponent("preview", Preview);
this.layout.registerComponent("logs", Logs);
this.layout.registerComponent("call-stack", CallStack);
this.layout.registerComponent("graph", Graph);
// Initialize layout
try {
await Tools.Wait(0);
this.layout.init();
await Tools.Wait(0);
} catch (e) {
localStorage.removeItem("babylonjs-editor-graph-layout-state");
localStorage.removeItem("babylonjs-editor-graph-layout-version");
localStorage.removeItem("babylonjs-editor-graph-window-dimensions");
}
// Initialize code generation
await GraphCodeGenerator.Init();
// Initialize components
this.logs.clear();
await this.graph.initGraph(this._path!);
// Bind all events
this._bindEvents();
this.forceUpdate();
this.layout.updateSize();
// Init templates
await this._loadTemplates();
}
/**
* Called on the component did update.
*/
public componentDidUpdate(): void {
const buttons: ITouchBarButton[] = [];
if (!this.state.playing) {
buttons.push({ label: "Play", click: () => this.start(false) });
} else {
buttons.push({ label: "Stop", click: () => this.stop() });
buttons.push({ label: "Restart", click: () => {
this.stop();
this.start(this.state.standalone);
} });
}
TouchBarHelper.SetTouchBarElements(buttons);
}
/**
* Inits the plugin.
* @param path defines the path of the JSON graph to load.
*/
public async init(path: string, linkPath: string): Promise<void> {
this._path = path;
this._linkPath = linkPath;
document.title = `${document.title} - ${basename(path)}`;
}
/**
* Gets the link path of the graph in case it is attached to nodes.
*/
public get linkPath(): Nullable<string> {
return this._linkPath;
}
/**
* Called on the window is being closed.
*/
public async onClose(e: BeforeUnloadEvent): Promise<boolean> {
if (!this._closing) {
e.returnValue = false;
this._closing = await Confirm.Show("Close?", "Are you sure to close?");
if (this._closing) {
window.close();
}
return false;
}
IPCTools.SendWindowMessage<{ error: boolean; }>(-1, "graph-json", {
path: this._path,
closed: true,
});
return true;
}
/**
* Called on the window or layout is resized.
*/
public resize(): void {
this.graph?.resize();
this.preview?.resize();
this.inspector?.resize();
this.logs?.resize();
}
/**
* Returns the current size of the panel identified by the given id.
* @param panelId the id of the panel to retrieve its size.
*/
public getPanelSize(panelId: string): ISize {
const panel = this._components[panelId];
if (!panel) {
return { width: 0, height: 0 };
}
return { width: panel.container.width, height: panel.container.height };
}
/**
* Starts the graph.
* @param standalone defines wehter or not only the current graph will be executed.
*/
public async start(standalone: boolean): Promise<void> {
this.logs.clear();
await this.preview.reset(standalone);
await this.graph.start(this.preview.getScene());
this.setState({ playing: true, standalone });
}
/**
* Stops the graph.
*/
public stop(): void {
this.graph.stop();
this.preview.stop();
this.callStack.clear();
this.setState({ playing: false });
}
/**
* Saves the current graph.
*/
private async _handleSave(closed: boolean = false): Promise<void> {
if (this._isSaving) { return; }
this._isSaving = true;
const result = await IPCTools.SendWindowMessage<{ error: boolean; }>(-1, "graph-json", {
path: this._path,
json: this.graph.graph?.serialize(),
preview: this.graph.graphCanvas?.canvas.toDataURL(),
closed,
});
this._isSaving = false;
if (result.data.error) {
this._toaster?.show({ message: "Failed to save.", intent: Intent.DANGER, timeout: 1000 });
} else {
this._toaster?.show({ message: "Saved.", intent: Intent.SUCCESS, timeout: 1000 });
}
// Save state
const config = this.layout.toConfig();
LayoutUtils.ClearLayoutContent(this, config.content);
localStorage.setItem("babylonjs-editor-graph-layout-state", JSON.stringify(config));
localStorage.setItem("babylonjs-editor-graph-layout-version", GraphEditorWindow.LayoutVersion);
localStorage.setItem("babylonjs-editor-graph-window-dimensions", JSON.stringify({ x: screenLeft, y: screenTop, width: innerWidth, height: innerHeight }));
if (this.graph?.graphCanvas) {
localStorage.setItem("babylonjs-editor-graph-preferences", JSON.stringify({
show_info: this.graph.graphCanvas.show_info,
render_execution_order: this.graph.graphCanvas.render_execution_order,
render_collapsed_slots: this.graph.graphCanvas.render_collapsed_slots,
}));
}
}
/**
* Saves the current graph as...
*/
private async _handleSaveAs(): Promise<void> {
const json = this.graph.graph?.serialize();
if (!json) { return; }
let path = await Tools.ShowSaveFileDialog("Save Graph...");
const extension = extname(path).toLowerCase();
if (extension !== ".json") {
path += ".json";
}
await writeJson(path, json, {
encoding: "utf-8",
spaces: "\t",
});
}
/**
* Loads the current graph from...
*/
private async _handleLoadFrom(): Promise<void> {
const path = await Tools.ShowOpenFileDialog("Load Graph From...");
try {
const override = await Confirm.Show("Override Current Graph?", "Are you sure to override the current graph? Existing graph will be overwritten and all changes will be lost.");
if (!override) { return; }
this.graph.initGraph(path);
} catch (e) {
Alert.Show("Failed To Parse Graph", `Failed to parse graph: ${e.message}`);
}
}
/**
* Called on the user wants to change a graph canvas option.
*/
private _handleGraphCanvasOption(option: string): void {
if (this.graph?.graphCanvas) {
this.graph.graphCanvas[option] = !this.graph.graphCanvas[option];
this.graph.graphCanvas.setDirty(true, true);
}
this.forceUpdate();
}
/**
* Called on the user right-clicks on the "play" button.
*/
private _handlePlayContextMenu(e: React.MouseEvent<HTMLButtonElement, MouseEvent>): void {
ContextMenu.show(
<Menu className={Classes.DARK}>
<MenuItem text="Play" icon={<Icon src="play.svg" />} onClick={() => this.start(false)} />
<MenuItem text="Play Only Current Graph" icon={<Icon src="play.svg" />} onClick={() => this.start(true)} />
</Menu>,
{ left: e.clientX, top: e.clientY },
);
}
/**
* Called on the user wants to show the generated code.
*/
private async _handleShowGeneratedCode(): Promise<void> {
if (!this.graph.graph) { return; }
const code = GraphCodeGenerator.GenerateCode(this.graph.graph);
if (!code) { return; }
Alert.Show("Generated Code", "", undefined, (
<Code code={code} language="typescript" readonly={true} style={{ width: "800px", height: "600px" }} />
), {
style: { width: "840px", height: "700px" }
});
}
/**
* Called on the user wants to clear the graph.
*/
private async _handleClearGraph(): Promise<void> {
const clear = await Confirm.Show("Clear whole graph?", "Are you sure to clear the whole graph? All work will be lost.");
if (!clear) { return; }
const graph = this.graph.graph;
if (!graph) { return; }
graph.clear();
}
/**
* Binds all the events.
*/
private _bindEvents(): void {
// Resize
window.addEventListener("resize", () => {
this.layout.updateSize();
this.resize();
});
// Shortcuts
ipcRenderer.on("save", () => this._handleSave());
ipcRenderer.on("save-as", () => this._handleSaveAs());
ipcRenderer.on("undo", () => undoRedo.undo());
ipcRenderer.on("redo", () => undoRedo.redo());
}
/**
* Returns the check icon if the given "checked" property is true.
*/
private _getCheckedIcon(checked: Undefinable<boolean>): Undefinable<JSX.Element> {
return checked ? <Icon src="check.svg" /> : undefined;
}
/**
* Loads the list of all existing templates.
*/
private async _loadTemplates(): Promise<void> {
try {
const templates = await GraphEditorTemplate.GetTemplatesList();
this.setState({ templates });
} catch (e) {
// Catch silently.
}
}
} | the_stack |
import ArrayHelper from './ArrayHelper';
import Atom from './Atom';
import Drawer from './Drawer';
import Line from './Line';
import SvgWrapper from './SvgWrapper';
import ThemeManager from './ThemeManager';
import Vector2 from './Vector2';
import { arraysCompare, arrayDelElement} from '../../../utils';
class SvgDrawer {
public preprocessor: any;
public themeManager: any;
public svgWrapper: any;
public bridgedRing: any;
constructor(options) {
this.preprocessor = new Drawer(options);
}
/**
* Draws the parsed smiles data to an svg element.
*
* @param {Object} data The tree returned by the smiles parser.
* @param {(String|HTMLElement)} target The id of the HTML svg element the structure is drawn to - or the element itself.
* @param {String} themeName='dark' The name of the theme to use. Built-in themes are 'light' and 'dark'.
* @param {Boolean} infoOnly=false Only output info on the molecule without drawing anything to the canvas.
* @returns {Oject} The dimensions of the drawing in { width, height }
*/
draw(data, target, themeName = 'light', infoOnly = false) {
let preprocessor = this.preprocessor;
preprocessor.initDraw(data, themeName, infoOnly);
if (!infoOnly) {
this.themeManager = new ThemeManager(this.preprocessor.opts.themes, themeName);
this.svgWrapper = new SvgWrapper(this.themeManager, target, this.preprocessor.opts);
}
preprocessor.processGraph();
// Set the canvas to the appropriate size
this.svgWrapper.determineDimensions(preprocessor.graph.vertices);
this.putEdgesForRings();
//need to checking of correct aromatic ring
this.putEdgesLForRings();
this.checkAllEdgesRings();
this.drawEdges(preprocessor.opts.debug);
this.drawVertices(preprocessor.opts.debug);
if (preprocessor.opts.debug) {
console.log(preprocessor.graph);
console.log(preprocessor.rings);
console.log(preprocessor.ringConnections);
}
return this.svgWrapper.constructSvg();
}
putEdgesForRings() {
let preprocessor = this.preprocessor;
let rings = preprocessor.rings;
let graph = preprocessor.graph;
let edges = preprocessor.graph.edges;
for (let i = 0; i < rings.length; i++) {
const ring = rings[i];
ring.membersS = this.sortMembers(ring);
if (ring.neighbours.length) {
ring.neighbours.map(item => {
const nRing = rings[item];
if (nRing && nRing.neighbours.indexOf(ring.id) === -1) {
nRing.neighbours.push(ring.id)
}
})
}
const members = ring.membersS;
for (let j = 0; j < members.length; j++) {
const v = members[j];
let vertex = graph.vertices[v];
if (this.isHydrogenVertices([v])) {
ring.hasHydrogen = true;
}
if (this.isVertexHasDoubleBondWithO(ring, v)) {
ring.hasDoubleBondWithO = true;
}
if (!ring.isHaveElements && vertex.value.element !== 'C') {
ring.isHaveElements = true
}
ring.elements.push(vertex.value.element);
const v2 = j < members.length - 1
? members[j + 1]
: members[0];
const {item, isBetweenRings } = this.getEdgeBetweenVertexAB(v, v2);
let edge = edges[item];
if (edge) {
const vertexA = graph.vertices[edge.sourceId];
const vertexB = graph.vertices[edge.targetId];
if (!this.edgeHaveDoubleBound(edge) && vertexA.neighbourCount > 2
&& vertexA.neighbourCount < vertexA.value.bondCount
) {
edge.sourceHasOuterDoubleBond = true;
ring.hasOuterDoubleBond = true;
}
if (!this.edgeHaveDoubleBound(edge) && vertexB.neighbourCount > 2
&& vertexB.neighbourCount < vertexB.value.bondCount
) {
edge.targetHasOuterDoubleBond = true;
ring.hasOuterDoubleBond = true;
}
}
if (edge?.isPartOfAromaticRing) {
if (ring.edges.indexOf(item) === -1) {
if (ring.edges.length > 0) {
const prev = edges[ring.edges[ring.edges.length - 1]];
if (prev.neighbours.indexOf(item) === -1) {
prev.neighbours.push(item);
}
if (edge.neighbours.indexOf(prev.id) === -1) {
edge.neighbours.push(prev.id);
}
}
ring.edges.push(item);
edge.isPartOfRing = true;
if (edge.rings.indexOf(ring.id) === -1) {
edge.rings.push(ring.id)
}
}
if (isBetweenRings) {
if (ring.edgesR.indexOf(item) === -1) {
ring.edgesR.push(item);
}
}
}
}
//Edit last and first Edges
if (ring.edges.length > 0) {
const first = edges[ring.edges[0]];
const last = edges[ring.edges[ring.edges.length - 1]];
if (first.neighbours.indexOf(last.id) === -1) {
first.neighbours.push(last.id);
}
if (last.neighbours.indexOf(first.id) === -1) {
last.neighbours.push(first.id);
}
}
if (ring.edgesR.length) {
const arr = [...ring.edges];
ring.edgesR.map(item => {
const index = arr.indexOf(item);
if (index > -1) {
arr.splice(index, 1);
}
});
if (!arr.length || arr.length < 1) {
ring.edges = [];
}
}
}
};
putEdgesLForRings() {
let preprocessor = this.preprocessor;
let rings = preprocessor.rings;
for (let i = 0; i < rings.length; i++) {
const ring = rings[i];
if (this.isRing_SNN(ring)){
continue;
}
if (this.isRing_ONN(ring)){
continue;
}
if (this.isRing_NNN(ring)){
continue;
}
}
};
checkAllEdgesRings() {
let preprocessor = this.preprocessor;
let rings = preprocessor.rings;
let graph = preprocessor.graph;
let edges = preprocessor.graph.edges;
const arr = [];
let arrBottoms = [];
for (let i = 0; i < edges.length; i++) {
const edge = edges[i];
if (edge.rings.length > 1) {
if (arr.indexOf(edge.id) === -1) {
arr.push(edge.id)
}
}
if (this.edgeHaveDoubleBound(edge)) {
edge.isHaveLine = true;
edge.isChecked = true;
continue;
}
const currentRing = edge.rings.length === 1
? rings[edge.rings]
: null;
let vertexA = graph.vertices[edge.sourceId];
let vertexB = graph.vertices[edge.targetId];
if (currentRing && !this.ringStartedCheck(currentRing)) {
if (this.ringStartedCheckForEdge(currentRing, edge)) {
edge.isChecked = true;
currentRing.isStartedCheck = true;
continue
}
if (!edge.isAtomSlat &&
currentRing.members.length === 6 && this.ringHasAtoms_N(currentRing)
&& edge.sourceId === Math.min(...currentRing.members)
&& vertexB.value.element === 'N' &&
currentRing.elements.filter(item => item === 'N').length > 2) {
edge.isChecked = true;
currentRing.isStartedCheck = true;
continue
}
}
if ((edge.isBottomSlat && (!edge.isBeforeHaveLine || edge.rings.length >1)
|| this.edgeNeighboursAreAtomSlat(edge)
|| (currentRing && currentRing.members.length >= 5 && edge.rings.length === 1
&& (this.getVertexElementFromRing(currentRing) !== '' || currentRing.members.length === 6)
&& vertexA.value.rings.length > 1 && vertexB.value.rings.length > 1))
&& !(vertexA.value.element === 'N' && vertexB.value.element === 'N' && currentRing?.members.length > 5)
) {
if (edge.isBottomSlat && currentRing && currentRing.neighbours.length === 1
&& rings[currentRing.neighbours[0]].members.length === 5
&& this.getVertexElementFromRing(rings[currentRing.neighbours[0]]) === 'N'
&& currentRing.members.length === 6 && this.getVertexElementFromRing(currentRing) === 'N') {
} else
{
if (arrBottoms.indexOf(edge.id) === -1) {
arrBottoms.push(edge.id)
}
if(currentRing) {currentRing.isStartedCheck = true;}
continue;
}
}
if (edge.isAtomVertex ) {
continue;
}
if (!edge.isPartOfRing || edge.isChecked) {
continue;
}
if (!edge.isChecked) {
this.checkEdge(edge, vertexA, vertexB, arr, currentRing);
if (currentRing) {
currentRing.isStartedCheck = true;
}
}
}
if (this.preprocessor.opts.debug) {
console.log('arr=>', arr);
}
if (arr.length) {
for (let i = 0; i < arr.length; i++) {
const edge = edges[arr[i]];
if(edge.isChecked && (edge.isHaveLine || edge.isNotHaveLine)
) {
continue
}
let vertexA = graph.vertices[edge.targetId];
let vertexB = graph.vertices[edge.sourceId];
if (this.edgeNeighboursHaveDoubleBound(edge, vertexA, vertexB)
|| (vertexA.value.element === 'N' && vertexA.neighbourCount === 3)
|| (vertexB.value.element === 'N' && vertexB.neighbourCount === 3)
) {
edge.isNotHaveLine = true;
continue;
}
edge.isHaveLine = true;
edge.isChecked = true;
}
}
if (this.preprocessor.opts.debug) {
console.log('arrBottoms=>', arrBottoms);
}
if (arrBottoms.length) {
for (let i = 0; i < arrBottoms.length; i++) {
const edge = edges[arrBottoms[i]];
if(edge.isChecked) {
continue
}
let vertexA = graph.vertices[edge.targetId];
let vertexB = graph.vertices[edge.sourceId];
if (this.edgeNeighboursHaveDoubleBound(edge, vertexA, vertexB)
|| (vertexA.value.element === 'N' && vertexA.neighbourCount === 3 && vertexA.neighbourCount !== vertexA.value.bondCount)
|| (vertexB.value.element === 'N' && vertexB.neighbourCount === 3 && vertexB.neighbourCount !== vertexB.value.bondCount)
) {
edge.isNotHaveLine = true;
continue;
}
edge.isHaveLine = true;
edge.isChecked = true;
}
}
};
checkEdge(edge, vertexA, vertexB, arr, ring) {
const atoms = ['O', 'S', 'Se', 'As'];
const vertexA_NotOS = atoms.indexOf(vertexA.value.element) === -1;
const vertexB_NotOS = atoms.indexOf(vertexB.value.element) === -1;
const vertexA_NotN = !(vertexA.value.element === 'N' && vertexA.neighbourCount === 3 && !(vertexA.value.bracket?.charge === 1)
&& !this.checkVertex_N(vertexA));
const vertexB_NotN = !(vertexB.value.element === 'N' && vertexB.neighbourCount === 3 && !(vertexB.value.bracket?.charge === 1)
&& !this.checkVertex_N(vertexB));
if (this.edgeHaveDoubleBound(edge)) {
edge.isHaveLine = true;
edge.isChecked = true;
if (ring && !ring.isStartedCheck) {
let prev = false;
for (let i = 0; i < ring.edges.length; i++) {
if (ring.edges[i] === edge.id) {
prev = true;
continue
}
if (!prev) {
const rEdge = this.preprocessor.graph.edges[ring.edges[i]];
rEdge.isBeforeHaveLine = true;
prev = true;
} else {
prev = false;
}
}
}
return
}
if (this.checkVertex_N(vertexA)) {
if (!this.edgeNeighboursHaveDoubleBound(edge, vertexA, vertexB)) {
edge.isHaveLine = true;
edge.isChecked = true;
return
}
}
if (
this.edgeHaveDoubleBound(edge) ||
vertexA_NotOS && vertexB_NotOS
&& vertexA_NotN && vertexB_NotN
&& !(vertexA.neighbourCount > 2 && vertexA.neighbourCount < vertexA.value.bondCount)
&& !(vertexB.neighbourCount > 2 && vertexB.neighbourCount < vertexB.value.bondCount)
&& (!vertexA.hasDoubleBondWithO || this.checkVertex_N(vertexA))
&& (!vertexB.hasDoubleBondWithO || this.checkVertex_N(vertexB))
&& !this.isHydrogenVertices([vertexA.id, vertexB.id])
&& !this.edgeNeighboursHaveDoubleBound(edge, vertexA, vertexB)
) {
if (!edge.isBeforeNotHaveLine) {
edge.isHaveLine = true;
}
edge.isChecked = true;
if (ring && !ring.isStartedCheck
&& ring.members.length === 6
&& !ring.hasDoubleBondWithO
&& !ring.hasOuterDoubleBond
) {
let prev = false;
for (let i = 0; i < ring.edges.length; i++) {
if (ring.edges[i] === edge.id) {
prev = true;
continue
}
const rEdge = this.preprocessor.graph.edges[ring.edges[i]];
if (!prev) {
rEdge.isBeforeHaveLine = true;
prev = true;
} else {
rEdge.isBeforeNotHaveLine = true;
prev = false;
}
}
}
} else {
edge.isNotHaveLine = true;
edge.isChecked = true;
}
};
edgeHaveDoubleBound(edge, vertexA = null, vertexB = null){
if (!vertexA) {
vertexA = this.preprocessor.graph.vertices[edge.sourceId];
}
if (!vertexB) {
vertexB = this.preprocessor.graph.vertices[edge.targetId];
}
if (edge.bondType === '=' && !edge.isPartOfRing
&& vertexB.value.element === 'N') {
return false
}
return edge.bondType === '=' || this.preprocessor.getRingbondType(vertexA, vertexB) === '=';
}
edgesHaveDoubleBound(edges, checkAtom){
let res = false;
for (let i = 0; i < edges.length; i++) {
const edge = this.preprocessor.graph.edges[edges[i]];
const vertexA = this.preprocessor.graph.vertices[edge.sourceId];
const vertexB = this.preprocessor.graph.vertices[edge.targetId];
if (edge.bondType === '=' || this.preprocessor.getRingbondType(vertexA, vertexB) === '='
|| (checkAtom && (vertexA.value.element === 'O' ||
vertexA.value.neighbouringElements.indexOf('F') !== -1
))
) {
res = true;
break
}
}
return res;
}
edgeNeighboursHaveDoubleBound(edge, vertexA, vertexB){
let res = false;
let eNeighbours = [].concat(vertexA.edges, vertexB.edges);
for (let i = 0; i < eNeighbours.length; i++) {
const edge = this.preprocessor.graph.edges[eNeighbours[i]];
if (edge.isHaveLine || this.edgeHaveDoubleBound(edge)) {
res = true;
break
}
}
return res;
};
ringHasAtoms_N(ring) {
let res = false;
for(let i = 0; i < ring.members.length; i++) {
let vertex = this.preprocessor.graph.vertices[ring.members[i]];
if (vertex.value.element === 'N' && vertex.neighbourCount === 3) {
res = true;
break;
}
}
return res;
}
ringStartedCheck(ring){
let res = false;
for(let i = 0; i < ring.edges.length; i++) {
let edge = this.preprocessor.graph.edges[ring.edges[i]];
if (edge.isChecked) {
res = true;
break;
}
}
return res;
}
isVertexNeighboursHasDoubleBond(vertexId, ring) {
let vertexA = this.preprocessor.graph.vertices[vertexId];
let neighbours = vertexA.neighbours.filter(item => ring.members.indexOf(item) === -1);
let res = false;
for (let i = 0; i < neighbours.length; i++) {
const vertex = this.preprocessor.graph.vertices[neighbours[i]];
if (this.edgesHaveDoubleBound(vertex.edges, true)) {
res = true;
break;
}
}
return res;
}
getVertexElementFromRing(ring){
let res = '';
for (let i = 0; i < ring.members.length; i++) {
const vertex = this.preprocessor.graph.vertices[ring.members[i]];
if (vertex.isAtomVertex) {
if (this.isHydrogenVertices([vertex.id])) {
res = vertex.value.element + 'H';
} else {
res = vertex.value.element;
}
break
}
}
return res;
}
ringStartedCheckForEdge(ring, edge){
let res = false;
if (ring.isStartedCheck) {
return false
}
if (ring.members.length === 6) {
if (ring.neighbours.length === 1) {
const commonEdge = this.preprocessor.graph.edges[ring.edgesR[0]];
if (commonEdge) {
const rN = commonEdge.rings.filter(item => item !== ring.id);
const nRing = this.preprocessor.rings[rN[0]];
const index = ring.edges.indexOf(commonEdge.id);
if (this.preprocessor.opts.debug) {
console.log('>>>>>>> commonEdge=> ', commonEdge);
console.log('>>>>>>> index=> ', index);
}
if (index === 0 ) {
if (!nRing.edges.length) {
return true
}
}
if (index === 3) {
if (commonEdge.isBottomSlat && nRing.members?.length === 5) {
return true
}
if (this.edgeHaveDoubleBound(commonEdge)
|| (commonEdge && commonEdge.isBottomSlat && commonEdge?.members?.length === 5)) {
res = true;
}
if (commonEdge.isAtomVertex && nRing.members?.length === 5) {
return true
}
}
if (index === 2 && commonEdge.isAtomSlat) {
if (this.isVertexNeighboursHasDoubleBond(edge.sourceId, ring)) {
if (nRing.members.length === 6) {
return false
} else {
return true
}
}
}
if (index === 4 && commonEdge.isAtomSlat) {
if (nRing && nRing.members.length === 5
&& nRing.hasHydrogen
&& nRing.elements.indexOf('S') === -1
&& nRing.elements.indexOf('O') === -1
) {
return true;
}
}
if ((index === 1) && commonEdge.isAtomSlat) {
if (this.isVertexNeighboursHasDoubleBond(edge.sourceId, ring)) {
res = false;
} else {
if (nRing.members.length === 5) {
return false;
}
if (index === 4) {
const rN = commonEdge.rings.filter(item => item !== ring.id);
const nRing = this.preprocessor.rings[rN[0]];
if (nRing && nRing.members.length > 5) {
return false;
}
}
res = true;
}
}
}
}
}
return res;
}
edgeNeighboursAreAtomSlat(edge) {
let res = false;
if (edge.neighbours.length === 2) {
return this.preprocessor.graph.edges[edge.neighbours[0]].isAtomSlat
&& this.preprocessor.graph.edges[edge.neighbours[1]].isAtomSlat
}
return res;
}
sortMembers(ring){
const members = [...ring.members].sort((a, b) => a - b);
const arr = [];
const edgesAll = [];
let prev;
for (let i = 0; i < members.length; i++) {
const v = members[i];
if (i === 0) {
arr.push(v);
prev = v
}
const vertex = this.preprocessor.graph.vertices[prev];
const neighbours = vertex.neighbours.filter(item => members.indexOf(item) !== -1 && arr.indexOf(item) === -1);
let vNext;
if (neighbours?.length) {
if (neighbours.length > 1) {
vNext = Math.min(...neighbours)
} else {
vNext = neighbours[0];
}
} else {
vNext = arr[0]
}
const vertexIds = vertex.id + '_' + vNext;
const ed = this.preprocessor.graph.vertexIdsToEdgeId[vertexIds]
prev = vNext;
if (ed || ed === 0) {
if (edgesAll.indexOf(vNext) === -1) {
edgesAll.push(ed);
}
if (arr.indexOf(vNext) === -1) {
arr.push(vNext);
}
}
}
return arr;
}
getEdgeBetweenVertexAB(vA, vB){
let vertexA = this.preprocessor.graph.vertices[vA];
let vertexB = this.preprocessor.graph.vertices[vB];
let edgesA = [...vertexA.edges];
let edgesB = [...vertexB.edges];
const edges = edgesA.filter(i => edgesB.indexOf(i) >= 0);
const isBetweenRings = vertexA.value.rings?.length > 1
&& vertexB.value.rings?.length > 1
&& arraysCompare(vertexA.value.rings, vertexB.value.rings);
const rings = isBetweenRings
? vertexA.value.rings
: [];
return {
item: edges[0],
isBetweenRings: isBetweenRings,
bRings: rings
};
}
isRing_SNN(ring) {
const elements = ring.elements;
let graph = this.preprocessor.graph;
let arrE = [...ring.edges];
if (elements.length < 5) {
return false
}
const arr = elements.filter(item => item === 'N' || item === 'S');
if (arr?.length > 0 && arr.indexOf('S') !== -1) {
const members = ring.membersS;
const indexS = elements.indexOf('S');
if (indexS !== -1) {
const vS = members[indexS];
let vertex = graph.vertices[vS];
vertex.isAtomVertex = true;
vertex.edges.map(item => {
if (ring.edges.indexOf(item) !== -1) {
const edge = this.preprocessor.graph.edges[item];
edge.isAtomVertex = true;
arrayDelElement(arrE, item);
}
});
let neighbours = vertex.neighbours;
neighbours.map(item => {
if (members.indexOf(item) !== -1) {
let vertexN = graph.vertices[item];
const vertexNEdges = vertexN.edges.filter(ed => ring.edges.indexOf(ed) !== -1);
vertexNEdges.map (ed => {
const edge = this.preprocessor.graph.edges[ed];
if (!edge.isAtomVertex) {
edge.isAtomSlat = true
}
arrayDelElement(arrE, ed);
});
}
});
if (elements.length === 5 && arrE?.length === 1) {
this.preprocessor.graph.edges[arrE[0]].isBottomSlat = true;
} else {
if (elements.length === 6) {
arrE.map(item => {
this.preprocessor.graph.edges[item].isBottomSlat = true;
})
}
}
ring.isDrawed = true;
return true
}
}
return false;
}
isRing_ONN(ring) {
const elements = ring.elements;
let arrE = [...ring.edges];
let graph = this.preprocessor.graph;
if (elements.length < 5) {
return false
}
const arr = elements.filter(item => item === 'N' || item === 'O');
if (
(arr?.length > 0
&& arr.indexOf('O') !== -1)
) {
const members = ring.membersS;
let indexS = this.findStartElementbyEdges(members, elements, 'O');
if (indexS !== -1) {
const vS = members[indexS];
let vertex = graph.vertices[vS];
vertex.isAtomVertex = true;
vertex.edges.map(item => {
if (ring.edges.indexOf(item) !== -1) {
const edge = this.preprocessor.graph.edges[item];
edge.isAtomVertex = true;
arrayDelElement(arrE, item);
}
});
let neighbours = vertex.neighbours.filter(item => members.indexOf(item) !== -1);
neighbours.map(item => {
let vertexN = graph.vertices[item];
vertexN.edges.map(ed => {
if (ring.edges.indexOf(ed) !== -1) {
const edge = this.preprocessor.graph.edges[ed];
if (!edge.isAtomVertex) {
edge.isAtomSlat = true
}
arrayDelElement(arrE, ed);
}
})
})
}
if (elements.length === 5 && arrE?.length === 1) {
this.preprocessor.graph.edges[arrE[0]].isBottomSlat = true;
} else {
if (elements.length === 6) {
arrE.map(item => {
this.preprocessor.graph.edges[item].isBottomSlat = true;
})
}
}
return true
}
return false;
}
isRing_NNN(ring) {
const elements = ring.elements;
let arrE = [...ring.edges];
let graph = this.preprocessor.graph;
if (elements.length < 5) {
return false
}
if (ring.isDrawed) {
return false
}
const arr = elements.filter(item => item === 'N');
if (arr?.length > 0) {
const members = ring.membersS;
let { indexS } = this.findStartNbyEdges(members, elements);
let vS = -1;
if (indexS !== -1) {
vS = members[indexS];
}
if (vS !== -1) {
let vertex = graph.vertices[vS];
vertex.isAtomVertex = true;
vertex.edges
.filter((e,i,a)=>a.indexOf(e)==i)
.map(item => {
if (ring.edges.indexOf(item) !== -1) {
const edge = this.preprocessor.graph.edges[item];
edge.isAtomVertex = true;
arrayDelElement(arrE, item);
}
});
let neighbours = vertex.neighbours.filter(item => members.indexOf(item) !== -1);
neighbours.map(item => {
let vertexN = graph.vertices[item];
const vEdges = vertexN.edges.filter(ed => ring.edges.indexOf(ed) !== -1 && arrE.indexOf(ed) !== -1);
vEdges.map(ed => {
const edge = this.preprocessor.graph.edges[ed];
if (!edge.isAtomVertex) {
edge.isAtomSlat = true
}
arrayDelElement(arrE, ed);
})
});
if (elements.length === 5 && arrE?.length === 1) {
this.preprocessor.graph.edges[arrE[0]].isBottomSlat = true;
} else {
if (elements.length === 6) {
arrE.map(item => {
this.preprocessor.graph.edges[item].isBottomSlat = true;
})
}
}
return true
}
}
return false;
}
isHydrogenVertices(arr) {
let res = false;
for (let i = 0; i < arr.length; i++) {
if (this.preprocessor.graph.vertices[arr[i]].value.bracket
&& Number(this.preprocessor.graph.vertices[arr[i]].value.bracket.hcount) > 0) {
res = true;
break;
}
}
return res
}
isVertexHasDoubleBondWithO(ring, v){
let res = false;
const vertex = this.preprocessor.graph.vertices[v];
const vEdges = vertex.edges.filter(item => ring.edges.indexOf(item) === -1);
if (vEdges.length > 1) {
for (let i = 0; i < vEdges.length; i++) {
const edge = this.preprocessor.graph.edges[vEdges[i]];
const vertexB = this.preprocessor.graph.vertices[edge.targetId];
if (this.edgeHaveDoubleBound(edge) && vertexB.value.element === 'O') {
vertex.hasDoubleBondWithO = true;
res = true;
}
}
}
return res;
};
checkVertex_N(vertex){
if (vertex.value.element !== 'N') {
return false;
}
let neighbours = this.preprocessor.graph.vertices[vertex.id].neighbours;
let bonds = 0;
for (let j = 0; j < neighbours.length; j++) {
bonds += this.preprocessor.graph.getEdge(vertex.id, neighbours[j]).weight;
}
if (bonds > vertex.value.getMaxBonds()) {
return true;
}
return false;
}
findStartNbyEdges(members, elements) {
let res = -1;
let isHydrogen = false;
for (let i = 0; i < elements.length; i++) {
if (elements[i] !== 'N') {
continue;
}
const v = members[i];
const vertex = this.preprocessor.graph.vertices[v];
if (vertex.value.bracket?.charge === 1) {
continue;
}
const edges = vertex.edges.filter((e,i,a)=>a.indexOf(e)==i);
if (this.checkVertex_N(vertex)) {
continue;
}
if (edges.length > 2) {
res = i;
if (vertex.value.rings.length > 1) {
continue
} else {
break;
}
}
if ( members.length >= 5 && this.isHydrogenVertices([v])) {
res = i;
isHydrogen = true;
break;
}
}
return {indexS: res, isHydrogen: isHydrogen};
}
findStartElementbyEdges(members, elements, element) {
let res = -1;
for (let i = 0; i < elements.length; i++) {
if (elements[i] !== element) {
continue;
}
const v = members[i];
const vertex = this.preprocessor.graph.vertices[v];
if (vertex.value.bracket?.charge === 1) {
continue;
}
res = i;
}
return res;
}
/**
* Draw the actual edges as bonds.
*
* @param {Boolean} debug A boolean indicating whether or not to draw debug helpers.
*/
drawEdges(debug) {
let preprocessor = this.preprocessor,
graph = preprocessor.graph,
rings = preprocessor.rings,
drawn = Array(this.preprocessor.graph.edges.length);
drawn.fill(false);
graph.traverseBF(0, vertex => {
let edges = graph.getEdges(vertex.id);
for (var i = 0; i < edges.length; i++) {
let edgeId = edges[i];
if (!drawn[edgeId]) {
drawn[edgeId] = true;
this.drawEdge(edgeId, debug);
}
}
});
// Draw ring for implicitly defined aromatic rings
if (!this.preprocessor.bridgedRing
&& this.preprocessor.opts.ringVisualization === 'circle'
) {
for (var i = 0; i < rings.length; i++) {
let ring = rings[i];
if (preprocessor.isRingAromatic(ring)) {
this.svgWrapper.drawAromaticityRing(ring);
}
}
}
}
/**
* Draw the an edge as a bond.
*
* @param {Number} edgeId An edge id.
* @param {Boolean} debug A boolean indicating whether or not to draw debug helpers.
*/
drawEdge(edgeId, debug) {
let preprocessor = this.preprocessor,
opts = preprocessor.opts,
svgWrapper = this.svgWrapper,
edge = preprocessor.graph.edges[edgeId],
vertexA = preprocessor.graph.vertices[edge.sourceId],
vertexB = preprocessor.graph.vertices[edge.targetId],
elementA = vertexA.value.element,
elementB = vertexB.value.element;
if ((!vertexA.value.isDrawn || !vertexB.value.isDrawn) && preprocessor.opts.atomVisualization === 'default') {
return;
}
let a = vertexA.position,
b = vertexB.position,
normals = preprocessor.getEdgeNormals(edge),
// Create a point on each side of the line
sides = ArrayHelper.clone(normals);
sides[0].multiplyScalar(10).add(a);
sides[0].multiplyScalar(10).add(a);
sides[1].multiplyScalar(10).add(a);
if (edge.bondType === '=' || preprocessor.getRingbondType(vertexA, vertexB) === '=' || this.edgeHaveDoubleBound(edge) ||
(edge.isPartOfAromaticRing && preprocessor.bridgedRing
&& edge.isPartOfRing
)
|| (edge.isPartOfRing
&& opts.ringVisualization === 'default'
)
) {
// Always draw double bonds inside the ring
let inRing = preprocessor.areVerticesInSameRing(vertexA, vertexB);
let s = preprocessor.chooseSide(vertexA, vertexB, sides);
if (inRing) {
// Always draw double bonds inside a ring
// if the bond is shared by two rings, it is drawn in the larger
// problem: smaller ring is aromatic, bond is still drawn in larger -> fix this
let lcr = preprocessor.getLargestOrAromaticCommonRing(vertexA, vertexB);
let center = lcr.center;
normals[0].multiplyScalar(opts.bondSpacing);
normals[1].multiplyScalar(opts.bondSpacing);
// Choose the normal that is on the same side as the center
let line = null;
if (center.sameSideAs(vertexA.position, vertexB.position, Vector2.add(a, normals[0]))) {
line = new Line(Vector2.add(a, normals[0]), Vector2.add(b, normals[0]), elementA, elementB);
} else {
line = new Line(Vector2.add(a, normals[1]), Vector2.add(b, normals[1]), elementA, elementB);
}
line.shorten(opts.bondLength - opts.shortBondLength * opts.bondLength);
// The shortened edge
if (edge.isPartOfAromaticRing) {
if (opts.ringAromaticVisualization === 'dashed' && preprocessor.bridgedRing) {
svgWrapper.drawLine(line, true);
} else {
if (((edge.isHaveLine && !edge.isNotHaveLine)
|| (edge.bondType === '=' || this.edgeHaveDoubleBound(edge)))) {
svgWrapper.drawLine(line);
}
}
} else {
svgWrapper.drawLine(line);
}
svgWrapper.drawLine(new Line(a, b, elementA, elementB));
} else if ((edge.center || vertexA.isTerminal() && vertexB.isTerminal()) ||
(s.anCount == 0 && s.bnCount > 1 || s.bnCount == 0 && s.anCount > 1)) {
this.multiplyNormals(normals, opts.halfBondSpacing);
let lineA = new Line(Vector2.add(a, normals[0]), Vector2.add(b, normals[0]), elementA, elementB),
lineB = new Line(Vector2.add(a, normals[1]), Vector2.add(b, normals[1]), elementA, elementB);
svgWrapper.drawLine(lineA);
svgWrapper.drawLine(lineB);
} else if ((s.sideCount[0] > s.sideCount[1]) ||
(s.totalSideCount[0] > s.totalSideCount[1])) {
this.multiplyNormals(normals, opts.bondSpacing);
let line = new Line(Vector2.add(a, normals[0]), Vector2.add(b, normals[0]), elementA, elementB);
line.shorten(opts.bondLength - opts.shortBondLength * opts.bondLength);
svgWrapper.drawLine(line);
svgWrapper.drawLine(new Line(a, b, elementA, elementB));
} else if ((s.sideCount[0] < s.sideCount[1]) ||
(s.totalSideCount[0] <= s.totalSideCount[1])) {
this.multiplyNormals(normals, opts.bondSpacing);
let line = new Line(Vector2.add(a, normals[1]), Vector2.add(b, normals[1]), elementA, elementB);
line.shorten(opts.bondLength - opts.shortBondLength * opts.bondLength);
svgWrapper.drawLine(line);
svgWrapper.drawLine(new Line(a, b, elementA, elementB));
}
} else if (edge?.bondType === '#') {
normals[0].multiplyScalar(opts.bondSpacing / 1.5);
normals[1].multiplyScalar(opts.bondSpacing / 1.5);
let lineA = new Line(Vector2.add(a, normals[0]), Vector2.add(b, normals[0]), elementA, elementB);
let lineB = new Line(Vector2.add(a, normals[1]), Vector2.add(b, normals[1]), elementA, elementB);
svgWrapper.drawLine(lineA);
svgWrapper.drawLine(lineB);
svgWrapper.drawLine(new Line(a, b, elementA, elementB));
} else if (edge?.bondType === '.') {
// TODO: Something... maybe... version 2?
} else {
let isChiralCenterA = vertexA.value.isStereoCenter;
let isChiralCenterB = vertexB.value.isStereoCenter;
if (edge.wedge === 'up') {
svgWrapper.drawWedge(new Line(a, b, elementA, elementB, isChiralCenterA, isChiralCenterB));
} else if (edge.wedge === 'down') {
svgWrapper.drawDashedWedge(new Line(a, b, elementA, elementB, isChiralCenterA, isChiralCenterB));
} else {
svgWrapper.drawLine(new Line(a, b, elementA, elementB, isChiralCenterA, isChiralCenterB));
}
}
if (debug) {
let midpoint = Vector2.midpoint(a, b);
svgWrapper.drawDebugText(midpoint.x, midpoint.y, 'e: ' + edgeId);
}
}
allNeighboursHasDoubleLine(vertex){
const edges = vertex.edges;
if (edges.length < 2 || vertex.value.rings.length) {
return false;
}
let res = true;
for (let i = 0; i < edges.length; i++) {
const edge = this.preprocessor.graph.edges[edges[i]];
if (edge.bondType !== '=') {
res = false;
break;
}
}
return res;
}
/**
* Draws the vertices representing atoms to the canvas.
*
* @param {Boolean} debug A boolean indicating whether or not to draw debug messages to the canvas.
*/
drawVertices(debug) {
let preprocessor = this.preprocessor,
opts = preprocessor.opts,
graph = preprocessor.graph,
rings = preprocessor.rings,
svgWrapper = this.svgWrapper;
var i = graph.vertices.length;
for (var i: any = 0; i < graph.vertices.length; i++) {
let vertex = graph.vertices[i];
let atom = vertex.value;
let charge = 0;
let isotope = 0;
let bondCount = vertex.value.bondCount;
let element = atom.element;
let hydrogens = Atom.maxBonds[element] - bondCount;
let dir = vertex.getTextDirection(graph.vertices);
let isShowC = element === 'C' && this.allNeighboursHasDoubleLine(vertex);
let isTerminal = opts.terminalCarbons || element !== 'C' || atom.hasAttachedPseudoElements ? vertex.isTerminal() : false;
let isCarbon = atom.element === 'C';
// This is a HACK to remove all hydrogens from nitrogens in aromatic rings, as this
// should be the most common state. This has to be fixed by kekulization
if (atom.element === 'N' && atom.isPartOfAromaticRing) {
hydrogens = 0;
}
if (atom.bracket) {
hydrogens = atom.bracket.hcount;
charge = atom.bracket.charge;
isotope = atom.bracket.isotope;
}
if (opts.atomVisualization === 'allballs') {
svgWrapper.drawBall(vertex.position.x, vertex.position.y, element);
} else if ((atom.isDrawn && (!isCarbon || atom.drawExplicit || isTerminal || atom.hasAttachedPseudoElements) || isShowC) || graph.vertices.length === 1) {
if (opts.atomVisualization === 'default') {
const isCentre = atom.hasPseudoElements && vertex.neighbours.length === 4 && !vertex.value.rings.length;
svgWrapper.drawText(vertex.position.x, vertex.position.y,
element, hydrogens, dir, isTerminal, charge, isotope, atom.getAttachedPseudoElements(), isCentre);
} else if (opts.atomVisualization === 'balls') {
svgWrapper.drawBall(vertex.position.x, vertex.position.y, element);
}
} else if (vertex.getNeighbourCount() === 2 && vertex.forcePositioned == true) {
// If there is a carbon which bonds are in a straight line, draw a dot
let a = graph.vertices[vertex.neighbours[0]].position;
let b = graph.vertices[vertex.neighbours[1]].position;
let angle = Vector2.threePointangle(vertex.position, a, b);
if (Math.abs(Math.PI - angle) < 0.1) {
svgWrapper.drawPoint(vertex.position.x, vertex.position.y, element);
}
}
if (debug) {
let value = 'v: ' + vertex.id + ' ' + ArrayHelper.print(atom.ringbonds);
svgWrapper.drawDebugText(vertex.position.x, vertex.position.y, value);
} else {
svgWrapper.drawDebugText(vertex.position.x, vertex.position.y, vertex.value.chirality);
}
}
// Draw the ring centers for debug purposes
if (opts.debug) {
for (var i: any = 0; i < rings.length; i++) {
let center = rings[i].center;
svgWrapper.drawDebugPoint(center.x, center.y, 'r: ' + rings[i].id);
}
}
}
/**
* Returns the total overlap score of the current molecule.
*
* @returns {Number} The overlap score.
*/
getTotalOverlapScore() {
return this.preprocessor.getTotalOverlapScore();
}
/**
* Returns the molecular formula of the loaded molecule as a string.
*
* @returns {String} The molecular formula.
*/
getMolecularFormula() {
return this.preprocessor.getMolecularFormula();
}
/**
* @param {Array} normals list of normals to multiply
* @param {Number} spacing value to multiply normals by
*/
multiplyNormals(normals, spacing) {
normals[0].multiplyScalar(spacing);
normals[1].multiplyScalar(spacing);
}
}
export default SvgDrawer; | the_stack |
import { expect } from 'chai';
import * as childProcess from 'child_process';
// tslint:disable-next-line:no-require-imports
import deepEqual = require('deep-equal');
import * as fs from 'fs';
import * as fsExtra from 'fs-extra';
import * as path from 'path';
import { DryCommandConfig } from './dry-command-config';
import { DryPackageContent } from './dry-package-content';
import { DryPackagerDescriptor } from './dry-packager-descriptor';
import { JsonUtils } from './json-utils';
describe('index', () => {
const childProcessStdio = 'ignore';
const dryIndexJs = path.resolve('dist/index.js');
const testDir = path.resolve('dist-test');
const npmDescriptorFile = path.resolve('packagerDescriptorTemplates/npm.json');
const pnpmDescriptorFile = path.resolve('packagerDescriptorTemplates/pnpm.json');
const mkdirIfNotExist = (dir: string): void => {
if (fs.existsSync(dir)) {
return;
}
fsExtra.mkdirsSync(dir);
};
const readJson = (file: string): any => JSON.parse(fs.readFileSync(path.resolve(file), 'utf8'));
const writeJson = (file: string, obj: any): any => fs.writeFileSync(path.resolve(file), JSON.stringify(obj, null, 2) + '\n');
beforeEach(function(this: Mocha.IBeforeAndAfterContext): any {
this.timeout(10000);
fsExtra.removeSync(testDir);
mkdirIfNotExist(testDir);
return;
});
describe('dry commands match npm commands', () => {
const executeAndAssertSame = (commands: string[], packageJson: boolean, lock: boolean) => {
const withNpmDir = path.resolve(`${testDir}/with-npm/foo`);
mkdirIfNotExist(withNpmDir);
const withDryDir = path.resolve(`${testDir}/with-dry/foo`);
mkdirIfNotExist(withDryDir);
commands.forEach((command) => childProcess.execSync(`npm ${command}`, { cwd: withNpmDir, stdio: childProcessStdio }));
commands.forEach((command) =>
childProcess.execSync(`node ${dryIndexJs} ${command}`, { cwd: withDryDir, stdio: childProcessStdio }),
);
if (packageJson) {
expect(deepEqual(readJson(`${withDryDir}/package-dry.json`), readJson(`${withNpmDir}/package.json`))).to.be.true;
}
if (lock) {
expect(deepEqual(readJson(`${withDryDir}/package-lock.json`), readJson(`${withNpmDir}/package-lock.json`))).to.be.true;
}
};
it('init -f', () => executeAndAssertSame(['init -f'], true, false)).timeout(30000);
it('init -f && install', () => executeAndAssertSame(['init -f', 'install'], true, true)).timeout(30000);
it('init -f && install && pack', () => executeAndAssertSame(['init -f', 'install', 'pack'], true, true)).timeout(30000);
});
describe('dry inheritance', () => {
it('inherits foo script when foo is defined in dry package parent', () => {
// Build parent
const parentProject = path.resolve(`${testDir}/parent`);
mkdirIfNotExist(parentProject);
childProcess.execSync(`node ${dryIndexJs} init -f`, { cwd: parentProject, stdio: childProcessStdio });
const parentDryPackage = readJson(path.resolve(`${parentProject}/package-dry.json`));
parentDryPackage.scripts.foo = 'npm help';
writeJson(`${parentProject}/package-dry.json`, parentDryPackage);
childProcess.execSync(`node ${dryIndexJs} pack`, { cwd: parentProject, stdio: childProcessStdio });
// Build child
const childProject = path.resolve(`${testDir}/child`);
mkdirIfNotExist(childProject);
childProcess.execSync(`node ${dryIndexJs} init -f`, { cwd: childProject, stdio: childProcessStdio });
const childDryPackage: DryPackageContent = readJson(path.resolve(`${childProject}/package-dry.json`));
childDryPackage.dry = {
extends: 'parent/package-dry.json',
dependencies: {
parent: 'file:../parent/parent-1.0.0.tgz',
},
};
writeJson(`${childProject}/package-dry.json`, childDryPackage);
// Run the script
childProcess.execSync(`node ${dryIndexJs} run foo`, { cwd: childProject, stdio: childProcessStdio });
expect(fs.existsSync(`${childProject}/package.json`)).to.be.false;
}).timeout(30000);
it('inherits version for dependencies and devDependencies script when version is defined in dry package parent', () => {
// Build parent
const parentProject = path.resolve(`${testDir}/parent`);
mkdirIfNotExist(parentProject);
childProcess.execSync(`node ${dryIndexJs} init -f`, { cwd: parentProject, stdio: childProcessStdio });
const parentDryPackage = readJson(path.resolve(`${parentProject}/package-dry.json`));
parentDryPackage.dependencyManagement = {
dfirst: 'parentValue',
dsecond: 'parentValue',
ddfirst: 'parentValue',
ddsecond: 'parentValue',
};
writeJson(`${parentProject}/package-dry.json`, parentDryPackage);
childProcess.execSync(`node ${dryIndexJs} pack`, { cwd: parentProject, stdio: childProcessStdio });
// Build child
const childProject = path.resolve(`${testDir}/child`);
mkdirIfNotExist(childProject);
childProcess.execSync(`node ${dryIndexJs} init -f`, { cwd: childProject, stdio: childProcessStdio });
const childDryPackage: DryPackageContent = readJson(path.resolve(`${childProject}/package-dry.json`));
childDryPackage.dry = {
extends: 'parent/package-dry.json',
dependencies: {
parent: 'file:../parent/parent-1.0.0.tgz',
},
};
const classicNpmPackage: any = childDryPackage;
classicNpmPackage.dependencies = {
dfirst: 'managed',
dsecond: 'childValue',
};
classicNpmPackage.devDependencies = {
ddfirst: 'managed',
ddsecond: 'childValue',
};
writeJson(`${childProject}/package-dry.json`, classicNpmPackage);
// Run the script
childProcess.execSync(`node ${dryIndexJs} --dry-keep-package-json`, { cwd: childProject, stdio: childProcessStdio });
const packageJson: any = readJson(`${childProject}/package.json`);
const dependencies = packageJson.dependencies;
const devDependencies = packageJson.devDependencies;
expect(dependencies.dfirst).to.be.equals('parentValue');
expect(dependencies.dsecond).to.be.equals('childValue');
expect(devDependencies.ddfirst).to.be.equals('parentValue');
expect(devDependencies.ddsecond).to.be.equals('childValue');
expect(fs.existsSync(`${childProject}/package.json`)).to.be.true;
fs.unlinkSync(`${childProject}/package.json`);
expect(fs.existsSync(`${childProject}/package.json`)).to.be.false;
}).timeout(30000);
});
describe('dry json config loading', () => {
it('npm packager definition loading', () => {
const npm: DryPackagerDescriptor = JsonUtils.loadObject(npmDescriptorFile, DryPackagerDescriptor);
expect(npm.getPackageManager()).to.be.equals('npm');
});
it('npm packager arguments simple mapping without argument value', () => {
const npm: DryPackagerDescriptor = JsonUtils.loadObject(npmDescriptorFile, DryPackagerDescriptor);
const arg: string = '-dd';
const argValue: string = undefined;
const inArgs: string[] = [];
const outArgs: string[] = [];
const outInstallParentArgs: string[] = [];
npm.mapArguments(arg, argValue, inArgs, outArgs, outInstallParentArgs);
expect(outArgs[0]).to.be.equals('--loglevel');
expect(outArgs[1]).to.be.equals('verbose');
expect(outArgs.length).to.be.equals(2);
expect(outInstallParentArgs[0]).to.be.equals('--loglevel');
expect(outInstallParentArgs[1]).to.be.equals('verbose');
expect(outInstallParentArgs.length).to.be.equals(2);
});
it('npm packager arguments simple mapping with argument', () => {
const npm: DryPackagerDescriptor = JsonUtils.loadObject(npmDescriptorFile, DryPackagerDescriptor);
const arg: string = '--loglevel';
const argValue: string = 'trace';
const inArgs: string[] = [];
const outArgs: string[] = [];
const outInstallParentArgs: string[] = [];
npm.mapArguments(arg, argValue, inArgs, outArgs, outInstallParentArgs);
expect(outArgs[0]).to.be.equals('--loglevel');
expect(outArgs[1]).to.be.equals('silly');
expect(outArgs.length).to.be.equals(2);
expect(outInstallParentArgs[0]).to.be.equals('--loglevel');
expect(outInstallParentArgs[1]).to.be.equals('silly');
expect(outInstallParentArgs.length).to.be.equals(2);
});
it('npm packager arguments simple mapping without argument value extracted', () => {
const npm: DryPackagerDescriptor = JsonUtils.loadObject(npmDescriptorFile, DryPackagerDescriptor);
const arg: string = '--loglevel';
const argValue: string = undefined;
const inArgs: string[] = ['trace'];
const outArgs: string[] = [];
const outInstallParentArgs: string[] = [];
npm.mapArguments(arg, argValue, inArgs, outArgs, outInstallParentArgs);
expect(outArgs[0]).to.be.equals('--loglevel');
expect(outArgs[1]).to.be.equals('silly');
expect(outArgs.length).to.be.equals(2);
expect(outInstallParentArgs[0]).to.be.equals('--loglevel');
expect(outInstallParentArgs[1]).to.be.equals('silly');
expect(outInstallParentArgs.length).to.be.equals(2);
expect(inArgs.length).to.be.equals(0);
});
it('check dry command config mapping', () => {
const inArgs: string[] = ['init', '-f', '-D'];
const cfg: DryCommandConfig = new DryCommandConfig(inArgs);
const outArgs: string[] = cfg.getCommandProxyArgs();
const outInstallParentArgs: string[] = cfg.getInstallParentCommandProxyArgs();
expect(cfg.getPackagerDescriptor().getPackageManager()).to.be.equals('npm');
expect(outArgs.length).to.be.equals(4);
expect(outArgs[0]).to.be.equals('init');
expect(outArgs[1]).to.be.equals('-f');
expect(outArgs[2]).to.be.equals('--loglevel');
expect(outArgs[3]).to.be.equals('info');
expect(outInstallParentArgs.length).to.be.equals(2);
expect(outInstallParentArgs[0]).to.be.equals('--loglevel');
expect(outInstallParentArgs[1]).to.be.equals('info');
});
it('pnpm packager definition loading', () => {
const pnpm: DryPackagerDescriptor = JsonUtils.loadObject(pnpmDescriptorFile, DryPackagerDescriptor);
expect(pnpm.getPackageManager()).to.be.equals('pnpm');
expect(pnpm.getMappedArguments().length).to.be.equals(6);
});
});
}); | the_stack |
import { CSSStyles, CSSPseudoStyles, CSSStylesItem, CSSInlineStyles } from "./cssTypes";
import {
applyDynamicStyle,
ColorlessSprite,
destroyDynamicStyle,
IBobrilCacheChildren,
IBobrilCacheNode,
IBobrilCacheNodeUnsafe,
IBobrilChildren,
IBobrilNode,
IBobrilStyleDef,
IBobrilStyles,
internalSetCssInJsCallbacks,
invalidate,
} from "./core";
import { assert, createTextNode, hOP, newHashObj, noop } from "./localHelpers";
import { isArray, isFunction, isNumber, isObject, isString } from "./isFunc";
import { setAfterFrame } from "./frameCallbacks";
import { getMedia } from "./media";
declare var DEBUG: boolean;
const vendors = ["Webkit", "Moz", "ms", "O"];
const testingDivStyle: any = document.createElement("div").style;
function testPropExistence(name: string) {
return isString(testingDivStyle[name]);
}
export type IBobrilShimStyleMapping = Map<string, (style: any, value: any, oldName: string) => void>;
var mapping: IBobrilShimStyleMapping = new Map();
var isUnitlessNumber: ReadonlySet<string> = new Set(
"boxFlex boxFlexGroup columnCount flex flexGrow flexNegative flexPositive flexShrink fontWeight lineClamp lineHeight opacity order orphans strokeDashoffset widows zIndex zoom".split(
" "
)
);
function renamer(newName: string) {
return (style: any, value: any, oldName: string) => {
style[newName] = value;
style[oldName] = undefined;
};
}
function renamerPx(newName: string) {
return (style: any, value: any, oldName: string) => {
if (isNumber(value)) {
style[newName] = value + "px";
} else {
style[newName] = value;
}
style[oldName] = undefined;
};
}
function pxAdder(style: any, value: any, name: string) {
if (isNumber(value)) style[name] = value + "px";
}
function shimStyle(newValue: any) {
var k = Object.keys(newValue);
for (var i = 0, l = k.length; i < l; i++) {
var ki = k[i]!;
var mi = mapping.get(ki);
var vi = newValue[ki];
if (vi === undefined) continue; // don't want to map undefined
if (mi === undefined) {
if (DEBUG) {
if (/-/.test(ki))
console.warn("Style property " + ki + " contains dash (must use JS props instead of css names)");
}
if (testPropExistence(ki)) {
mi = isUnitlessNumber.has(ki) ? noop : pxAdder;
} else {
var titleCaseKi = ki.replace(/^\w/, (match) => match.toUpperCase());
for (var j = 0; j < vendors.length; j++) {
if (testPropExistence(vendors[j] + titleCaseKi)) {
mi = (isUnitlessNumber.has(ki) ? renamer : renamerPx)(vendors[j] + titleCaseKi);
break;
}
}
if (mi === undefined) {
mi = isUnitlessNumber.has(ki) ? noop : pxAdder;
if (
DEBUG &&
["overflowScrolling", "touchCallout"].indexOf(ki) < 0 // whitelist rare but useful
)
console.warn("Style property " + ki + " is not supported in this browser");
}
}
mapping.set(ki, mi);
}
mi(newValue, vi, ki);
}
}
function removeStyleProperty(s: CSSStyleDeclaration, name: string) {
s.removeProperty(hyphenateStyle(name));
}
function setStyleProperty(s: CSSStyleDeclaration, name: string, value: string) {
let len = value.length;
if (len > 11 && value.substr(len - 11, 11) === " !important") {
s.setProperty(hyphenateStyle(name), value.substr(0, len - 11), "important");
return;
}
s.setProperty(hyphenateStyle(name), value);
}
function setClassName(el: Element, className: string, inSvg: boolean) {
if (inSvg) el.setAttribute("class", className);
else (<HTMLElement>el).className = className;
}
export function updateElementStyle(
el: HTMLElement,
newStyle: Record<string, string | number | undefined> | undefined,
oldStyle: Record<string, string | undefined> | undefined
) {
var s = el.style;
if (newStyle !== undefined) {
shimStyle(newStyle);
var rule: string;
if (oldStyle !== undefined) {
for (rule in oldStyle) {
if (oldStyle[rule] === undefined) continue;
if (newStyle[rule] === undefined) removeStyleProperty(s, rule);
}
for (rule in newStyle) {
var v = newStyle[rule];
if (v !== undefined && oldStyle[rule] !== v) setStyleProperty(s, rule, v as string);
}
} else {
for (rule in newStyle) {
var v = newStyle[rule];
if (v !== undefined) setStyleProperty(s, rule, v as string);
}
}
} else {
if (oldStyle !== undefined) {
for (rule in oldStyle) {
removeStyleProperty(s, rule);
}
}
}
}
function createNodeStyle(
el: HTMLElement,
newStyle: Record<string, string | number | undefined> | (() => IBobrilStyles) | undefined,
newClass: string | undefined,
c: IBobrilCacheNode,
inSvg: boolean
) {
if (isFunction(newStyle)) {
assert(newClass === undefined);
var appliedStyle = applyDynamicStyle(newStyle, c);
newStyle = appliedStyle.style as Record<string, string | number | undefined> | undefined;
newClass = appliedStyle.className;
}
if (newStyle) updateElementStyle(el, newStyle, undefined);
if (newClass) setClassName(el, newClass, inSvg);
}
function updateNodeStyle(
el: HTMLElement,
newStyle: Record<string, string | number | undefined> | (() => IBobrilStyles) | undefined,
newClass: string | undefined,
c: IBobrilCacheNode,
inSvg: boolean
) {
if (isFunction(newStyle)) {
assert(newClass === undefined);
var appliedStyle = applyDynamicStyle(newStyle, c);
newStyle = appliedStyle.style as Record<string, string | number | undefined> | undefined;
newClass = appliedStyle.className;
} else {
destroyDynamicStyle(c);
}
updateElementStyle(el, newStyle, c.style);
(c as IBobrilCacheNodeUnsafe).style = newStyle as Record<string, string | undefined>;
if (newClass !== c.className) {
setClassName(el, newClass || "", inSvg);
(c as IBobrilCacheNodeUnsafe).className = newClass;
}
}
interface ISprite {
styleId: IBobrilStyleDef;
url: string;
width: number | undefined;
height: number | undefined;
left: number;
top: number;
}
interface ISvgSprite {
styleId: IBobrilStyleDef;
svg: string;
}
interface IDynamicSprite extends ISprite {
color: () => string;
lastColor: string;
lastUrl: string;
}
interface IResponsiveSprite {
styleId: IBobrilStyleDef;
width: number;
height: number;
left: number;
top: number;
}
interface IResponsiveDynamicSprite extends IResponsiveSprite {
color: string | (() => string);
lastColor: string;
lastUrl: string;
}
interface IInternalStyle {
name: string | null;
realName: string | null;
parent?: string | IBobrilStyleDef | IBobrilStyleDef[];
style: CSSStyles | (() => [CSSStyles, CSSPseudoStyles]);
pseudo?: CSSPseudoStyles;
}
export type Keyframes = { from?: CSSStyles; to?: CSSStyles; [step: number]: CSSStyles };
interface IInternalKeyFrames {
name: string;
def: Keyframes;
}
interface IInteralMediaQuery {
[key: string]: CSSStylesItem;
}
var allStyles: { [id: string]: IInternalStyle } = newHashObj();
var allAnimations: { [id: string]: IInternalKeyFrames } = newHashObj();
var allMediaQueries: { [id: string]: IInteralMediaQuery[] } = newHashObj();
var allSprites: { [key: string]: ISprite } = newHashObj();
var bundledSprites: { [key: string]: IResponsiveSprite } = newHashObj();
var allNameHints: { [name: string]: boolean } = newHashObj();
var dynamicSprites: IDynamicSprite[] = [];
var svgSprites = new Map<string, ColorlessSprite>();
var bundledDynamicSprites: IResponsiveDynamicSprite[] = [];
var imageCache: { [url: string]: HTMLImageElement | null } = newHashObj();
var injectedCss = "";
var rebuildStyles = false;
var htmlStyle: HTMLStyleElement | null = null;
var globalCounter: number = 0;
var chainedAfterFrame = setAfterFrame(afterFrame);
const cssSubRuleDelimiter = /\:|\ |\>/;
function buildCssSubRule(parent: string): string | null {
let matchSplit = cssSubRuleDelimiter.exec(parent);
if (!matchSplit) return allStyles[parent]!.name;
let posSplit = matchSplit.index;
return allStyles[parent.substring(0, posSplit)]!.name + parent.substring(posSplit);
}
function buildCssRule(parent: string | string[] | undefined, name: string): string {
let result = "";
if (parent) {
if (isArray(parent)) {
for (let i = 0; i < parent.length; i++) {
if (i > 0) {
result += ",";
}
result += "." + buildCssSubRule(parent[i]!) + "." + name;
}
} else {
result = "." + buildCssSubRule(<string>parent) + "." + name;
}
} else {
result = "." + name;
}
return result;
}
function flattenStyle(cur: any, curPseudo: any, style: any, stylePseudo: any): void {
if (isString(style)) {
let externalStyle = allStyles[style];
if (externalStyle === undefined) {
throw new Error("Unknown style " + style);
}
flattenStyle(cur, curPseudo, externalStyle.style, externalStyle.pseudo);
} else if (isFunction(style)) {
style(cur, curPseudo);
} else if (isArray(style)) {
for (let i = 0; i < style.length; i++) {
flattenStyle(cur, curPseudo, style[i], undefined);
}
} else if (isObject(style)) {
for (let key in style) {
if (!hOP.call(style, key)) continue;
let val = style[key];
if (isFunction(val)) {
val = val(cur, key);
}
cur[key] = val;
}
}
if (stylePseudo != undefined && curPseudo != undefined) {
for (let pseudoKey in stylePseudo) {
let curPseudoVal = curPseudo[pseudoKey];
if (curPseudoVal === undefined) {
curPseudoVal = newHashObj();
curPseudo[pseudoKey] = curPseudoVal;
}
flattenStyle(curPseudoVal, undefined, stylePseudo[pseudoKey], undefined);
}
}
}
let lastDppx = 0;
let lastSpriteUrl = "";
let lastSpriteDppx = 1;
let hasBundledSprites = false;
let wasSpriteUrlChanged = true;
function afterFrame(root: IBobrilCacheChildren | null) {
var currentDppx = getMedia().dppx;
if (hasBundledSprites && lastDppx != currentDppx) {
lastDppx = currentDppx;
let newSpriteUrl = bundlePath;
let newSpriteDppx = 1;
if (lastDppx > 1) {
for (let i = 0; i < bundlePath2.length; i++) {
if (i == bundlePath2.length - 1 || bundlePath2[i]![1] >= lastDppx) {
newSpriteUrl = bundlePath2[i]![0];
newSpriteDppx = bundlePath2[i]![1];
} else break;
}
}
if (lastSpriteUrl != newSpriteUrl) {
lastSpriteUrl = newSpriteUrl;
lastSpriteDppx = newSpriteDppx;
rebuildStyles = true;
wasSpriteUrlChanged = true;
}
}
if (rebuildStyles) {
if (hasBundledSprites) {
let imageSprite = imageCache[lastSpriteUrl];
if (imageSprite === undefined) {
imageSprite = null;
imageCache[lastSpriteUrl] = imageSprite;
loadImage(lastSpriteUrl, (image) => {
imageCache[lastSpriteUrl] = image;
invalidateStyles();
});
}
if (imageSprite != null) {
for (let i = 0; i < bundledDynamicSprites.length; i++) {
let dynSprite = bundledDynamicSprites[i]!;
let colorStr = dynSprite.color;
if (!isString(colorStr)) colorStr = colorStr();
if (wasSpriteUrlChanged || colorStr !== dynSprite.lastColor) {
dynSprite.lastColor = colorStr;
let mulWidth = (dynSprite.width * lastSpriteDppx) | 0;
let mulHeight = (dynSprite.height * lastSpriteDppx) | 0;
let lastUrl = recolorAndClip(
imageSprite,
colorStr,
mulWidth,
mulHeight,
(dynSprite.left * lastSpriteDppx) | 0,
(dynSprite.top * lastSpriteDppx) | 0
);
var stDef = allStyles[dynSprite.styleId]!;
stDef.style = {
backgroundImage: `url(${lastUrl})`,
width: dynSprite.width,
height: dynSprite.height,
backgroundPosition: 0,
backgroundSize: "100%",
};
}
}
if (wasSpriteUrlChanged) {
let iWidth = imageSprite.width / lastSpriteDppx;
let iHeight = imageSprite.height / lastSpriteDppx;
for (let key in bundledSprites) {
let sprite = bundledSprites[key]!;
if ((sprite as IResponsiveDynamicSprite).color !== undefined) continue;
var stDef = allStyles[sprite.styleId]!;
let width = sprite.width;
let height = sprite.height;
let percentWidth = (100 * iWidth) / width;
let percentHeight = (100 * iHeight) / height;
stDef.style = {
backgroundImage: `url(${lastSpriteUrl})`,
width: width,
height: height,
backgroundPosition: `${(100 * sprite.left) / (iWidth - width)}% ${
(100 * sprite.top) / (iHeight - height)
}%`,
backgroundSize: `${percentWidth}% ${percentHeight}%`,
};
}
}
wasSpriteUrlChanged = false;
}
}
for (let i = 0; i < dynamicSprites.length; i++) {
let dynSprite = dynamicSprites[i]!;
let image = imageCache[dynSprite.url];
if (image == undefined) continue;
let colorStr = dynSprite.color();
if (colorStr !== dynSprite.lastColor) {
dynSprite.lastColor = colorStr;
if (dynSprite.width == undefined) dynSprite.width = image.width;
if (dynSprite.height == undefined) dynSprite.height = image.height;
let lastUrl = recolorAndClip(
image,
colorStr,
dynSprite.width,
dynSprite.height,
dynSprite.left,
dynSprite.top
);
var stDef = allStyles[dynSprite.styleId]!;
stDef.style = {
backgroundImage: `url(${lastUrl})`,
width: dynSprite.width,
height: dynSprite.height,
backgroundPosition: 0,
};
}
}
var styleStr = injectedCss;
for (var key in allAnimations) {
var anim = allAnimations[key]!;
styleStr += "@keyframes " + anim.name + " {";
for (var key2 in anim.def) {
let item = anim.def[key2];
let style = newHashObj();
flattenStyle(style, undefined, item, undefined);
shimStyle(style);
styleStr +=
key2 +
(key2 == "from" || key2 == "to" ? "" : "%") +
" {" +
inlineStyleToCssDeclaration(style) +
"}\n";
}
styleStr += "}\n";
}
for (var key in allStyles) {
var ss = allStyles[key]!;
let parent = ss.parent;
let name = ss.name;
let ssPseudo = ss.pseudo;
let ssStyle = ss.style;
if (isFunction(ssStyle) && ssStyle.length === 0) {
[ssStyle, ssPseudo] = (ssStyle as any)();
}
if (isString(ssStyle) && ssPseudo == undefined) {
ss.realName = ssStyle;
assert(name != undefined, "Cannot link existing class to selector");
continue;
}
ss.realName = name;
let style = newHashObj();
let flattenPseudo = newHashObj();
flattenStyle(undefined, flattenPseudo, undefined, ssPseudo);
flattenStyle(style, flattenPseudo, ssStyle, undefined);
shimStyle(style);
let cssStyle = inlineStyleToCssDeclaration(style);
if (cssStyle.length > 0)
styleStr += (name == undefined ? parent : buildCssRule(parent, name)) + " {" + cssStyle + "}\n";
for (var key2 in flattenPseudo) {
let item = flattenPseudo[key2];
shimStyle(item);
styleStr +=
(name == undefined
? parent + addDoubleDot(key2)
: buildCssRule(parent, name + addDoubleDot(key2))) +
" {" +
inlineStyleToCssDeclaration(item) +
"}\n";
}
}
for (var key in allMediaQueries) {
var mediaQuery = allMediaQueries[key]!;
styleStr += "@media " + key + "{";
for (var definition of mediaQuery) {
for (var key2 in definition) {
let item = definition[key2];
let style = newHashObj();
flattenStyle(style, undefined, item, undefined);
shimStyle(style);
styleStr += "." + key2 + " {" + inlineStyleToCssDeclaration(style) + "}\n";
}
}
styleStr += "}\n";
}
var styleElement = document.createElement("style");
styleElement.appendChild(createTextNode(styleStr));
var head = document.head || document.getElementsByTagName("head")[0];
if (htmlStyle != null) {
head.replaceChild(styleElement, htmlStyle);
} else {
head.appendChild(styleElement);
}
htmlStyle = styleElement;
rebuildStyles = false;
}
chainedAfterFrame(root);
}
function addDoubleDot(pseudoOrElse: string) {
var c = pseudoOrElse.charCodeAt(0);
if (c == 32 || c == 0x5b || c == 0x2e)
// " ", "[", "."
return pseudoOrElse;
return ":" + pseudoOrElse;
}
export function style(node: IBobrilNode, ...styles: IBobrilStyles[]): IBobrilNode {
let className = node.className;
let inlineStyle = node.style;
let stack: (IBobrilStyles | number)[] | null = null;
let i = 0;
let ca = styles;
while (true) {
if (ca.length === i) {
if (stack === null || stack.length === 0) break;
ca = <IBobrilStyles[]>stack.pop();
i = <number>stack.pop() + 1;
continue;
}
let s = ca[i];
if (s == undefined || s === true || s === false || s === "" || s === 0) {
// skip
} else if (isString(s)) {
var sd = allStyles[s];
if (sd != undefined) {
s = sd.realName! as IBobrilStyleDef;
}
if (className == undefined) className = s;
else className += " " + s;
} else if (isArray(s)) {
if (ca.length > i + 1) {
if (stack == undefined) stack = [];
stack.push(i);
stack.push(ca);
}
ca = <IBobrilStyles[]>s;
i = 0;
continue;
} else {
if (inlineStyle == undefined) inlineStyle = newHashObj();
for (let key in s) {
if (hOP.call(s, key)) {
let val = (<any>s)[key];
if (isFunction(val)) val = val();
(inlineStyle as any)[key] = val;
}
}
}
i++;
}
node.className = className;
node.style = inlineStyle;
return node;
}
const uppercasePattern = /([A-Z])/g;
const msPattern = /^ms-/;
const hyphenateCache = new Map([["cssFloat", "float"]]);
function hyphenateStyle(s: string): string {
var res = hyphenateCache.get(s);
if (res === undefined) {
res = s.replace(uppercasePattern, "-$1").toLowerCase().replace(msPattern, "-ms-");
hyphenateCache.set(s, res);
}
return res;
}
function inlineStyleToCssDeclaration(style: any): string {
var res = "";
for (var key in style) {
var v = style[key];
if (v === undefined) continue;
res += hyphenateStyle(key) + ":" + (v === "" ? '""' : v) + ";";
}
res = res.slice(0, -1);
return res;
}
// PureFuncs: styleDef, styleDefEx, sprite, spriteb, spritebc
export function styleDef(style: CSSStyles, pseudoOrAttr?: CSSPseudoStyles, nameHint?: string): IBobrilStyleDef {
return styleDefEx(undefined, style, pseudoOrAttr, nameHint);
}
function makeName(nameHint?: string): string {
if (nameHint && nameHint !== "b-") {
nameHint = nameHint.replace(/[^a-z0-9_-]/gi, "_").replace(/^[0-9]/, "_$&");
if (allNameHints[nameHint]) {
var counter = 1;
while (allNameHints[nameHint + counter]) counter++;
nameHint = nameHint + counter;
}
allNameHints[nameHint] = true;
} else {
nameHint = "b-" + globalCounter++;
}
return nameHint;
}
export type AnimationNameFactory = ((params?: string) => string) & ((styles: CSSInlineStyles, key: string) => string);
export function keyframesDef(def: Keyframes, nameHint?: string): AnimationNameFactory {
nameHint = makeName(nameHint);
allAnimations[nameHint] = { name: nameHint, def };
rebuildStyles = true;
const res = (params?: string) => {
if (isString(params)) return params + " " + nameHint;
return nameHint!;
};
res.toString = res;
return res as AnimationNameFactory;
}
type MediaQueryDefinition = {
[key: string]: CSSStylesItem;
};
/**
* create media query
* @example
* // can be called with string query definition
* mediaQueryDef("only screen (min-width: 1200px)", {
[style]: {
opacity: 1
}
});
* @example
* // also build can be used with builder
* mediaQueryDef(createMediaQuery()
.rule("only", "screen")
.and({type: "max-width", value: 1200, unit: "px"})
.and({type: "min-width", value: 768, unit: "px"})
.or()
.rule()
.and({type: "aspect-ratio", width: 11, height: 5})
.build(), {
[style]: {
opacity: 1
}
});
*
**/
export function mediaQueryDef(def: string, mediaQueryDefinition: MediaQueryDefinition): void {
let mediaQuery = allMediaQueries[def];
if (!mediaQuery) {
mediaQuery = [];
allMediaQueries[def] = mediaQuery;
}
mediaQuery.push(mediaQueryDefinition);
rebuildStyles = true;
}
export function namedStyleDefEx(
name: string,
parent: IBobrilStyleDef | IBobrilStyleDef[] | undefined,
style: CSSStyles,
pseudoOrAttr?: CSSPseudoStyles
): IBobrilStyleDef {
var res = styleDefEx(parent, style, pseudoOrAttr, name);
if (res != name) throw new Error("named style " + name + " is not unique");
return res;
}
export function namedStyleDef(name: string, style: CSSStyles, pseudoOrAttr?: CSSPseudoStyles): IBobrilStyleDef {
return namedStyleDefEx(name, undefined, style, pseudoOrAttr);
}
export function styleDefEx(
parent: IBobrilStyleDef | IBobrilStyleDef[] | undefined,
style: CSSStyles,
pseudoOrAttr?: CSSPseudoStyles,
nameHint?: string
): IBobrilStyleDef {
nameHint = makeName(nameHint);
allStyles[nameHint] = {
name: nameHint,
realName: nameHint,
parent,
style,
pseudo: pseudoOrAttr,
};
if (isString(style) && pseudoOrAttr == undefined) {
allStyles[nameHint]!.realName = style;
} else rebuildStyles = true;
return nameHint as IBobrilStyleDef;
}
export function selectorStyleDef(selector: string, style: CSSStyles, pseudoOrAttr?: CSSPseudoStyles) {
allStyles["b-" + globalCounter++] = {
name: null,
realName: null,
parent: selector,
style,
pseudo: pseudoOrAttr,
};
rebuildStyles = true;
}
export function invalidateStyles(): void {
rebuildStyles = true;
invalidate();
}
function updateSprite(spDef: ISprite): void {
var stDef = allStyles[spDef.styleId]!;
var style: any = {
backgroundImage: `url(${spDef.url})`,
width: spDef.width,
height: spDef.height,
backgroundPosition: `${-spDef.left}px ${-spDef.top}px`,
backgroundSize: `${spDef.width}px ${spDef.height}px`,
};
stDef.style = style;
invalidateStyles();
}
function emptyStyleDef(url: string): IBobrilStyleDef {
return styleDef({ width: 0, height: 0 }, undefined, url);
}
const rgbaRegex = /\s*rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d+|\d*\.\d+)\s*\)\s*/;
function recolorAndClip(
image: HTMLImageElement,
colorStr: string,
width: number,
height: number,
left: number,
top: number
): string {
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var ctx = <CanvasRenderingContext2D>canvas.getContext("2d");
ctx.drawImage(image, -left, -top);
var imgData = ctx.getImageData(0, 0, width, height);
var imgDataData = imgData.data;
let rgba = rgbaRegex.exec(colorStr);
let cRed: number, cGreen: number, cBlue: number, cAlpha: number;
if (rgba) {
cRed = parseInt(rgba[1]!, 10);
cGreen = parseInt(rgba[2]!, 10);
cBlue = parseInt(rgba[3]!, 10);
cAlpha = Math.round(parseFloat(rgba[4]!) * 255);
} else {
cRed = parseInt(colorStr.substr(1, 2), 16);
cGreen = parseInt(colorStr.substr(3, 2), 16);
cBlue = parseInt(colorStr.substr(5, 2), 16);
cAlpha = parseInt(colorStr.substr(7, 2), 16) || 0xff;
}
if (cAlpha === 0xff) {
for (var i = 0; i < imgDataData.length; i += 4) {
// Horrible workaround for imprecisions due to browsers using premultiplied alpha internally for canvas
let red = imgDataData[i]!;
if (
red === imgDataData[i + 1] &&
red === imgDataData[i + 2] &&
(red === 0x80 || (imgDataData[i + 3]! < 0xff && red > 0x70))
) {
imgDataData[i] = cRed;
imgDataData[i + 1] = cGreen;
imgDataData[i + 2] = cBlue;
}
}
} else {
for (var i = 0; i < imgDataData.length; i += 4) {
let red = imgDataData[i]!;
let alpha = imgDataData[i + 3]!;
if (
red === imgDataData[i + 1] &&
red === imgDataData[i + 2] &&
(red === 0x80 || (alpha < 0xff && red > 0x70))
) {
if (alpha === 0xff) {
imgDataData[i] = cRed;
imgDataData[i + 1] = cGreen;
imgDataData[i + 2] = cBlue;
imgDataData[i + 3] = cAlpha;
} else {
alpha = alpha * (1.0 / 255);
imgDataData[i] = Math.round(cRed * alpha);
imgDataData[i + 1] = Math.round(cGreen * alpha);
imgDataData[i + 2] = Math.round(cBlue * alpha);
imgDataData[i + 3] = Math.round(cAlpha * alpha);
}
}
}
}
ctx.putImageData(imgData, 0, 0);
return canvas.toDataURL();
}
let lastFuncId = 0;
const funcIdName = "b@funcId";
let imagesWithCredentials = false;
const colorLessSpriteMap = new Map<string, ISprite | IResponsiveSprite | ISvgSprite>();
function loadImage(url: string, onload: (image: HTMLImageElement) => void) {
var image = new Image();
image.crossOrigin = imagesWithCredentials ? "use-credentials" : "anonymous";
image.addEventListener("load", () => onload(image));
image.src = url;
}
export function setImagesWithCredentials(value: boolean) {
imagesWithCredentials = value;
}
export function sprite(url: string): ColorlessSprite;
export function sprite(
url: string,
color: null | undefined,
width?: number,
height?: number,
left?: number,
top?: number
): ColorlessSprite;
export function sprite(
url: string,
color: string | (() => string),
width?: number,
height?: number,
left?: number,
top?: number
): IBobrilStyleDef;
export function sprite(
url: string,
color?: string | (() => string) | null | undefined,
width?: number,
height?: number,
left?: number,
top?: number
): IBobrilStyleDef {
assert(allStyles[url] === undefined, "Wrong sprite url");
left = left || 0;
top = top || 0;
let colorId = color || "";
let isVarColor = false;
if (isFunction(color)) {
isVarColor = true;
colorId = (<any>color)[funcIdName];
if (colorId == undefined) {
colorId = "" + lastFuncId++;
(<any>color)[funcIdName] = colorId;
}
}
var key = url + ":" + colorId + ":" + (width || 0) + ":" + (height || 0) + ":" + left + ":" + top;
var spDef = allSprites[key]!;
if (spDef) return spDef.styleId;
var styleId = emptyStyleDef(url);
spDef = { styleId, url, width, height, left, top };
if (isVarColor) {
(<IDynamicSprite>spDef).color = <() => string>color;
(<IDynamicSprite>spDef).lastColor = "";
(<IDynamicSprite>spDef).lastUrl = "";
dynamicSprites.push(<IDynamicSprite>spDef);
if (imageCache[url] === undefined) {
imageCache[url] = null;
loadImage(url, (image) => {
imageCache[url] = image;
invalidateStyles();
});
}
invalidateStyles();
} else if (width == undefined || height == undefined || color != undefined) {
loadImage(url, (image) => {
if (spDef.width == undefined) spDef.width = image.width;
if (spDef.height == undefined) spDef.height = image.height;
if (color != undefined) {
spDef.url = recolorAndClip(image, <string>color, spDef.width, spDef.height, spDef.left, spDef.top);
spDef.left = 0;
spDef.top = 0;
}
updateSprite(spDef);
});
} else {
updateSprite(spDef);
}
allSprites[key] = spDef;
if (colorId === "") {
colorLessSpriteMap.set(styleId, spDef);
}
return styleId;
}
export function svg(content: string): ColorlessSprite {
var key = content + ":1";
var styleId = svgSprites.get(key);
if (styleId !== undefined) return styleId;
styleId = buildSvgStyle(content, 1);
var svgSprite: ISvgSprite = {
styleId,
svg: content,
};
svgSprites.set(key, styleId);
colorLessSpriteMap.set(styleId, svgSprite);
return styleId;
}
export function isSvgSprite(id: ColorlessSprite) {
let orig = colorLessSpriteMap.get(id);
if (orig == undefined) throw new Error(id + " is not colorless sprite");
return "svg" in orig;
}
/// Function can take colors as functions but they are evaluated immediately => use only in render like function
export function svgWithColor(
id: ColorlessSprite,
colors: string | (() => string) | Record<string, string | (() => string)>,
size: number = 1
): IBobrilStyleDef {
var original = colorLessSpriteMap.get(id);
if (DEBUG && (original == undefined || !("svg" in original))) throw new Error(id + " is not colorless svg");
var key = (original! as ISvgSprite).svg + ":" + size;
if (isFunction(colors)) {
colors = colors();
key += ":gray:" + colors;
} else if (isString(colors)) {
key += ":gray:" + colors;
} else
for (let ckey in colors) {
if (hOP.call(colors, ckey)) {
let val = colors[ckey];
if (isFunction(val)) val = val();
key += ":" + ckey + ":" + val;
}
}
var styleId = svgSprites.get(key);
if (styleId !== undefined) return styleId;
var colorsMap = new Map<string, string>();
if (isString(colors)) {
colorsMap.set("gray", colors);
} else
for (let ckey in colors) {
if (hOP.call(colors, ckey)) {
let val = colors[ckey];
if (isFunction(val)) val = val();
colorsMap.set(ckey, val as string);
}
}
styleId = buildSvgStyle(
(original! as ISvgSprite).svg.replace(/[\":][A-Z-]+[\";]/gi, (m) => {
var c = colorsMap.get(m.substr(1, m.length - 2));
return c !== undefined ? m[0] + c + m[m.length - 1] : m;
}),
size
);
svgSprites.set(key, styleId);
return styleId;
}
function buildSvgStyle(content: string, size: number): ColorlessSprite {
var sizeStr = content.split('"', 1)[0];
var [width, height] = sizeStr!.split(" ").map((s) => parseFloat(s) * size);
var backgroundImage =
'url("data:image/svg+xml,' +
encodeURIComponent(
'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="' +
width +
'" height="' +
height +
'" viewBox="0 0 ' +
content +
"</svg>"
) +
'")';
return styleDef({ width, height, backgroundImage }) as ColorlessSprite;
}
var bundlePath = (<any>window)["bobrilBPath"] || "bundle.png";
var bundlePath2: [string, number][] = (<any>window)["bobrilBPath2"] || [];
export function setBundlePngPath(path: string) {
bundlePath = path;
}
export function getSpritePaths(): [string, [string, number][]] {
return [bundlePath, bundlePath2];
}
export function setSpritePaths(main: string, others: [string, number][]) {
bundlePath = main;
bundlePath2 = others;
}
export function spriteb(width: number, height: number, left: number, top: number): IBobrilStyleDef {
var key = ":" + width + ":" + height + ":" + left + ":" + top;
var spDef = bundledSprites[key];
if (spDef) return spDef.styleId;
hasBundledSprites = true;
var styleId = styleDef({ width, height });
spDef = {
styleId,
width,
height,
left,
top,
};
bundledSprites[key] = spDef;
wasSpriteUrlChanged = true;
colorLessSpriteMap.set(styleId, spDef);
return styleId;
}
export function spritebc(
color: undefined | string | (() => string),
width: number,
height: number,
left: number,
top: number
): IBobrilStyleDef {
if (color == undefined) {
return spriteb(width, height, left, top);
}
var colorId: string;
if (isString(color)) {
colorId = color;
} else {
colorId = (<any>color)[funcIdName];
if (colorId == undefined) {
colorId = "" + lastFuncId++;
(<any>color)[funcIdName] = colorId;
}
}
var key = colorId + ":" + width + ":" + height + ":" + left + ":" + top;
var spDef = bundledSprites[key];
if (spDef) return spDef.styleId;
hasBundledSprites = true;
var styleId = styleDef({ width, height });
spDef = {
styleId,
width,
height,
left,
top,
};
(<IResponsiveDynamicSprite>spDef).color = color;
(<IResponsiveDynamicSprite>spDef).lastColor = "";
(<IResponsiveDynamicSprite>spDef).lastUrl = "";
bundledDynamicSprites.push(<IResponsiveDynamicSprite>spDef);
bundledSprites[key] = spDef;
return styleId;
}
/// Function can take colors as functions but they are evaluated immediately => use only in render like function
export function spriteWithColor(colorLessSprite: ColorlessSprite, color: string | (() => string)): IBobrilStyleDef {
const original = colorLessSpriteMap.get(colorLessSprite);
if (DEBUG && original == undefined) throw new Error(colorLessSprite + " is not colorless sprite");
if ("svg" in original!) {
return svgWithColor(colorLessSprite, { gray: color }, 1);
} else if ("url" in original!) {
return sprite(original.url, color, original.width, original.height, original.left, original.top);
} else {
return spritebc(color, original!.width, original!.height, original!.left, original!.top);
}
}
export function injectCss(css: string): void {
injectedCss += css;
invalidateStyles();
}
// PureFuncs: styledDiv
export function styledDiv(children: IBobrilChildren, ...styles: IBobrilStyles[]): IBobrilNode {
return style({ tag: "div", children }, styles);
}
export function setStyleShim(name: string, action: (style: any, value: any, oldName: string) => void) {
mapping.set(name, action);
}
setStyleShim("float", renamer("cssFloat"));
internalSetCssInJsCallbacks(createNodeStyle, updateNodeStyle, style); | the_stack |
import React, { useState, forwardRef, useEffect, useCallback } from 'react';
import find from 'lodash/find';
import classNames from 'classnames';
import warning from 'warning';
import canUseDOM from '../../utils/can-use-dom';
import useLazyLoad from './use-lazy-load';
import styles from './index.module.scss';
// --------------------------------------------------------------------------------------------
// Steps in rendering Image
//
// 1. Picture is rendered without src, srcSets, and with a padding-top placholder on the <img>
// based on the containerAspectRatio.
// 2. The "sizes" attr is calculated on initial render to determine width of image.
// 3. When lazyload is triggered the src and scrSet props are populated based on the sizes value.
// 4. The image is set to opacity:0 to start to prevent flash of alt text
// 5. The image onLoad and onError events remove padding-top placholder and sets opacity to 1.
// --------------------------------------------------------------------------------------------
type ImageSource = {
type: 'image/webp' | 'image/jpeg' | 'image/png' | 'image/gif';
srcSet: string;
};
interface ImagePropTypes {
/**
* If `sources` is provided, this image will be loaded by search engines and lazy-loaded for
* users on browsers that don't support responsive images. If `sources` is not provided, this
* image will be lazy-loaded.
*/
src: string;
/**
* Allows the browser to choose the best file format and image size based on the device screen
* density and the width of the rendered image.
*/
sources?: ImageSource[];
alt?: string;
/**
* Crops the image at the provided height. The `objectFit` and `objectPosition` props can be
* used to control how the image is cropped.
*/
height?: string;
/**
* Creates a [placeholder box](https://css-tricks.com/aspect-ratio-boxes/) for the image.
* The placeholder prevents the browser scroll from jumping when the image is lazy-loaded.
*/
containerAspectRatio?: number;
/**
* Disables lazy-loading and overrides the default calculation of the `sizes` attribute.
* Primarily for important images in a server-side rendered environment that must be
* loaded before JavaScript is parsed and executed on the client. The value gets used
* as the `sizes` attribute. [See allowable values](https://mzl.la/2Hh6neO).
*/
forceEarlyRender?: React.ImgHTMLAttributes<HTMLImageElement>['sizes'];
/**
* Provides control over how the image should be resized to fit the container. This controls the
* `object-fit` CSS property. It is only useful if `height` is used to "crop" the image.
*/
objectFit?: 'cover' | 'contain';
/**
* Provides control over how the image position in the container. This controls the
* `object-position` CSS property. It is only useful if `height` is used to "crop" the image.
*/
objectPosition?: 'top' | 'center' | 'bottom' | 'left' | 'right';
className?: string;
}
type ObjectFitPropsType = {
style?: {
// Not using React.CSSProperties types for these two, because we use a restricted subset.
objectFit?: 'cover' | 'contain';
objectPosition?: 'top' | 'center' | 'bottom' | 'left' | 'right';
fontFamily?: React.CSSProperties['fontFamily'];
height?: '100%';
};
};
type AspectRatioBoxPropsType = {
style?: {
paddingTop?: React.CSSProperties['paddingTop'];
overflow?: React.CSSProperties['overflow'];
height?: React.CSSProperties['height'];
};
};
const Image = forwardRef<HTMLElement, ImagePropTypes>((props: ImagePropTypes, outerRef) => {
const {
src,
sources = [],
height,
containerAspectRatio,
objectFit = 'cover',
objectPosition = 'center',
alt = '',
className,
forceEarlyRender = null,
...rest
} = props;
// The outermost DOM node that this component references. We use `useState` instead of
// `useRef` because callback refs allow us to add more than one `ref` to a DOM node.
const [containerRef, setContainerRef] = useState<Element | null>(null);
// --------------------------------------------------------------------------------------------
// Sizes
// --------------------------------------------------------------------------------------------
// Used by srcSet to determine which image in the list will be requested. This value has to be
// calculated client-side because we don't know the viewport width.
const computeSizes = (): string =>
containerRef && containerRef.clientWidth ? `${containerRef.clientWidth}px` : '0px';
// If `forceEarlyRender` is truthy use that value, otherwise use the computed width.
const sizes = forceEarlyRender || computeSizes();
// --------------------------------------------------------------------------------------------
// Lazy-loading: library setup and polyfill
// --------------------------------------------------------------------------------------------
const [browserSupportIntersectionObserver, setBrowserSupportIntersectionObserver] = useState<
boolean
>(canUseDOM && typeof window.IntersectionObserver !== 'undefined');
const shouldLoad = useLazyLoad(containerRef, browserSupportIntersectionObserver);
// Loads the `IntersectionObserver` polyfill asynchronously on browsers that don't support it.
if (canUseDOM && typeof window.IntersectionObserver === 'undefined') {
import('intersection-observer').then(() => {
setBrowserSupportIntersectionObserver(true);
});
}
// If `forceEarlyRender` is truthy, bypass lazy loading and load the image.
const shouldLoadImage = shouldLoad || forceEarlyRender;
// --------------------------------------------------------------------------------------------
// Object Fit: polyfill and CSS styles
// --------------------------------------------------------------------------------------------
const objectFitProps: ObjectFitPropsType = {};
// Checking for the use of the `height` prop is not enough since users can also change the
// image height using `className`, or `style`.
const shouldObjectFit = !!height || !!props.objectFit;
const shouldPolyfillObjectFit =
canUseDOM &&
document.documentElement &&
document.documentElement.style &&
'objectFit' in document.documentElement.style !== true;
warning(
(!height && !containerAspectRatio) ||
(height && !containerAspectRatio) ||
(!height && containerAspectRatio),
'You can pass either a `height` or `containerAspectRatio` to the `Image` component, but not both.',
);
useEffect(() => {
// We polyfill `object-fit` for browsers that don't support it. We only do it if we're
// using a `height` or `containerAspectRatio`. The `shouldLoadImage` variable ensures
// that we don't try to polyfill the image before the `src` exists. This can happy
// when we lazy-load.
if (shouldObjectFit && containerRef && shouldLoadImage && shouldPolyfillObjectFit) {
import('object-fit-images').then(({ default: ObjectFitImages }) => {
ObjectFitImages(containerRef.querySelector('img'));
});
}
}, [shouldObjectFit, containerRef, shouldLoadImage, shouldPolyfillObjectFit]);
if (shouldObjectFit) {
objectFitProps.style = {
objectFit,
objectPosition,
};
if (!height) {
// Add `height: 100%` as an inline style if the user wants to `objectFit` but hasn't
// passed in the `height` prop. Almost always, this means that the user is setting the
// height with CSS or an inline style. Since inline styles and `className` get added to
// `picture`, not `img`, the `img` element would become taller than the picture,
// preventing the `objectFit` from working. Adding `height: 100%` to the `img` in these
// cases allows `objectFit` to work as well as it would if the `height` was provided as
// a prop rather than through `style` or `className`.
objectFitProps.style.height = '100%';
}
if (shouldPolyfillObjectFit) {
// Weird, but this is how the polyfill knows what to do with the image in IE.
objectFitProps.style.fontFamily = `"object-fit: ${objectFit}; object-position: ${objectPosition}"`;
}
}
// --------------------------------------------------------------------------------------------
// Image Aspect Ratio used for image placeholder
// --------------------------------------------------------------------------------------------
const aspectRatioBoxProps: AspectRatioBoxPropsType = {};
if (containerAspectRatio) {
// This ensures that lazy-loaded images don't cause the browser scroll to jump once the
// image has loaded. It uses the following technique:
// https://css-tricks.com/aspect-ratio-boxes/
const h = 100000;
const w = h * containerAspectRatio;
aspectRatioBoxProps.style = {
paddingTop: `${(h / w) * 100}%`,
overflow: 'hidden', // Prevents alt text from taking up space before `src` is populated
height: 0,
};
}
// --------------------------------------------------------------------------------------------
// Sources and srcSets
// --------------------------------------------------------------------------------------------
// We separate `webp` from the `jpeg`/`png` so that we can apply the `imgTagSource` directly
// onto the `img` tag. While this makes the code messier, it is needed to work around a bug in
// Safari:
// - https://bugs.webkit.org/show_bug.cgi?id=190031
// - https://bugs.webkit.org/show_bug.cgi?id=177068
const webpSource = find(sources, s => s.type === 'image/webp');
const imgTagSource = find(sources, s => s.type === 'image/jpeg' || s.type === 'image/png');
// --------------------------------------------------------------------------------------------
// Image load and error states
// --------------------------------------------------------------------------------------------
const [isLoaded, setIsLoaded] = useState<boolean>(false);
const [isError, setIsError] = useState<boolean>(false);
// --------------------------------------------------------------------------------------------
// Combining refs: This component has three refs that need to be combined into one. This
// method of combining refs is suggested by `react-intersection-observer`:
// https://github.com/thebuilder/react-intersection-observer#how-can-i-assign-multiple-refs-to-a-component
// --------------------------------------------------------------------------------------------
const setRefs = useCallback(
node => {
// Using a callback `ref` on this `picture` allows us to have multiple `ref`s on one
// element.
setContainerRef(node);
// Check if the consumer sets a ref.
if (typeof outerRef === 'function') {
outerRef(node);
}
},
[outerRef, setContainerRef],
);
return (
<>
<picture {...rest} className={classNames(styles.picture, className)} ref={setRefs}>
{webpSource && (
<source
type={webpSource.type}
// Only add this attribute if lazyload has been triggered.
srcSet={shouldLoadImage ? webpSource.srcSet : undefined}
sizes={sizes}
/>
)}
<img
// The order of `sizes`, `srcSet`, and `src` is important to work around a bug in
// Safari. Once the bug is fixed, we should simplify this by using `src` on the
// `img` tag and using `source` tags.
sizes={sizes}
// Only add this attribute if lazyload has been triggered.
srcSet={shouldLoadImage && imgTagSource ? imgTagSource.srcSet : undefined}
// Only add this attribute if lazyload has been triggered.
src={shouldLoadImage ? src : undefined}
// Height is generally only used for full-width hero images.
height={height}
alt={alt}
// Adds object fit values if specified and adds/removes placeholder padding.
// For SSR we want this to fire instantly.
style={{
...(shouldObjectFit ? objectFitProps.style : {}),
...(isLoaded || isError || forceEarlyRender
? {}
: aspectRatioBoxProps.style),
}}
onLoad={(): void => {
setIsLoaded(true);
}}
onError={(): void => {
setIsError(true);
}}
className={classNames({
// Opacity to 0, prevents flash of alt text when `height` prop used
[styles.imageStart]: true,
// Opacity to 1 to reveal image or show alt text on error
// For SSR we want this to fire instantly.
[styles.imageEnd]: isLoaded || isError || forceEarlyRender,
})}
/>
</picture>
{!forceEarlyRender && (
<noscript>
<img src={src} alt={alt} />
</noscript>
)}
</>
);
});
// Needed because of the `forwardRef`.
Image.displayName = 'Image';
export default Image; | the_stack |
* @group unit/requestforattestation
*/
/* eslint-disable dot-notation */
/* eslint-disable @typescript-eslint/ban-ts-comment */
import type {
IClaim,
IClaimContents,
CompressedCredential,
ICType,
CompressedRequestForAttestation,
IRequestForAttestation,
DidSignature,
} from '@kiltprotocol/types'
import { Crypto, SDKErrors } from '@kiltprotocol/utils'
import { Attestation } from '../attestation/Attestation'
import { Credential } from '../credential/Credential'
import { CType } from '../ctype/CType'
import { RequestForAttestation } from './RequestForAttestation'
import * as RequestForAttestationUtils from './RequestForAttestation.utils'
import '../../../../testingTools/jestErrorCodeMatcher'
function buildRequestForAttestation(
claimerDid: string,
contents: IClaimContents,
legitimations: Credential[]
): RequestForAttestation {
// create claim
const rawCType: ICType['schema'] = {
$id: 'kilt:ctype:0x2',
$schema: 'http://kilt-protocol.org/draft-01/ctype#',
title: 'raw ctype',
properties: {
name: { type: 'string' },
},
type: 'object',
}
const testCType: CType = CType.fromSchema(rawCType)
const claim: IClaim = {
cTypeHash: testCType.hash,
contents,
owner: claimerDid,
}
// build request for attestation with legitimations
const request = RequestForAttestation.fromClaim(claim, {
legitimations,
})
return request
}
describe('RequestForAttestation', () => {
const identityAlice =
'did:kilt:4nv4phaKc4EcwENdRERuMF79ZSSB5xvnAk3zNySSbVbXhSwS'
const identityBob =
'did:kilt:4s5d7QHWSX9xx4DLafDtnTHK87n5e9G3UoKRrCDQ2gnrzYmZ'
const identityCharlie =
'did:kilt:4rVHmxSCxGTEv6rZwQUvZa6HTis4haefXPuEqj4zGafug7xL'
let legitimationRequest: RequestForAttestation
let legitimationAttestation: Attestation
let legitimation: Credential
let legitimationAttestationCharlie: Attestation
let legitimationCharlie: Credential
beforeEach(async () => {
legitimationRequest = buildRequestForAttestation(identityAlice, {}, [])
// build attestation
legitimationAttestation = Attestation.fromRequestAndDid(
legitimationRequest,
identityCharlie
)
// combine to credential
legitimation = new Credential({
request: legitimationRequest,
attestation: legitimationAttestation,
})
// build attestation
legitimationAttestationCharlie = Attestation.fromRequestAndDid(
legitimationRequest,
identityCharlie
)
// combine to credential
legitimationCharlie = new Credential({
request: legitimationRequest,
attestation: legitimationAttestationCharlie,
})
})
it.todo('signing and verification')
it('verify request for attestation', async () => {
const request = buildRequestForAttestation(
identityBob,
{
a: 'a',
b: 'b',
c: 'c',
},
[legitimation]
)
// check proof on complete data
expect(request.verifyData()).toBeTruthy()
// just deleting a field will result in a wrong proof
delete request.claimNonceMap[Object.keys(request.claimNonceMap)[0]]
expect(() => request.verifyData()).toThrowErrorWithCode(
SDKErrors.ErrorCode.ERROR_NO_PROOF_FOR_STATEMENT
)
})
it('throws on wrong hash in claim hash tree', async () => {
const request = buildRequestForAttestation(
identityBob,
{
a: 'a',
b: 'b',
c: 'c',
},
[]
)
request.claimNonceMap[Object.keys(request.claimNonceMap)[0]] = '1234'
expect(() => {
RequestForAttestation.verifyData(request)
}).toThrow()
})
it('compresses and decompresses the request for attestation object', async () => {
const legitimationAttestationBob = Attestation.fromRequestAndDid(
legitimationRequest,
identityBob
)
const legitimationBob = new Credential({
request: legitimationRequest,
attestation: legitimationAttestationBob,
})
const reqForAtt = buildRequestForAttestation(
identityBob,
{
a: 'a',
b: 'b',
c: 'c',
},
[legitimationCharlie, legitimationBob]
)
const compressedLegitimationCharlie: CompressedCredential = [
[
[
legitimationCharlie.request.claim.cTypeHash,
legitimationCharlie.request.claim.owner,
legitimationCharlie.request.claim.contents,
],
legitimationCharlie.request.claimNonceMap,
legitimationCharlie.request.claimerSignature,
legitimationCharlie.request.claimHashes,
legitimationCharlie.request.rootHash,
[],
legitimationCharlie.request.delegationId,
],
[
legitimationCharlie.attestation.claimHash,
legitimationCharlie.attestation.cTypeHash,
legitimationCharlie.attestation.owner,
legitimationCharlie.attestation.revoked,
legitimationCharlie.attestation.delegationId,
],
]
const compressedLegitimationBob: CompressedCredential = [
[
[
legitimationBob.request.claim.cTypeHash,
legitimationBob.request.claim.owner,
legitimationBob.request.claim.contents,
],
legitimationBob.request.claimNonceMap,
legitimationBob.request.claimerSignature,
legitimationBob.request.claimHashes,
legitimationBob.request.rootHash,
[],
legitimationBob.request.delegationId,
],
[
legitimationBob.attestation.claimHash,
legitimationBob.attestation.cTypeHash,
legitimationBob.attestation.owner,
legitimationBob.attestation.revoked,
legitimationBob.attestation.delegationId,
],
]
const compressedReqForAtt: CompressedRequestForAttestation = [
[
reqForAtt.claim.cTypeHash,
reqForAtt.claim.owner,
reqForAtt.claim.contents,
],
reqForAtt.claimNonceMap,
reqForAtt.claimerSignature,
reqForAtt.claimHashes,
reqForAtt.rootHash,
[compressedLegitimationCharlie, compressedLegitimationBob],
reqForAtt.delegationId,
]
expect(RequestForAttestationUtils.compress(reqForAtt)).toEqual(
compressedReqForAtt
)
expect(RequestForAttestationUtils.decompress(compressedReqForAtt)).toEqual(
reqForAtt
)
expect(reqForAtt.compress()).toEqual(compressedReqForAtt)
expect(RequestForAttestation.decompress(compressedReqForAtt)).toEqual(
reqForAtt
)
compressedReqForAtt.pop()
// @ts-expect-error
delete reqForAtt.claim.owner
expect(() => {
RequestForAttestationUtils.compress(reqForAtt)
}).toThrow()
expect(() => {
RequestForAttestationUtils.decompress(compressedReqForAtt)
}).toThrow()
expect(() => {
reqForAtt.compress()
}).toThrow()
expect(() => {
RequestForAttestation.decompress(compressedReqForAtt)
}).toThrow()
})
it('hides claim properties', async () => {
const request = buildRequestForAttestation(
identityBob,
{ a: 'a', b: 'b' },
[]
)
request.removeClaimProperties(['a'])
expect((request.claim.contents as any).a).toBeUndefined()
expect(Object.keys(request.claimNonceMap)).toHaveLength(
request.claimHashes.length - 1
)
expect((request.claim.contents as any).b).toBe('b')
expect(request.verifyData()).toBe(true)
expect(request.verifyRootHash()).toBe(true)
})
it('should throw error on faulty constructor input', async () => {
const builtRequest = buildRequestForAttestation(
identityBob,
{
a: 'a',
b: 'b',
c: 'c',
},
[]
)
const builtRequestWithLegitimation = buildRequestForAttestation(
identityBob,
{
a: 'a',
b: 'b',
c: 'c',
},
[legitimationCharlie]
) as IRequestForAttestation
const builtRequestNoLegitimations = {
...buildRequestForAttestation(
identityBob,
{
a: 'a',
b: 'b',
c: 'c',
},
[]
),
} as IRequestForAttestation
// @ts-expect-error
delete builtRequestNoLegitimations.legitimations
const builtRequestMalformedRootHash = {
...buildRequestForAttestation(
identityBob,
{
a: 'a',
b: 'b',
c: 'c',
},
[]
),
} as IRequestForAttestation
builtRequestMalformedRootHash.rootHash = [
builtRequestMalformedRootHash.rootHash.slice(0, 15),
(
(parseInt(builtRequestMalformedRootHash.rootHash.charAt(15), 16) + 1) %
16
).toString(16),
builtRequestMalformedRootHash.rootHash.slice(16),
].join('')
const builtRequestIncompleteClaimHashTree = {
...buildRequestForAttestation(
identityBob,
{
a: 'a',
b: 'b',
c: 'c',
},
[]
),
} as IRequestForAttestation
const deletedKey = Object.keys(
builtRequestIncompleteClaimHashTree.claimNonceMap
)[0]
delete builtRequestIncompleteClaimHashTree.claimNonceMap[deletedKey]
builtRequestIncompleteClaimHashTree.rootHash =
// @ts-expect-error
RequestForAttestation.calculateRootHash(
builtRequestIncompleteClaimHashTree
)
const builtRequestMalformedSignature = {
...buildRequestForAttestation(
identityBob,
{
a: 'a',
b: 'b',
c: 'c',
},
[]
),
} as IRequestForAttestation
builtRequestMalformedSignature.claimerSignature = {
signature: Crypto.hashStr('aaa'),
} as DidSignature
builtRequestMalformedSignature.rootHash =
// @ts-expect-error
RequestForAttestation.calculateRootHash(builtRequestMalformedSignature)
const builtRequestMalformedHashes = {
...buildRequestForAttestation(
identityBob,
{
a: 'a',
b: 'b',
c: 'c',
},
[]
),
} as IRequestForAttestation
Object.entries(builtRequestMalformedHashes.claimNonceMap).forEach(
([hash, nonce]) => {
const scrambledHash = [
hash.slice(0, 15),
((parseInt(hash.charAt(15), 16) + 1) % 16).toString(16),
hash.slice(16),
].join('')
builtRequestMalformedHashes.claimNonceMap[scrambledHash] = nonce
delete builtRequestMalformedHashes.claimNonceMap[hash]
}
)
builtRequestMalformedHashes.rootHash =
// @ts-expect-error
RequestForAttestation.calculateRootHash(builtRequestMalformedHashes)
expect(() =>
RequestForAttestationUtils.errorCheck(builtRequestNoLegitimations)
).toThrowError(SDKErrors.ERROR_LEGITIMATIONS_NOT_PROVIDED())
expect(() =>
RequestForAttestationUtils.errorCheck(builtRequestMalformedRootHash)
).toThrowError(SDKErrors.ERROR_ROOT_HASH_UNVERIFIABLE())
expect(() =>
RequestForAttestationUtils.errorCheck(builtRequestIncompleteClaimHashTree)
).toThrowErrorWithCode(SDKErrors.ErrorCode.ERROR_NO_PROOF_FOR_STATEMENT)
expect(() =>
RequestForAttestationUtils.errorCheck(builtRequestMalformedSignature)
).toThrowError(SDKErrors.ERROR_SIGNATURE_DATA_TYPE())
expect(() =>
RequestForAttestationUtils.errorCheck(builtRequestMalformedHashes)
).toThrowErrorWithCode(SDKErrors.ErrorCode.ERROR_NO_PROOF_FOR_STATEMENT)
expect(() =>
RequestForAttestationUtils.errorCheck(builtRequest)
).not.toThrow()
expect(() => {
RequestForAttestationUtils.errorCheck(builtRequestWithLegitimation)
}).not.toThrow()
})
it('checks Object instantiation', async () => {
const builtRequest = buildRequestForAttestation(
identityBob,
{
a: 'a',
b: 'b',
c: 'c',
},
[]
)
expect(builtRequest instanceof RequestForAttestation).toEqual(true)
})
}) | the_stack |
import {
User,
ProgressObj,
SavedLevel,
SavedLevelMetadata,
storeModule,
} from '@/store/storeInterfaces'
import router from '@/router'
function importFirebase() {
return import(/* webpackChunkName: 'chunk-firebase' */ '@/config/firebase')
}
interface UserState {
user: User
progressArr: ProgressObj[]
savedLevelsList: SavedLevelMetadata[]
publicLevels: SavedLevelMetadata[]
}
export default storeModule({
namespaced: true,
state: {
user: {
loggedIn: false,
rememberMe: true,
data: {
displayName: '',
email: '',
},
},
progressArr: [],
savedLevelsList: [],
publicLevels: [],
fetchedLevel: undefined,
} as UserState,
getters: {
user(state): User {
return state.user
},
userName(state): string {
return state.user.data.displayName
},
progressArr(state): ProgressObj[] {
return state.progressArr
},
savedLevelsList(state): SavedLevelMetadata[] {
return state.savedLevelsList
},
publicLevels(state): SavedLevelMetadata[] {
return state.publicLevels
},
isLoggedIn(state): boolean {
return state.user.loggedIn
},
},
mutations: {
SET_LOGGED_IN(state, payload: boolean): void {
state.user.loggedIn = payload
},
SET_REMEMBER_ME(state, payload: boolean): void {
state.user.rememberMe = payload
},
SET_USER(state, payload: User['data']): void {
state.user.data = payload
},
SET_PROGRESS(state, payload: ProgressObj[]): void {
state.progressArr = payload
},
SET_SAVED_LEVELS_LIST(state, payload: SavedLevelMetadata[]): void {
state.savedLevelsList = payload
},
SET_PUBLIC_LEVELS(state, payload: SavedLevelMetadata[]): void {
state.publicLevels = payload
},
SET_PUBLIC(state, payload: string): void {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
state.savedLevelsList.find((x) => x.id === payload)!.public = true
},
SET_PRIVATE(state, payload: string): void {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
state.savedLevelsList.find((x) => x.id === payload)!.public = false
},
REMOVE_LEVEL(state, payload: string): void {
state.savedLevelsList = state.savedLevelsList.filter((obj) => {
return obj.id !== payload
})
},
},
actions: {
async SET_INITIAL_PROGRESS({ commit }) {
const { firebase } = await importFirebase()
const payload: ProgressObj[] = [
{ id: 0, status: 'won', timeOpened: firebase.firestore.Timestamp.fromDate(new Date()) },
]
commit('SET_PROGRESS', payload)
},
FETCH_USER({ commit, dispatch }, user: User['data'] | null): void {
commit('SET_LOGGED_IN', user != null)
if (user != null) {
dispatch('GET_PROGRESS')
dispatch('FETCH_MY_LEVELS')
dispatch('FETCH_PUBLIC_LEVELS')
commit('errors/RESET_ERRORS', null, { root: true })
commit('SET_USER', {
displayName: user.displayName,
email: user.email,
})
} else {
commit('SET_USER', null)
}
},
async SIGN_IN({ commit, getters }, user) {
const { auth, firebase } = await importFirebase()
commit('SET_REMEMBER_ME', user.rememberMe)
let authPersistance = auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL)
if (!getters.user.rememberMe) {
authPersistance = auth.setPersistence(firebase.auth.Auth.Persistence.SESSION)
}
authPersistance
.then(() => {
return auth.signInWithEmailAndPassword(user.email, user.password)
})
.then(() => {
router.replace({ name: 'myaccount' })
})
.catch((err) => {
commit('errors/SET_ERROR', err.message, { root: true })
})
},
async SIGN_IN_GITHUB({ dispatch }) {
const { firebase } = await importFirebase()
const provider = new firebase.auth.GithubAuthProvider()
dispatch('SIGN_IN_WITH_POPUP', provider)
},
async SIGN_IN_FACEBOOK({ dispatch }) {
const { firebase } = await importFirebase()
const provider = new firebase.auth.FacebookAuthProvider()
dispatch('SIGN_IN_WITH_POPUP', provider)
},
async SIGN_IN_GOOGLE({ dispatch }) {
const { firebase } = await importFirebase()
const provider = new firebase.auth.GoogleAuthProvider()
dispatch('SIGN_IN_WITH_POPUP', provider)
},
async SIGN_IN_WITH_POPUP({ commit }, provider) {
const { auth } = await importFirebase()
auth
.signInWithPopup(provider)
.then(() => {
router.replace({ name: 'myaccount' })
})
.catch((err) => {
commit('errors/SET_ERROR', err.message, { root: true })
})
},
async SIGN_UP({ commit }, user) {
const { auth } = await importFirebase()
auth
.createUserWithEmailAndPassword(user.email, user.password)
.then((data) => {
if (data.user) {
data.user.updateProfile({
displayName: user.name,
})
}
})
.then(() => {
router.replace({ name: 'myaccount' })
})
.catch((err) => {
commit('errors/SET_ERROR', err.message, { root: true })
})
},
async SIGN_OUT({ commit }) {
const { auth } = await importFirebase()
auth.signOut().then(() => {
commit('SET_LOGGED_IN', false)
router.replace({
name: 'login',
})
})
},
async SAVE_PROGRESS({ commit, getters }) {
const { auth, db } = await importFirebase()
if (auth.currentUser) {
const { progressArr }: { progressArr: ProgressObj } = getters
const dbRef = db.collection('users').doc(auth.currentUser.uid)
const data = { uid: auth.currentUser.uid, progress: progressArr }
dbRef
.set(data)
.then(() => {
console.debug('Data stored: ', data)
})
.catch((err) => {
commit('errors/SET_ERROR', err.message, { root: true })
})
}
},
/**
* @todo It should be a database, not a list.
*/
async GET_PROGRESS({ commit }) {
const { auth, db } = await importFirebase()
if (auth.currentUser) {
const dbRef = db.collection('users').doc(auth.currentUser.uid)
dbRef
.get()
.then((doc) => {
if (doc.exists) {
const data = doc.data()
if (data != null) {
commit('SET_PROGRESS', data.progress)
}
} else {
console.debug('No such document!')
}
})
.catch((err) => {
commit('errors/SET_ERROR', err.message, { root: true })
})
}
},
/**
* @todo Does not match level structure from levels in JSON.
*/
async SAVE_LEVEL({ commit, dispatch }, level: SavedLevel['level']) {
const { auth, firebase, db } = await importFirebase()
if (auth.currentUser == null) {
console.log('You are not logged in!')
return
}
const customLevel: SavedLevel = {
userId: auth.currentUser.uid,
level,
public: false,
createdAt: firebase.firestore.Timestamp.fromDate(new Date()),
lastModified: firebase.firestore.Timestamp.fromDate(new Date()),
}
const dbRef = db.collection('levels')
dbRef
.add(customLevel)
.then((data) => {
console.log('Level saved: ', data.id)
router.replace({ path: `/level/${data.id}` })
commit('SET_PUBLIC', data.id)
dispatch('UPDATE_LEVEL_LISTS')
})
.catch((err) => {
commit('errors/SET_ERROR', err.message, { root: true })
})
},
async UPDATE_LEVEL({ commit }, level: SavedLevel['level']) {
const { auth, firebase, db } = await importFirebase()
if (auth.currentUser == null) {
console.log('You are not logged in!')
return
}
const customLevel: Partial<SavedLevel> = {
userId: auth.currentUser.uid,
level,
lastModified: firebase.firestore.Timestamp.fromDate(new Date()),
}
const levelSaved = router.currentRoute.value.params.id as string
const doc = db.collection('levels').doc(levelSaved)
doc.update(customLevel).catch((err) => {
commit('errors/SET_ERROR', err.message, { root: true })
})
},
async FETCH_MY_LEVELS({ commit }) {
const { auth, db } = await importFirebase()
if (auth.currentUser) {
const myLevels: SavedLevelMetadata[] = []
const docs = db.collection('levels').where('userId', '==', auth.currentUser.uid)
docs
.get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
const data = doc.data()
myLevels.push({
id: doc.id,
link: `/level/${doc.id}`,
public: data.public,
createdAt: data.createdAt,
lastModified: data.lastModified,
})
})
})
.then(() => {
commit('SET_SAVED_LEVELS_LIST', myLevels)
})
.catch((err) => {
commit('errors/SET_ERROR', err.message, { root: true })
})
} else {
console.log('You are not logged in!')
}
},
async FETCH_PUBLIC_LEVELS({ commit }) {
const { auth, db } = await importFirebase()
if (auth.currentUser) {
const publicLevels: SavedLevelMetadata[] = []
const docs = db.collection('levels').where('public', '==', true)
docs
.get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
const data = doc.data()
publicLevels.push({
id: doc.id,
link: `/levels/${doc.id}`,
public: data.public, // always true
createdAt: data.createdAt,
lastModified: data.lastModified,
})
})
})
.then(() => {
commit('SET_PUBLIC_LEVELS', publicLevels)
})
.catch((err) => {
commit('errors/SET_ERROR', err.message, { root: true })
})
} else {
console.log('You are not logged in!')
}
},
async MAKE_LEVEL_PUBLIC({ commit, dispatch }, levelID: string) {
const { auth, firebase, db } = await importFirebase()
if (auth.currentUser) {
const docs = db
.collection('levels')
.where('userId', '==', auth.currentUser.uid)
.where(firebase.firestore.FieldPath.documentId(), '==', levelID)
docs
.get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
if (doc.id === levelID) {
doc.ref.update({ public: true })
}
})
})
.then(() => {
dispatch('UPDATE_LEVEL_LISTS')
})
.catch((err) => {
commit('errors/SET_ERROR', err.message, { root: true })
})
} else {
console.log('You are not logged in!')
}
},
async MAKE_LEVEL_PRIVATE({ commit, dispatch }, levelID: string) {
const { auth, db } = await importFirebase()
if (auth.currentUser) {
const doc = db.collection('levels').doc(levelID)
doc
.update({ public: false })
.then(() => {
dispatch('UPDATE_LEVEL_LISTS')
})
.catch((err) => {
commit('errors/SET_ERROR', err.message, { root: true })
})
} else {
console.log('You are not logged in!')
}
},
async REMOVE_LEVEL({ commit }, levelID: string) {
const { db } = await importFirebase()
const dbRef = db.collection('levels')
dbRef
.doc(levelID)
.delete()
.then(() => {
commit('REMOVE_LEVEL', levelID)
console.log('Level removed', levelID)
})
.catch((err) => {
commit('errors/SET_ERROR', err.message, { root: true })
})
},
// GET_LEVEL_DATA({ commit }, { id }): Promise<void> {
// return db
// .collection('levels')
// .doc(id)
// .get()
// .then((response) => {
// const levelData = response.data()
// console.log(levelData)
// if (levelData) {
// commit('SET_FETCHED_LEVEL', levelData.level.boardState)
// } else {
// console.log('No Level Data Found!')
// }
// })
// .catch((err) => {
// commit('errors/SET_ERROR', err.message, { root: true })
// })
// },
UPDATE_LEVEL_LISTS({ dispatch }): void {
dispatch('FETCH_MY_LEVELS')
dispatch('FETCH_PUBLIC_LEVELS')
},
},
}) | the_stack |
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export namespace OpenAPI {
export interface Contact {
/**
* The identifying name of the contact person/organization.
*/
name?: string;
/**
* The URL pointing to the contact information. MUST be in the format of a URL.
*/
url?: string;
/**
* The email address of the contact person/organization. MUST be in the format of an email address.
*/
email?: string;
}
export interface License {
/**
* The license name used for the API.
*/
name: string;
/**
* A URL to the license used for the API. MUST be in the format of a URL.
*/
url?: string;
}
export interface Info {
/**
* The title of the application.
*/
title: string;
/**
* A short description of the application. CommonMark syntax MAY be used for rich text representation.
*/
description?: string;
/**
* A URL to the Terms of Service for the API. MUST be in the format of a URL.
*/
termsOfService?: string;
/**
* The contact information for the exposed API.
*/
contact?: Contact;
/**
* The license information for the exposed API.
*/
license?: License;
/**
* The version of the OpenAPI document (which is distinct from the OpenAPI Specification version or the API implementation version).
*/
version: string;
}
export interface Reference {
/**
* The reference string.
*/
$ref: string;
}
export interface Parameter {
/**
* The name of the parameter. Parameter names are case sensitive.
* - If in is "path", the name field MUST correspond to the associated path segment from the path field in the Paths Object. See Path Templating for further information.
* - If in is "header" and the name field is "Accept", "Content-Type" or "Authorization", the parameter definition SHALL be ignored.
* - For all other cases, the name corresponds to the parameter name used by the in property
*/
name: string;
/**
* The location of the parameter. Possible values are "query", "header", "path" or "cookie".
*/
in: 'query' | 'header' | 'path' | 'cookie';
/**
* A brief description of the parameter. This could contain examples of use. CommonMark syntax MAY be used for rich text representation.
*/
description?: string;
/**
* Determines whether this parameter is mandatory. If the parameter location is "path", this property is REQUIRED and its value MUST be true. Otherwise, the property MAY be included and its default value is false.
*/
required: boolean;
/**
* Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. Default value is false.
*/
deprecated?: boolean;
/**
* Sets the ability to pass empty-valued parameters. This is valid only for query parameters and allows sending a parameter with an empty value. Default value is false. If style is used, and if behavior is n/a (cannot be serialized), the value of allowEmptyValue SHALL be ignored. Use of this property is NOT RECOMMENDED, as it is likely to be removed in a later revision.
*/
allowEmptyValue?: boolean;
schema?: Reference | Schema;
}
export interface RequestBody {
/**
* A brief description of the request body. This could contain examples of use. CommonMark syntax MAY be used for rich text representation.
*/
description?: string;
/**
* The content of the request body. The key is a media type or media type range and the value describes it. For requests that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/*
*/
content: Array<string>;
/**
* Determines if the request body is required in the request. Defaults to false.
*/
required?: boolean;
}
export type Header = Omit<Parameter, 'name' | 'in'>;
export interface Link {
/**
* A relative or absolute reference to an OAS operation. This field is mutually exclusive of the operationId field, and MUST point to an Operation Object. Relative operationRef values MAY be used to locate an existing Operation Object in the OpenAPI definition.
*/
operationRef?: string;
/**
* The name of an existing, resolvable OAS operation, as defined with a unique operationId. This field is mutually exclusive of the operationRef field.
*/
operationId?: string;
/**
* A map representing parameters to pass to an operation as specified with operationId or identified via operationRef. The key is the parameter name to be used, whereas the value can be a constant or an expression to be evaluated and passed to the linked operation. The parameter name can be qualified using the parameter location [{in}.]{name} for operations that use the same parameter name in different locations (e.g. path.id).
*/
parameters?: Record<string, any>;
/**
* A literal value or {expression} to use as a request body when calling the target operation.
*/
requestBody?: any;
/**
* A description of the link. CommonMark syntax MAY be used for rich text representation.
*/
description?: string;
}
interface Response {
/**
* A short description of the response. CommonMark syntax MAY be used for rich text representation.
*/
description: string;
headers?: {
[header: string]: Header | Reference;
};
links?: {
[link: string]: Link | Reference;
};
}
interface Responses {
default: Response | Reference;
[httpStatusCode: number]: Response | Reference;
}
export interface Operation {
/**
* A list of tags for API documentation control.
* Tags can be used for logical grouping of operations by resources or any other qualifier.
*/
tags?: string[];
/**
* A short summary of what the operation does.
*/
summary?: string;
/**
* A verbose explanation of the operation behavior. CommonMark syntax MAY be used for rich text representation.
*/
description?: string;
/**
* Additional external documentation for this operation.
*/
externalDocs?: {
/**
* The URL for the target documentation. Value MUST be in the format of a URL.
*/
url: string;
/**
* A short description of the target documentation. CommonMark syntax MAY be used for rich text representation.
*/
description?: string;
};
/**
* Unique string used to identify the operation.
* The id MUST be unique among all operations described in the API.
* The operationId value is case-sensitive.
* Tools and libraries MAY use the operationId to uniquely identify an operation,
* therefore, it is RECOMMENDED to follow common programming naming conventions.
*/
operationId?: string;
/**
* A list of parameters that are applicable for this operation.
* If a parameter is already defined at the Path Item, the new definition will override it but can never remove it.
* The list MUST NOT include duplicated parameters.
* A unique parameter is defined by a combination of a name and location.
* The list can use the Reference Object to link to parameters that are defined at the OpenAPI Object's components/parameters.
*/
parameters?: Array<Parameter | Reference>;
/**
* The request body applicable for this operation. The requestBody is only supported in HTTP methods where the HTTP 1.1 specification RFC7231 has explicitly defined semantics for request bodies. In other cases where the HTTP spec is vague, requestBody SHALL be ignored by consumers.
*/
requestBody?: RequestBody | Reference;
/**
* The list of possible responses as they are returned from executing this operation.
*/
responses?: Responses;
/**
* Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation. Default value is false.
*/
deprecated?: boolean;
}
export interface PathItem {
/**
* Allows for an external definition of this path item.
* The referenced structure MUST be in the format of a Path Item Object.
* If there are conflicts between the referenced definition and this Path Item's definition, the behavior is undefined.
*/
$ref?: string;
/**
* An optional, string summary, intended to apply to all operations in this path.
*/
summary?: string;
/**
* An optional, string description, intended to apply to all operations in this path.
* CommonMark syntax MAY be used for rich text representation.
*/
description?: string;
/**
* A definition of a GET operation on this path.
*/
get?: Operation;
/**
* A definition of a PUT operation on this path.
*/
put?: Operation;
/**
* A definition of a POST operation on this path.
*/
post?: Operation;
/**
* A definition of a DELETE operation on this path.
*/
delete?: Operation;
/**
* A definition of a OPTIONS operation on this path.
*/
options?: Operation;
/**
* A definition of a HEAD operation on this path.
*/
head?: Operation;
/**
* A definition of a PATCH operation on this path.
*/
patch?: Operation;
/**
* A definition of a TRACE operation on this path.
*/
trace?: Operation;
/**
* A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined at the OpenAPI Object's components/parameters.
*/
parameters?: Array<Parameter | Reference>;
}
export interface XML {
/**
* Replaces the name of the element/attribute used for the described schema property. When defined within items, it will affect the name of the individual XML elements within the list. When defined alongside type being array (outside the items), it will affect the wrapping element and only if wrapped is true. If wrapped is false, it will be ignored.
*/
name?: string;
/**
* The URI of the namespace definition. Value MUST be in the form of an absolute URI.
*/
namespace?: string;
/**
* The prefix to be used for the name.
*/
prefix?: string;
/**
* Declares whether the property definition translates to an attribute instead of an element. Default value is false.
*/
attribute?: boolean;
/**
* MAY be used only for an array definition. Signifies whether the array is wrapped (for example, <books><book/><book/></books>) or unwrapped (<book/><book/>). Default value is false. The definition takes effect only when defined alongside type being array (outside the items).
*/
wrapped?: boolean;
}
export interface Schema {
/**
* Allows sending a null value for the defined schema. Default value is false.
*/
nullable?: boolean;
/**
* Relevant only for Schema "properties" definitions. Declares the property as "read only". This means that it MAY be sent as part of a response but SHOULD NOT be sent as part of the request. If the property is marked as readOnly being true and is in the required list, the required will take effect on the response only. A property MUST NOT be marked as both readOnly and writeOnly being true. Default value is false.
*/
readOnly?: boolean;
/**
* Relevant only for Schema "properties" definitions. Declares the property as "write only". Therefore, it MAY be sent as part of a request but SHOULD NOT be sent as part of the response. If the property is marked as writeOnly being true and is in the required list, the required will take effect on the request only. A property MUST NOT be marked as both readOnly and writeOnly being true. Default value is false.
*/
writeOnly?: boolean;
/**
* This MAY be used only on properties schemas. It has no effect on root schemas. Adds additional metadata to describe the XML representation of this property.
*/
xml?: XML;
/**
* Specifies that a schema is deprecated and SHOULD be transitioned out of usage. Default value is false.
*/
deprecated?: boolean;
}
export interface Components {
/**
* An object to hold reusable Schema Objects.
*/
schemas?: Record<string, Schema | Reference>;
}
export interface OpenAPI {
/**
* This string MUST be the semantic version number of the OpenAPI Specification version that the OpenAPI document uses.
* The openapi field SHOULD be used by tooling specifications and clients to interpret the OpenAPI document.
* This is not related to the API info.version string.
*/
openapi: string;
/**
* Provides metadata about the API. The metadata MAY be used by tooling as required.
*/
info: Info;
/**
* The available paths and operations for the API.
*/
paths: {
[path: string]: PathItem;
};
/**
* An element to hold various schemas for the specification.
*/
components?: Components;
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.