text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import * as vscode from 'vscode';
import { JupyterDisplay } from './display/main';
import { KernelStatus } from './display/kernelStatus';
import { Commands } from './common/constants';
import { JupyterCodeLensProvider } from './editorIntegration/codeLensProvider';
import { JupyterSymbolProvider } from './editorIntegration/symbolProvider';
import { formatErrorForLogging } from './common/utils';
import { CodeHelper } from './common/codeHelper';
import { KernelManagerImpl } from './kernel-manager';
import { ParsedIOMessage } from './contracts';
import { MessageParser } from './jupyterServices/jupyter_client/resultParser';
import { LanguageProviders } from './common/languageProvider';
import * as Rx from 'rx';
import { Kernel } from '@jupyterlab/services';
import { NotebookManager, Notebook, inputNotebookDetails, selectExistingNotebook } from './jupyterServices/notebook/manager';
import { Manager } from './jupyterServices/manager';
import * as PyManager from './pythonClient/manager';
import { Deferred, createDeferred } from './common/helpers';
import { JupyterClientAdapter } from "./pythonClient/jupyter_client/main";
// Todo: Refactor the error handling and displaying of messages
export class Jupyter extends vscode.Disposable {
public kernelManager: KernelManagerImpl;
public kernel: Kernel.IKernel = null;
private status: KernelStatus;
private disposables: vscode.Disposable[];
private display: JupyterDisplay;
private codeLensProvider: JupyterCodeLensProvider;
private codeHelper: CodeHelper;
private messageParser: MessageParser;
private notebookManager: NotebookManager;
constructor(private outputChannel: vscode.OutputChannel) {
super(() => { });
this.disposables = [];
this.registerCommands();
this.registerKernelCommands();
this.messageParser = new MessageParser(this.outputChannel);
this.activate();
}
public dispose() {
this.kernelManager.dispose();
this.disposables.forEach(d => d.dispose());
}
private kernelCreationPromise: Deferred<KernelManagerImpl>;
private getKernelManager(): Promise<KernelManagerImpl> {
return this.createKernelManager();
}
private jupyterVersionWorksWithJSServices: boolean;
private createKernelManager(): Promise<KernelManagerImpl> {
if (this.kernelCreationPromise) {
return this.kernelCreationPromise.promise;
}
this.kernelCreationPromise = createDeferred<any>();
KernelManagerImpl.jupyterVersionWorksWithJSServices(this.outputChannel)
.then(yes => {
this.jupyterVersionWorksWithJSServices = yes;
if (yes) {
this.kernelManager = new Manager(this.outputChannel, this.notebookManager);
}
else {
const jupyterClient = new JupyterClientAdapter(this.outputChannel, vscode.workspace.rootPath);
this.kernelManager = new PyManager.Manager(this.outputChannel, this.notebookManager, jupyterClient);
}
this.kernelCreationPromise.resolve(this.kernelManager);
// This happend when user changes it from status bar
this.kernelManager.on('kernelChanged', (kernel: Kernel.IKernel, language: string) => {
this.onKernelChanged(kernel);
});
})
.catch(error => {
this.kernelCreationPromise.reject(error);
throw error;
});
}
private activate() {
this.notebookManager = new NotebookManager(this.outputChannel);
this.disposables.push(this.notebookManager);
this.createKernelManager();
this.disposables.push(vscode.window.onDidChangeActiveTextEditor(this.onEditorChanged.bind(this)));
this.codeLensProvider = new JupyterCodeLensProvider();
let symbolProvider = new JupyterSymbolProvider();
this.status = new KernelStatus();
this.disposables.push(this.status);
this.display = new JupyterDisplay(this.codeLensProvider, this.outputChannel);
this.disposables.push(this.display);
this.codeHelper = new CodeHelper(this.codeLensProvider);
LanguageProviders.getInstance().on('onLanguageProviderRegistered', (language: string) => {
this.disposables.push(vscode.languages.registerCodeLensProvider(language, this.codeLensProvider));
this.disposables.push(vscode.languages.registerDocumentSymbolProvider(language, symbolProvider));
});
this.handleNotebookEvents();
}
private handleNotebookEvents() {
this.notebookManager.on('onNotebookChanged', (nb: Notebook) => {
this.display.setNotebook(nb, this.notebookManager.canShutdown(nb));
});
this.notebookManager.on('onShutdown', () => {
this.getKernelManager().then(k => k.clearAllKernels());
this.onKernelChanged(null);
});
}
public hasCodeCells(document: vscode.TextDocument, token: vscode.CancellationToken): Promise<boolean> {
return new Promise<boolean>(resolve => {
this.codeLensProvider.provideCodeLenses(document, token).then(codeLenses => {
resolve(Array.isArray(codeLenses) && codeLenses.length > 0);
}, reason => {
console.error('Failed to detect code cells in document');
console.error(reason);
resolve(false);
});
});
}
private onEditorChanged(editor: vscode.TextEditor) {
if (!editor || !editor.document) {
return;
}
this.getKernelManager()
.then(kernelManager => {
const kernel = kernelManager.getRunningKernelFor(editor.document.languageId);
if (this.kernel !== kernel && (this.kernel && kernel && this.kernel.id !== kernel.id)) {
return this.onKernelChanged(kernel);
}
});
}
onKernelChanged(kernel?: Kernel.IKernel) {
if (kernel) {
kernel.statusChanged.connect((sender, status) => {
// We're only interested in status of the active kernels
if (this.kernel && (sender.id === this.kernel.id)) {
this.status.setKernelStatus(status);
}
});
}
this.kernel = kernel;
this.status.setActiveKernel(this.kernel);
}
executeCode(code: string, language: string): Promise<any> {
return this.getKernelManager()
.then(kernelManager => {
const kernelToUse = kernelManager.getRunningKernelFor(language);
if (kernelToUse) {
if (!this.kernel || kernelToUse.id !== this.kernel.id) {
this.onKernelChanged(kernelToUse);
}
return Promise.resolve(this.kernel);
}
else {
return kernelManager.startKernelFor(language).then(kernel => {
kernelManager.setRunningKernelFor(language, kernel);
return kernel;
});
}
})
.then(() => {
return this.executeAndDisplay(this.kernel, code).catch(reason => {
const message = typeof reason === 'string' ? reason : reason.message;
vscode.window.showErrorMessage(message);
this.outputChannel.appendLine(formatErrorForLogging(reason));
});
}).catch(reason => {
let message = typeof reason === 'string' ? reason : reason.message;
if (reason.xhr && reason.xhr.responseText) {
message = reason.xhr && reason.xhr.responseText;
}
if (!message) {
message = 'Unknown error';
}
this.outputChannel.appendLine(formatErrorForLogging(reason));
vscode.window.showErrorMessage(message, 'View Errors').then(item => {
if (item === 'View Errors') {
this.outputChannel.show();
}
});
});
}
private executeAndDisplay(kernel: Kernel.IKernel, code: string): Promise<any> {
let observable = this.executeCodeInKernel(kernel, code);
let executor = (code: string) => this.executeCodeInKernel(kernel, code);
return this.display.showResults(observable, executor);
}
private executeCodeInKernel(kernel: Kernel.IKernel, code: string): Rx.Observable<ParsedIOMessage> {
if (this.jupyterVersionWorksWithJSServices) {
let source = Rx.Observable.create<ParsedIOMessage>(observer => {
let future = kernel.requestExecute({ code: code });
future.onDone = () => {
observer.onCompleted();
};
future.onIOPub = (msg) => {
this.messageParser.processResponse(msg, observer);
};
});
return source;
}
else {
return this.kernelManager.runCodeAsObservable(code, kernel);
}
}
async executeSelection(): Promise<any> {
const activeEditor = vscode.window.activeTextEditor;
if (!activeEditor || !activeEditor.document) {
return Promise.resolve();
}
let code = await this.codeHelper.getSelectedCode();
let cellRange = await this.codeHelper.getActiveCell();
let selectedCode = await LanguageProviders.getSelectedCode(activeEditor.document.languageId, code, cellRange);
return this.executeCode(selectedCode, activeEditor.document.languageId);
}
private registerCommands() {
this.disposables.push(vscode.commands.registerCommand(Commands.Jupyter.ExecuteRangeInKernel, (document: vscode.TextDocument, range: vscode.Range) => {
if (!document || !range || range.isEmpty) {
return Promise.resolve();
}
const code = document.getText(range);
return this.executeCode(code, document.languageId);
}));
this.disposables.push(vscode.commands.registerCommand(Commands.Jupyter.ExecuteSelectionOrLineInKernel,
this.executeSelection.bind(this)));
this.disposables.push(vscode.commands.registerCommand(Commands.Jupyter.Get_All_KernelSpecs_For_Language, (language: string) => {
if (this.kernelManager) {
return this.kernelManager.getAllKernelSpecsFor(language);
}
return Promise.resolve();
}));
this.disposables.push(vscode.commands.registerCommand(Commands.Jupyter.StartKernelForKernelSpeck, (kernelSpec: Kernel.ISpecModel, language: string) => {
if (this.kernelManager) {
return this.kernelManager.startKernel(kernelSpec, language);
}
return Promise.resolve();
}));
this.disposables.push(vscode.commands.registerCommand(Commands.Jupyter.StartNotebook, () => {
this.notebookManager.startNewNotebook();
}));
this.disposables.push(vscode.commands.registerCommand(Commands.Jupyter.ProvideNotebookDetails, () => {
inputNotebookDetails()
.then(nb => {
if (!nb) { return; }
this.notebookManager.setNotebook(nb);
});
}));
this.disposables.push(vscode.commands.registerCommand(Commands.Jupyter.SelectExistingNotebook, () => {
selectExistingNotebook()
.then(nb => {
if (!nb) { return; }
this.notebookManager.setNotebook(nb);
});
}));
this.disposables.push(vscode.commands.registerCommand(Commands.Jupyter.Notebook.ShutDown, () => {
this.notebookManager.shutdown();
}));
}
private registerKernelCommands() {
this.disposables.push(vscode.commands.registerCommand(Commands.Jupyter.Kernel.Interrupt, () => {
this.kernel.interrupt();
}));
this.disposables.push(vscode.commands.registerCommand(Commands.Jupyter.Kernel.Restart, () => {
if (this.kernelManager) {
this.kernelManager.restartKernel(this.kernel).then(kernel => {
kernel.getSpec().then(spec => {
this.kernelManager.setRunningKernelFor(spec.language, kernel);
});
this.onKernelChanged(kernel);
});
}
}));
this.disposables.push(vscode.commands.registerCommand(Commands.Jupyter.Kernel.Shutdown, (kernel: Kernel.IKernel) => {
kernel.getSpec().then(spec => {
this.kernelManager.destroyRunningKernelFor(spec.language);
this.onKernelChanged();
});
}));
}
}; | the_stack |
import React from "react"
import { AppRegistry, View, YellowBox } from "react-native"
import { Container as RelayContainer } from "react-relay"
import { SafeAreaInsets } from "lib/types/SafeAreaInsets"
import Consignments from "./Components/Consignments"
import Containers from "./Containers/"
import BidFlow from "./Containers/BidFlow"
import RegistrationFlow from "./Containers/RegistrationFlow"
import {
ArtistRenderer,
BidderFlowRendererProps,
BidFlowRenderer,
CityBMWListRenderer,
CityFairListRenderer,
CitySavedListRenderer,
CitySectionListRenderer,
CollectionRenderer,
ConversationRenderer,
FairRenderer,
GeneRenderer,
InboxRenderer,
InquiryRenderer,
RegistrationFlowRenderer,
ShowRenderer,
WorksForYouRenderer,
} from "./relay/QueryRenderers"
import { ArtworkRenderer } from "./Scenes/Artwork"
import { ArtworkAttributionClassFAQRenderer } from "./Scenes/ArtworkAttributionClassFAQ"
import { CityView } from "./Scenes/City"
import { CityPicker } from "./Scenes/City/CityPicker"
import { CollectionContainer } from "./Scenes/Collection/Collection"
import {
FairArtistsRenderer,
FairArtworksRenderer,
FairBMWArtActivationRenderer,
FairBoothRenderer,
FairExhibitorsRenderer,
FairMoreInfoRenderer,
} from "./Scenes/Fair"
import FavoritesScene from "./Scenes/Favorites"
import HomeScene from "./Scenes/Home"
import { MapContainer } from "./Scenes/Map"
import { BucketKey } from "./Scenes/Map/bucketCityResults"
import { PartnerRenderer } from "./Scenes/Partner"
import { PartnerLocationsRenderer } from "./Scenes/Partner/Screens/PartnerLocations"
import { PrivacyRequest } from "./Scenes/PrivacyRequest"
import { Search } from "./Scenes/Search"
import { ShowArtistsRenderer, ShowArtworksRenderer, ShowMoreInfoRenderer } from "./Scenes/Show"
import renderWithLoadProgress from "./utils/renderWithLoadProgress"
import { Schema, screenTrack as track } from "./utils/track"
YellowBox.ignoreWarnings([
"Warning: RelayResponseNormalizer: Payload did not contain a value for field `id: id`. Check that you are parsing with the same query that was used to fetch the payload.",
// Deprecated, we'll transition when it's removed.
"Warning: ListView is deprecated and will be removed in a future release. See https://fb.me/nolistview for more information",
// RN 0.59.0 ships with RNCameraRoll with this issue: https://github.com/facebook/react-native/issues/23755
// We can remove this once this PR gets shipped and we update: https://github.com/facebook/react-native/pull/24314
"Module RCTImagePickerManager requires main queue setup since it overrides `init`",
// RN 0.59.0 ships with this bug, see: https://github.com/facebook/react-native/issues/16376
"RCTBridge required dispatch_sync to load RCTDevLoadingView. This may lead to deadlocks",
// The following two items exist in node_modules. Once this PR is merged, to make warnings opt-in, we can ignore: https://github.com/facebook/metro/issues/287
// react-native-sentry ships with this error, tracked here: https://github.com/getsentry/react-native-sentry/issues/479
"Require cycle: node_modules/react-native-sentry/lib/Sentry.js -> node_modules/react-native-sentry/lib/RavenClient.js -> node_modules/react-native-sentry/lib/Sentry.js",
// RN 0.59.0 ships with this issue, which has been effectively marked as #wontfix: https://github.com/facebook/react-native/issues/23130
"Require cycle: node_modules/react-native/Libraries/Network/fetch.js -> node_modules/react-native/Libraries/vendor/core/whatwg-fetch.js -> node_modules/react-native/Libraries/Network/fetch.js",
// This is for the Artist page, which will likely get redone soon anyway.
"VirtualizedLists should never be nested inside plain ScrollViews with the same orientation - use another VirtualizedList-backed container instead.",
])
interface ArtistProps {
artistID: string
isPad: boolean
}
const Artist: React.SFC<ArtistProps> = props => (
<ArtistRenderer {...props} render={renderWithLoadProgress(Containers.Artist, props)} />
)
interface ArtworkProps {
artworkID: string
safeAreaInsets: SafeAreaInsets
isVisible: boolean
}
const Artwork: React.SFC<ArtworkProps> = props => <ArtworkRenderer {...props} />
interface PartnerProps {
partnerID: string
safeAreaInsets: SafeAreaInsets
isVisible: boolean
}
const Partner: React.SFC<PartnerProps> = props => <PartnerRenderer {...props} />
interface PartnerLocationsProps {
partnerID: string
safeAreaInsets: SafeAreaInsets
isVisible: boolean
}
const PartnerLocations: React.SFC<PartnerLocationsProps> = props => <PartnerLocationsRenderer {...props} />
const Inbox: React.SFC<{}> = track<{}>(() => {
return { context_screen: Schema.PageNames.InboxPage, context_screen_owner_type: null }
})(props => <InboxRenderer {...props} render={renderWithLoadProgress(Containers.Inbox, props)} />)
interface GeneProps {
geneID: string
refineSettings: { medium: string; price_range: string }
}
const Gene: React.SFC<GeneProps> = track<GeneProps>(props => {
return {
context_screen: Schema.PageNames.GenePage,
context_screen_owner_slug: props.geneID,
context_screen_owner_type: Schema.OwnerEntityTypes.Gene,
}
})(({ geneID, refineSettings: { medium, price_range } }) => {
const initialProps = { geneID, medium, price_range }
return <GeneRenderer {...initialProps} render={renderWithLoadProgress(Containers.Gene, initialProps)} />
})
// FIXME: This isn't being used
// const Sale: React.SFC<{ saleID: string }> = ({ saleID }) => {
// const initialProps = { saleID }
// return <SaleRenderer {...initialProps} render={renderWithLoadProgress(Containers.Sale, initialProps)} />
// }
// TODO: This was required to trigger the 1px wake-up hack (in case the scrollview goes blank)
//
// this.renderFetched = data => <Containers.WorksForYou {...data} trigger1pxScrollHack={this.props.trigger1pxScrollHack} />
//
// FIXME: Is this really still being used?
const WorksForYou: React.SFC<{ selectedArtist: string }> = props => (
<WorksForYouRenderer
{...props}
render={renderWithLoadProgress(
query => (
<Containers.WorksForYou query={query as any} />
),
props
)}
/>
)
interface InquiryProps {
artworkID: string
}
const Inquiry: React.SFC<InquiryProps> = track<InquiryProps>(props => {
return {
context_screen: Schema.PageNames.InquiryPage,
context_screen_owner_slug: props.artworkID,
context_screen_owner_type: Schema.OwnerEntityTypes.Artwork,
}
})(props => <InquiryRenderer {...props} render={renderWithLoadProgress(Containers.Inquiry, props)} />)
interface ConversationProps {
conversationID: string
}
const Conversation: React.SFC<ConversationProps> = track<ConversationProps>(props => {
return {
context_screen: Schema.PageNames.ConversationPage,
context_screen_owner_id: props.conversationID,
context_screen_owner_type: Schema.OwnerEntityTypes.Conversation,
}
})(props => <ConversationRenderer {...props} render={renderWithLoadProgress(Containers.Conversation, props)} />)
const MyProfile = Containers.MyProfile
interface CollectionProps {
collectionID: string
}
const Collection: React.SFC<CollectionProps> = ({ collectionID }) => {
return (
<CollectionRenderer
collectionID={collectionID}
render={renderWithLoadProgress(CollectionContainer, { collectionID })}
/>
)
}
/*
* Route bid/register requests coming from the Emission pod to either a BidFlow
* or RegisterFlow component with an appropriate query renderer
*/
type BidderFlowIntent = "bid" | "register"
interface BidderFlowProps {
artworkID?: string
saleID: string
intent: BidderFlowIntent
}
interface BidderFlow {
queryRenderer: React.ComponentType<BidderFlowRendererProps>
container: RelayContainer<any>
}
const BidderFlows: { [BidderFlowIntent: string]: BidderFlow } = {
bid: {
queryRenderer: BidFlowRenderer,
container: BidFlow,
},
register: {
queryRenderer: RegistrationFlowRenderer,
container: RegistrationFlow,
},
}
const BidderFlow: React.SFC<BidderFlowProps> = ({ intent, ...restProps }) => {
const { queryRenderer: Renderer, container: Container } = BidderFlows[intent]
return <Renderer {...restProps} render={renderWithLoadProgress(Container)} />
}
interface FairProps {
fairID: string
}
const Fair: React.SFC<FairProps> = ({ fairID }) => {
return <FairRenderer fairID={fairID} render={renderWithLoadProgress(Containers.Fair, { fairID })} />
}
interface ShowProps {
showID: string
}
const Show: React.SFC<ShowProps> = ({ showID }) => {
return <ShowRenderer showID={showID} render={renderWithLoadProgress(Containers.Show, { showID })} />
}
interface ShowArtistsProps {
showID: string
}
const ShowArtists: React.SFC<ShowArtistsProps> = ({ showID }) => {
return <ShowArtistsRenderer showID={showID} />
}
interface ShowArtworksProps {
showID: string
}
const ShowArtworks: React.SFC<ShowArtworksProps> = ({ showID }) => {
return <ShowArtworksRenderer showID={showID} />
}
interface ShowMoreInfoProps {
showID: string
}
const ShowMoreInfo: React.SFC<ShowMoreInfoProps> = ({ showID }) => {
return <ShowMoreInfoRenderer showID={showID} />
}
interface CityFairListProps {
citySlug: string
}
const CityFairList: React.SFC<CityFairListProps> = ({ citySlug }) => {
return (
<CityFairListRenderer citySlug={citySlug} render={renderWithLoadProgress(Containers.CityFairList, { citySlug })} />
)
}
interface CitySectionListProps {
citySlug: string
section: BucketKey
}
const CitySectionList: React.SFC<CitySectionListProps> = ({ citySlug, section }) => {
return (
<CitySectionListRenderer
citySlug={citySlug}
section={section}
render={renderWithLoadProgress(Containers.CitySectionList, { citySlug, section })}
/>
)
}
interface FairBoothProps {
fairBoothID: string
}
const FairBooth: React.SFC<FairBoothProps> = ({ fairBoothID }) => {
return <FairBoothRenderer showID={fairBoothID} />
}
interface FairArtistsProps {
fairID: string
}
const FairArtists: React.SFC<FairArtistsProps> = track<FairArtistsProps>(props => {
return {
context_screen: Schema.PageNames.FairAllArtistsPage,
context_screen_owner_slug: props.fairID,
context_screen_owner_type: Schema.OwnerEntityTypes.Fair,
}
})(({ fairID }) => {
return <FairArtistsRenderer fairID={fairID} />
})
interface FairArtworksProps {
fairID: string
}
const FairArtworks: React.SFC<FairArtworksProps> = ({ fairID }) => {
return <FairArtworksRenderer fairID={fairID} />
}
interface FairExhibitorsProps {
fairID: string
}
const FairExhibitors: React.SFC<FairExhibitorsProps> = ({ fairID }) => {
return <FairExhibitorsRenderer fairID={fairID} />
}
interface CityBMWListProps {
citySlug: string
}
const CityBMWList: React.SFC<CityBMWListProps> = ({ citySlug }) => {
return (
<CityBMWListRenderer citySlug={citySlug} render={renderWithLoadProgress(Containers.CityBMWList, { citySlug })} />
)
}
interface FairBMWArtActivationProps {
fairID: string
}
const FairBMWArtActivation: React.SFC<FairBMWArtActivationProps> = ({ fairID }) => {
return <FairBMWArtActivationRenderer fairID={fairID} />
}
interface CitySavedListProps {
citySlug: string
}
const CitySavedList: React.SFC<CitySavedListProps> = ({ citySlug }) => {
return (
<CitySavedListRenderer
citySlug={citySlug}
render={renderWithLoadProgress(
props => (
<Containers.CitySavedList viewer={props as any} citySlug={citySlug} />
),
{ citySlug }
)}
/>
)
}
interface SearchWithTrackingProps {
safeAreaInsets: SafeAreaInsets
}
const SearchWithTracking: React.SFC<SearchWithTrackingProps> = track<SearchWithTrackingProps>(() => {
return {
context_screen: Schema.PageNames.Search,
context_screen_owner_type: Schema.OwnerEntityTypes.Search,
}
})(props => {
return <Search {...props} />
})
AppRegistry.registerComponent("Consignments", () => Consignments)
AppRegistry.registerComponent("Artist", () => Artist)
AppRegistry.registerComponent("Artwork", () => Artwork)
AppRegistry.registerComponent("ArtworkAttributionClassFAQ", () => ArtworkAttributionClassFAQRenderer)
AppRegistry.registerComponent("Home", () => HomeScene)
AppRegistry.registerComponent("Gene", () => Gene)
AppRegistry.registerComponent("WorksForYou", () => WorksForYou)
AppRegistry.registerComponent("MyProfile", () => MyProfile)
AppRegistry.registerComponent("MySellingProfile", () => () => <View />)
AppRegistry.registerComponent("Inbox", () => Inbox)
AppRegistry.registerComponent("Conversation", () => Conversation)
AppRegistry.registerComponent("Inquiry", () => Inquiry)
AppRegistry.registerComponent("Partner", () => Partner)
AppRegistry.registerComponent("PartnerLocations", () => PartnerLocations)
AppRegistry.registerComponent("Favorites", () => FavoritesScene)
// TODO: Change everything to BidderFlow? AuctionAction?
AppRegistry.registerComponent("BidFlow", () => BidderFlow)
AppRegistry.registerComponent("Fair", () => Fair)
AppRegistry.registerComponent("FairMoreInfo", () => FairMoreInfoRenderer)
AppRegistry.registerComponent("FairBooth", () => FairBooth)
AppRegistry.registerComponent("FairArtists", () => FairArtists)
AppRegistry.registerComponent("FairArtworks", () => FairArtworks)
AppRegistry.registerComponent("FairExhibitors", () => FairExhibitors)
AppRegistry.registerComponent("FairBMWArtActivation", () => FairBMWArtActivation)
AppRegistry.registerComponent("Search", () => SearchWithTracking)
AppRegistry.registerComponent("Show", () => Show)
AppRegistry.registerComponent("ShowArtists", () => ShowArtists)
AppRegistry.registerComponent("ShowArtworks", () => ShowArtworks)
AppRegistry.registerComponent("ShowMoreInfo", () => ShowMoreInfo)
AppRegistry.registerComponent("Map", () => MapContainer)
AppRegistry.registerComponent("City", () => CityView)
AppRegistry.registerComponent("CityPicker", () => CityPicker)
AppRegistry.registerComponent("CityBMWList", () => CityBMWList)
AppRegistry.registerComponent("CityFairList", () => CityFairList)
AppRegistry.registerComponent("CitySavedList", () => CitySavedList)
AppRegistry.registerComponent("CitySectionList", () => CitySectionList)
AppRegistry.registerComponent("Collection", () => Collection)
AppRegistry.registerComponent("PrivacyRequest", () => PrivacyRequest) | the_stack |
import * as d3 from "d3";
import { IdMap } from "./messages";
import { dbgLog } from "./source";
import { getEntityId } from "./view";
import { Activity, TraceDataUpdate, SendOp } from "./execution-data";
import { KomposMetaModel } from "./meta-model";
import { getLightTangoColor, PADDING } from "./system-view";
const actorStart = 20; // height at which actor headings are created
const actorHeight = 30; // height of actor headings
const actorSpacing = 100; // space between actors (width)
const turnRadius = 20; // radius of turns
const turnSpacing = 50; // space between consequent turns
const messageSpacing = 20; // space between multiple message when enlarged
const markerSize = 10; // size of markers (arrows and squares of enlarged messages)
const noHighlightWidth = 2; // width of turn borders when not highlighted
const highlightedWidth = 5; // width of turn borders when highlighted
let svgContainer; // global canvas, stores actor <g> elements
let defs; // global container to store all markers
const lineGenerator: any =
d3.svg.line()
.x(function(d) { return d[0]; })
.y(function(d) { return d[1]; })
.interpolate("linear");
/** each actor has their own svg group.
one heading group: the square, the text field and the other group.
one collection group: turns and messages
to hide an actor the other group and all incoming messages are set to hidden */
class ActorHeading {
private readonly turns: TurnNode[];
private readonly activity: Activity;
public readonly x: number;
private readonly y: number;
public readonly color: string;
private visibility: boolean;
private container: d3.Selection<SVGElement>;
constructor(activity: Activity, num: number) {
this.turns = [];
this.activity = activity;
this.x = 50 + num * actorSpacing;
this.y = actorStart;
this.color = getLightTangoColor(activity.type, activity.id);
this.visibility = true;
}
public addTurn(turn: TurnNode) {
this.turns.push(turn);
return this.turns.length;
}
public getLastTurn() {
if (this.turns.length === 0) {
return new TurnNode(this, new EmptyMessage());
} else {
return this.turns[this.turns.length - 1];
}
}
public getContainer() {
return this.container;
}
public getActivityId() {
return this.activity.id;
}
// -----------visualization------------
// set the visibility of the collection group, this hides all turns and
// messages outgoing from these turns.
// afterwards set the visibility of each incoming message individually
private changeVisibility() {
this.visibility = !this.visibility;
if (this.visibility) {
this.container.style("visibility", "inherit");
} else {
this.container.style("visibility", "hidden");
}
for (const turn of this.turns) {
turn.changeVisibility(this.visibility);
}
}
// a turn in this actor is enlarged. Move all other turns below that turn,
// downwards with the given yShift
public transpose(threshold, yShift) {
for (let i = threshold; i < this.turns.length; i++) {
this.turns[i].transpose(yShift);
}
}
public draw(metaModel: KomposMetaModel) {
const actorHeading = svgContainer.append("g");
this.container = actorHeading.append("g");
actorHeading.append("rect")
.attr("y", this.y)
.attr("rx", 5)
.attr("height", actorHeight)
.style("fill", this.color)
.style("stroke", d3.rgb(this.color).darker().toString())
.on("click", () => {
this.changeVisibility();
});
actorHeading.append("text")
.attr("x", this.x)
.attr("y", this.y + actorHeight / 2)
.attr("font-size", "20px")
.attr("text-anchor", "middle")
.html(
metaModel.getActivityDef(this.activity).marker +
" " + this.activity.name);
const that = this;
// center position after text was rendered, and we can determine its width
actorHeading.selectAll("rect")
.attr("width", function() {
return this.nextSibling.getComputedTextLength() + PADDING;
})
.attr("x", function() {
const width = this.nextSibling.getComputedTextLength();
return that.x - (PADDING + width) / 2.0;
});
}
}
/** A turn happens every time an actor processes a message.
Turns store their incoming message and each outgoing message. */
class TurnNode {
private readonly actor: ActorHeading;
private readonly incoming: EmptyMessage;
private readonly outgoing: Message[];
private readonly count: number;
public readonly x: number;
public readonly y: number;
private readonly visualization: d3.Selection<SVGElement>;
private popover: JQuery;
constructor(actor: ActorHeading, message: EmptyMessage) {
this.actor = actor;
this.incoming = message; // possible no message
this.outgoing = [];
this.count = this.actor.addTurn(this);
this.x = actor.x;
this.y = actorStart + actorHeight + this.count * turnSpacing;
this.visualization = this.draw();
}
public addMessage(message: Message) {
this.outgoing.push(message);
return this.outgoing.length;
}
public getContainer() {
return this.actor.getContainer();
}
public getColor() {
return this.actor.color;
}
private getId() {
return "turn" + this.actor.getActivityId() + "-" + this.count;
}
// -----------visualization------------
/** highlight this turn.
make the circle border bigger and black
highlight the incoming message. */
public highlightOn() {
this.visualization.style("stroke-width", highlightedWidth)
.style("stroke", "black");
this.incoming.highlightOn();
}
/** remove highlight from this turn */
public highlightOff() {
this.visualization.style("stroke-width", noHighlightWidth)
.style("stroke", d3.rgb(this.getColor()).darker().toString());
this.incoming.highlightOff();
}
/** the turn itself is made invisible by the group, only the incoming arc
needs to be made invisible */
public changeVisibility(visible: boolean) {
this.incoming.changeVisibility(visible);
}
/** enlarge this turn
every message receives own exit point from this turn
shift other turns downwards to prevent overlap. */
public enlarge() {
this.highlightOn();
ctrl.toggleHighlightMethod(getEntityId(this.actor.getActivityId()),
this.incoming.getText(), true); // hight source section
const growSize = this.outgoing.length * messageSpacing;
this.visualization.attr("ry", turnRadius + growSize / 2);
this.visualization.attr("cy", this.y + growSize / 2);
// move all turns below this turn down by growSize
this.actor.transpose(this.count, growSize);
for (const message of this.outgoing) {
message.enlarge(); // create separate point of origins for all outgoing messages
}
}
/** shrink this turn
every message starts from the center of the node. */
public shrink() {
this.highlightOff();
ctrl.toggleHighlightMethod(
getEntityId(this.actor.getActivityId()), this.incoming.getText(), false);
this.visualization.attr("ry", turnRadius);
this.visualization.attr("cy", this.y);
this.actor.transpose(this.count, 0);
// move all turns below this turn back to original location
for (const message of this.outgoing) {
message.shrink(); // remove separate point of origins for all outgoing messages
}
}
/** move this turn with the give yShift vertically. */
public transpose(yShift: number) {
this.visualization.attr("transform", "translate(0," + yShift + ")");
this.incoming.shiftAtTarget(yShift);
for (const message of this.outgoing) {
message.shiftAtSender(yShift);
}
}
/** only one node can be highlighted at a time.
If the user highlights another node,
remove the popover of the previously highlighted node. */
public hidePopup() {
this.popover.popover("hide");
}
private draw() {
const turn = this;
// draw the svg circle
const circle = this.getContainer().append("ellipse")
.attr("id", this.getId())
.attr("cx", this.x)
.attr("cy", this.y)
.attr("rx", turnRadius)
.attr("ry", turnRadius)
.style("fill", this.actor.color)
.style("stroke-width", noHighlightWidth)
.style("stroke", d3.rgb(this.actor.color).darker().toString())
.on("click", function() {
ProcessView.changeHighlight(turn);
});
/*add popover, a on hover/click menu with the name of the message causing
the turn and two buttons
one to do minimal restore
one to do full restore
*/
circle.attr({
"data-toggle": "popover",
"data-trigger": "click",
"title": this.incoming.getText(),
"animation": "false",
"data-html": "true",
"data-animation": "false",
"data-placement": "top"
});
// popover is a css element and has a different dom then svg,
// popover requires jQuery select to pass typechecking
this.popover = $("#" + this.getId());
this.popover.popover();
return circle;
}
}
class EmptyMessage {
public highlightOn() { }
public highlightOff() { }
public changeVisibility(_visible: boolean) { }
public getText() { return "42"; }
public shiftAtSender(_yShift: number) { }
public shiftAtTarget(_yShift: number) { }
}
/** message represent a message send between two actors
messages go from a turn to another turn
normally a message goes from the center of a turn to the center of a turn.
this can change if the turns shift or are enlarged
when undoing a shift the original shift is unknown, so we shift back to the old position
message can be shifted at both sender and receiver. */
class Message extends EmptyMessage {
private text: string;
private sender: TurnNode;
private target: TurnNode;
private messageToSelf: boolean; // is both the sender and receiver the same object
private order: number; // indicates order of message sends inside tur
private senderShift: number;
private targetShift: number;
private visibility: string;
private visualization: d3.Selection<SVGElement>;
private anchor: d3.Selection<SVGElement>;
// private readonly sendOp: SendOp;
constructor(senderActor: ActorHeading, targetActor: ActorHeading,
_sendOp: SendOp, senderTurn: TurnNode) {
super();
// this.sendOp = sendOp;
this.sender = senderTurn;
this.target = new TurnNode(targetActor, this);
this.messageToSelf = senderActor === targetActor;
this.order = this.sender.addMessage(this);
this.senderShift = 0;
this.targetShift = 0;
this.visibility = "inherit";
this.draw();
this.text = "TODO";
}
public getText() {
return this.text;
}
private getColor() {
return this.sender.getColor();
}
private draw() {
if (this.messageToSelf) {
this.drawMessageToSelf();
} else {
this.drawMessageToOther();
}
}
/** remove the visualization and create a new one
if the anchor where not defined yet the remove doesn't do anything. */
private redraw() {
this.visualization.remove();
this.draw();
}
public highlightOn() {
this.visualization.style("stroke-width", highlightedWidth);
this.sender.highlightOn();
}
public highlightOff() {
this.visualization.style("stroke-width", 1);
this.sender.highlightOff();
}
/** standard visibility is inherit
this allows message going from and to a hidden turn to stay hidden
if either party becomes visible. */
public changeVisibility(visible: boolean) {
if (visible) {
this.visibility = "inherit";
} else {
this.visibility = "hidden";
}
this.visualization.style("visibility", this.visibility);
if (this.anchor) {
// if the anchor exist, update its visibility
this.anchor.style("visibility", this.visibility);
}
}
public enlarge() {
this.senderShift = this.order * messageSpacing;
this.anchor = this.createMessageAnchor();
this.redraw();
}
public shrink() {
this.anchor.remove();
this.anchor = null;
this.senderShift = 0;
this.redraw();
}
public shiftAtSender(yShift: number) {
this.senderShift = yShift;
this.redraw();
}
public shiftAtTarget(yShift: number) {
this.targetShift = yShift;
this.redraw();
}
private createMessageArrow() {
const lineData: [number, number][] =
[[0, 0],
[markerSize, markerSize / 2],
[0, markerSize]];
defs.append("marker")
.attr("refX", markerSize + turnRadius) // shift along path (place arrow on path outside turn)
.attr("refY", markerSize / 2) // shift orthogonal of path (place arrow on middle of path)
.attr("markerWidth", markerSize)
.attr("markerHeight", markerSize)
.attr("orient", "auto")
.attr("markerUnits", "userSpaceOnUse")
.style("fill", this.getColor())
.append("path")
.attr("d", lineGenerator(lineData))
.attr("class", "arrowHead");
}
private createMessageAnchor() {
return this.sender.getContainer().append("rect")
.attr("x", this.sender.x - markerSize / 2)
.attr("y", this.sender.y + this.senderShift - markerSize / 2)
.attr("height", markerSize)
.attr("width", markerSize)
.style("fill", this.target.getColor())
.style("stroke", "black")
.style("visibility", this.visibility)
.on("click", function() {
dbgLog("clicked marker");
});
}
private drawMessageToSelf() {
this.createMessageArrow();
const lineData: [number, number][] = [
[this.sender.x, this.sender.y + this.senderShift],
[this.sender.x + turnRadius * 1.5, this.sender.y + this.senderShift],
[this.target.x + turnRadius * 1.5, this.target.y + this.targetShift],
[this.target.x, this.target.y + this.targetShift]];
this.visualization =
this.sender.getContainer().append("path")
.attr("d", lineGenerator(lineData))
.style("fill", "none")
.style("stroke", d3.rgb(this.getColor()).darker().toString())
.style("visibility", this.visibility);
}
private drawMessageToOther() {
this.createMessageArrow();
this.visualization =
this.sender.getContainer().append("line")
.attr("x1", this.sender.x)
.attr("y1", this.sender.y + this.senderShift)
.attr("x2", this.target.x)
.attr("y2", this.target.y + this.targetShift)
.style("stroke", d3.rgb(this.sender.getColor()).darker().toString())
.style("visibility", this.visibility);
}
}
/** The ProcessView stores all actors currently in use.
Only one turn can be highlighted at a time. */
export class ProcessView {
private static highlighted: TurnNode;
private actors: IdMap<ActorHeading>;
private metaModel: KomposMetaModel;
private numActors: number;
public constructor() {
const canvas = $("#protocol-canvas");
canvas.empty(); // after every restart the canvas needs to be redrawn in case a different program is running on the backend
svgContainer = d3.select("#protocol-canvas")
.append("svg")
.attr("width", 1000)
.attr("height", 1000)
.attr("style", "background: none;");
defs = svgContainer.append("defs");
this.actors = {};
this.numActors = 0;
}
public reset() {
this.numActors = 0;
this.actors = {};
}
public setMetaModel(metaModel: KomposMetaModel) {
this.metaModel = metaModel;
}
public updateTraceData(data: TraceDataUpdate) {
this.newActivities(data.activities);
this.newMessages(data.sendOps);
}
private newActivities(newActivities: Activity[]) {
for (const act of newActivities) {
if (this.metaModel.isActor(act)) {
const actor = new ActorHeading(act, this.numActors);
dbgLog("new activity: " + act.id + " " + act.name);
this.actors[act.id] = actor;
this.numActors += 1;
actor.draw(this.metaModel);
}
}
}
private newMessages(newMessages: SendOp[]) {
for (const msg of newMessages) {
if (!this.metaModel.isActorMessage(msg)) {
// ignore all non-actor message sends
continue;
}
const senderActor = this.actors[msg.creationActivity.id];
const targetActor = this.actors[(<Activity> msg.target).id];
new Message(senderActor, targetActor, msg, senderActor.getLastTurn());
}
}
/** Ensure only one node chain can be highlighted at the same time. */
public static changeHighlight(turn: TurnNode) {
if (ProcessView.highlighted) {
ProcessView.highlighted.shrink();
if (turn === ProcessView.highlighted) {
ProcessView.highlighted = null;
return;
} else {
ProcessView.highlighted.hidePopup();
}
}
turn.enlarge();
ProcessView.highlighted = turn;
}
} | the_stack |
import * as React from 'react';
import * as _ from 'lodash';
import { ChromePicker } from 'react-color';
import * as browser_utils from '../utils/browser';
import logger from '../../../shared/utils/logger';
import { MODES } from '../modes';
import Path from '../path';
import Document from '../document';
import { DocumentStore, ClientStore } from '../datastore';
import { InMemory } from '../../../shared/data_backend';
import Session from '../session';
import Menu from '../menu';
import Config from '../config';
import KeyBindings from '../keyBindings';
import KeyMappings from '../keyMappings';
import { PluginsManager } from '../plugins';
import { BackendType } from '../data_backend';
import { Theme, getStyles, themes } from '../themes';
import { SERVER_CONFIG } from '../constants';
import SessionComponent from './session';
import SpinnerComponent from './spinner';
import MenuComponent from './menu';
import HotkeysTableComponent from './hotkeysTable';
import PluginsTableComponent from './pluginTable';
import BackendSettingsComponent from './settings/backendSettings';
import FileInput from './fileInput';
import BehaviorSettingsComponent from './settings/behaviorSettings';
enum TABS {
DATA,
THEME,
BEHAVIOR,
HOTKEYS,
PLUGIN,
ABOUT,
}
type Props = {
session: Session;
config: Config;
keyBindings: KeyBindings;
pluginManager: PluginsManager;
initialBackendType: BackendType;
onExport: () => void;
rerenderAll: () => void;
};
type State = {
currentTab: TABS,
themeProperty: keyof Theme, // color theme property currently being changed
presetTheme: string,
};
function getCurrentTheme(clientStore: ClientStore) {
const theme: Theme = {} as Theme;
Object.keys(themes.Default).forEach((theme_property: string) => {
theme[theme_property as keyof Theme] = clientStore.getClientSetting(theme_property as keyof Theme);
});
return theme;
}
export default class SettingsComponent extends React.Component<Props, State> {
private keyBindingsUpdate: () => void;
private preview_session: Session | null = null;
private preview_menu: Menu | null = null;
private initial_theme: Theme;
constructor(props: Props) {
super(props);
this.state = {
currentTab: TABS.DATA,
themeProperty: 'theme-bg-primary',
presetTheme: 'Default',
};
this.keyBindingsUpdate = () => {
this.forceUpdate();
};
this.initial_theme = getCurrentTheme(props.session.clientStore);
(async () => {
const preview_document = new Document(new DocumentStore(new InMemory()));
await preview_document.load([
{ text: 'Preview document', children: [
{ text: 'Breadcrumbs', children: [
{ text: 'Header', children: [
'This is a preview document',
'This is a link: http://www.google.com',
'Here is a visual selection',
/*
{ text: 'This is marked, if marks are on', plugins: { mark: 'mark' } },
*/
] }
] }
] }
]);
this.preview_session = new Session(
this.props.session.clientStore, preview_document,
{ viewRoot: Path.loadFromAncestry([1, 2, 3]) }
);
const cursorPath = Path.loadFromAncestry([1, 2, 3, 6]);
await this.preview_session.cursor.setPosition(cursorPath, 10);
await this.preview_session.setMode('VISUAL');
await this.preview_session.anchor.setPosition(cursorPath, 4);
this.preview_session.document.cache.clear();
function makeAccents(min: number, max: number) {
const accents: {[key: number]: boolean} = {};
for (let i = min; i <= max; i++) { accents[i] = true; }
return accents;
}
this.preview_menu = new Menu(async (_query) => {
return [
{
contents: 'Some blah result'.split(''),
renderOptions: { accents: makeAccents(5, 8) },
fn: () => null
},
{
contents: 'Another blah result'.split(''),
renderOptions: { accents: makeAccents(8, 11) },
fn: () => null
},
];
});
await this.preview_menu.session.addCharsAtCursor('blah'.split(''));
await this.preview_menu.update();
this.forceUpdate();
})();
}
public componentDidMount() {
// set up listener for keybindings
this.props.keyBindings.on('update', this.keyBindingsUpdate);
}
public componentWillUnmount() {
this.props.keyBindings.off('update', this.keyBindingsUpdate);
}
public render() {
const session = this.props.session;
const keyBindings = this.props.keyBindings;
const updateAll = () => {
if (this.preview_session) {
this.preview_session.document.cache.clear();
}
this.props.rerenderAll();
};
const applyTheme = (theme: Theme) => {
Object.keys(theme).forEach((theme_prop: string) => {
session.clientStore.setClientSetting(theme_prop as keyof Theme, theme[theme_prop as keyof Theme]);
});
updateAll();
};
const colorPickerRow = (name: string, theme_property: keyof Theme) => {
const hex_color = session.clientStore.getClientSetting('theme-bg-primary');
const rgb = parseInt(hex_color.substring(1), 16);
// tslint:disable no-bitwise
const r = (rgb >> 16) & 0xff; // extract red
const g = (rgb >> 8) & 0xff; // extract green
const b = (rgb >> 0) & 0xff; // extract blue
// tslint:enable no-bitwise
const luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; // per ITU-R BT.709
const style = { fontSize: 11, padding: 10, cursor: 'pointer' };
if (theme_property === this.state.themeProperty) {
Object.assign(style, getStyles(session.clientStore, ['theme-bg-highlight']));
}
return (
<tr style={style} onClick={
() => this.setState({themeProperty: theme_property} as State)
}>
<td style = {{
width: '50px',
border: `1px solid ${luma > 40 ? 'black' : 'white'}`,
backgroundColor: session.clientStore.getClientSetting(theme_property)
}}/>
<td style={{ paddingLeft: 10 }}> {name} </td>
</tr>
);
};
const tabs_info = [
{
tab: TABS.DATA,
heading: 'Data',
div: (
<div>
{
SERVER_CONFIG.socketserver ? (
<div style={{
marginBottom: 20, padding: 10,
...getStyles(session.clientStore, ['theme-trim-accent'])
}}>
NOTE: Since you are using a Vimflowy server,
you can simply back up the data server-side,
assuming you have access to the server.
</div>
) : (
<div>
<div className='settings-header'
style={{
...getStyles(session.clientStore, ['theme-bg-secondary', 'theme-trim'])
}}
>
Data storage
</div>
<div className='settings-content'>
<BackendSettingsComponent
clientStore={session.clientStore}
initialBackendType={this.props.initialBackendType}
/>
</div>
</div>
)
}
<div className='settings-header'
style={{
...getStyles(session.clientStore, ['theme-bg-secondary', 'theme-trim'])
}}>
Export Data
</div>
<div className='settings-content'>
<table><tbody>
<tr>
<td>
<div className='btn'
style={{
...getStyles(session.clientStore, ['theme-bg-tertiary', 'theme-trim'])
}}
onClick={() => session.exportFile('json')} >
Export as JSON
</div>
</td>
<td>
Best for vimflowy backups, re-imports preserving all features.
</td>
</tr>
<tr>
<td>
<div className='btn'
style={{
...getStyles(session.clientStore, ['theme-bg-tertiary', 'theme-trim'])
}}
onClick={() => session.exportFile('txt')}>
Export as plaintext
</div>
</td>
<td>
Workflowy compatible.
Does not support all features (e.g. vimflowy's marks/clones, or workflowy's tags, etc.)
</td>
</tr>
</tbody></table>
</div>
<div className='settings-header'
style={{
...getStyles(session.clientStore, ['theme-bg-secondary', 'theme-trim'])
}}
>
Import Data
</div>
<div className='settings-content'>
<FileInput
onSelect={(filename) => {
session.showMessage(`Reading in file ${filename}...`);
}}
onLoad={async (filename, contents) => {
const mimetype = browser_utils.mimetypeLookup(filename);
if (!mimetype) {
session.showMessage('Invalid filetype!', { time: 0 });
return;
}
session.showMessage('Importing contents...', { time: 0 });
if (await session.importContent(contents, mimetype)) {
session.showMessage('Imported!', {text_class: 'success'});
await session.setMode('NORMAL');
} else {
session.showMessage('Import failed due to parsing issue', {text_class: 'error'});
}
}}
onError={(error) => {
logger.error('Data file input error', error);
session.showMessage(`Error reading data: ${error}`, {text_class: 'error'});
}}
>
<div className='btn'
style={{
...getStyles(session.clientStore, ['theme-bg-tertiary', 'theme-trim'])
}}
>
Import from file
</div>
</FileInput>
</div>
</div>
),
},
{
tab: TABS.THEME,
heading: 'Visual theme',
div: (
<div style={{ display: 'flex' }}>
<div style={{ padding: 5, flexBasis: 1, flexGrow: 1 }}>
<div className='settings-header'
style={{
...getStyles(session.clientStore, ['theme-bg-secondary', 'theme-trim'])
}}
>
Colors
</div>
<div className='settings-content' style={{ display: 'flex' }}>
<div>
<div style={{ paddingTop: 10 }}>
<table style={{ borderCollapse: 'collapse' }}><tbody>
{colorPickerRow('Main background color', 'theme-bg-primary')}
{colorPickerRow('Secondary background color', 'theme-bg-secondary')}
{colorPickerRow('Tertiary background color', 'theme-bg-tertiary')}
{colorPickerRow('Highlight background color', 'theme-bg-highlight')}
{colorPickerRow('Main text color', 'theme-text-primary')}
{colorPickerRow('Accented text color', 'theme-text-accent')}
{colorPickerRow('Trim color', 'theme-trim')}
{colorPickerRow('Accented trim color', 'theme-trim-accent')}
{colorPickerRow('Cursor text color', 'theme-text-cursor')}
{colorPickerRow('Cursor background color', 'theme-bg-cursor')}
{colorPickerRow('Link text color', 'theme-text-link')}
</tbody></table>
</div>
<div style={{padding: 10}}>
<span className='btn' style={{
...getStyles(session.clientStore, ['theme-bg-tertiary', 'theme-trim'])
}}
onClick={() => applyTheme(this.initial_theme) }>
Reset
</span>
<span className='btn' style={{
...getStyles(session.clientStore, ['theme-bg-tertiary', 'theme-trim'])
}} onClick={() => {
browser_utils.downloadFile(
'vimflowy_colors.json',
JSON.stringify(getCurrentTheme(session.clientStore)),
'application/json') ;
}}>
Download
</span>
</div>
<div>
<select
value={this.state.presetTheme}
onChange={(e) => {
const theme_name = (e.target as HTMLSelectElement).value;
this.setState({ presetTheme: theme_name } as State);
}}
>
{
Object.keys(themes).map((theme_name) => {
return (
<option value={theme_name} key={theme_name}>
{theme_name}
</option>
);
})
}
</select>
<span className='btn' style={{
...getStyles(session.clientStore, ['theme-bg-tertiary', 'theme-trim'])
}}
onClick={() => applyTheme(themes[this.state.presetTheme]) }>
Apply preset theme
</span>
<div style={{marginTop: 5}}>
<FileInput
onSelect={(filename) => {
session.showMessage(`Reading in file ${filename}...`);
}}
onLoad={(_filename, contents) => {
let theme;
try {
theme = JSON.parse(contents);
} catch (e) {
session.showMessage(`Failed to parse JSON: ${e}`, {text_class: 'error'});
return;
}
applyTheme(theme);
}}
onError={(error) => {
logger.error('Theme file input error', error);
session.showMessage(`Error reading theme: ${error}`, {text_class: 'error'});
}}
style={{float: 'left', position: 'relative'}}
>
<div className='btn'
style={{
...getStyles(session.clientStore, ['theme-bg-tertiary', 'theme-trim'])
}}
>
Import theme from file
</div>
</FileInput>
</div>
</div>
</div>
<div style={{ marginLeft: 50 }}>
<ChromePicker
color={ session.clientStore.getClientSetting(this.state.themeProperty) }
onChangeComplete={({ hex: hexColor }: any) => {
session.clientStore.setClientSetting(this.state.themeProperty, hexColor);
updateAll();
}}
/>
</div>
</div>
</div>
<div style={{ padding: 5, flexBasis: 1, flexGrow: 1 }}>
<div className='settings-header'
style={{
...getStyles(session.clientStore, ['theme-bg-secondary', 'theme-trim'])
}}
>
Preview
</div>
<div className='settings-content' style={{
...getStyles(session.clientStore, ['theme-trim-accent']),
padding: 10, marginTop: 10, pointerEvents: 'none'
}}>
{ this.preview_session ?
<SessionComponent
session={this.preview_session}
/> : <SpinnerComponent/>
}
</div>
<div className='settings-content' style={{
...getStyles(session.clientStore, ['theme-trim-accent']),
padding: 10, marginTop: 10, pointerEvents: 'none'
}}>
{ (this.preview_menu && this.preview_session) ?
<MenuComponent
menu={this.preview_menu}
session={this.preview_session}
/> : <SpinnerComponent/>
}
</div>
</div>
</div>
),
},
{
tab: TABS.BEHAVIOR,
heading: 'Yank behavior',
div: (
<div>
{
<div className='settings-content'>
<BehaviorSettingsComponent
clientStore={session.clientStore}
/>
</div>
}
</div>
),
},
{
tab: TABS.HOTKEYS,
heading: 'Hotkeys',
div: (
<div>
<div className='settings-content'>
<div className='clearfix' style={{marginBottom: 10}}>
<div className='btn'
style={{
float: 'left',
...getStyles(session.clientStore, ['theme-bg-tertiary', 'theme-trim'])
}}
onClick={this.props.onExport} >
Export as file
</div>
<div className='btn'
style={{
float: 'left',
...getStyles(session.clientStore, ['theme-bg-tertiary', 'theme-trim'])
}}
onClick={() => {
keyBindings.setMappings(this.props.config.defaultMappings);
return session.showMessage('Loaded defaults!', {text_class: 'success'});
}}>
Load defaults
</div>
<FileInput
onSelect={(filename) => {
session.showMessage(`Reading in file ${filename}...`);
}}
onLoad={(_filename, contents) => {
let hotkey_settings;
try {
hotkey_settings = JSON.parse(contents);
} catch (e) {
session.showMessage(`Failed to parse JSON: ${e}`, {text_class: 'error'});
return;
}
const mappings = new KeyMappings(hotkey_settings);
keyBindings.setMappings(mappings);
// TODO: validation of mappings?
// if (err) {
// session.showMessage(err, {text_class: 'error'});
// } else {
// session.showMessage('Loaded new hotkey settings!', {text_class: 'success'});
// }
session.clientStore.setClientSetting('hotkeys', hotkey_settings);
}}
onError={(error) => {
logger.error('Hotkeys file input error', error);
session.showMessage(`Error reading hotkeys: ${error}`, {text_class: 'error'});
}}
style={{float: 'left', position: 'relative'}}
>
<div className='btn'
style={{
...getStyles(session.clientStore, ['theme-bg-tertiary', 'theme-trim'])
}}
>
Import from file
</div>
</FileInput>
</div>
<div>
{
Object.keys(MODES).map((mode) => {
return (
<div key={mode}>
{mode}
<HotkeysTableComponent
keyMap={keyBindings.mappings.mappings[mode]}
definitions={keyBindings.definitions}
clientStore={session.clientStore}
/>
</div>
);
})
}
</div>
</div>
</div>
),
},
{
tab: TABS.PLUGIN,
heading: 'Plugins',
div: (
<PluginsTableComponent
clientStore={session.clientStore}
pluginManager={this.props.pluginManager}
/>
),
},
{
tab: TABS.ABOUT,
heading: 'About',
div: (
<div>
For more info, or to contact the maintainers, please visit
{' '}
<a href='https://github.com/WuTheFWasThat/vimflowy' style={{
...getStyles(session.clientStore, ['theme-link'])
}}>
the github website
</a>.
</div>
),
},
];
return (
<div>
{/* NOTE: must have theme as well so that inherit works for tabs*/}
<ul className='tabs' style={{
margin: 20,
...getStyles(session.clientStore, ['theme-bg-primary'])
}}>
{
(() => {
return _.map(tabs_info, (info) => {
const isActive = info.tab === this.state.currentTab;
return (
<li className={isActive ? 'active' : ''} key={info.tab}
style={{
...getStyles(session.clientStore, ['theme-bg-secondary', 'theme-trim'])
}}
onClick={() => this.setState({currentTab: info.tab} as State)}>
{info.heading}
</li>
);
});
})()
}
</ul>
{
(() => {
return _.map(tabs_info, (info) => {
const isActive = info.tab === this.state.currentTab;
return (
<div key={info.tab}
className={isActive ? '' : 'hidden'} style={{padding: 20}}
>
{info.div}
</div>
);
});
})()
}
</div>
);
}
} | the_stack |
import React from 'react'
import { MapLike } from 'typescript'
import { getUtopiaID } from '../../../core/model/element-template-utils'
import {
UTOPIA_PATHS_KEY,
UTOPIA_SCENE_ID_KEY,
UTOPIA_INSTANCE_PATH,
UTOPIA_UIDS_KEY,
UTOPIA_UID_ORIGINAL_PARENTS_KEY,
} from '../../../core/model/utopia-constants'
import { flatMapEither, forEachRight } from '../../../core/shared/either'
import {
JSXElementChild,
isJSXElement,
JSXElement,
jsxAttributeValue,
ElementsWithin,
isIntrinsicElement,
isIntrinsicHTMLElement,
JSXArbitraryBlock,
getJSXAttribute,
emptyComments,
} from '../../../core/shared/element-template'
import {
getAccumulatedElementsWithin,
jsxAttributesToProps,
setJSXValueAtPath,
} from '../../../core/shared/jsx-attributes'
import {
ElementPath,
HighlightBoundsForUids,
Imports,
} from '../../../core/shared/project-file-types'
import { fastForEach, NO_OP } from '../../../core/shared/utils'
import { Utils } from '../../../uuiui-deps'
import { UIFileBase64Blobs } from '../../editor/store/editor-state'
import { DomWalkerInvalidatePathsCtxData, UiJsxCanvasContextData } from '../ui-jsx-canvas'
import { SceneComponent } from './scene-component'
import * as PP from '../../../core/shared/property-path'
import * as EP from '../../../core/shared/element-path'
import { Storyboard } from 'utopia-api'
import { resolveParamsAndRunJsCode } from '../../../core/shared/javascript-cache'
import { objectMap } from '../../../core/shared/object-utils'
import { cssValueOnlyContainsComments } from '../../../printer-parsers/css/css-parser-utils'
import { filterDataProps } from '../../../utils/canvas-react-utils'
import { buildSpyWrappedElement } from './ui-jsx-canvas-spy-wrapper'
import { appendToUidString, createIndexedUid } from '../../../core/shared/uid-utils'
import { isComponentRendererComponent } from './ui-jsx-canvas-component-renderer'
import { optionalMap } from '../../../core/shared/optional-utils'
import { canvasMissingJSXElementError } from './canvas-render-errors'
import { importedFromWhere } from '../../editor/import-utils'
import { JSX_CANVAS_LOOKUP_FUNCTION_NAME } from '../../../core/shared/dom-utils'
export function createLookupRender(
elementPath: ElementPath | null,
rootScope: MapLike<any>,
parentComponentInputProps: MapLike<any>,
requireResult: MapLike<any>,
hiddenInstances: Array<ElementPath>,
fileBlobs: UIFileBase64Blobs,
validPaths: Array<ElementPath>,
reactChildren: React.ReactNode | undefined,
metadataContext: UiJsxCanvasContextData,
updateInvalidatedPaths: DomWalkerInvalidatePathsCtxData,
jsxFactoryFunctionName: string | null,
shouldIncludeCanvasRootInTheSpy: boolean,
filePath: string,
imports: Imports,
code: string,
highlightBounds: HighlightBoundsForUids | null,
): (element: JSXElement, scope: MapLike<any>) => React.ReactChild {
let index = 0
return (element: JSXElement, scope: MapLike<any>): React.ReactChild => {
index++
const innerUID = getUtopiaID(element)
const generatedUID = createIndexedUid(innerUID, index)
const withGeneratedUID = setJSXValueAtPath(
element.props,
PP.create(['data-uid']),
jsxAttributeValue(generatedUID, emptyComments),
)
// TODO BALAZS should this be here? or should the arbitrary block never have a template path with that last generated element?
const elementPathWithoutTheLastElementBecauseThatsAWeirdGeneratedUID = optionalMap(
EP.parentPath,
elementPath,
)
const innerPath = optionalMap(
(path) => EP.appendToPath(path, generatedUID),
elementPathWithoutTheLastElementBecauseThatsAWeirdGeneratedUID,
)
let augmentedInnerElement = element
forEachRight(withGeneratedUID, (attrs) => {
augmentedInnerElement = {
...augmentedInnerElement,
props: attrs,
}
})
return renderCoreElement(
augmentedInnerElement,
innerPath,
rootScope,
scope,
parentComponentInputProps,
requireResult,
hiddenInstances,
fileBlobs,
validPaths,
generatedUID,
reactChildren,
metadataContext,
updateInvalidatedPaths,
jsxFactoryFunctionName,
null,
shouldIncludeCanvasRootInTheSpy,
filePath,
imports,
code,
highlightBounds,
)
}
}
function monkeyUidProp(uid: string | undefined, propsToUpdate: MapLike<any>): MapLike<any> {
let monkeyedProps: MapLike<any> = {
...propsToUpdate,
}
const uidsFromProps = monkeyedProps[UTOPIA_UIDS_KEY]
const uidsToPass = appendToUidString(uidsFromProps, uid)
monkeyedProps[UTOPIA_UIDS_KEY] = uidsToPass
return monkeyedProps
}
function NoOpLookupRender(element: JSXElement, scope: MapLike<any>): React.ReactChild {
throw new Error(
`Utopia Error: createLookupRender was not used properly for element: ${element.name.baseVariable}`,
)
}
export function renderCoreElement(
element: JSXElementChild,
elementPath: ElementPath | null,
rootScope: MapLike<any>,
inScope: MapLike<any>,
parentComponentInputProps: MapLike<any>,
requireResult: MapLike<any>,
hiddenInstances: Array<ElementPath>,
fileBlobs: UIFileBase64Blobs,
validPaths: Array<ElementPath>,
uid: string | undefined,
reactChildren: React.ReactNode | undefined,
metadataContext: UiJsxCanvasContextData,
updateInvalidatedPaths: DomWalkerInvalidatePathsCtxData,
jsxFactoryFunctionName: string | null,
codeError: Error | null,
shouldIncludeCanvasRootInTheSpy: boolean,
filePath: string,
imports: Imports,
code: string,
highlightBounds: HighlightBoundsForUids | null,
): React.ReactChild {
if (codeError != null) {
throw codeError
}
switch (element.type) {
case 'JSX_ELEMENT': {
const elementsWithinProps = getAccumulatedElementsWithin(element.props)
const anyElementsWithin = Object.keys(elementsWithinProps).length > 0
const innerRender = anyElementsWithin
? createLookupRender(
elementPath,
rootScope,
parentComponentInputProps,
requireResult,
hiddenInstances,
fileBlobs,
validPaths,
reactChildren,
metadataContext,
updateInvalidatedPaths,
jsxFactoryFunctionName,
shouldIncludeCanvasRootInTheSpy,
filePath,
imports,
code,
highlightBounds,
)
: NoOpLookupRender
const blockScope = anyElementsWithin
? {
...inScope,
[JSX_CANVAS_LOOKUP_FUNCTION_NAME]: utopiaCanvasJSXLookup(
elementsWithinProps,
inScope,
innerRender,
),
}
: inScope
const assembledProps = jsxAttributesToProps(
filePath,
blockScope,
element.props,
requireResult,
)
const passthroughProps = monkeyUidProp(uid, assembledProps)
const key = optionalMap(EP.toString, elementPath) ?? passthroughProps[UTOPIA_UIDS_KEY]
return renderJSXElement(
key,
element,
elementPath,
parentComponentInputProps,
requireResult,
rootScope,
inScope,
hiddenInstances,
fileBlobs,
validPaths,
passthroughProps,
metadataContext,
updateInvalidatedPaths,
jsxFactoryFunctionName,
null,
shouldIncludeCanvasRootInTheSpy,
filePath,
imports,
code,
highlightBounds,
)
}
case 'JSX_ARBITRARY_BLOCK': {
const innerRender = createLookupRender(
elementPath,
rootScope,
parentComponentInputProps,
requireResult,
hiddenInstances,
fileBlobs,
validPaths,
reactChildren,
metadataContext,
updateInvalidatedPaths,
jsxFactoryFunctionName,
shouldIncludeCanvasRootInTheSpy,
filePath,
imports,
code,
highlightBounds,
)
const blockScope = {
...inScope,
[JSX_CANVAS_LOOKUP_FUNCTION_NAME]: utopiaCanvasJSXLookup(
element.elementsWithin,
inScope,
innerRender,
),
}
return runJSXArbitraryBlock(filePath, requireResult, element, blockScope)
}
case 'JSX_FRAGMENT': {
let renderedChildren: Array<React.ReactChild> = []
fastForEach(element.children, (child) => {
const childPath = optionalMap(
(path) => EP.appendToPath(EP.parentPath(path), getUtopiaID(child)),
elementPath,
)
const renderResult = renderCoreElement(
child,
childPath,
rootScope,
inScope,
parentComponentInputProps,
requireResult,
hiddenInstances,
fileBlobs,
validPaths,
uid,
reactChildren,
metadataContext,
updateInvalidatedPaths,
jsxFactoryFunctionName,
codeError,
shouldIncludeCanvasRootInTheSpy,
filePath,
imports,
code,
highlightBounds,
)
renderedChildren.push(renderResult)
})
return <>{renderedChildren}</>
}
case 'JSX_TEXT_BLOCK': {
return element.text
}
default:
const _exhaustiveCheck: never = element
throw new Error(`Unhandled type ${JSON.stringify(element)}`)
}
}
function renderJSXElement(
key: string,
jsx: JSXElement,
elementPath: ElementPath | null,
parentComponentInputProps: MapLike<any>,
requireResult: MapLike<any>,
rootScope: MapLike<any>,
inScope: MapLike<any>,
hiddenInstances: Array<ElementPath>,
fileBlobs: UIFileBase64Blobs,
validPaths: Array<ElementPath>,
passthroughProps: MapLike<any>,
metadataContext: UiJsxCanvasContextData,
updateInvalidatedPaths: DomWalkerInvalidatePathsCtxData,
jsxFactoryFunctionName: string | null,
codeError: Error | null,
shouldIncludeCanvasRootInTheSpy: boolean,
filePath: string,
imports: Imports,
code: string,
highlightBounds: HighlightBoundsForUids | null,
): React.ReactElement {
let elementProps = { key: key, ...passthroughProps }
if (isHidden(hiddenInstances, elementPath)) {
elementProps = hideElement(elementProps)
}
elementProps = streamlineInFileBlobs(elementProps, fileBlobs)
const createChildrenElement = (child: JSXElementChild): React.ReactChild => {
const childPath = optionalMap((path) => EP.appendToPath(path, getUtopiaID(child)), elementPath)
return renderCoreElement(
child,
childPath,
rootScope,
inScope,
parentComponentInputProps,
requireResult,
hiddenInstances,
fileBlobs,
validPaths,
undefined,
undefined,
metadataContext,
updateInvalidatedPaths,
jsxFactoryFunctionName,
codeError,
shouldIncludeCanvasRootInTheSpy,
filePath,
imports,
code,
highlightBounds,
)
}
const childrenElements = jsx.children.map(createChildrenElement)
const elementIsIntrinsic = isIntrinsicElement(jsx.name)
const elementIsBaseHTML = elementIsIntrinsic && isIntrinsicHTMLElement(jsx.name)
const elementInScope = elementIsIntrinsic ? null : getElementFromScope(jsx, inScope)
const elementFromImport = elementIsIntrinsic ? null : getElementFromScope(jsx, requireResult)
const elementFromScopeOrImport = Utils.defaultIfNull(elementFromImport, elementInScope)
// Not necessary to check the top level elements, as we'll use a comparison of the
// elements from scope and import to confirm it's not a top level element.
const importedFrom = importedFromWhere(filePath, jsx.name.baseVariable, [], imports)
const elementIsScene =
!elementIsIntrinsic &&
importedFrom != null &&
importedFrom.type === 'IMPORTED_ORIGIN' && // Imported and not from the same file.
importedFrom.filePath === 'utopia-api' && // Originating from `utopia-api`
importedFrom.exportedName === 'Scene' && // `Scene` component.
elementFromImport === elementInScope // Ensures this is not a user defined component with the same name.
const elementOrScene = elementIsScene ? SceneComponent : elementFromScopeOrImport
const FinalElement = elementIsIntrinsic ? jsx.name.baseVariable : elementOrScene
const elementPropsWithScenePath = isComponentRendererComponent(FinalElement)
? { ...elementProps, [UTOPIA_INSTANCE_PATH]: elementPath }
: elementProps
const elementPropsWithSceneID =
elementIsScene && elementPath != null
? { ...elementPropsWithScenePath, [UTOPIA_SCENE_ID_KEY]: EP.toString(elementPath) }
: elementPropsWithScenePath
const finalProps =
elementIsIntrinsic && !elementIsBaseHTML
? filterDataProps(elementPropsWithSceneID)
: elementPropsWithSceneID
const finalPropsIcludingElementPath = {
...finalProps,
[UTOPIA_PATHS_KEY]: optionalMap(EP.toString, elementPath),
}
const staticElementPathForGeneratedElement = optionalMap(EP.makeLastPartOfPathStatic, elementPath)
const staticValidPaths = validPaths.map(EP.makeLastPartOfPathStatic)
if (FinalElement == null) {
throw canvasMissingJSXElementError(jsxFactoryFunctionName, code, jsx, filePath, highlightBounds)
}
if (
elementPath != null &&
EP.containsPath(staticElementPathForGeneratedElement, staticValidPaths)
) {
return buildSpyWrappedElement(
jsx,
finalPropsIcludingElementPath,
elementPath,
metadataContext,
updateInvalidatedPaths,
childrenElements,
FinalElement,
inScope,
jsxFactoryFunctionName,
shouldIncludeCanvasRootInTheSpy,
imports,
)
} else {
return renderComponentUsingJsxFactoryFunction(
inScope,
jsxFactoryFunctionName,
FinalElement,
finalPropsIcludingElementPath,
...childrenElements,
)
}
}
function isHidden(hiddenInstances: ElementPath[], elementPath: ElementPath | null): boolean {
return elementPath != null && hiddenInstances.some((path) => EP.pathsEqual(path, elementPath))
}
function hideElement(props: any): any {
const styleProps = Utils.propOr({}, 'style', props as any)
return {
...props,
style: {
...styleProps,
visibility: 'hidden',
},
} as any
}
export function utopiaCanvasJSXLookup(
elementsWithin: ElementsWithin,
executionScope: MapLike<any>,
render: (element: JSXElement, inScope: MapLike<any>) => React.ReactChild,
): (uid: string, inScope: MapLike<any>) => React.ReactChild | null {
return (uid, inScope) => {
const element = elementsWithin[uid]
if (element == null) {
return null
} else {
const combinedScope = { ...executionScope, ...inScope }
return render(element, combinedScope)
}
}
}
function runJSXArbitraryBlock(
filePath: string,
requireResult: MapLike<any>,
block: JSXArbitraryBlock,
currentScope: MapLike<any>,
): any {
return resolveParamsAndRunJsCode(filePath, block, requireResult, currentScope)
}
function getElementFromScope(jsxElementToLookup: JSXElement, scope: MapLike<any> | null): any {
if (scope == null) {
return undefined
} else {
if (jsxElementToLookup.name.baseVariable in scope) {
const fromVar = scope[jsxElementToLookup.name.baseVariable]
const result = Utils.pathOr(
undefined,
PP.getElements(jsxElementToLookup.name.propertyPath),
fromVar,
)
return result
} else {
return undefined
}
}
}
export function renderComponentUsingJsxFactoryFunction(
inScope: MapLike<any>,
factoryFunctionName: string | null,
type: any,
props: any,
...children: Array<any>
): any {
const fixedProps = fixStyleObjectRemoveCommentOnlyValues(props)
let factoryFunction = React.createElement
if (factoryFunctionName != null) {
if (factoryFunctionName in inScope) {
if (
inScope[factoryFunctionName] != null &&
typeof inScope[factoryFunctionName] === 'function'
) {
factoryFunction = inScope[factoryFunctionName]
} else {
// TODO add StackFrame!
throw new Error(`Factory function ${factoryFunctionName} is undefined or not a function.`)
}
} else {
// TODO add StackFrame!
throw new Error(`Unable to find factory function ${factoryFunctionName} in scope.`)
}
}
return factoryFunction.call(null, type, fixedProps, ...children)
}
function fixStyleObjectRemoveCommentOnlyValues(props: Readonly<unknown>): any {
if (typeof props === 'object' && 'style' in props && (props as any)['style'] != null) {
const propsAsAny = props as any
const style = propsAsAny.style
const fixedStyle: any = objectMap((styleProp) => {
if (typeof styleProp === 'string' && cssValueOnlyContainsComments(styleProp)) {
/**
* see https://github.com/facebook/react/issues/19477
* our problem: we store the disabled style values as commented out,
* and we allow a style prop to only contain commented out values.
*
* This is fine if you render something from scratch, so this will never be an issue for our users.
*
* But in the case of the canvas, when you change the value from _something_ to _only comments_,
* we expect the DOM API to clear out the previous value. The real behavior however is to ignore the comments-only new value,
* and keep the old value alive.
*
* Solution: we explicitly mange the style prop such that if a property only contains comments, we replace it with a `null`,
* which the DOM API will treat as "remove existing value" as expected.
*
* Example: { backgroundColor: '\/*red*\/ \/*green*\/' } should disable the backgroundColor, so we will
* replace it with { backgroundColor: null } in the Canvas.
*/
return null
} else {
return styleProp
}
}, style)
return {
...propsAsAny,
style: fixedStyle,
}
} else {
// no style props, just return the props object without mangling
return props
}
}
function streamlineInFileBlobs(props: any, fileBlobs: UIFileBase64Blobs): any {
if (typeof props === 'object' && !Array.isArray(props) && props !== null) {
const elementID = props['data-uid']
if (elementID in fileBlobs) {
return {
...props,
src: `data:;base64,${fileBlobs[elementID].base64}`,
}
} else {
return props
}
} else {
return props
}
} | the_stack |
import { Command } from 'commander';
import { web3Provider } from './utils';
import { BigNumber } from 'ethers';
import { ethers } from 'ethers';
import * as hre from 'hardhat';
const provider = web3Provider();
const cache: Map<BigNumber, string> = new Map<BigNumber, string>();
async function getStorageAt(address: string, slot: BigNumber): Promise<string> {
if (!cache.has(slot)) {
cache.set(slot, await provider.getStorageAt(address, slot));
}
return cache.get(slot);
}
// Read bytes from storage like hex string
async function readBytes(slot: BigNumber, shift: number, bytes: number, address: string): Promise<string> {
const data = await getStorageAt(address, slot);
return '0x' + data.substr(66 - bytes * 2 - shift * 2, bytes * 2);
}
// Read dynamic sized bytes (encoding: bytes)
async function readDynamicBytes(slot: BigNumber, address: string): Promise<string> {
const data = await getStorageAt(address, slot);
if (Number.parseInt(data.substr(64, 2), 16) % 2 === 0) {
const length = Number.parseInt(data.substr(64, 2), 16) / 2;
return '0x' + data.substr(2, 2 * length);
} else {
const length = (Number.parseInt(data, 16) - 1) / 2;
const firstSlot = BigNumber.from(ethers.utils.solidityKeccak256(['uint'], [slot]));
const slots = [];
for (let slotShift = 0; slotShift * 32 < length; slotShift++) {
slots.push(getStorageAt(address, firstSlot.add(slotShift)));
}
const lastLength = length % 32;
let hex: string = '0x';
for (let i = 0; i < slots.length; i++) {
if (i === slots.length - 1) {
hex += (await slots[i]).substr(2, lastLength * 2);
} else {
hex += (await slots[i]).substr(2, 64);
}
}
return hex;
}
}
// Functions for read all types, except user defined structs and arrays
async function readString(slot: BigNumber, address: string): Promise<string> {
return ethers.utils.toUtf8String(await readDynamicBytes(slot, address));
}
async function readNumber(slot: BigNumber, shift: number, label: string, address: string): Promise<string> {
let bytes: number;
if (label.substr(0, 3) === 'int') {
bytes = +label.substring(3, label.length) / 8;
} else {
bytes = +label.substring(4, label.length) / 8;
}
let data: string = await readBytes(slot, shift, bytes, address);
data = ethers.utils.hexZeroPad(data, 32);
return ethers.utils.defaultAbiCoder.decode([label], data).toString();
}
async function readBoolean(slot: BigNumber, shift: number, address: string): Promise<boolean> {
return (await readNumber(slot, shift, 'uint8', address)) !== '0';
}
async function readAddress(slot: BigNumber, shift: number, address: string): Promise<string> {
return readBytes(slot, shift, 20, address);
}
async function readEnum(slot: BigNumber, shift: number, bytes: number, address: string): Promise<string> {
return await readNumber(slot, shift, 'uint' + bytes * 8, address);
}
let types: any;
async function readPrimitive(slot: BigNumber, shift: number, address: string, type: string): Promise<any> {
if (type.substr(0, 5) === 't_int' || type.substr(0, 6) === 't_uint') {
return readNumber(slot, shift, types[type].label, address);
}
if (type === 't_bool') {
return readBoolean(slot, shift, address);
}
if (type === 't_address' || type === 't_address_payable') {
return readAddress(slot, shift, address);
}
if (type === 't_bytes_storage') {
return readDynamicBytes(slot, address);
}
if (type.substr(0, 7) === 't_bytes') {
return readBytes(slot, shift, types[type].numberOfBytes, address);
}
if (type === 't_string_storage') {
return readString(slot, address);
}
if (type.substr(0, 6) === 't_enum') {
return readEnum(slot, shift, types[type].numberOfBytes, address);
}
}
// Read user defined struct
async function readStruct(slot: BigNumber, address: string, type: string): Promise<object> {
const result = {};
const data = new Map();
types[type].members.forEach((member) => {
data.set(
member.label,
readVariable(slot.add(Number.parseInt(member.slot, 10)), member.offset, address, member.type)
);
});
for (const [key, value] of data) {
result[key] = await value;
}
return result;
}
// Read array (Static or dynamic sized)
async function readArray(slot: BigNumber, address: string, type: string): Promise<any[]> {
let length: number;
const baseType = types[type].base;
if (types[type].encoding === 'dynamic_array') {
length = +(await readNumber(slot, 0, 'uint256', address));
slot = BigNumber.from(ethers.utils.solidityKeccak256(['uint'], [slot]));
} else {
length = Number.parseInt(type.substring(type.lastIndexOf(')') + 1, type.lastIndexOf('_')), 10);
}
const baseBytes = +types[baseType].numberOfBytes;
const data = [];
if (baseBytes < 32) {
let shift: number = -baseBytes;
for (let i = 0; i < length; i++) {
shift += baseBytes;
if (shift + baseBytes > 32) {
shift = 0;
slot = slot.add(1);
}
data.push(readVariable(slot, shift, address, baseType));
}
} else {
for (let i = 0; i < length; i++) {
data.push(readVariable(slot, 0, address, baseType));
slot = slot.add(baseBytes / 32);
}
}
return Promise.all(data);
}
// Read any type, except mapping (it needs key for reading)
async function readVariable(slot: BigNumber, shift: number, address: string, type: string): Promise<any> {
if (type.substr(0, 7) === 't_array') return readArray(slot, address, type);
if (type.substr(0, 8) === 't_struct') return readStruct(slot, address, type);
return readPrimitive(slot, shift, address, type);
}
// Read field of struct
async function readPartOfStruct(slot: BigNumber, address: string, type: string, params: string[]): Promise<any> {
const last = params.pop();
const member = types[type].members.find((element) => {
return element.label === last;
});
if (!member) throw new Error('Invalid field name of struct');
return readPartOfVariable(slot.add(Number.parseInt(member.slot, 10)), member.offset, address, member.type, params);
}
// Read array element by index
async function readPartOfArray(slot: BigNumber, address: string, type: string, params: string[]): Promise<any> {
const index = +params.pop();
const baseType = types[type].base;
if (types[type].encoding === 'dynamic_array') {
slot = BigNumber.from(ethers.utils.solidityKeccak256(['uint'], [slot]));
}
const baseBytes = +types[baseType].numberOfBytes;
if (baseBytes < 32) {
const inOne = Math.floor(32 / baseBytes);
slot = slot.add(Math.floor(index / inOne));
const shift = baseBytes * (index % inOne);
return readPartOfVariable(slot, shift, address, baseType, params);
} else {
slot = slot.add((index * baseBytes) / 32);
return readPartOfVariable(slot, 0, address, baseType, params);
}
}
// Encode key for mapping type
function encodeKey(key: string, type: string): string {
if (type === 't_bool') {
if (key === 'false' || key === '0') {
return ethers.utils.defaultAbiCoder.encode(['bool'], [false]);
} else {
return ethers.utils.defaultAbiCoder.encode(['bool'], [true]);
}
}
if (type === 't_address' || type === 't_address_payable') {
if (key.length === 42) {
return '0x' + key.substring(2, key.length).padStart(64, '0');
} else {
return '0x' + key.padStart(64, '0');
}
}
if (type === 't_string_memory_ptr') {
return ethers.utils.hexlify(ethers.utils.toUtf8Bytes(key));
}
if (type === 't_bytes_memory_ptr') {
if (key.substr(0, 2) === '0x') {
return key;
} else {
return '0x' + key;
}
}
return ethers.utils.defaultAbiCoder.encode([types[type].label], [+key]);
}
// Read mapping element by key
async function readPartOfMap(slot: BigNumber, address: string, type: string, params: string[]): Promise<any> {
const key = params.pop();
const valueType = types[type].value;
const keyType = types[type].key;
const encodedKey = encodeKey(key, keyType);
const encodedSlot = ethers.utils.defaultAbiCoder.encode(['uint'], [slot]);
const hex = encodedKey + encodedSlot.substring(2, encodedSlot.length);
slot = BigNumber.from(ethers.utils.keccak256(ethers.utils.arrayify(hex)));
return readPartOfVariable(slot, 0, address, valueType, params);
}
// Read part of variable (By indexes, field names, keys)
async function readPartOfVariable(
slot: BigNumber,
shift: number,
address: string,
type: string,
params: string[]
): Promise<any> {
if (params.length === 0) {
return readVariable(slot, shift, address, type);
}
if (type.substr(0, 7) === 't_array') {
return readPartOfArray(slot, address, type, params);
}
if (type.substr(0, 8) === 't_struct') {
return readPartOfStruct(slot, address, type, params);
}
if (types[type].encoding === 'mapping') {
return readPartOfMap(slot, address, type, params);
}
return readPrimitive(slot, shift, address, type);
}
// Get reverse array of indexes, struct fields and mapping keys from name
// Field names, keys cannot contain square brackets or points
function parseName(fullName: string): string[] {
const firstPoint = fullName.indexOf('.');
const firstBracket = fullName.indexOf('[');
if (firstPoint === -1 && firstBracket === -1) {
return [];
}
const result = [];
let first: number;
if (firstPoint === -1) {
first = firstBracket;
} else if (firstBracket === -1) {
first = firstPoint;
} else {
first = Math.min(firstPoint, firstBracket);
}
let str: string = '';
let bracket: boolean = false;
for (let i = first; i < fullName.length; i++) {
if (fullName.charAt(i) === '.') {
if (bracket) {
throw new Error('Field names, keys cannot contain square brackets or points');
}
if (i !== first) result.push(str);
str = '';
} else if (fullName.charAt(i) === '[') {
if (bracket) {
throw new Error('Field names, keys cannot contain square brackets or points');
}
bracket = true;
if (i !== first) result.push(str);
str = '';
} else if (fullName.charAt(i) === ']') {
if (!bracket) {
throw new Error('Field names, keys cannot contain square brackets or points');
}
bracket = false;
} else {
str += fullName.charAt(i);
}
}
if (bracket) {
throw new Error('Invalid name');
}
result.push(str);
return result.reverse();
}
// Get variableName (Without indexes, fields, keys)
function getVariableName(fullName: string): string {
let variableName: string = fullName;
if (variableName.indexOf('[') !== -1) {
variableName = variableName.substr(0, variableName.indexOf('['));
}
if (variableName.indexOf('.') !== -1) {
variableName = variableName.substr(0, variableName.indexOf('.'));
}
return variableName;
}
async function getValue(address: string, contractName: string, name: string): Promise<any> {
// Mapping from Contract name to fully qualified name known to hardhat
// e.g ZkSync => cache/solpp-generated-contracts/ZkSync.sol
const contractMap = {};
const allContracts = await hre.artifacts.getAllFullyQualifiedNames();
allContracts.forEach((fullName) => {
const [file, contract] = fullName.split(':');
contractMap[contract] = {
fullName,
file
};
});
if (!(contractName in contractMap)) {
throw new Error(`Unknown contract name, available contracts: ${Object.keys(contractMap)}`);
}
const buildInfo = await hre.artifacts.getBuildInfo(contractMap[contractName].fullName);
// @ts-ignore
const layout = buildInfo.output.contracts[contractMap[contractName].file][contractName].storageLayout;
types = layout.types;
const storage = layout.storage;
const variableName = getVariableName(name);
const params = parseName(name);
let variable: any;
storage.forEach((node) => {
if (node.label === variableName) variable = node;
});
if (!variable) {
throw new Error('Invalid name');
}
return readPartOfVariable(BigNumber.from(variable.slot), variable.offset, address, variable.type, params);
}
async function main() {
const program = new Command();
program.version('0.1.0').name('read-variable').description('returns value of private and public variables');
program
.command('read <address> <contractName> <variableName>')
.option('-f, --file <file>')
.description('Reads value of variable')
.action(async (address: string, contractName: string, variableName: string) => {
console.log(JSON.stringify(await getValue(address, contractName, variableName), null, 4));
});
await program.parseAsync(process.argv);
}
main()
.then(() => process.exit(0))
.catch((err) => {
console.error('Error:', err.message || err);
process.exit(1);
}); | the_stack |
import {
Counter,
ObservableResult,
ObservableCounter,
ObservableUpDownCounter,
ObservableGauge,
Histogram,
ValueType,
} from '@opentelemetry/api-metrics';
import { InstrumentationLibrary, VERSION } from '@opentelemetry/core';
import * as metrics from '@opentelemetry/sdk-metrics-base';
import { Resource } from '@opentelemetry/resources';
import * as assert from 'assert';
import { otlpTypes } from '@opentelemetry/exporter-trace-otlp-http';
const meterProvider = new metrics.MeterProvider({
interval: 30000,
resource: new Resource({
service: 'ui',
version: 1,
cost: 112.12,
}),
});
const meter = meterProvider.getMeter('default', '0.0.1');
if (typeof Buffer === 'undefined') {
(window as any).Buffer = {
from: function (arr: []) {
return new Uint8Array(arr);
},
};
}
export function mockCounter(): metrics.Metric<metrics.BoundCounter> & Counter {
const name = 'int-counter';
const metric =
meter['_metrics'].get(name) ||
meter.createCounter(name, {
description: 'sample counter description',
valueType: ValueType.INT,
});
metric.clear();
metric.bind({});
return metric;
}
export function mockDoubleCounter(): metrics.Metric<metrics.BoundCounter> &
Counter {
const name = 'double-counter';
const metric =
meter['_metrics'].get(name) ||
meter.createCounter(name, {
description: 'sample counter description',
valueType: ValueType.DOUBLE,
});
metric.clear();
metric.bind({});
return metric;
}
export function mockObservableGauge(
callback: (observableResult: ObservableResult) => unknown,
name = 'double-observable-gauge'
): metrics.Metric<metrics.BoundObservable> & ObservableGauge {
const metric =
meter['_metrics'].get(name) ||
meter.createObservableGauge(
name,
{
description: 'sample observable gauge description',
valueType: ValueType.DOUBLE,
},
callback
);
metric.clear();
metric.bind({});
return metric;
}
export function mockObservableCounter(
callback: (observableResult: ObservableResult) => unknown,
name = 'double-observable-counter'
): metrics.Metric<metrics.BoundObservable> & ObservableCounter {
const metric =
meter['_metrics'].get(name) ||
meter.createObservableCounter(
name,
{
description: 'sample observable counter description',
valueType: ValueType.DOUBLE,
},
callback
);
metric.clear();
metric.bind({});
return metric;
}
export function mockObservableUpDownCounter(
callback: (observableResult: ObservableResult) => unknown,
name = 'double-up-down-observable-counter'
): metrics.Metric<metrics.BoundObservable> & ObservableUpDownCounter {
const metric =
meter['_metrics'].get(name) ||
meter.createObservableUpDownCounter(
name,
{
description: 'sample observable up down counter description',
valueType: ValueType.DOUBLE,
},
callback
);
metric.clear();
metric.bind({});
return metric;
}
export function mockHistogram(): metrics.Metric<metrics.BoundHistogram> &
Histogram {
const name = 'int-histogram';
const metric =
meter['_metrics'].get(name) ||
meter.createHistogram(name, {
description: 'sample histogram description',
valueType: ValueType.INT,
boundaries: [0, 100],
});
metric.clear();
metric.bind({});
return metric;
}
export const mockedResources: Resource[] = [
new Resource({ name: 'resource 1' }),
new Resource({ name: 'resource 2' }),
];
export const mockedInstrumentationLibraries: InstrumentationLibrary[] = [
{
name: 'lib1',
version: '0.0.1',
},
{
name: 'lib2',
version: '0.0.2',
},
];
export const multiResourceMetricsGet = function (
callback: (observableResult: ObservableResult) => unknown
): any[] {
return [
{
...mockCounter(),
resource: mockedResources[0],
instrumentationLibrary: mockedInstrumentationLibraries[0],
},
{
...mockObservableGauge(callback),
resource: mockedResources[1],
instrumentationLibrary: mockedInstrumentationLibraries[0],
},
{
...mockCounter(),
resource: mockedResources[0],
instrumentationLibrary: mockedInstrumentationLibraries[0],
},
];
};
export const multiInstrumentationLibraryMetricsGet = function (
callback: (observableResult: ObservableResult) => unknown
): any[] {
return [
{
...mockCounter(),
resource: mockedResources[0],
instrumentationLibrary: mockedInstrumentationLibraries[0],
},
{
...mockObservableGauge(callback),
resource: mockedResources[0],
instrumentationLibrary: mockedInstrumentationLibraries[1],
},
{
...mockCounter(),
resource: mockedResources[0],
instrumentationLibrary: mockedInstrumentationLibraries[0],
},
];
};
export function ensureAttributesAreCorrect(
attributes: otlpTypes.opentelemetryProto.common.v1.KeyValue[]
) {
assert.deepStrictEqual(
attributes,
[
{
key: 'component',
value: {
stringValue: 'document-load',
},
},
],
'attributes are incorrect'
);
}
export function ensureWebResourceIsCorrect(
resource: otlpTypes.opentelemetryProto.resource.v1.Resource
) {
assert.strictEqual(resource.attributes.length, 7);
assert.strictEqual(resource.attributes[0].key, 'service.name');
assert.strictEqual(resource.attributes[0].value.stringValue, 'unknown_service');
assert.strictEqual(resource.attributes[1].key, 'telemetry.sdk.language');
assert.strictEqual(resource.attributes[1].value.stringValue, 'webjs');
assert.strictEqual(resource.attributes[2].key, 'telemetry.sdk.name');
assert.strictEqual(resource.attributes[2].value.stringValue, 'opentelemetry');
assert.strictEqual(resource.attributes[3].key, 'telemetry.sdk.version');
assert.strictEqual(resource.attributes[3].value.stringValue, VERSION);
assert.strictEqual(resource.attributes[4].key, 'service');
assert.strictEqual(resource.attributes[4].value.stringValue, 'ui');
assert.strictEqual(resource.attributes[5].key, 'version');
assert.strictEqual(resource.attributes[5].value.intValue, 1);
assert.strictEqual(resource.attributes[6].key, 'cost');
assert.strictEqual(resource.attributes[6].value.doubleValue, 112.12);
assert.strictEqual(resource.droppedAttributesCount, 0);
}
export function ensureCounterIsCorrect(
metric: otlpTypes.opentelemetryProto.metrics.v1.Metric,
time: number
) {
assert.deepStrictEqual(metric, {
name: 'int-counter',
description: 'sample counter description',
unit: '1',
intSum: {
dataPoints: [
{
labels: [],
value: 1,
startTimeUnixNano: 1592602232694000000,
timeUnixNano: time,
},
],
isMonotonic: true,
aggregationTemporality:
otlpTypes.opentelemetryProto.metrics.v1.AggregationTemporality
.AGGREGATION_TEMPORALITY_CUMULATIVE,
},
});
}
export function ensureDoubleCounterIsCorrect(
metric: otlpTypes.opentelemetryProto.metrics.v1.Metric,
time: number
) {
assert.deepStrictEqual(metric, {
name: 'double-counter',
description: 'sample counter description',
unit: '1',
doubleSum: {
dataPoints: [
{
labels: [],
value: 8,
startTimeUnixNano: 1592602232694000000,
timeUnixNano: time,
},
],
isMonotonic: true,
aggregationTemporality:
otlpTypes.opentelemetryProto.metrics.v1.AggregationTemporality
.AGGREGATION_TEMPORALITY_CUMULATIVE,
},
});
}
export function ensureObservableGaugeIsCorrect(
metric: otlpTypes.opentelemetryProto.metrics.v1.Metric,
time: number,
value: number,
name = 'double-observable-gauge'
) {
assert.deepStrictEqual(metric, {
name,
description: 'sample observable gauge description',
unit: '1',
doubleGauge: {
dataPoints: [
{
labels: [],
value,
startTimeUnixNano: 1592602232694000000,
timeUnixNano: time,
},
],
},
});
}
export function ensureObservableCounterIsCorrect(
metric: otlpTypes.opentelemetryProto.metrics.v1.Metric,
time: number,
value: number,
name = 'double-observable-counter'
) {
assert.deepStrictEqual(metric, {
name,
description: 'sample observable counter description',
unit: '1',
doubleSum: {
isMonotonic: true,
dataPoints: [
{
labels: [],
value,
startTimeUnixNano: 1592602232694000000,
timeUnixNano: time,
},
],
aggregationTemporality:
otlpTypes.opentelemetryProto.metrics.v1.AggregationTemporality
.AGGREGATION_TEMPORALITY_CUMULATIVE,
},
});
}
export function ensureObservableUpDownCounterIsCorrect(
metric: otlpTypes.opentelemetryProto.metrics.v1.Metric,
time: number,
value: number,
name = 'double-up-down-observable-counter'
) {
assert.deepStrictEqual(metric, {
name,
description: 'sample observable up down counter description',
unit: '1',
doubleSum: {
isMonotonic: false,
dataPoints: [
{
labels: [],
value,
startTimeUnixNano: 1592602232694000000,
timeUnixNano: time,
},
],
aggregationTemporality:
otlpTypes.opentelemetryProto.metrics.v1.AggregationTemporality
.AGGREGATION_TEMPORALITY_CUMULATIVE,
},
});
}
export function ensureHistogramIsCorrect(
metric: otlpTypes.opentelemetryProto.metrics.v1.Metric,
time: number,
explicitBounds: (number | null)[] = [Infinity],
bucketCounts: number[] = [2, 0]
) {
assert.deepStrictEqual(metric, {
name: 'int-histogram',
description: 'sample histogram description',
unit: '1',
intHistogram: {
dataPoints: [
{
labels: [],
sum: 21,
count: 2,
startTimeUnixNano: 1592602232694000000,
timeUnixNano: time,
bucketCounts,
explicitBounds,
},
],
aggregationTemporality:
otlpTypes.opentelemetryProto.metrics.v1.AggregationTemporality
.AGGREGATION_TEMPORALITY_CUMULATIVE,
},
});
}
export function ensureExportMetricsServiceRequestIsSet(
json: otlpTypes.opentelemetryProto.collector.metrics.v1.ExportMetricsServiceRequest
) {
const resourceMetrics = json.resourceMetrics;
assert.strictEqual(
resourceMetrics.length,
1,
'resourceMetrics has incorrect length'
);
const resource = resourceMetrics[0].resource;
assert.strictEqual(!!resource, true, 'resource is missing');
const instrumentationLibraryMetrics =
resourceMetrics[0].instrumentationLibraryMetrics;
assert.strictEqual(
instrumentationLibraryMetrics && instrumentationLibraryMetrics.length,
1,
'instrumentationLibraryMetrics is missing'
);
const instrumentationLibrary =
instrumentationLibraryMetrics[0].instrumentationLibrary;
assert.strictEqual(
!!instrumentationLibrary,
true,
'instrumentationLibrary is missing'
);
const metrics = resourceMetrics[0].instrumentationLibraryMetrics[0].metrics;
assert.strictEqual(metrics.length, 3, 'Metrics are missing');
}
export function ensureHeadersContain(
actual: { [key: string]: string },
expected: { [key: string]: string }
) {
Object.entries(expected).forEach(([k, v]) => {
assert.strictEqual(
v,
actual[k],
`Expected ${actual} to contain ${k}: ${v}`
);
});
} | the_stack |
import { HttpClient, HttpHeaders, HttpParams, HttpResponse, HttpEvent } from '@angular/common/http';
import { Inject, Injectable, InjectionToken, Optional } from '@angular/core';
import { APIClientInterface } from './api-client.interface';
import { Observable } from 'rxjs';import { DefaultHttpOptions, HttpOptions } from './types';
import * as models from './models';
export const USE_DOMAIN = new InjectionToken<string>('APIClient_USE_DOMAIN');
export const USE_HTTP_OPTIONS = new InjectionToken<HttpOptions>('APIClient_USE_HTTP_OPTIONS');
type APIHttpOptions = HttpOptions & {
headers: HttpHeaders;
params: HttpParams;
};
@Injectable()
export class APIClient implements APIClientInterface {
readonly options: APIHttpOptions;
readonly domain: string = `https://petstore.swagger.io/v2`;
constructor(
private readonly http: HttpClient,
@Optional() @Inject(USE_DOMAIN) domain?: string,
@Optional() @Inject(USE_HTTP_OPTIONS) options?: DefaultHttpOptions,
) {
if (domain != null) {
this.domain = domain;
}
this.options = {
headers: new HttpHeaders(options && options.headers ? options.headers : {}),
params: new HttpParams(options && options.params ? options.params : {}),
...(options && options.reportProgress ? { reportProgress: options.reportProgress } : {}),
...(options && options.withCredentials ? { withCredentials: options.withCredentials } : {})
};
}
/**
* Find pet by ID
* Returns a single pet
* Response generated for [ 200 ] HTTP response code.
*/
getPetById(
args: Exclude<APIClientInterface['getPetByIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Pet>;
getPetById(
args: Exclude<APIClientInterface['getPetByIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Pet>>;
getPetById(
args: Exclude<APIClientInterface['getPetByIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Pet>>;
getPetById(
args: Exclude<APIClientInterface['getPetByIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Pet | HttpResponse<models.Pet> | HttpEvent<models.Pet>> {
const path = `/pet/${args.petId}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
return this.http.get<models.Pet>(`${this.domain}${path}`, options);
}
/**
* Updates a pet in the store with form data
* Response generated for [ default ] HTTP response code.
*/
updatePetWithForm(
args: Exclude<APIClientInterface['updatePetWithFormParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
updatePetWithForm(
args: Exclude<APIClientInterface['updatePetWithFormParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
updatePetWithForm(
args: Exclude<APIClientInterface['updatePetWithFormParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
updatePetWithForm(
args: Exclude<APIClientInterface['updatePetWithFormParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/pet/${args.petId}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
const formData = new FormData();
if (args.name != undefined) {
formData.append('name', args.name);
}
if (args.status != undefined) {
formData.append('status', args.status);
}
return this.http.post<void>(`${this.domain}${path}`, formData, options);
}
/**
* Deletes a pet
* Response generated for [ default ] HTTP response code.
*/
deletePet(
args: Exclude<APIClientInterface['deletePetParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deletePet(
args: Exclude<APIClientInterface['deletePetParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deletePet(
args: Exclude<APIClientInterface['deletePetParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deletePet(
args: Exclude<APIClientInterface['deletePetParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/pet/${args.petId}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('apiKey' in args) {
options.headers = options.headers.set('api_key', String(args.apiKey));
}
return this.http.delete<void>(`${this.domain}${path}`, options);
}
/**
* uploads an image
* Response generated for [ 200 ] HTTP response code.
*/
uploadFile(
args: Exclude<APIClientInterface['uploadFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.ApiResponse>;
uploadFile(
args: Exclude<APIClientInterface['uploadFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.ApiResponse>>;
uploadFile(
args: Exclude<APIClientInterface['uploadFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.ApiResponse>>;
uploadFile(
args: Exclude<APIClientInterface['uploadFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.ApiResponse | HttpResponse<models.ApiResponse> | HttpEvent<models.ApiResponse>> {
const path = `/pet/${args.petId}/uploadImage`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
const formData = new FormData();
if (args.additionalMetadata != undefined) {
formData.append('additionalMetadata', args.additionalMetadata);
}
if (args.file != undefined) {
formData.append('file', args.file);
}
return this.http.post<models.ApiResponse>(`${this.domain}${path}`, formData, options);
}
/**
* Add a new pet to the store
* Response generated for [ default ] HTTP response code.
*/
addPet(
args: Exclude<APIClientInterface['addPetParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
addPet(
args: Exclude<APIClientInterface['addPetParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
addPet(
args: Exclude<APIClientInterface['addPetParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
addPet(
args: Exclude<APIClientInterface['addPetParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/pet`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
return this.http.post<void>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Update an existing pet
* Response generated for [ default ] HTTP response code.
*/
updatePet(
args: Exclude<APIClientInterface['updatePetParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
updatePet(
args: Exclude<APIClientInterface['updatePetParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
updatePet(
args: Exclude<APIClientInterface['updatePetParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
updatePet(
args: Exclude<APIClientInterface['updatePetParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/pet`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
return this.http.put<void>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Finds Pets by status
* Multiple status values can be provided with comma separated strings
* Response generated for [ 200 ] HTTP response code.
*/
findPetsByStatus(
args: Exclude<APIClientInterface['findPetsByStatusParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Pet[]>;
findPetsByStatus(
args: Exclude<APIClientInterface['findPetsByStatusParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Pet[]>>;
findPetsByStatus(
args: Exclude<APIClientInterface['findPetsByStatusParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Pet[]>>;
findPetsByStatus(
args: Exclude<APIClientInterface['findPetsByStatusParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Pet[] | HttpResponse<models.Pet[]> | HttpEvent<models.Pet[]>> {
const path = `/pet/findByStatus`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('status' in args) {
options.params = options.params.set('status', String(args.status));
}
return this.http.get<models.Pet[]>(`${this.domain}${path}`, options);
}
/**
* Finds Pets by tags
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* @deprecated this method has been deprecated and may be removed in future.
* Response generated for [ 200 ] HTTP response code.
*/
findPetsByTags(
args: Exclude<APIClientInterface['findPetsByTagsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Pet[]>;
findPetsByTags(
args: Exclude<APIClientInterface['findPetsByTagsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Pet[]>>;
findPetsByTags(
args: Exclude<APIClientInterface['findPetsByTagsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Pet[]>>;
findPetsByTags(
args: Exclude<APIClientInterface['findPetsByTagsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Pet[] | HttpResponse<models.Pet[]> | HttpEvent<models.Pet[]>> {
const path = `/pet/findByTags`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('tags' in args) {
options.params = options.params.set('tags', String(args.tags));
}
return this.http.get<models.Pet[]>(`${this.domain}${path}`, options);
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
* Response generated for [ 200 ] HTTP response code.
*/
getInventory(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<{ [key: string]: number }>;
getInventory(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<{ [key: string]: number }>>;
getInventory(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<{ [key: string]: number }>>;
getInventory(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<{ [key: string]: number } | HttpResponse<{ [key: string]: number }> | HttpEvent<{ [key: string]: number }>> {
const path = `/store/inventory`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
return this.http.get<{ [key: string]: number }>(`${this.domain}${path}`, options);
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions
* Response generated for [ 200 ] HTTP response code.
*/
getOrderById(
args: Exclude<APIClientInterface['getOrderByIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Order>;
getOrderById(
args: Exclude<APIClientInterface['getOrderByIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Order>>;
getOrderById(
args: Exclude<APIClientInterface['getOrderByIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Order>>;
getOrderById(
args: Exclude<APIClientInterface['getOrderByIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Order | HttpResponse<models.Order> | HttpEvent<models.Order>> {
const path = `/store/order/${args.orderId}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
return this.http.get<models.Order>(`${this.domain}${path}`, options);
}
/**
* Delete purchase order by ID
* For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors
* Response generated for [ default ] HTTP response code.
*/
deleteOrder(
args: Exclude<APIClientInterface['deleteOrderParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteOrder(
args: Exclude<APIClientInterface['deleteOrderParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteOrder(
args: Exclude<APIClientInterface['deleteOrderParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteOrder(
args: Exclude<APIClientInterface['deleteOrderParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/store/order/${args.orderId}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
return this.http.delete<void>(`${this.domain}${path}`, options);
}
/**
* Place an order for a pet
* Response generated for [ 200 ] HTTP response code.
*/
placeOrder(
args: Exclude<APIClientInterface['placeOrderParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Order>;
placeOrder(
args: Exclude<APIClientInterface['placeOrderParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Order>>;
placeOrder(
args: Exclude<APIClientInterface['placeOrderParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Order>>;
placeOrder(
args: Exclude<APIClientInterface['placeOrderParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Order | HttpResponse<models.Order> | HttpEvent<models.Order>> {
const path = `/store/order`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
return this.http.post<models.Order>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Get user by user name
* Response generated for [ 200 ] HTTP response code.
*/
getUserByName(
args: Exclude<APIClientInterface['getUserByNameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.User>;
getUserByName(
args: Exclude<APIClientInterface['getUserByNameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.User>>;
getUserByName(
args: Exclude<APIClientInterface['getUserByNameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.User>>;
getUserByName(
args: Exclude<APIClientInterface['getUserByNameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.User | HttpResponse<models.User> | HttpEvent<models.User>> {
const path = `/user/${args.username}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
return this.http.get<models.User>(`${this.domain}${path}`, options);
}
/**
* Updated user
* This can only be done by the logged in user.
* Response generated for [ default ] HTTP response code.
*/
updateUser(
args: Exclude<APIClientInterface['updateUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
updateUser(
args: Exclude<APIClientInterface['updateUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
updateUser(
args: Exclude<APIClientInterface['updateUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
updateUser(
args: Exclude<APIClientInterface['updateUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/user/${args.username}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
return this.http.put<void>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Delete user
* This can only be done by the logged in user.
* Response generated for [ default ] HTTP response code.
*/
deleteUser(
args: Exclude<APIClientInterface['deleteUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteUser(
args: Exclude<APIClientInterface['deleteUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteUser(
args: Exclude<APIClientInterface['deleteUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteUser(
args: Exclude<APIClientInterface['deleteUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/user/${args.username}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
return this.http.delete<void>(`${this.domain}${path}`, options);
}
/**
* Logs user into the system
* Response generated for [ 200 ] HTTP response code.
*/
loginUser(
args: Exclude<APIClientInterface['loginUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<string>;
loginUser(
args: Exclude<APIClientInterface['loginUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<string>>;
loginUser(
args: Exclude<APIClientInterface['loginUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<string>>;
loginUser(
args: Exclude<APIClientInterface['loginUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<string | HttpResponse<string> | HttpEvent<string>> {
const path = `/user/login`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('username' in args) {
options.params = options.params.set('username', String(args.username));
}
if ('password' in args) {
options.params = options.params.set('password', String(args.password));
}
return this.http.get<string>(`${this.domain}${path}`, options);
}
/**
* Logs out current logged in user session
* Response generated for [ default ] HTTP response code.
*/
logoutUser(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
logoutUser(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
logoutUser(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
logoutUser(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/user/logout`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
return this.http.get<void>(`${this.domain}${path}`, options);
}
/**
* Create user
* This can only be done by the logged in user.
* Response generated for [ default ] HTTP response code.
*/
createUser(
args: Exclude<APIClientInterface['createUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
createUser(
args: Exclude<APIClientInterface['createUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
createUser(
args: Exclude<APIClientInterface['createUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
createUser(
args: Exclude<APIClientInterface['createUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/user`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
return this.http.post<void>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Creates list of users with given input array
* Response generated for [ default ] HTTP response code.
*/
createUsersWithArrayInput(
args: Exclude<APIClientInterface['createUsersWithArrayInputParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
createUsersWithArrayInput(
args: Exclude<APIClientInterface['createUsersWithArrayInputParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
createUsersWithArrayInput(
args: Exclude<APIClientInterface['createUsersWithArrayInputParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
createUsersWithArrayInput(
args: Exclude<APIClientInterface['createUsersWithArrayInputParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/user/createWithArray`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
return this.http.post<void>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* Creates list of users with given input array
* Response generated for [ default ] HTTP response code.
*/
createUsersWithListInput(
args: Exclude<APIClientInterface['createUsersWithListInputParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
createUsersWithListInput(
args: Exclude<APIClientInterface['createUsersWithListInputParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
createUsersWithListInput(
args: Exclude<APIClientInterface['createUsersWithListInputParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
createUsersWithListInput(
args: Exclude<APIClientInterface['createUsersWithListInputParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/user/createWithList`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
return this.http.post<void>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
} | the_stack |
import { Injectable, Autowired, INJECTOR_TOKEN, Injector } from '@opensumi/di';
import {
ClientAppContribution,
CommandContribution,
CommandRegistry,
CommandService,
ComponentContribution,
ComponentRegistry,
Domain,
EDITOR_COMMANDS,
Event,
FileType,
getIcon,
KeybindingContribution,
KeybindingRegistry,
MaybePromise,
TabBarToolbarContribution,
ToolbarRegistry,
URI,
} from '@opensumi/ide-core-browser';
import { TestingIsPeekVisible } from '@opensumi/ide-core-browser/lib/contextkey/testing';
import { IMenuRegistry, MenuContribution, MenuId } from '@opensumi/ide-core-browser/lib/menu/next';
import { Emitter, IMarkdownString } from '@opensumi/ide-core-common';
import {
BrowserEditorContribution,
IEditorFeatureRegistry,
IEditorDocumentModelContentRegistry,
IEditorDocumentModelContentProvider,
WorkbenchEditorService,
EditorComponentRegistry,
ResourceService,
IResource,
} from '@opensumi/ide-editor/lib/browser';
import { IEditor } from '@opensumi/ide-editor/lib/common';
import { IFileServiceClient } from '@opensumi/ide-file-service';
import { MARKDOWN_EDITOR_COMPONENT_ID } from '@opensumi/ide-markdown/lib/browser/contribution';
import { MarkdownEditorComponent } from '@opensumi/ide-markdown/lib/browser/editor.markdown';
import { TestServiceToken } from '../common';
import {
ClearTestResults,
ClosePeekTest,
DebugAllTestCommand,
DebugTestCommand,
GoToNextMessage,
GoToPreviousMessage,
GoToTestCommand,
OpenMessageInEditor,
PeekTestError,
RuntAllTestCommand,
RuntTestCommand,
TestingDebugCurrentFile,
TestingRunCurrentFile,
} from '../common/commands';
import { Testing } from '../common/constants';
import { TestResultServiceToken } from '../common/test-result';
import { TestRunProfileBitset } from '../common/testCollection';
import { TestingPeekOpenerServiceToken } from '../common/testingPeekOpener';
import { ITestTreeViewModel, TestTreeViewModelToken } from '../common/tree-view.model';
import { TEST_DATA_SCHEME } from './../common/testingUri';
import { TestOutputPeekContribution } from './outputPeek/test-output-peek';
import { TestingPeekOpenerServiceImpl } from './outputPeek/test-peek-opener.service';
import { TestDecorationsContribution } from './test-decorations';
import { TestResultServiceImpl } from './test.result.service';
import { TestServiceImpl } from './test.service';
@Injectable()
export class TestingOutputPeekDocumentProvider implements IEditorDocumentModelContentProvider {
@Autowired(TestResultServiceToken)
private readonly testResultService: TestResultServiceImpl;
private _onDidChangeContent = new Emitter<URI>();
onDidChangeContent: Event<URI> = this._onDidChangeContent.event;
provideEditorDocumentModelContent(uri: URI, encoding?: string): MaybePromise<string> {
const dto = this.testResultService.retrieveTest(uri);
if (!dto) {
return '';
}
const message = dto.messages[dto.messageIndex];
if (dto.isDiffable || typeof message.message === 'string') {
return '';
}
const mdStr = message.message;
const content = mdStr ? (mdStr as IMarkdownString).value.replace(/\t/g, '') : '';
return content;
}
isReadonly(uri: URI): MaybePromise<boolean> {
return true;
}
handlesScheme(scheme: string) {
return scheme === TEST_DATA_SCHEME;
}
}
@Injectable()
@Domain(
ClientAppContribution,
ComponentContribution,
CommandContribution,
BrowserEditorContribution,
MenuContribution,
KeybindingContribution,
TabBarToolbarContribution,
)
export class TestingContribution
implements
ClientAppContribution,
ComponentContribution,
CommandContribution,
BrowserEditorContribution,
MenuContribution,
KeybindingContribution,
TabBarToolbarContribution
{
@Autowired(TestTreeViewModelToken)
private readonly testTreeViewModel: ITestTreeViewModel;
@Autowired(IFileServiceClient)
protected readonly filesystem: IFileServiceClient;
@Autowired(CommandService)
private readonly commandService: CommandService;
@Autowired(INJECTOR_TOKEN)
private readonly injector: Injector;
@Autowired(TestingPeekOpenerServiceToken)
private readonly testingPeekOpenerService: TestingPeekOpenerServiceImpl;
@Autowired()
private readonly testingOutputPeekDocumentProvider: TestingOutputPeekDocumentProvider;
@Autowired(WorkbenchEditorService)
private readonly editorService: WorkbenchEditorService;
@Autowired(TestServiceToken)
private readonly testService: TestServiceImpl;
@Autowired(TestResultServiceToken)
private readonly testResultService: TestResultServiceImpl;
initialize(): void {
this.testTreeViewModel.initTreeModel();
}
registerComponent(registry: ComponentRegistry): void {}
registerCommands(commands: CommandRegistry): void {
commands.registerCommand(RuntTestCommand, {
execute: async (extId: string) => {
const test = this.testTreeViewModel.getTestItem(extId);
if (!test) {
return;
}
await this.testService.runTests({
group: TestRunProfileBitset.Run,
tests: [test],
});
},
});
commands.registerCommand(DebugTestCommand, {
execute: async (extId: string) => {
const test = this.testTreeViewModel.getTestItem(extId);
if (!test) {
return;
}
await this.testService.runTests({
group: TestRunProfileBitset.Debug,
tests: [test],
});
},
});
commands.registerCommand(GoToTestCommand, {
execute: async (extId: string) => {
const test = this.testTreeViewModel.getTestItem(extId);
if (!test) {
return;
}
const { range, uri } = test.item;
if (!uri) {
return;
}
const fileStat = await this.filesystem.getFileStat(uri.toString());
if (!fileStat) {
return;
}
if (fileStat.type === FileType.Directory) {
// ** filetree 未实现文件夹的 focus , 只能是将窗口切到资源管理器但无法选中文件夹 **
this.commandService.executeCommand('revealInExplorer', uri);
return;
}
if (fileStat.type === FileType.File) {
this.commandService.executeCommand(EDITOR_COMMANDS.OPEN_RESOURCE.id, URI.parse(uri.toString()), {
range,
focus: true,
});
}
},
isVisible: () => false,
});
commands.registerCommand(PeekTestError, {
execute: async (extId: string) => {
this.testingPeekOpenerService.open();
},
isVisible: () => false,
});
commands.registerCommand(ClosePeekTest, {
execute: async (uri: string | undefined) => {
uri = uri ?? this.editorService.currentEditor?.currentUri?.toString();
if (!uri) {
return;
}
const ctor = this.testingPeekOpenerService.peekControllerMap.get(uri);
if (ctor) {
ctor.removePeek();
}
},
isVisible: () => false,
});
commands.registerCommand(TestingRunCurrentFile, {
execute: async () => {
executeTestsInCurrentFile(TestRunProfileBitset.Run);
},
});
commands.registerCommand(TestingDebugCurrentFile, {
execute: async () => {
executeTestsInCurrentFile(TestRunProfileBitset.Debug);
},
});
const executeTestsInCurrentFile = (group: TestRunProfileBitset) => {
const currentEditor = this.editorService.currentEditor;
const monacoEditor = currentEditor?.monacoEditor;
const position = monacoEditor?.getPosition();
const model = monacoEditor?.getModel();
if (!position || !model || !('uri' in model)) {
return;
}
const demandedUri = model.uri.toString();
for (const test of this.testService.collection.all) {
if (test.item.uri?.toString() === demandedUri) {
this.testService.runTests({
tests: [test],
group,
});
}
}
};
commands.registerCommand(GoToPreviousMessage, {
execute: async (uri: string | undefined) => {
uri = uri ?? this.editorService.currentEditor?.currentUri?.toString();
if (!uri) {
return;
}
const ctor = this.testingPeekOpenerService.peekControllerMap.get(uri);
if (ctor) {
ctor.previous();
}
},
});
commands.registerCommand(GoToNextMessage, {
execute: async (uri: string | undefined) => {
uri = uri ?? this.editorService.currentEditor?.currentUri?.toString();
if (!uri) {
return;
}
const ctor = this.testingPeekOpenerService.peekControllerMap.get(uri);
if (ctor) {
ctor.next();
}
},
});
commands.registerCommand(ClearTestResults, {
execute: async (uri: string | undefined) => {
this.testResultService.clear();
this.commandService.executeCommand(ClosePeekTest.id, uri);
},
});
commands.registerCommand(OpenMessageInEditor, {
execute: async (uri: string | undefined) => {
uri = uri ?? this.editorService.currentEditor?.currentUri?.toString();
if (!uri) {
return;
}
const ctor = this.testingPeekOpenerService.peekControllerMap.get(uri);
if (ctor) {
ctor.openCurrentInEditor();
}
},
});
const runOrDebugAllTestsAction = async (group: TestRunProfileBitset) => {
const roots = [...this.testService.collection.rootItems];
if (!roots.length) {
return;
}
await this.testService.runTests({ tests: roots, group });
};
commands.registerCommand(RuntAllTestCommand, {
execute: async () => {
await runOrDebugAllTestsAction(TestRunProfileBitset.Run);
},
});
commands.registerCommand(DebugAllTestCommand, {
execute: async () => {
await runOrDebugAllTestsAction(TestRunProfileBitset.Debug);
},
});
}
registerKeybindings(keybindings: KeybindingRegistry): void {
keybindings.registerKeybinding({
command: ClosePeekTest.id,
keybinding: 'esc',
when: TestingIsPeekVisible.equalsTo(true),
});
}
registerMenus(menuRegistry: IMenuRegistry) {
/** glyph margin start */
menuRegistry.registerMenuItem(MenuId.TestingGlyphMarginContext, {
command: RuntTestCommand.id,
group: '1_has_decoration',
order: 1,
});
menuRegistry.registerMenuItem(MenuId.TestingGlyphMarginContext, {
command: DebugTestCommand.id,
group: '1_has_decoration',
order: 2,
});
/** glyph margin end */
/** output peek view actions start */
menuRegistry.registerMenuItem(MenuId.TestPeekTitleContext, {
command: GoToPreviousMessage.id,
iconClass: GoToPreviousMessage.iconClass,
group: 'navigation',
order: 5,
});
menuRegistry.registerMenuItem(MenuId.TestPeekTitleContext, {
command: GoToNextMessage.id,
iconClass: GoToNextMessage.iconClass,
group: 'navigation',
order: 6,
});
menuRegistry.registerMenuItem(MenuId.TestPeekTitleContext, {
command: ClearTestResults.id,
iconClass: ClearTestResults.iconClass,
group: 'navigation',
order: 7,
});
menuRegistry.registerMenuItem(MenuId.TestPeekTitleContext, {
command: OpenMessageInEditor.id,
iconClass: OpenMessageInEditor.iconClass,
group: 'navigation',
order: 9,
});
/** output peek view actions end */
}
registerToolbarItems(registry: ToolbarRegistry): void {
registry.registerItem({
id: RuntAllTestCommand.id,
command: RuntAllTestCommand.id,
viewId: Testing.ExplorerViewId,
});
registry.registerItem({
id: DebugAllTestCommand.id,
command: DebugAllTestCommand.id,
viewId: Testing.ExplorerViewId,
});
registry.registerItem({
id: ClearTestResults.id,
command: ClearTestResults.id,
viewId: Testing.ExplorerViewId,
});
}
registerEditorFeature(registry: IEditorFeatureRegistry) {
registry.registerEditorFeatureContribution({
contribute: (editor: IEditor) => this.injector.get(TestDecorationsContribution, [editor]).contribute(),
});
registry.registerEditorFeatureContribution({
contribute: (editor: IEditor) => this.injector.get(TestOutputPeekContribution, [editor]).contribute(),
});
}
registerEditorDocumentModelContentProvider(registry: IEditorDocumentModelContentRegistry) {
registry.registerEditorDocumentModelContentProvider(this.testingOutputPeekDocumentProvider);
}
registerEditorComponent(componentRegistry: EditorComponentRegistry) {
componentRegistry.registerEditorComponent({
uid: MARKDOWN_EDITOR_COMPONENT_ID,
component: MarkdownEditorComponent,
scheme: TEST_DATA_SCHEME,
});
componentRegistry.registerEditorComponentResolver(TEST_DATA_SCHEME, (_, results) => {
results.push({
type: 'component',
componentId: MARKDOWN_EDITOR_COMPONENT_ID,
weight: 10,
});
});
}
registerResource(service: ResourceService) {
service.registerResourceProvider({
scheme: TEST_DATA_SCHEME,
provideResource: async (uri: URI): Promise<IResource<Partial<{ [prop: string]: any }>>> => ({
uri,
icon: getIcon('file-text'),
name: `Preview ${uri.displayName}`,
}),
});
}
} | the_stack |
import { Logger } from './logger-interface';
import STATUS_CODES from './status-codes';
import { AnyObject } from './interfaces';
import { getFirst } from './arrays';
import { isFunction } from './functions';
import { getTypeOf, isPlainObject } from './deps';
import { tryParseJSON } from './json';
import * as s from './strings';
/**
* A custom Error class with additional properties,
* like statusCode and fatalError
*/
export class TSError extends Error {
/**
* An descriptive error code that specifies the error type, this follows more
* node convention
*/
code: string;
/**
* A HTTP status code for easy use
*/
statusCode: number;
/**
* Used to indicate the an error is fatal
*/
fatalError: boolean;
/**
* Used sometimes to indicate whether an error is retryable
*
* If this is not set then it is better not to assume either way
*/
retryable?: boolean;
/**
* Additional context metadata
*/
context: TSErrorContext;
static [Symbol.hasInstance](_instance: unknown): boolean {
if (_instance == null || typeof _instance !== 'object') return false;
const instance = _instance as Record<string, unknown>;
if (instance.message == null || instance.stack == null) return false;
if (instance.statusCode == null) return false;
if (typeof instance.cause !== 'function') return false;
return true;
}
constructor(input: unknown, config: TSErrorConfig = {}) {
const { fatalError = false } = config;
const {
message, statusCode, context, code
} = parseErrorInfo(input, config);
super(message);
this.fatalError = fatalError;
this.statusCode = statusCode;
this.context = context;
this.code = code;
if (isTSError(input)) {
this.fatalError = !!input.fatalError;
this.retryable = input.retryable;
}
if (!this.fatalError && config.retryable != null) {
this.retryable = config.retryable;
}
Object.defineProperty(this, 'name', {
value: this.constructor.name,
});
Error.captureStackTrace(this, TSError);
}
cause(): any {
return this.context._cause;
}
}
export interface TSErrorConfig {
/**
* An descriptive error code that specifies the error type, this follows more
* node convention
*/
code?: string;
/**
* A HTTP status code for easy use
*/
statusCode?: number;
/**
* Used to indicate the an error is fatal
*/
fatalError?: boolean;
/**
* Used sometimes to indicate whether an error is retryable
*/
retryable?: boolean;
/**
* Prefix the error message with a reason
*/
reason?: string;
/**
* Override the message when given an error
*/
message?: string;
/**
* Attach any context metadata to the error
*/
context?: AnyObject;
defaultStatusCode?: number;
defaultErrorMsg?: string;
}
export interface TSErrorContext extends AnyObject {
/** ISO Date string */
_createdAt: string;
_cause: any;
/**
* Used to indicate the error message is safe to log and send to the user
*/
safe?: boolean;
}
type ErrorInfo = {
message: string;
stack?: string;
context: TSErrorContext;
statusCode: number;
code: string;
};
const DEFAULT_STATUS_CODE = 500;
const DEFAULT_ERR_MSG = STATUS_CODES[DEFAULT_STATUS_CODE] as string;
/**
* Use following the chain of caused by stack of an error.
* Don't use this when logging the error, only when sending it
* */
export function getFullErrorStack(err: unknown): string {
return `${parseError(err, true)}${getCauseStack(err)}`;
}
function getCauseStack(err: any) {
if (!err || !isFunction(err.cause)) return '';
const cause = err.cause();
if (!cause) return '';
return `\nCaused by: ${getFullErrorStack(cause)}`;
}
/** parse error for info */
export function parseErrorInfo(input: unknown, config: TSErrorConfig = {}): ErrorInfo {
const { defaultErrorMsg, defaultStatusCode = DEFAULT_STATUS_CODE } = config;
const statusCode = getErrorStatusCode(input, config, defaultStatusCode);
if (isElasticsearchError(input)) {
const esErrorInfo = _parseESErrorInfo(input);
if (esErrorInfo) {
const updatedContext = Object.assign({}, esErrorInfo.context, config.context);
return {
message: config.message
|| prefixErrorMsg(
esErrorInfo.message,
config.reason,
defaultErrorMsg
),
context: createErrorContext(input, { ...config, context: updatedContext }),
statusCode,
code: esErrorInfo.code,
};
}
}
const context = createErrorContext(input, config);
let stack: string | undefined;
const message = config.message || prefixErrorMsg(input, config.reason, defaultErrorMsg);
if (input && (input as any).stack) {
stack = (input as any).stack;
}
let code: string;
if (config.code && s.isString(config.code)) {
code = toStatusErrorCode(config.code);
} else if (input && (input as any).code && s.isString((input as any).code)) {
code = toStatusErrorCode((input as any).code);
} else {
const httpMsg = STATUS_CODES[statusCode] as string;
code = toStatusErrorCode(httpMsg);
}
return {
stack,
message,
context,
statusCode,
code,
};
}
/**
* Safely log an error (with the error first Logger syntax)
*/
export function logError(logger: Logger, err: unknown, ...messages: any[]): void {
if (typeof err === 'string') {
logger.error(new TSError(err), ...messages);
return;
}
if (isError(err)) {
logger.error(err, ...messages);
return;
}
// make sure we don't lose the stack
logger.error(new TSError(err), ...messages, `invalid message format ${getTypeOf(err)} error`);
}
function createErrorContext(input: any, config: TSErrorConfig = {}) {
const context = Object.assign({}, input && input.context, config && config.context);
Object.defineProperties(context, {
_createdAt: {
value: new Date().toISOString(),
enumerable: false,
},
_cause: {
value: input,
enumerable: false,
},
});
// don't propogate safe
if (context.safe && !(config.context && config.context.safe)) {
context.safe = false;
}
return context;
}
/** parse input to get error message or stack */
export function parseError(input: unknown, withStack = false): string {
const result = parseErrorInfo(input);
if (withStack && result.stack) return result.stack;
return result.message;
}
function _cleanErrorMsg(input: string): string {
return s.truncate(input.trim(), 3000);
}
function _parseESErrorInfo(
input: ElasticsearchError
): { message: string; context: Record<string, any>; code: string } | null {
const bodyError = input && input.body && input.body.error;
const name = (input && input.name) || 'ElasticSearchError';
const rootCause = bodyError && bodyError.root_cause && getFirst(bodyError.root_cause);
let type: string | undefined;
let reason: string | undefined;
let index: string | undefined;
[input, bodyError, rootCause].forEach((obj) => {
if (obj == null) return;
if (!isPlainObject(obj)) return;
if (obj.type) type = obj.type;
if (obj.reason) reason = obj.reason;
if (obj.index) index = obj.index;
});
const metadata = input.toJSON();
if (metadata.response) {
const response = tryParseJSON(metadata.response);
metadata.response = response;
} else if (input.body) {
metadata.response = input.body as any;
}
if (!index && metadata.response) {
index = (metadata.response as any).index || (metadata.response as any)._index;
}
const message = `Elasticsearch Error: ${_normalizeESError(metadata.msg)}`;
const code = toStatusErrorCode(reason ? `${name} ${reason}` : name);
return {
message,
context: {
metadata,
type,
reason,
index,
},
code,
};
}
export function toStatusErrorCode(input: string | undefined): string {
if (!s.isString(input)) return 'UNKNOWN_ERROR';
return input
.trim()
.toUpperCase()
.replace(/\W+/g, '_');
}
function _normalizeESError(message?: string) {
if (!message) return '';
const msg = message.toLowerCase();
if (msg.includes('document missing')) {
return 'Not Found';
}
if (msg.includes('document already exists')) {
return 'Document Already Exists (version conflict)';
}
if (msg.includes('version conflict')) {
return 'Document Out-of-Date (version conflict)';
}
if (msg.indexOf('unknown error') === 0) {
return 'Unknown Elasticsearch Error, Cluster may be Unavailable';
}
return message;
}
export function prefixErrorMsg(
input: unknown, prefix?: string, defaultMsg = 'Unknown Error'
): string {
if (!prefix) {
if (isError(input)) {
return _cleanErrorMsg(input.message || defaultMsg);
}
return _cleanErrorMsg(s.toString(input) || defaultMsg);
}
return _cleanErrorMsg(`${prefix}, caused by ${s.toString(input || defaultMsg)}`);
}
export function isFatalError(err: unknown): boolean {
return !!(err && (err as any).fatalError);
}
export function isRetryableError(err: unknown): boolean {
return !!(err && (err as any).retryable === true && !(err as any).fatalError);
}
/** Check if an input has an error compatible api */
export function isError(err: unknown): err is Error {
return err && (err as any).stack && (err as any).message;
}
/** Check is a TSError */
export function isTSError(err: unknown): err is TSError {
if (err instanceof TSError) return true;
if (!isError(err)) return false;
return (err as any).statusCode != null;
}
/** Check is a elasticsearch error */
export function isElasticsearchError(err: unknown): err is ElasticsearchError {
return !!(err && isFunction((err as any).toJSON));
}
export interface ElasticsearchError extends Error {
body?: {
error?: {
type?: string;
reason?: string;
index?: string;
root_cause?: [
{
type?: string;
reason?: string;
index?: string;
}
];
};
};
status?: number;
type?: string;
reason?: string;
index?: string;
toJSON(): {
msg?: string;
statusCode?: number;
response?: string;
};
}
function coerceStatusCode(input: any): number | null {
return STATUS_CODES[input] != null ? input : null;
}
export function getErrorStatusCode(
err: unknown,
config: TSErrorConfig = {},
defaultCode = DEFAULT_STATUS_CODE
): number {
const metadata = isElasticsearchError(err) ? err.toJSON() : {};
for (const key of ['statusCode', 'status', 'code']) {
for (const obj of [config, err, metadata]) {
if (!obj || s.isString(obj)) continue;
const statusCode = coerceStatusCode((obj as any)[key]);
if (statusCode != null) {
return statusCode;
}
}
}
return defaultCode;
}
export function stripErrorMessage(
error: unknown,
reason: string = DEFAULT_ERR_MSG,
requireSafe = false
): string {
const { message, context, statusCode } = parseErrorInfo(error, {
defaultErrorMsg: reason,
context: error && (error as any).context,
});
const messages = s.parseList(message.split('caused by'));
const firstErr = getFirst(messages);
if (!firstErr) return reason;
const msg = firstErr
.replace(/^\s*,\s*/, '')
.replace(/\s*,\s*$/, '')
.replace(/TSError/g, 'Error')
.trim();
if (requireSafe) {
if (context && context.safe) return msg;
if (statusCode === 403) return 'Access Denied';
if (statusCode === 404) return 'Not Found';
return reason;
}
if (firstErr.includes(reason)) return msg;
return `${reason}: ${msg}`;
} | the_stack |
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { EventEmitter } from '@angular/core';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { TranslationLanguageService } from 'pages/exploration-editor-page/translation-tab/services/translation-language.service';
import { TranslationTopicService } from 'pages/exploration-editor-page/translation-tab/services/translation-topic.service';
import { ExplorationOpportunity } from '../opportunities-list-item/opportunities-list-item.component';
import { ContributionOpportunitiesService } from '../services/contribution-opportunities.service';
import { OpportunitiesListComponent } from './opportunities-list.component';
describe('Opportunities List Component', () => {
let component: OpportunitiesListComponent;
let fixture: ComponentFixture<OpportunitiesListComponent>;
let translationLanguageService: TranslationLanguageService;
let translationTopicService: TranslationTopicService;
let contributionOpportunitiesService: ContributionOpportunitiesService;
const mockActiveLanguageEventEmitter = new EventEmitter();
const mockActiveTopicEventEmitter = new EventEmitter();
const mockReloadOpportunitiesEventEmitter = new EventEmitter();
const mockRemoveOpportunitiesEventEmitter = new EventEmitter();
const explorationOpportunitiesLoad1: ExplorationOpportunity[] = [{
id: 'id1',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id2',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id3',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id4',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id5',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id6',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id7',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id8',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id9',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id10',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id11',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id12',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id13',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id14',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id15',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id16',
labelText: 'text',
labelColor: 'blue',
progressPercentage: 30,
inReviewCount: 20,
totalCount: 100,
translationsCount: 30
}];
const explorationOpportunitiesLoad2: ExplorationOpportunity[] = [{
id: 'id17',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id18',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id19',
labelText: 'text',
labelColor: 'blue',
progressPercentage: 30,
inReviewCount: 20,
totalCount: 100,
translationsCount: 30
},
{
id: 'id20',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id21',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id22',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id23',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id24',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id25',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id26',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
}];
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
declarations: [OpportunitiesListComponent],
providers: [
ContributionOpportunitiesService,
TranslationLanguageService,
TranslationTopicService
],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(OpportunitiesListComponent);
component = fixture.componentInstance;
translationLanguageService = TestBed.inject(TranslationLanguageService);
translationTopicService = TestBed.inject(TranslationTopicService);
contributionOpportunitiesService = TestBed.inject(
ContributionOpportunitiesService);
component.loadOpportunities = () => Promise.resolve({
opportunitiesDicts: explorationOpportunitiesLoad1,
more: true
});
component.loadMoreOpportunities = () => Promise.resolve({
opportunitiesDicts: explorationOpportunitiesLoad2,
more: false
});
spyOnProperty(translationLanguageService, 'onActiveLanguageChanged')
.and.returnValue(mockActiveLanguageEventEmitter);
spyOnProperty(translationTopicService, 'onActiveTopicChanged')
.and.returnValue(mockActiveTopicEventEmitter);
spyOnProperty(
contributionOpportunitiesService, 'reloadOpportunitiesEventEmitter')
.and.returnValue(mockReloadOpportunitiesEventEmitter);
spyOnProperty(
contributionOpportunitiesService, 'removeOpportunitiesEventEmitter')
.and.returnValue(mockRemoveOpportunitiesEventEmitter);
});
afterEach(() => {
component.ngOnDestroy();
});
it('should load opportunities when initialized', fakeAsync(() => {
expect(component.opportunities).toEqual([]);
// Since the constructor will be automatically called in unit tests, it
// is hard to test or spy on the constructor. So, we have created a
// function to manually trigger and tests different edge cases.
component.init();
tick();
// Added two opportunities with id's as 'id1' and 'id2'.
mockActiveLanguageEventEmitter.emit();
tick();
mockActiveTopicEventEmitter.emit();
tick();
mockReloadOpportunitiesEventEmitter.emit();
tick();
expect(component.opportunities).toEqual(explorationOpportunitiesLoad1);
expect(component.opportunities.length).toEqual(16);
// Removed opportunity with id as 'id2'.
mockRemoveOpportunitiesEventEmitter.emit(['id2']);
tick();
expect(component.opportunities).toEqual([{
id: 'id1',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id3',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id4',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id5',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id6',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id7',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id8',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id9',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id10',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id11',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id12',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id13',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id14',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id15',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id16',
labelText: 'text',
labelColor: 'blue',
progressPercentage: 30,
inReviewCount: 20,
totalCount: 100,
translationsCount: 30
}]);
expect(component.opportunities.length).toEqual(15);
}));
describe('when clicking on page number ', () => {
it('should go to the new page when opportunities ' +
'are greater then page length', fakeAsync(() => {
expect(component.activePageNumber).toBe(1);
component.init();
tick();
mockReloadOpportunitiesEventEmitter.emit();
tick();
component.gotoPage(1);
tick();
expect(component.activePageNumber).toBe(1);
expect(component.visibleOpportunities).toEqual([{
id: 'id1',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id2',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id3',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id4',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id5',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id6',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id7',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id8',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id9',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id10',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
}]);
component.gotoPage(2);
tick();
expect(component.activePageNumber).toBe(2);
expect(component.visibleOpportunities).toEqual([{
id: 'id11',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id12',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id13',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id14',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id15',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id16',
labelText: 'text',
labelColor: 'blue',
progressPercentage: 30,
inReviewCount: 20,
totalCount: 100,
translationsCount: 30
},
{
id: 'id17',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id18',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
},
{
id: 'id19',
labelText: 'text',
labelColor: 'blue',
progressPercentage: 30,
inReviewCount: 20,
totalCount: 100,
translationsCount: 30
},
{
id: 'id20',
labelText: 'text',
labelColor: 'red',
progressPercentage: 50,
inReviewCount: 20,
totalCount: 100,
translationsCount: 50
}]);
}));
it('should not go to the new page when opportunities ' +
'are less then page length', fakeAsync(() => {
// Setting more option to be false.
component.loadMoreOpportunities = () => Promise.resolve({
opportunitiesDicts: explorationOpportunitiesLoad1,
more: false
});
expect(component.activePageNumber).toBe(1);
component.init();
tick();
mockReloadOpportunitiesEventEmitter.emit();
tick();
component.gotoPage(1);
tick();
expect(component.activePageNumber).toBe(1);
}));
});
}); | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* Represents an Image resource.
*
* Google Compute Engine uses operating system images to create the root
* persistent disks for your instances. You specify an image when you create
* an instance. Images contain a boot loader, an operating system, and a
* root file system. Linux operating system images are also capable of
* running containers on Compute Engine.
*
* Images can be either public or custom.
*
* Public images are provided and maintained by Google, open-source
* communities, and third-party vendors. By default, all projects have
* access to these images and can use them to create instances. Custom
* images are available only to your project. You can create a custom image
* from root persistent disks and other images. Then, use the custom image
* to create an instance.
*
* To get more information about Image, see:
*
* * [API documentation](https://cloud.google.com/compute/docs/reference/v1/images)
* * How-to Guides
* * [Official Documentation](https://cloud.google.com/compute/docs/images)
*
* ## Example Usage
* ### Image Basic
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const example = new gcp.compute.Image("example", {
* rawDisk: {
* source: "https://storage.googleapis.com/bosh-gce-raw-stemcells/bosh-stemcell-97.98-google-kvm-ubuntu-xenial-go_agent-raw-1557960142.tar.gz",
* },
* });
* ```
* ### Image Guest Os
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const example = new gcp.compute.Image("example", {
* guestOsFeatures: [
* {
* type: "SECURE_BOOT",
* },
* {
* type: "MULTI_IP_SUBNET",
* },
* ],
* rawDisk: {
* source: "https://storage.googleapis.com/bosh-gce-raw-stemcells/bosh-stemcell-97.98-google-kvm-ubuntu-xenial-go_agent-raw-1557960142.tar.gz",
* },
* });
* ```
*
* ## Import
*
* Image can be imported using any of these accepted formats
*
* ```sh
* $ pulumi import gcp:compute/image:Image default projects/{{project}}/global/images/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:compute/image:Image default {{project}}/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:compute/image:Image default {{name}}
* ```
*/
export class Image extends pulumi.CustomResource {
/**
* Get an existing Image 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?: ImageState, opts?: pulumi.CustomResourceOptions): Image {
return new Image(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'gcp:compute/image:Image';
/**
* Returns true if the given object is an instance of Image. 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 Image {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === Image.__pulumiType;
}
/**
* Size of the image tar.gz archive stored in Google Cloud Storage (in bytes).
*/
public /*out*/ readonly archiveSizeBytes!: pulumi.Output<number>;
/**
* Creation timestamp in RFC3339 text format.
*/
public /*out*/ readonly creationTimestamp!: pulumi.Output<string>;
/**
* An optional description of this resource. Provide this property when
* you create the resource.
*/
public readonly description!: pulumi.Output<string | undefined>;
/**
* Size of the image when restored onto a persistent disk (in GB).
*/
public readonly diskSizeGb!: pulumi.Output<number>;
/**
* The name of the image family to which this image belongs. You can
* create disks by specifying an image family instead of a specific
* image name. The image family always returns its latest image that is
* not deprecated. The name of the image family must comply with
* RFC1035.
*/
public readonly family!: pulumi.Output<string | undefined>;
/**
* A list of features to enable on the guest operating system.
* Applicable only for bootable images.
* Structure is documented below.
*/
public readonly guestOsFeatures!: pulumi.Output<outputs.compute.ImageGuestOsFeature[]>;
/**
* The fingerprint used for optimistic locking of this resource. Used internally during updates.
*/
public /*out*/ readonly labelFingerprint!: pulumi.Output<string>;
/**
* Labels to apply to this Image.
*/
public readonly labels!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* Any applicable license URI.
*/
public readonly licenses!: pulumi.Output<string[]>;
/**
* Name of the resource; provided by the client when the resource is
* created. The name must be 1-63 characters long, and comply with
* RFC1035. Specifically, the name must be 1-63 characters long and
* match the regular expression `a-z?` which means
* the first character must be a lowercase letter, and all following
* characters must be a dash, lowercase letter, or digit, except the
* last character, which cannot be a dash.
*/
public readonly name!: pulumi.Output<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
public readonly project!: pulumi.Output<string>;
/**
* The parameters of the raw disk image.
* Structure is documented below.
*/
public readonly rawDisk!: pulumi.Output<outputs.compute.ImageRawDisk | undefined>;
/**
* The URI of the created resource.
*/
public /*out*/ readonly selfLink!: pulumi.Output<string>;
/**
* The source disk to create this image based on.
* You must provide either this property or the
* rawDisk.source property but not both to create an image.
*/
public readonly sourceDisk!: pulumi.Output<string | undefined>;
/**
* URL of the source image used to create this image. In order to create an image, you must provide the full or partial
* URL of one of the following:
* * The selfLink URL
* * This property
* * The rawDisk.source URL
* * The sourceDisk URL
*/
public readonly sourceImage!: pulumi.Output<string | undefined>;
/**
* URL of the source snapshot used to create this image.
* In order to create an image, you must provide the full or partial URL of one of the following:
* * The selfLink URL
* * This property
* * The sourceImage URL
* * The rawDisk.source URL
* * The sourceDisk URL
*/
public readonly sourceSnapshot!: pulumi.Output<string | undefined>;
/**
* Create a Image 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?: ImageArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: ImageArgs | ImageState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as ImageState | undefined;
inputs["archiveSizeBytes"] = state ? state.archiveSizeBytes : undefined;
inputs["creationTimestamp"] = state ? state.creationTimestamp : undefined;
inputs["description"] = state ? state.description : undefined;
inputs["diskSizeGb"] = state ? state.diskSizeGb : undefined;
inputs["family"] = state ? state.family : undefined;
inputs["guestOsFeatures"] = state ? state.guestOsFeatures : undefined;
inputs["labelFingerprint"] = state ? state.labelFingerprint : undefined;
inputs["labels"] = state ? state.labels : undefined;
inputs["licenses"] = state ? state.licenses : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["project"] = state ? state.project : undefined;
inputs["rawDisk"] = state ? state.rawDisk : undefined;
inputs["selfLink"] = state ? state.selfLink : undefined;
inputs["sourceDisk"] = state ? state.sourceDisk : undefined;
inputs["sourceImage"] = state ? state.sourceImage : undefined;
inputs["sourceSnapshot"] = state ? state.sourceSnapshot : undefined;
} else {
const args = argsOrState as ImageArgs | undefined;
inputs["description"] = args ? args.description : undefined;
inputs["diskSizeGb"] = args ? args.diskSizeGb : undefined;
inputs["family"] = args ? args.family : undefined;
inputs["guestOsFeatures"] = args ? args.guestOsFeatures : undefined;
inputs["labels"] = args ? args.labels : undefined;
inputs["licenses"] = args ? args.licenses : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["project"] = args ? args.project : undefined;
inputs["rawDisk"] = args ? args.rawDisk : undefined;
inputs["sourceDisk"] = args ? args.sourceDisk : undefined;
inputs["sourceImage"] = args ? args.sourceImage : undefined;
inputs["sourceSnapshot"] = args ? args.sourceSnapshot : undefined;
inputs["archiveSizeBytes"] = undefined /*out*/;
inputs["creationTimestamp"] = undefined /*out*/;
inputs["labelFingerprint"] = undefined /*out*/;
inputs["selfLink"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(Image.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering Image resources.
*/
export interface ImageState {
/**
* Size of the image tar.gz archive stored in Google Cloud Storage (in bytes).
*/
archiveSizeBytes?: pulumi.Input<number>;
/**
* Creation timestamp in RFC3339 text format.
*/
creationTimestamp?: pulumi.Input<string>;
/**
* An optional description of this resource. Provide this property when
* you create the resource.
*/
description?: pulumi.Input<string>;
/**
* Size of the image when restored onto a persistent disk (in GB).
*/
diskSizeGb?: pulumi.Input<number>;
/**
* The name of the image family to which this image belongs. You can
* create disks by specifying an image family instead of a specific
* image name. The image family always returns its latest image that is
* not deprecated. The name of the image family must comply with
* RFC1035.
*/
family?: pulumi.Input<string>;
/**
* A list of features to enable on the guest operating system.
* Applicable only for bootable images.
* Structure is documented below.
*/
guestOsFeatures?: pulumi.Input<pulumi.Input<inputs.compute.ImageGuestOsFeature>[]>;
/**
* The fingerprint used for optimistic locking of this resource. Used internally during updates.
*/
labelFingerprint?: pulumi.Input<string>;
/**
* Labels to apply to this Image.
*/
labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* Any applicable license URI.
*/
licenses?: pulumi.Input<pulumi.Input<string>[]>;
/**
* Name of the resource; provided by the client when the resource is
* created. The name must be 1-63 characters long, and comply with
* RFC1035. Specifically, the name must be 1-63 characters long and
* match the regular expression `a-z?` which means
* the first character must be a lowercase letter, and all following
* characters must be a dash, lowercase letter, or digit, except the
* last character, which cannot be a dash.
*/
name?: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* The parameters of the raw disk image.
* Structure is documented below.
*/
rawDisk?: pulumi.Input<inputs.compute.ImageRawDisk>;
/**
* The URI of the created resource.
*/
selfLink?: pulumi.Input<string>;
/**
* The source disk to create this image based on.
* You must provide either this property or the
* rawDisk.source property but not both to create an image.
*/
sourceDisk?: pulumi.Input<string>;
/**
* URL of the source image used to create this image. In order to create an image, you must provide the full or partial
* URL of one of the following:
* * The selfLink URL
* * This property
* * The rawDisk.source URL
* * The sourceDisk URL
*/
sourceImage?: pulumi.Input<string>;
/**
* URL of the source snapshot used to create this image.
* In order to create an image, you must provide the full or partial URL of one of the following:
* * The selfLink URL
* * This property
* * The sourceImage URL
* * The rawDisk.source URL
* * The sourceDisk URL
*/
sourceSnapshot?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a Image resource.
*/
export interface ImageArgs {
/**
* An optional description of this resource. Provide this property when
* you create the resource.
*/
description?: pulumi.Input<string>;
/**
* Size of the image when restored onto a persistent disk (in GB).
*/
diskSizeGb?: pulumi.Input<number>;
/**
* The name of the image family to which this image belongs. You can
* create disks by specifying an image family instead of a specific
* image name. The image family always returns its latest image that is
* not deprecated. The name of the image family must comply with
* RFC1035.
*/
family?: pulumi.Input<string>;
/**
* A list of features to enable on the guest operating system.
* Applicable only for bootable images.
* Structure is documented below.
*/
guestOsFeatures?: pulumi.Input<pulumi.Input<inputs.compute.ImageGuestOsFeature>[]>;
/**
* Labels to apply to this Image.
*/
labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* Any applicable license URI.
*/
licenses?: pulumi.Input<pulumi.Input<string>[]>;
/**
* Name of the resource; provided by the client when the resource is
* created. The name must be 1-63 characters long, and comply with
* RFC1035. Specifically, the name must be 1-63 characters long and
* match the regular expression `a-z?` which means
* the first character must be a lowercase letter, and all following
* characters must be a dash, lowercase letter, or digit, except the
* last character, which cannot be a dash.
*/
name?: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* The parameters of the raw disk image.
* Structure is documented below.
*/
rawDisk?: pulumi.Input<inputs.compute.ImageRawDisk>;
/**
* The source disk to create this image based on.
* You must provide either this property or the
* rawDisk.source property but not both to create an image.
*/
sourceDisk?: pulumi.Input<string>;
/**
* URL of the source image used to create this image. In order to create an image, you must provide the full or partial
* URL of one of the following:
* * The selfLink URL
* * This property
* * The rawDisk.source URL
* * The sourceDisk URL
*/
sourceImage?: pulumi.Input<string>;
/**
* URL of the source snapshot used to create this image.
* In order to create an image, you must provide the full or partial URL of one of the following:
* * The selfLink URL
* * This property
* * The sourceImage URL
* * The rawDisk.source URL
* * The sourceDisk URL
*/
sourceSnapshot?: pulumi.Input<string>;
} | the_stack |
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { TestBed, async } from '@angular/core/testing';
import { FormsModule, FormGroupDirective, NgControl, FormControlName, FormBuilder } from '@angular/forms';
// Vendor
import { TextMaskModule } from 'angular2-text-mask';
import { OverlayModule } from '@angular/cdk/overlay';
// App
import { NovoOverlayModule } from '../overlay/Overlay.module';
import { NovoTableElement } from './Table';
import { Pagination } from './extras/pagination/Pagination';
import { RowDetails } from './extras/row-details/RowDetails';
import { TableCell } from './extras/table-cell/TableCell';
import { TableFilter } from './extras/table-filter/TableFilter';
import { ThOrderable } from './extras/th-orderable/ThOrderable';
import { ThSortable } from './extras/th-sortable/ThSortable';
import { NovoTableKeepFilterFocus } from './extras/keep-filter-focus/KeepFilterFocus';
import { NovoTableActionsElement } from './extras/table-actions/TableActions';
import { NovoTableFooterElement } from './extras/table-footer/TableFooter';
import { NovoTableHeaderElement } from './extras/table-header/TableHeader';
import { NovoFormElement } from '../form/Form';
import { NovoControlElement } from '../form/Control';
import { NovoCheckboxElement } from '../form/extras/checkbox/Checkbox';
import { NovoCheckListElement } from '../form/extras/checkbox/CheckList';
import { NovoAddressElement } from '../form/extras/address/Address';
import { NovoDatePickerElement } from '../date-picker/DatePicker';
import { NovoToastElement } from '../toast/Toast';
import { NovoLoadingElement } from '../loading/Loading';
import { NovoItemElement, NovoDropdownListElement } from '../dropdown/Dropdown';
import { NovoChipsElement, NovoChipElement } from '../chips/Chips';
import { NovoDropdownElement } from '../dropdown/Dropdown';
import { TooltipDirective } from '../tooltip/Tooltip.directive';
import { NovoSelectElement } from '../select/Select';
import { NovoLabelService } from '../../services/novo-label-service';
import { FormUtils } from '../../utils/form-utils/FormUtils';
import { DateFormatService } from '../../services/date-format/DateFormat';
import { OptionsService } from '../../services/options/OptionsService';
describe('Elements: NovoTableElement', () => {
let fixture;
let component;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
// Table:
NovoTableElement,
Pagination,
RowDetails,
TableCell,
TableFilter,
ThOrderable,
ThSortable,
NovoTableKeepFilterFocus,
NovoTableActionsElement,
NovoTableFooterElement,
NovoTableHeaderElement,
// Form:
NovoFormElement,
NovoControlElement,
NovoCheckboxElement,
NovoCheckListElement,
NovoAddressElement,
// Novo Elements
NovoDatePickerElement,
NovoToastElement,
NovoDropdownListElement,
NovoChipElement,
NovoLoadingElement,
NovoItemElement,
NovoChipsElement,
NovoDropdownElement,
TooltipDirective,
NovoSelectElement,
// NG2
FormGroupDirective,
FormControlName,
],
imports: [
FormsModule,
// Vendor
TextMaskModule,
OverlayModule,
NovoOverlayModule,
],
providers: [
{ provide: NovoLabelService, useClass: NovoLabelService },
{ provide: FormUtils, useClass: FormUtils },
OptionsService,
NgControl,
FormBuilder,
DateFormatService,
],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
}).compileComponents();
fixture = TestBed.createComponent(NovoTableElement);
component = fixture.debugElement.componentInstance;
}));
it('should initialize with all of its defaults.', () => {
expect(component).toBeDefined();
component._rows = [];
component.mode = 'TEST';
// NG2
expect(component.onRowClick).toBeDefined();
expect(component.onRowSelect).toBeDefined();
expect(component.onTableChange).toBeDefined();
// Vars
expect(component.activeId).toBeDefined();
expect(component.master).toBeDefined();
expect(component.indeterminate).toBeDefined();
expect(component.lastPage).toBeDefined();
expect(component.rows).toBeDefined();
// Setters
component.rows = [];
component.dataProvider = [];
// Getters
expect(component.dataProvider).toBeDefined();
expect(component.editing).toBeDefined();
expect(component.formValue).toBeDefined();
});
describe('Method: onDropdownToggled()', () => {
it('should be defined.', () => {
expect(component.onDropdownToggled).toBeDefined();
component.onDropdownToggled();
});
});
describe('Method: onPageChange()', () => {
it('should be defined.', () => {
expect(component.onPageChange).toBeDefined();
component.onPageChange();
});
});
describe('Method: getOptionDataAutomationId()', () => {
it('should be defined.', () => {
expect(component.getOptionDataAutomationId).toBeDefined();
component.getOptionDataAutomationId({ value: 2 });
});
});
describe('Method: setupColumnDefaults()', () => {
it('should be defined.', () => {
expect(component.setupColumnDefaults).toBeDefined();
component.columns = [{ type: 'misc' }];
component.setupColumnDefaults();
});
});
describe('Method: ngDoCheck()', () => {
it('should be defined.', () => {
expect(component.ngDoCheck).toBeDefined();
component.ngDoCheck();
});
});
describe('Method: getPageStart()', () => {
it('should be defined.', () => {
expect(component.getPageStart).toBeDefined();
component.getPageStart();
});
});
describe('Method: getPageEnd()', () => {
it('should be defined.', () => {
expect(component.getPageEnd).toBeDefined();
});
});
describe('Method: onFilterClick(column, filter)', () => {
beforeEach(() => {
component._dataProvider = {
edit: () => { },
};
component.columns = [
{
filtering: true,
name: 'date',
type: 'date',
},
{
filtering: true,
name: 'type',
options: ['Lead', 'Contact'],
},
];
component.originalRows = [
{
id: 1,
date: new Date(),
type: 'Lead',
},
{
id: 2,
date: new Date(),
type: 'Contact',
},
];
component.config = {
filtering: true,
};
});
it('should allow multiple date selections if multiple=true/false', () => {
expect(component.onFilterClick).toBeDefined();
component.columns[0].multiple = true;
component.setupColumnDefaults();
// Select 4 rows
component.onFilterClick(component.columns[0], component.columns[0].options[0]);
component.onFilterClick(component.columns[0], component.columns[0].options[1]);
component.onFilterClick(component.columns[0], component.columns[0].options[2]);
component.onFilterClick(component.columns[0], component.columns[0].options[3]);
expect(component.columns[0].filter.length).toBe(4);
// deselect 4 rows
component.onFilterClick(component.columns[0], component.columns[0].options[0]);
component.onFilterClick(component.columns[0], component.columns[0].options[1]);
component.onFilterClick(component.columns[0], component.columns[0].options[2]);
component.onFilterClick(component.columns[0], component.columns[0].options[3]);
expect(component.columns[0].filter).toBe(null);
// set multiple to false and try and click 2 rows
component.columns[0].multiple = false;
component.onFilterClick(component.columns[0], component.columns[0].options[1]);
component.onFilterClick(component.columns[0], component.columns[0].options[2]);
expect(component.columns[0].filter.length).toBeUndefined();
expect(component.columns[0].filter).toBeTruthy();
});
it('should allow multiple text selections if multiple=true/false', () => {
expect(component.onFilterClick).toBeDefined();
component.columns[1].multiple = true;
component.setupColumnDefaults();
// Select 2 rows
component.onFilterClick(component.columns[1], component.columns[1].options[0]);
component.onFilterClick(component.columns[1], component.columns[1].options[1]);
expect(component.columns[1].filter.length).toBe(2);
// deselect 2 rows
component.onFilterClick(component.columns[1], component.columns[1].options[0]);
component.onFilterClick(component.columns[1], component.columns[1].options[1]);
expect(component.columns[1].filter).toBe(null);
// set multiple to false and try and click 2 rows
component.columns[1].multiple = false;
component.onFilterClick(component.columns[1], component.columns[1].options[0]);
component.onFilterClick(component.columns[1], component.columns[1].options[1]);
expect(component.columns[1].filter.length).toBe(7);
expect(component.columns[1].filter).toBeTruthy();
});
it('should add range to options (11 total) if range is set', () => {
expect(component.onFilterClick).toBeDefined();
component.columns[0].range = true;
component.setupColumnDefaults();
expect(component.columns[0].options.length).toBe(11);
});
it('should add calenderShow if range is set', () => {
expect(component.onFilterClick).toBeDefined();
component.columns[0].range = true;
component.setupColumnDefaults();
component.onFilterClick(component.columns[0], component.columns[0].options[component.columns[0].options.length - 1]);
expect(component.columns[0].calenderShow).toBeTruthy();
});
});
describe('Method: onFilterClear(column)', () => {
it('should be defined.', () => {
expect(component.onFilterClear).toBeDefined();
component.onFilterClear({ filer: true, freetextFilter: true });
});
});
describe('Method: clearAllSortAndFilters()', () => {
it('should be defined.', () => {
expect(component.clearAllSortAndFilters).toBeDefined();
component.clearAllSortAndFilters();
});
});
xdescribe('Method: onFilterChange()', () => {
beforeEach(() => {
component.columns = [
{
filter: 'a',
filtering: true,
name: 'name',
},
];
component.originalRows = [
{
id: 1,
name: 'Jane',
},
{
id: 2,
name: 'John',
},
];
component.config = {
filtering: true,
};
});
it('should update the row data to reflect the active filters (string comparison).', () => {
expect(component.onFilterChange).toBeDefined();
component.onFilterChange();
expect(component.rows.length).toBe(1);
});
it('should update the row data to reflect the active filters (array comparison).', () => {
expect(component.onFilterChange).toBeDefined();
component.originalRows[0].name = ['Jane', 'Janet', 'Janice'];
component.originalRows[1].name = ['Jon', 'Joe', 'Jose'];
component.onFilterChange();
expect(component.rows.length).toBe(1);
});
it('should update the row data to reflect the active filters (custom filter).', () => {
expect(component.onFilterChange).toBeDefined();
component.config.filtering = (filterValue, data) => {
const matches = [];
data.forEach((row) => {
if (row.name === 'John') {
matches.push(row);
}
});
return matches;
};
component.onFilterChange();
expect(component.rows.length).toBe(1);
});
it('should update the row data to reflect the active filters (custom config filter).', () => {
expect(component.onFilterChange).toBeDefined();
const mockOption = { label: 'Today', min: -2, max: 2 };
component.columns = [
{
name: 'name',
type: 'date',
options: [mockOption],
},
];
// Set dates
component.originalRows[0].name = new Date();
component.originalRows[1].name = new Date(1970, 3, 11, 13, 13);
// Set active filter
component.columns[0].filter = [mockOption];
component.onFilterChange();
expect(component.rows.length).toBe(1);
});
it('should update the row data to reflect the active filters (custom match function).', () => {
expect(component.onFilterChange).toBeDefined();
component.columns[0].match = (item, filter) => {
return item.match(new RegExp(filter, 'gi'));
};
component.onFilterChange();
expect(component.rows.length).toBe(1);
});
});
xdescribe('Method: isFilterActive(columnFilters, filter)', () => {
it('should return true when the filter is active and false when it is not.', () => {
expect(component.isFilterActive).toBeDefined();
const mockColumnFilters = {
filter: [],
};
const mockFilter = {
label: 'Filter',
};
// Using Filter Objects
expect(component.isFilterActive(mockColumnFilters, mockFilter)).toBeFalsy();
mockColumnFilters.filter.push(mockFilter);
expect(component.isFilterActive(mockColumnFilters, mockFilter)).toBeTruthy();
// Using strings
expect(component.isFilterActive({ filter: ['Filter'] }, 'Filter')).toBeTruthy();
expect(component.isFilterActive({ filter: ['Filter'] }, 'z')).toBeFalsy();
});
});
describe('Method: onSortChange(newSortColumn)', () => {
it('should be defined.', () => {
expect(component.onSortChange).toBeDefined();
});
});
describe('Method: fireTableChangeEvent()', () => {
it('should be defined.', () => {
expect(component.fireTableChangeEvent).toBeDefined();
});
});
describe('Method: findColumnIndex(value)', () => {
it('should be defined.', () => {
expect(component.findColumnIndex).toBeDefined();
});
});
describe('Method: onOrderChange(event)', () => {
it('should be defined.', () => {
expect(component.onOrderChange).toBeDefined();
});
});
describe('Method: selectPage()', () => {
it('should be defined.', () => {
expect(component.selectPage).toBeDefined();
});
});
describe('Method: selectAll()', () => {
it('should be defined.', () => {
expect(component.selectAll).toBeDefined();
});
});
describe('Method: rowSelectHandler()', () => {
it('should be defined.', () => {
expect(component.rowSelectHandler).toBeDefined();
});
});
describe('Method: emitSelected()', () => {
it('should be defined.', () => {
expect(component.emitSelected).toBeDefined();
});
});
describe('Method: rowClickHandler()', () => {
it('should be defined.', () => {
expect(component.rowClickHandler).toBeDefined();
});
});
describe('Method: getDefaultOptions()', () => {
it('should return a subset of options when the data dates cover a small range.', () => {
expect(component.getDefaultOptions).toBeDefined();
const mockOptions = component.getDefaultOptions();
expect(mockOptions.length).toBe(10);
});
});
describe('Method: onCalenderSelect(column, event)', () => {
it('should be defined.', () => {
expect(component.onCalenderSelect).toBeDefined();
component.onCalenderSelect(null, { startDate: new Date(), endDate: new Date() });
});
});
describe('Method: onFilterKeywords()', () => {
it('should be defined.', () => {
expect(component.onFilterKeywords).toBeDefined();
// component.onFilterKeywords();
});
});
describe('Method: setTableEdit()', () => {
beforeEach(() => {
component._dataProvider = {
edit: () => { },
};
component.columns = [
{
name: 'name',
},
{
name: 'id',
},
];
component._rows = [
{
id: 1,
name: 'Jane',
},
{
id: 2,
name: 'John',
},
];
});
it('should be defined.', () => {
expect(component.setTableEdit).toBeDefined();
});
it('should set the table to edit mode', () => {
component.setTableEdit();
expect(component.mode).toBe(2);
});
it('should set columns with viewOnly to editing false', () => {
component.columns[0].viewOnly = true;
component.setTableEdit();
expect(component._rows).toEqual([
{
id: 1,
name: 'Jane',
_editing: {
id: true,
name: false,
},
},
{
id: 2,
name: 'John',
_editing: {
id: true,
name: false,
},
},
]);
});
});
describe('Method: leaveEditMode()', () => {
beforeEach(() => {
component._dataProvider = {
undo: () => { },
commit: () => { },
};
component.columns = [
{
name: 'name',
},
{
name: 'id',
},
];
component._rows = [
{
id: 1,
name: 'Jane',
},
{
id: 2,
name: 'John',
},
];
});
it('should be defined.', () => {
expect(component.leaveEditMode).toBeDefined();
});
it('should set the table to view mode', () => {
component.leaveEditMode();
expect(component.mode).toBe(1);
});
it('should set the table colums editing to false', () => {
component.leaveEditMode();
expect(component._rows).toEqual([
{
id: 1,
name: 'Jane',
_editing: {
id: false,
name: false,
},
},
{
id: 2,
name: 'John',
_editing: {
id: false,
name: false,
},
},
]);
});
});
describe('Method: addEditableRow()', () => {
it('should be defined.', () => {
expect(component.addEditableRow).toBeDefined();
// component.addEditableRow();
});
});
describe('Method: validateAndGetUpdatedData()', () => {
it('should be defined.', () => {
expect(component.validateAndGetUpdatedData).toBeDefined();
component.validateAndGetUpdatedData();
});
});
describe('Method: cancelEditing()', () => {
beforeEach(() => {
component._dataProvider = {
undo: () => { },
commit: () => { },
};
});
it('should be defined.', () => {
expect(component.cancelEditing).toBeDefined();
});
it('should set the table to view mode', () => {
component.leaveEditMode();
expect(component.mode).toBe(1);
});
});
describe('Method: displayToastMessage()', () => {
it('should be defined.', () => {
expect(component.displayToastMessage).toBeDefined();
component.displayToastMessage();
});
});
describe('Method: hideToastMessage()', () => {
it('should be defined.', () => {
expect(component.hideToastMessage).toBeDefined();
component.hideToastMessage();
});
});
describe('Method: toggleLoading()', () => {
it('should be defined.', () => {
expect(component.toggleLoading).toBeDefined();
});
it('should set loading to true', () => {
component.toggleLoading(true);
expect(component.loading).toBe(true);
});
it('should set loading to false', () => {
component.toggleLoading(false);
expect(component.loading).toBe(false);
});
});
describe('Method: isColumnHidden()', () => {
it('should be defined.', () => {
expect(component.isColumnHidden).toBeDefined();
});
it('should return true if column has hideColumnOnEdit and in editing mode', () => {
const column = { name: 'name', hideColumnOnEdit: true };
component.mode = 2;
expect(component.isColumnHidden(column)).toBe(true);
});
it('should return false if column does not have hideColumnOnEdit and in editing mode', () => {
const column = { name: 'name' };
component.mode = 2;
expect(component.isColumnHidden(column)).toBe(false);
});
it('should return false if column does not have hideColumnOnEdit and not in editing mode', () => {
const column = { name: 'name' };
component.mode = 1;
expect(component.isColumnHidden(column)).toBe(false);
});
it('should return false if column has hideColumnOnEdit and not in editing mode', () => {
const column = { name: 'name', hideColumnOnEdit: true };
component.mode = 1;
expect(component.isColumnHidden(column)).toBe(false);
});
it('should return false if column has hideColumnOnView and in editing mode', () => {
const column = { name: 'name', hideColumnOnView: true };
component.mode = 2;
expect(component.isColumnHidden(column)).toBe(false);
});
it('should return false if column does not have hideColumnOnView and in editing mode', () => {
const column = { name: 'name' };
component.mode = 2;
expect(component.isColumnHidden(column)).toBe(false);
});
it('should return false if column does not have hideColumnOnView and not in editing mode', () => {
const column = { name: 'name' };
component.mode = 1;
expect(component.isColumnHidden(column)).toBe(false);
});
it('should return false if column has hideColumnOnView and not in editing mode', () => {
const column = { name: 'name', hideColumnOnView: true };
component.mode = 1;
expect(component.isColumnHidden(column)).toBe(true);
});
});
}); | the_stack |
import type { DataItem } from "../../../core/render/Component";
import type { Graphics } from "../../../core/render/Graphics";
import type { Template } from "../../../core/util/Template";
import type { ListTemplate } from "../../../core/util/List";
import type { CategoryAxis } from "../axes/CategoryAxis";
import type { DateAxis } from "../axes/DateAxis";
import type { ValueAxis } from "../axes/ValueAxis";
import type { ILegendDataItem } from "../../../core/render/Legend";
import type { Sprite } from "../../../core/render/Sprite";
import { XYSeries, IXYSeriesPrivate, IXYSeriesSettings, IXYSeriesDataItem, IXYSeriesAxisRange } from "./XYSeries";
import { Percent } from "../../../core/util/Percent";
import { visualSettings } from "../../../core/render/Graphics";
import * as $array from "../../../core/util/Array";
import * as $type from "../../../core/util/Type";
export interface IBaseColumnSeriesDataItem extends IXYSeriesDataItem {
/**
* An actual [[Graphics]] element (Column/Slice/Candlestick/OHLC).
*/
graphics?: Graphics;
/**
* In case axis ranges are added to the series, it creates a separate
* element ([[Graphics]]) for each axis range. This array holds them all.
*/
rangeGraphics?: Array<Graphics>;
/**
* If data items from this series are used to feed a [[Legend]], this
* will hold a reference to the equivalent Legend data item.
*
* @see {@link https://www.amcharts.com/docs/v5/concepts/legend/#Data_item_list} for more info
*/
legendDataItem?: DataItem<ILegendDataItem>;
}
export interface IBaseColumnSeriesSettings extends IXYSeriesSettings {
/**
* Indicates if series must divvy up available space with other column
* series (`true`; default) or take up the whole available space (`false`).
*
* @default true
* @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/series/column-series/#Clustering} for more info
*/
clustered?: boolean;
/**
* Whether positions of bullets should be calculated based on portion of
* column currently visual (`true`) or the whole length/height of the
* column (`false`).
*
* @default true
*/
adjustBulletPosition?: boolean;
}
export interface IBaseColumnSeriesPrivate extends IXYSeriesPrivate { }
export interface IBaseColumnSeriesAxisRange extends IXYSeriesAxisRange {
/**
* A list of actual [[Graphics]] elements for an axis range.
*
* Can be used to ajust the look of the axis range columns.
*/
columns: ListTemplate<Graphics>;
}
/**
* Base class for all "column-based" series
*/
export abstract class BaseColumnSeries extends XYSeries {
declare public _settings: IBaseColumnSeriesSettings;
declare public _privateSettings: IBaseColumnSeriesPrivate;
declare public _dataItemSettings: IBaseColumnSeriesDataItem;
declare public _axisRangeType: IBaseColumnSeriesAxisRange;
public static className: string = "BaseColumnSeries";
public static classNames: Array<string> = XYSeries.classNames.concat([BaseColumnSeries.className]);
/**
* @ignore
*/
public abstract makeColumn(dataItem: DataItem<this["_dataItemSettings"]>, listTemplate: ListTemplate<Graphics>): Graphics
/**
* ListTemplate of columns in series.
*/
public abstract columns: ListTemplate<Graphics>;
protected _makeGraphics(listTemplate: ListTemplate<Graphics>, dataItem: DataItem<this["_dataItemSettings"]>): Graphics {
return this.makeColumn(dataItem, listTemplate);
}
protected _ph: number = 0;
protected _pw: number = 0;
public _makeFieldNames() {
super._makeFieldNames();
const xAxis = this.get("xAxis");
const yAxis = this.get("yAxis");
const categoryAxis = "CategoryAxis";
const valueAxis = "ValueAxis";
if (xAxis.isType<CategoryAxis<any>>(categoryAxis)) {
if (!this.get("openCategoryXField")) {
this._xOpenField = this._xField;
}
}
if (xAxis.isType<DateAxis<any>>(valueAxis)) {
if (!this.get("openValueXField")) {
this._xOpenField = this._xField;
}
}
if (yAxis.isType<CategoryAxis<any>>(categoryAxis)) {
if (!this.get("openCategoryYField")) {
this._yOpenField = this._yField;
}
}
if (yAxis.isType<DateAxis<any>>(valueAxis)) {
if (!this.get("openValueYField")) {
this._yOpenField = this._yField;
}
}
}
public _prepareChildren() {
super._prepareChildren();
const xAxis = this.get("xAxis");
const yAxis = this.get("yAxis");
const len = this.dataItems.length;
const startIndex = Math.max(0, this.startIndex() - 2);
const endIndex = Math.min(this.endIndex() + 2, len - 1);
if (xAxis.inited && yAxis.inited) {
for (let i = startIndex; i <= endIndex; i++) {
let dataItem = this.dataItems[i];
this._createGraphics(dataItem);
}
}
}
public _updateChildren() {
const chart = this.chart;
if (chart) {
this._ph = chart.plotContainer.height();
this._pw = chart.plotContainer.width();
}
const xAxis = this.get("xAxis");
const yAxis = this.get("yAxis");
const baseAxis = this.get("baseAxis")!;
const columnsTemplate = this.columns.template;
if (this.isDirty("fill")) {
if (columnsTemplate.get("fill") == null) {
columnsTemplate.set("fill", this.get("fill"));
}
}
if (this.isDirty("stroke")) {
if (columnsTemplate.get("stroke") == null) {
columnsTemplate.set("stroke", this.get("stroke"));
}
}
let index = 0;
let clusterCount = 0;
let i = 0;
$array.each(baseAxis.series, (series) => {
if (series instanceof BaseColumnSeries) {
const stacked = series.get("stacked");
if (stacked && i == 0) {
clusterCount++;
}
if (!stacked && series.get("clustered")) {
clusterCount++;
}
}
if (series === this) {
index = clusterCount - 1;
}
i++;
})
if (!this.get("clustered")) {
index = 0;
clusterCount = 1;
}
if (clusterCount === 0) {
clusterCount = 1;
index = 0;
}
const xRenderer = xAxis.get("renderer");
const yRenderer = yAxis.get("renderer");
const cellStartLocation = "cellStartLocation";
const cellEndLocation = "cellEndLocation";
const cellLocationX0 = xRenderer.get(cellStartLocation, 0);
const cellLocationX1 = xRenderer.get(cellEndLocation, 1);
const cellLocationY0 = yRenderer.get(cellStartLocation, 0);
const cellLocationY1 = yRenderer.get(cellEndLocation, 1);
this._aLocationX0 = cellLocationX0 + (index / clusterCount) * (cellLocationX1 - cellLocationX0);
this._aLocationX1 = cellLocationX0 + (index + 1) / clusterCount * (cellLocationX1 - cellLocationX0);;
this._aLocationY0 = cellLocationY0 + (index / clusterCount) * (cellLocationY1 - cellLocationY0);
this._aLocationY1 = cellLocationY0 + (index + 1) / clusterCount * (cellLocationY1 - cellLocationY0);
if (xAxis.inited && yAxis.inited) {
if (this._axesDirty || this._valuesDirty || this._stackDirty || this.isDirty("vcx") || this.isDirty("vcy") || this._sizeDirty) {
const len = this.dataItems.length;
let startIndex = Math.max(0, this.startIndex() - 2);
let endIndex = Math.min(this.endIndex() + 2, len - 1);
for (let i = 0; i < startIndex; i++) {
this._toggleColumn(this.dataItems[i], false);
}
let previous = this.dataItems[startIndex];
for (let i = startIndex; i <= endIndex; i++) {
let dataItem = this.dataItems[i];
this._updateGraphics(dataItem, previous);
previous = dataItem;
}
for (let i = endIndex + 1; i < len; i++) {
this._toggleColumn(this.dataItems[i], false);
}
}
}
else {
this._skipped = true;
}
super._updateChildren();
}
protected _createGraphics(dataItem: DataItem<this["_dataItemSettings"]>) {
let graphics = dataItem.get("graphics");
if (!graphics) {
graphics = this._makeGraphics(this.columns, dataItem);
dataItem.set("graphics", graphics);
graphics._setDataItem(dataItem);
const legendDataItem = dataItem.get("legendDataItem");
if (legendDataItem) {
const markerRectangle = legendDataItem.get("markerRectangle");
if (markerRectangle) {
markerRectangle.setAll({ fill: graphics.get("fill"), stroke: graphics.get("stroke") });
}
}
this.axisRanges.each((axisRange) => {
const container = axisRange.container!;
const graphicsArray: Array<Graphics> = dataItem.get("rangeGraphics", []);
dataItem.set("rangeGraphics", graphicsArray);
const rangeGraphics = this._makeGraphics(axisRange.columns, dataItem);
graphicsArray.push(rangeGraphics);
rangeGraphics.setPrivate("list", axisRange.columns);
container.children.push(rangeGraphics);
})
}
}
protected _updateGraphics(dataItem: DataItem<this["_dataItemSettings"]>, previousDataItem: DataItem<this["_dataItemSettings"]>) {
let graphics = dataItem.get("graphics")!;
//if (!graphics) {
// this._createGraphics(dataItem);
// graphics = dataItem.get("graphics")!;
//}
const xField = this._xField;
const yField = this._yField;
const valueX = dataItem.get(xField as any);
const valueY = dataItem.get(yField as any);
if (valueX != null && valueY != null) {
const xOpenField = this._xOpenField;
const yOpenField = this._yOpenField;
const locationX = this.get("locationX", dataItem.get("locationX", 0.5));
const locationY = this.get("locationY", dataItem.get("locationY", 0.5));
const openLocationX = this.get("openLocationX", dataItem.get("openLocationX", locationX));
const openLocationY = this.get("openLocationY", dataItem.get("openLocationY", locationY));
const width = graphics.get("width");
const height = graphics.get("height");
const stacked = this.get("stacked");
const xAxis = this.get("xAxis");
const yAxis = this.get("yAxis");
const baseAxis = this.get("baseAxis");
const xStart = xAxis.get("start");
const xEnd = xAxis.get("end");
const yStart = yAxis.get("start");
const yEnd = yAxis.get("end");
let l!: number;
let r!: number;
let t!: number;
let b!: number;
let vcy = this.get("vcy", 1);
let vcx = this.get("vcx", 1);
let fitW = false;
let fitH = false;
if (yAxis.isType<CategoryAxis<any>>("CategoryAxis") && xAxis.isType<CategoryAxis<any>>("CategoryAxis")) {
let startLocation = this._aLocationX0 + openLocationX - 0.5;
let endLocation = this._aLocationX1 + locationX - 0.5;
if (width instanceof Percent) {
let offset: number = (endLocation - startLocation) * (1 - width.value) / 2;
startLocation += offset;
endLocation -= offset;
}
l = xAxis.getDataItemPositionX(dataItem, xOpenField, startLocation, vcx);
r = xAxis.getDataItemPositionX(dataItem, xField, endLocation, vcx);
startLocation = this._aLocationY0 + openLocationY - 0.5;
endLocation = this._aLocationY1 + locationY - 0.5;
if (height instanceof Percent) {
let offset: number = (endLocation - startLocation) * (1 - height.value) / 2;
startLocation += offset;
endLocation -= offset;
}
t = yAxis.getDataItemPositionY(dataItem, yOpenField, startLocation, vcy);
b = yAxis.getDataItemPositionY(dataItem, yField, endLocation, vcy);
dataItem.setRaw("point", { x: l + (r - l) / 2, y: t + (b - t) / 2 });
}
else if (xAxis === baseAxis) {
let startLocation = this._aLocationX0 + openLocationX - 0.5;
let endLocation = this._aLocationX1 + locationX - 0.5;
if (width instanceof Percent) {
let offset: number = (endLocation - startLocation) * (1 - width.value) / 2;
startLocation += offset;
endLocation -= offset;
}
l = xAxis.getDataItemPositionX(dataItem, xOpenField, startLocation, vcx);
r = xAxis.getDataItemPositionX(dataItem, xField, endLocation, vcx);
t = yAxis.getDataItemPositionY(dataItem, yField, locationY, vcy);
if (this._yOpenField !== this._yField) {
b = yAxis.getDataItemPositionY(dataItem, yOpenField, openLocationY, vcy);
}
else {
if (stacked) {
let stackToItemY = dataItem.get("stackToItemY")!;
if (stackToItemY) {
b = yAxis.getDataItemPositionY(stackToItemY, yField, openLocationY, (stackToItemY.component as XYSeries).get("vcy"));
}
else {
b = yAxis.basePosition();
}
}
else {
b = yAxis.basePosition();
}
}
dataItem.setRaw("point", { x: l + (r - l) / 2, y: t });
fitH = true;
}
else if (yAxis === baseAxis) {
let startLocation = this._aLocationY0 + openLocationY - 0.5;
let endLocation = this._aLocationY1 + locationY - 0.5;
if (height instanceof Percent) {
let offset: number = (endLocation - startLocation) * (1 - height.value) / 2;
startLocation += offset;
endLocation -= offset;
}
t = yAxis.getDataItemPositionY(dataItem, yOpenField, startLocation, vcy);
b = yAxis.getDataItemPositionY(dataItem, yField, endLocation, vcy);
r = xAxis.getDataItemPositionX(dataItem, xField, locationX, vcx);
if (this._xOpenField !== this._xField) {
l = xAxis.getDataItemPositionX(dataItem, xOpenField, openLocationX, vcx);
}
else {
if (stacked) {
let stackToItemX = dataItem.get("stackToItemX")!;
if (stackToItemX) {
l = xAxis.getDataItemPositionX(stackToItemX, xField, openLocationX, (stackToItemX.component as XYSeries).get("vcx"));
}
else {
l = xAxis.basePosition();
}
}
else {
l = xAxis.basePosition();
}
}
fitW = true;
dataItem.setRaw("point", { x: r, y: t + (b - t) / 2 });
}
this._updateSeriesGraphics(dataItem, graphics!, l, r, t, b, fitW, fitH);
if ((l < xStart && r < xStart) || (l > xEnd && r > xEnd) || (t < yStart && b < yStart) || (t > yEnd && b > yEnd)) {
this._toggleColumn(dataItem, false);
}
else {
this._toggleColumn(dataItem, true);
}
let rangeGraphics = dataItem.get("rangeGraphics")!;
if (rangeGraphics) {
$array.each(rangeGraphics, (graphics) => {
this._updateSeriesGraphics(dataItem, graphics, l, r, t, b, fitW, fitH);
})
}
this._applyGraphicsStates(dataItem, previousDataItem);
}
}
protected _updateSeriesGraphics(dataItem: DataItem<this["_dataItemSettings"]>, graphics: Graphics, l: number, r: number, t: number, b: number, fitW: boolean, fitH: boolean) {
const width = graphics.get("width");
const height = graphics.get("height");
const maxWidth = graphics.get("maxWidth");
const maxHeight = graphics.get("maxHeight");
const ptl = this.getPoint(l, t);
const pbr = this.getPoint(r, b);
const tooltipPoint = dataItem.get("point");
if (tooltipPoint) {
const point = this.getPoint(tooltipPoint.x, tooltipPoint.y);
tooltipPoint.x = point.x + this._x;
tooltipPoint.y = point.y + this._y;
}
l = ptl.x;
r = pbr.x;
t = ptl.y;
b = pbr.y;
if ($type.isNumber(width)) {
const offset: number = ((r - l) - width) / 2;
l += offset;
r -= offset;
}
if ($type.isNumber(maxWidth) && maxWidth < Math.abs(r - l)) {
const offset: number = ((r - l) - maxWidth) / 2;
l += offset;
r -= offset;
}
if ($type.isNumber(height)) {
const offset: number = ((b - t) - height) / 2;
t += offset;
b -= offset;
}
if ($type.isNumber(maxHeight) && maxHeight < Math.abs(b - t)) {
const offset: number = ((b - t) - maxHeight) / 2;
t += offset;
b -= offset;
}
if (this.get("adjustBulletPosition")) {
if (fitW) {
r = Math.min(Math.max(0, r), this._pw);
l = Math.min(Math.max(0, l), this._pw);
}
if (fitH) {
t = Math.min(Math.max(0, t), this._ph);
b = Math.min(Math.max(0, b), this._ph);
}
}
dataItem.setRaw("left", l);
dataItem.setRaw("right", r);
dataItem.setRaw("top", t);
dataItem.setRaw("bottom", b);
graphics.setPrivate("width", r - l);
graphics.setPrivate("height", b - t);
graphics.set("x", l);
graphics.set("y", b - (b - t));
}
protected _handleDataSetChange() {
super._handleDataSetChange();
$array.each(this._dataItems, (dataItem) => {
this._toggleColumn(dataItem, false);
})
}
protected _applyGraphicsStates(dataItem: DataItem<this["_dataItemSettings"]>, previousDataItem: DataItem<this["_dataItemSettings"]>) {
const graphics = dataItem.get("graphics")!;
const dropFromOpen = graphics.states.lookup("dropFromOpen");
const riseFromOpen = graphics.states.lookup("riseFromOpen");
const dropFromPrevious = graphics.states.lookup("dropFromPrevious");
const riseFromPrevious = graphics.states.lookup("riseFromPrevious");
if (dropFromOpen || dropFromPrevious || riseFromOpen || riseFromPrevious) {
const xAxis = this.get("xAxis");
const yAxis = this.get("yAxis");
const baseAxis = this.get("baseAxis");
let open: number | undefined;
let close: number | undefined;
let previousClose: number | undefined;
if (baseAxis === xAxis && yAxis.isType<ValueAxis<any>>("ValueAxis")) {
open = dataItem.get(this._yOpenField as any);
close = dataItem.get(this._yField as any);
previousClose = previousDataItem.get(this._yField as any);
}
else if (baseAxis === yAxis && xAxis.isType<ValueAxis<any>>("ValueAxis")) {
open = dataItem.get(this._xOpenField as any);
close = dataItem.get(this._xField as any);
previousClose = previousDataItem.get(this._xField as any);
}
if ($type.isNumber(open) && $type.isNumber(close)) {
if (close < open) {
if (dropFromOpen) {
dropFromOpen.apply();
}
}
else {
if (riseFromOpen) {
riseFromOpen.apply();
}
}
if ($type.isNumber(previousClose)) {
if (close < previousClose) {
if (dropFromPrevious) {
dropFromPrevious.apply();
}
}
else {
if (riseFromPrevious) {
riseFromPrevious.apply();
}
}
}
}
}
}
/**
* @ignore
*/
public disposeDataItem(dataItem: DataItem<this["_dataItemSettings"]>) {
super.disposeDataItem(dataItem);
const graphics = dataItem.get("graphics");
if (graphics) {
this.columns.removeValue(graphics);
graphics.dispose();
}
const rangeGraphics = dataItem.get("rangeGraphics")!;
if (rangeGraphics) {
$array.each(rangeGraphics, (graphics) => {
const list = graphics.getPrivate("list");
if (list) {
list.removeValue(graphics);
}
graphics.dispose();
})
}
}
/**
* Hides series's data item.
*
* @param dataItem Data item
* @param duration Animation duration in milliseconds
* @return Promise
*/
public async hideDataItem(dataItem: DataItem<this["_dataItemSettings"]>, duration?: number): Promise<void> {
const promises = [super.hideDataItem(dataItem, duration)];
const graphics = dataItem.get("graphics");
if (graphics) {
promises.push(graphics.hide(duration));
}
const rangeGraphics = dataItem.get("rangeGraphics")!;
if (rangeGraphics) {
$array.each(rangeGraphics, (graphics) => {
promises.push(graphics.hide(duration));
})
}
await Promise.all(promises);
}
protected _toggleColumn(dataItem: DataItem<this["_dataItemSettings"]>, visible: boolean) {
const graphics = dataItem.get("graphics");
if (graphics) {
graphics.setPrivate("visible", visible);
}
const rangeGraphics = dataItem.get("rangeGraphics")!;
if (rangeGraphics) {
$array.each(rangeGraphics, (graphics) => {
graphics.setPrivate("visible", visible);
})
}
const bullets = dataItem.bullets;
if (bullets) {
$array.each(bullets, (bullet) => {
bullet.setPrivate("hidden", !visible);
})
}
}
/**
* Shows series's data item.
*
* @param dataItem Data item
* @param duration Animation duration in milliseconds
* @return Promise
*/
public async showDataItem(dataItem: DataItem<this["_dataItemSettings"]>, duration?: number): Promise<void> {
const promises = [super.showDataItem(dataItem, duration)];
const graphics = dataItem.get("graphics");
if (graphics) {
promises.push(graphics.show(duration));
}
const rangeGraphics = dataItem.get("rangeGraphics")!;
if (rangeGraphics) {
$array.each(rangeGraphics, (graphics) => {
promises.push(graphics.show(duration));
})
}
await Promise.all(promises);
}
/**
* @ignore
*/
public updateLegendMarker(dataItem?: DataItem<IBaseColumnSeriesDataItem>) {
const legendDataItem = this.get("legendDataItem");
if (legendDataItem) {
let graphics: Template<Graphics> | Graphics = this.columns.template;
if (dataItem) {
let column = dataItem.get("graphics");
if (column) {
graphics = column;
}
}
const markerRectangle = legendDataItem.get("markerRectangle");
if (markerRectangle) {
if (!legendDataItem.get("itemContainer").get("disabled")) {
$array.each(visualSettings, (setting: any) => {
markerRectangle.set(setting, graphics.get(setting, this.get(setting)));
})
}
}
}
}
protected _getTooltipTarget(dataItem: DataItem<this["_dataItemSettings"]>): Sprite {
if (this.get("seriesTooltipTarget") == "bullet") {
return super._getTooltipTarget(dataItem);
}
let column = dataItem.get("graphics");
if (column) {
return column;
}
return this;
}
} | the_stack |
import * as React from "react";
import "./App.css";
import SuperTokens, { getSuperTokensRoutesForReactRouterDom } from "../../../";
import EmailPassword, {
GetRedirectionURLContext as EmailPasswordGetRedirectionURLContext,
OnHandleEventContext as EmailPasswordOnHandleEventContext,
PreAPIHookContext as EmailPasswordPreAPIHookContext,
} from "../../../recipe/emailpassword";
import Session from "../../../recipe/session";
import ThirdParty, {
GetRedirectionURLContext as ThirdPartyGetRedirectionURLContext,
OnHandleEventContext as ThirdPartyOnHandleEventContext,
PreAPIHookContext as ThirdPartyPreAPIHookContext,
} from "../../../recipe/thirdparty";
import ThirdPartyEmailPassword, {
GetRedirectionURLContext as ThirdPartyEmailPasswordGetRedirectionURLContext,
OnHandleEventContext as ThirdPartyEmailPasswordOnHandleEventContext,
PreAPIHookContext as ThirdPartyEmailPasswordPreAPIHookContext,
} from "../../../recipe/thirdpartyemailpassword";
import Home from "./Home";
import { Routes, BrowserRouter as Router, Route } from "react-router-dom";
import Footer from "./Footer";
import HeliumTheme from "./Themes/Helium";
import HydrogenTheme from "./Themes/Hydrogen";
import DarkTheme from "./Themes/Dark";
import { CSSObject } from "@emotion/react";
/*
* This application is used with the purpose of illustrating Supertokens with typescript.
* It is also used internally for deploy previews, hence a lot of code you will see
* in this file is not directly linked to initialising SuperTokens in a typescript environement.
*/
export function getApiDomain() {
const apiPort = process.env.REACT_APP_API_PORT || 8082;
const apiUrl = process.env.REACT_APP_API_URL || `http://localhost:${apiPort}`;
return apiUrl;
}
export function getWebsiteDomain() {
const websitePort = process.env.REACT_APP_WEBSITE_PORT || 3002;
const websiteUrl = process.env.REACT_APP_WEBSITE_URL || `http://localhost:${websitePort}`;
return websiteUrl;
}
const ridParams = getQueryParams("rid");
if (ridParams !== null) {
window.localStorage.setItem("rid", ridParams);
}
const mode = getQueryParams("mode");
if (mode !== null) {
window.localStorage.setItem("mode", mode);
}
const themeQueryParams = getQueryParams("theme");
if (themeQueryParams !== null) {
window.localStorage.setItem("useTheme", themeQueryParams);
}
const theme = getTheme();
const rid = window.localStorage.getItem("rid") || "emailpassword";
const recipeList = getRecipeList();
SuperTokens.init({
appInfo: {
appName: "SuperTokens Demo App",
apiDomain: getApiDomain(),
websiteDomain: window.location.origin,
},
recipeList,
});
function App() {
return (
<div className="App">
<Router>
<div className="fill">
<Routes>
{getSuperTokensRoutesForReactRouterDom(require("react-router-dom"))}
<Route
path="/"
element={
<Auth>
<Home />
</Auth>
}
/>
<Route
path="/redirect-to-this-custom-path"
element={
<Auth>
<Home />
</Auth>
}
/>
</Routes>
</div>
<div className="footer">
<Footer />
</div>
</Router>
</div>
);
}
export default App;
function getQueryParams(param: string): string | null {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get(param);
}
export type Theme = {
colors: Record<string, string>;
style: Record<string, CSSObject>;
};
function getTheme(): {
colors: Record<string, string>;
style?: Record<string, CSSObject>;
} {
let theme = {
colors: {},
style: {},
};
const themeParams = window.localStorage.getItem("useTheme");
if (themeParams === "dark") {
window.document.body.style.backgroundColor = "#1a1a1a";
return DarkTheme;
}
if (themeParams === "helium") {
return HeliumTheme;
}
if (themeParams === "hydrogen") {
return HydrogenTheme;
}
return theme;
}
function getRecipeList() {
return [
getEmailPasswordConfigs(),
getThirdPartyConfigs(),
getThirdPartyEmailPasswordConfigs(),
Session.init(),
Session.init({
autoAddCredentials: true,
isInIframe: true,
sessionExpiredStatusCode: 401,
sessionScope: "",
apiBasePath: "",
apiDomain: "",
cookieDomain: "",
onHandleEvent: (context) => {
if (context.action === "REFRESH_SESSION") {
} else if (context.action === "SIGN_OUT") {
} else if (context.action === "UNAUTHORISED") {
if (context.sessionExpiredOrRevoked) {
}
}
},
preAPIHook: async (context) => {
if (context.action === "REFRESH_SESSION") {
} else if (context.action === "SIGN_OUT") {
}
return context;
},
override: {
functions: (oI) => {
return {
addAxiosInterceptors: (instance, config) => {
return oI.addAxiosInterceptors(instance, config);
},
addFetchInterceptorsAndReturnModifiedFetch: (f, c) => {
return oI.addFetchInterceptorsAndReturnModifiedFetch(f, c);
},
doesSessionExist: (input) => {
return oI.doesSessionExist(input);
},
getAccessTokenPayloadSecurely: (input) => {
return oI.getAccessTokenPayloadSecurely(input);
},
getUserId: (config) => {
return oI.getUserId(config);
},
signOut: (config) => {
return oI.signOut(config);
},
};
},
},
}),
];
}
function getEmailPasswordConfigs() {
return EmailPassword.init({
palette: theme.colors,
emailVerificationFeature: {
sendVerifyEmailScreen: {
style: theme.style,
},
verifyEmailLinkClickedScreen: {
style: theme.style,
},
mode: "REQUIRED",
},
resetPasswordUsingTokenFeature: {
enterEmailForm: {
style: theme.style,
},
submitNewPasswordForm: {
style: theme.style,
},
},
signInAndUpFeature: {
signInForm: {
style: theme.style,
},
signUpForm: {
style: theme.style,
privacyPolicyLink: "https://supertokens.io/legal/privacy-policy",
termsOfServiceLink: "https://supertokens.io/legal/terms-and-conditions",
formFields: [
{
id: "email",
label: "Your Email",
placeholder: "Your work email",
},
{
id: "name",
label: "Full name",
placeholder: "First name and last name",
},
{
id: "age",
label: "Your age",
placeholder: "How old are you?",
validate: async (value) => {
if (parseInt(value) > 18) {
return undefined;
}
return "You must be over 18 to register";
},
},
{
id: "country",
label: "Your Country",
placeholder: "Where do you live?",
optional: true,
},
],
},
},
onHandleEvent(context: EmailPasswordOnHandleEventContext) {},
async preAPIHook(context: EmailPasswordPreAPIHookContext) {
return context;
},
async getRedirectionURL(context: EmailPasswordGetRedirectionURLContext) {
return undefined;
},
override: {
functions: (oI) => {
return {
...oI,
doesEmailExist: (input) => {
return oI.doesEmailExist(input);
},
sendPasswordResetEmail: (input) => {
return oI.sendPasswordResetEmail(input);
},
signIn: (input) => {
return oI.signIn(input);
},
signUp: (input) => {
return oI.signUp(input);
},
submitNewPassword: (input) => {
return oI.submitNewPassword(input);
},
};
},
components: {
EmailPasswordSignIn: ({ DefaultComponent, ...props }) => {
return (
<div>
<DefaultComponent {...props} />
</div>
);
},
EmailPasswordSignInHeader: ({ DefaultComponent, ...props }) => {
return (
<div>
<DefaultComponent {...props} />
</div>
);
},
EmailPasswordSubmitNewPassword: ({ DefaultComponent, ...props }) => {
return (
<div>
<DefaultComponent {...props} />
</div>
);
},
},
emailVerification: {
functions: (oI) => {
return {
isEmailVerified: (input) => {
return oI.isEmailVerified(input);
},
sendVerificationEmail: (input) => {
return oI.sendVerificationEmail(input);
},
verifyEmail: (input) => {
return oI.verifyEmail(input);
},
};
},
components: {
EmailVerificationSendVerifyEmail: ({ DefaultComponent, ...props }) => {
return (
<div>
<DefaultComponent {...props} />
</div>
);
},
},
},
},
});
}
function getThirdPartyConfigs() {
return ThirdParty.init({
onHandleEvent(context: ThirdPartyOnHandleEventContext) {},
async preAPIHook(context: ThirdPartyPreAPIHookContext) {
return context;
},
async getRedirectionURL(context: ThirdPartyGetRedirectionURLContext) {
return undefined;
},
palette: theme.colors,
signInAndUpFeature: {
style: theme.style,
privacyPolicyLink: "https://supertokens.io/legal/privacy-policy",
termsOfServiceLink: "https://supertokens.io/legal/terms-and-conditions",
providers: [
ThirdParty.Github.init(),
ThirdParty.Google.init({
clientId: "some client ID",
}),
ThirdParty.Facebook.init(),
ThirdParty.Apple.init(),
{
id: "custom",
name: "Custom",
},
],
},
oAuthCallbackScreen: {
style: theme.style,
},
override: {
functions: (oI) => {
return {
...oI,
};
},
components: {
ThirdPartySignInAndUpCallbackTheme: ({ DefaultComponent }) => {
return (
<div>
<DefaultComponent />
</div>
);
},
},
emailVerification: {
functions: (oI) => {
return {
...oI,
};
},
components: {
EmailVerificationVerifyEmailLinkClicked: ({ DefaultComponent, ...props }) => {
return (
<div>
<DefaultComponent {...props} />
</div>
);
},
},
},
},
});
}
function getThirdPartyEmailPasswordConfigs() {
return ThirdPartyEmailPassword.init({
onHandleEvent(context: ThirdPartyEmailPasswordOnHandleEventContext) {},
async preAPIHook(context: ThirdPartyEmailPasswordPreAPIHookContext) {
return context;
},
async getRedirectionURL(context: ThirdPartyEmailPasswordGetRedirectionURLContext) {
return undefined;
},
palette: theme.colors,
signInAndUpFeature: {
style: theme.style,
signUpForm: {
privacyPolicyLink: "https://supertokens.io/legal/privacy-policy",
termsOfServiceLink: "https://supertokens.io/legal/terms-and-conditions",
},
providers: [
ThirdPartyEmailPassword.Github.init(),
ThirdPartyEmailPassword.Google.init(),
ThirdPartyEmailPassword.Facebook.init(),
ThirdPartyEmailPassword.Apple.init(),
{
id: "custom",
name: "Custom",
},
],
},
oAuthCallbackScreen: {
style: theme.style,
},
override: {
components: {
ThirdPartySignInAndUpProvidersForm: ({ DefaultComponent, ...props }) => {
return (
<div>
<DefaultComponent {...props} />
</div>
);
},
EmailPasswordResetPasswordEmail: ({ DefaultComponent, ...props }) => {
return (
<div>
<DefaultComponent {...props} />
</div>
);
},
},
emailVerification: {
components: {
EmailVerificationVerifyEmailLinkClicked: ({ DefaultComponent, ...props }) => {
return (
<div>
<DefaultComponent {...props} />
</div>
);
},
},
},
},
});
}
function Auth(props: any) {
if (rid === "thirdparty") {
return <ThirdParty.ThirdPartyAuth>{props.children}</ThirdParty.ThirdPartyAuth>;
} else if (rid === "thirdpartyemailpassword") {
return (
<ThirdPartyEmailPassword.ThirdPartyEmailPasswordAuth>
{props.children}
</ThirdPartyEmailPassword.ThirdPartyEmailPasswordAuth>
);
}
return <EmailPassword.EmailPasswordAuth>{props.children}</EmailPassword.EmailPasswordAuth>;
} | the_stack |
import { i18nMark } from "@lingui/react";
import { Trans } from "@lingui/macro";
import { routerShape, Link } from "react-router";
import * as React from "react";
import mixin from "reactjs-mixin";
import { Icon } from "@dcos/ui-kit";
import { ProductIcons } from "@dcos/ui-kit/dist/packages/icons/dist/product-icons-enum";
import { iconSizeS } from "@dcos/ui-kit/dist/packages/design-tokens/build/js/designTokens";
import DCOSStore from "#SRC/js/stores/DCOSStore";
import * as ResourcesUtil from "#SRC/js/utils/ResourcesUtil";
import StoreMixin from "#SRC/js/mixins/StoreMixin";
import Breadcrumb from "../components/Breadcrumb";
import Loader from "../components/Loader";
import BreadcrumbTextContent from "../components/BreadcrumbTextContent";
import ComponentList from "../components/ComponentList";
import Config from "../config/Config";
import MesosSummaryStore from "../stores/MesosSummaryStore";
import Page from "../components/Page";
import Panel from "../components/Panel";
import ServiceList from "../../../plugins/services/src/js/components/ServiceList";
import StringUtil from "../utils/StringUtil";
import UnitHealthStore from "../stores/UnitHealthStore";
import DashboardHeadings from "../constants/DashboardHeadings";
import HealthUnitsList from "../structs/HealthUnitsList";
function getMesosState() {
const states = MesosSummaryStore.get("states");
const last = states.lastSuccessful();
return {
activeNodes: states.getActiveNodesByState(),
hostCount: last.getActiveSlaves().length,
usedResourcesStates: states.getResourceStatesForNodeIDs(),
usedResources: last.getSlaveUsedResources(),
tasks: last.getServiceList().sumTaskStates(),
totalResources: last.getSlaveTotalResources(),
};
}
const ResourceTimeSeriesChart = React.lazy(
() =>
import(
/* webpackChunkName: "resourcetimeserieschart" */ "../components/charts/ResourceTimeSeriesChart"
)
);
const HostTimeSeriesChart = React.lazy(
() =>
import(
/* webpackChunkName: "hosttimeserieschart" */ "../components/charts/HostTimeSeriesChart"
)
);
const TasksChart = React.lazy(
() =>
import(
/* webpackChunkName: "taskschart" */ "../components/charts/TasksChart"
)
);
const DashboardBreadcrumbs = () => {
const crumbs = [
<Breadcrumb key={0} title="Dashboard">
<BreadcrumbTextContent>
<Link to="/dashboard">
<Trans render="span">Dashboard</Trans>
</Link>
</BreadcrumbTextContent>
</Breadcrumb>,
];
return (
<Page.Header.Breadcrumbs iconID={ProductIcons.Graph} breadcrumbs={crumbs} />
);
};
export default class DashboardPage extends mixin(StoreMixin) {
static routeConfig = {
label: i18nMark("Dashboard"),
icon: <Icon shape={ProductIcons.GraphInverse} size={iconSizeS} />,
matches: /^\/dashboard/,
};
static contextTypes = {
router: routerShape,
};
static defaultProps = {
componentsListLength: 5,
servicesListLength: 5,
};
state = {
dcosServices: [],
unitHealthUnits: new HealthUnitsList({ items: [] }),
mesosState: getMesosState(),
};
store_listeners = [
{ name: "dcos", events: ["change"], suppressUpdate: true },
{ name: "summary", events: ["success", "error"], suppressUpdate: true },
{ name: "unitHealth", events: ["success", "error"], suppressUpdate: true },
];
onDcosStoreChange = () => {
this.setState({
dcosServices: DCOSStore.serviceTree.getServices().getItems(),
});
};
onSummaryStoreSuccess = () => {
this.setState({
mesosState: { ...this.state.mesosState, ...getMesosState() },
});
};
onSummaryStoreError = () => {
this.setState({
mesosState: { ...this.state.mesosState, ...getMesosState() },
});
};
onUnitHealthStoreSuccess = () => {
this.setState({
unitHealthUnits: UnitHealthStore.getUnits(),
});
};
onUnitHealthStoreError = () => {
this.setState({
unitHealthUnits: UnitHealthStore.getUnits(),
});
};
getServicesList() {
const services = this.state.dcosServices;
const sortedServices = services.sort((firstService, secondService) => {
const firstStatus = firstService.getServiceStatus();
const secondStatus = secondService.getServiceStatus();
// We invert this, since we want to show the highest priorities last.
return secondStatus.priority - firstStatus.priority;
});
return sortedServices.slice(0, this.props.servicesListLength);
}
getViewAllComponentsButton() {
const componentCount = this.state.unitHealthUnits.getItems().length;
if (!componentCount) {
return null;
}
/* L10NTODO: Pluralize */
const componentCountWord = StringUtil.pluralize(
"Component",
componentCount
);
return (
<Trans
render={
<Link to="/components" className="button button-primary-link" />
}
>
View all {componentCount} {componentCountWord}
</Trans>
);
}
getViewAllServicesBtn() {
let servicesCount = this.state.dcosServices.length;
if (!servicesCount) {
return null;
}
if (servicesCount < this.props.servicesListLength) {
servicesCount = null;
}
/* L10NTODO: Pluralize */
return (
<Trans
render={<Link to="/services" className="button button-primary-link" />}
>
View all {servicesCount} Services
</Trans>
);
}
getHeading(translationId) {
return (
<Trans
id={translationId}
render="h3"
className="flush text-align-center"
/>
);
}
render() {
const columnClasses = "column-12 column-small-6 column-large-4";
const resourceColors = ResourcesUtil.getResourceColors();
const data = this.state.mesosState;
return (
<Page title="Dashboard">
<Page.Header breadcrumbs={<DashboardBreadcrumbs />} />
<div className="panel-grid row">
<div className={columnClasses}>
<Panel
className="dashboard-panel dashboard-panel-chart dashboard-panel-chart-timeseries panel"
heading={this.getHeading(DashboardHeadings.CPU)}
>
<React.Suspense fallback={<Loader />}>
<ResourceTimeSeriesChart
colorIndex={resourceColors.cpus}
usedResourcesStates={data.usedResourcesStates}
usedResources={data.usedResources}
totalResources={data.totalResources}
mode="cpus"
refreshRate={Config.getRefreshRate()}
/>
</React.Suspense>
</Panel>
</div>
<div className={columnClasses}>
<Panel
className="dashboard-panel dashboard-panel-chart dashboard-panel-chart-timeseries panel"
heading={this.getHeading(DashboardHeadings.MEMORY)}
>
<React.Suspense fallback={<Loader />}>
<ResourceTimeSeriesChart
colorIndex={resourceColors.mem}
usedResourcesStates={data.usedResourcesStates}
usedResources={data.usedResources}
totalResources={data.totalResources}
mode="mem"
refreshRate={Config.getRefreshRate()}
/>
</React.Suspense>
</Panel>
</div>
<div className={columnClasses}>
<Panel
className="dashboard-panel dashboard-panel-chart dashboard-panel-chart-timeseries panel"
heading={this.getHeading(DashboardHeadings.DISK)}
>
<React.Suspense fallback={<Loader />}>
<ResourceTimeSeriesChart
colorIndex={resourceColors.disk}
usedResourcesStates={data.usedResourcesStates}
usedResources={data.usedResources}
totalResources={data.totalResources}
mode="disk"
refreshRate={Config.getRefreshRate()}
/>
</React.Suspense>
</Panel>
</div>
<div className={columnClasses}>
<Panel
className="dashboard-panel dashboard-panel-chart dashboard-panel-chart-timeseries panel"
heading={this.getHeading(DashboardHeadings.GPU)}
>
<React.Suspense fallback={<Loader />}>
<ResourceTimeSeriesChart
colorIndex={resourceColors.gpus}
usedResourcesStates={data.usedResourcesStates}
usedResources={data.usedResources}
totalResources={data.totalResources}
mode="gpus"
refreshRate={Config.getRefreshRate()}
/>
</React.Suspense>
</Panel>
</div>
<div className={columnClasses}>
<Panel
className="dashboard-panel dashboard-panel-chart dashboard-panel-chart-timeseries panel"
heading={this.getHeading(DashboardHeadings.NODES)}
>
<React.Suspense fallback={<Loader />}>
<HostTimeSeriesChart
data={data.activeNodes}
currentValue={data.hostCount}
refreshRate={Config.getRefreshRate()}
colorIndex={4}
/>
</React.Suspense>
</Panel>
</div>
<div className={columnClasses}>
<Panel
className="dashboard-panel dashboard-panel-list dashboard-panel-list-service-health allow-overflow panel"
heading={this.getHeading(DashboardHeadings.SERVICES_STATUS)}
footer={this.getViewAllServicesBtn()}
footerClass="text-align-center"
>
<ServiceList services={this.getServicesList()} />
</Panel>
</div>
<div className={columnClasses}>
<Panel
className="dashboard-panel dashboard-panel-chart panel"
heading={this.getHeading(DashboardHeadings.TASKS)}
>
<React.Suspense fallback={<Loader />}>
<TasksChart tasks={data.tasks} />
</React.Suspense>
</Panel>
</div>
<div className={columnClasses}>
<Panel
className="dashboard-panel dashboard-panel-list dashboard-panel-list-component-health panel"
heading={this.getHeading(DashboardHeadings.COMPONENT_HEALTH)}
footer={this.getViewAllComponentsButton()}
footerClass="text-align-center"
>
<ComponentList
displayCount={this.props.componentsListLength}
units={this.state.unitHealthUnits}
/>
</Panel>
</div>
</div>
</Page>
);
}
} | the_stack |
import {
options, objectForEach, clonePlainObjectDeep, extend, hasOwnProperty
} from '@tko/utils'
import {default as Expression} from './Expression'
import {default as Identifier} from './Identifier'
import {default as Arguments} from './Arguments'
import {default as Ternary} from './Ternary'
import {default as Node} from './Node'
import {default as operators} from './operators'
const escapee = {
"'": "'",
'"': '"',
'`': '`',
'\\': '\\',
'/': '/',
'$': '$',
b: '\b',
f: '\f',
n: '\n',
r: '\r',
t: '\t'
}
/**
* Construct a new Parser instance with new Parser(node, context)
* @param {Node} node The DOM element from which we parsed the
* content.
* @param {object} context The Knockout context.
* @param {object} globals An object containing any desired globals.
*/
export default class Parser {
white () {
var ch = this.ch
while (ch && ch <= ' ') {
ch = this.next()
}
return this.comment(ch)
}
/**
* Slurp any C or C++ style comments
*/
comment (ch) {
if (ch !== '/') { return ch }
var p = this.at
var second = this.lookahead()
if (second === '/') {
while (ch) {
ch = this.next()
if (ch === '\n' || ch === '\r') { break }
}
ch = this.next()
} else if (second === '*') {
while (ch) {
ch = this.next()
if (ch === '*' && this.lookahead() === '/') {
this.next()
break
}
}
if (!ch) {
this.error('Unclosed comment, starting at character ' + p)
}
this.next()
return this.white()
}
return ch
};
next (c) {
if (c && c !== this.ch) {
this.error("Expected '" + c + "' but got '" + this.ch + "'")
}
this.ch = this.text.charAt(this.at)
this.at += 1
return this.ch
}
lookahead () {
return this.text[this.at]
}
error (m) {
if (m instanceof Error) { throw m }
let [name, msg] = m.name ? [m.name, m.message] : [m, '']
const message = `\n${name} ${msg} of
${this.text}\n` + Array(this.at).join(' ') + '_/ 🔥 \\_\n'
throw new Error(message)
}
name () {
// A name of a binding
var name = ''
var enclosedBy
this.white()
var ch = this.ch
if (ch === "'" || ch === '"') {
enclosedBy = ch
ch = this.next()
}
while (ch) {
if (enclosedBy && ch === enclosedBy) {
this.white()
ch = this.next()
if (ch !== ':' && ch !== ',') {
this.error(
'Object name: ' + name + ' missing closing ' + enclosedBy
)
}
return name
} else if (ch === ':' || ch <= ' ' || ch === ',' || ch === '|') {
return name
}
name += ch
ch = this.next()
}
return name
}
number () {
let number
let string = ''
let ch = this.ch
if (ch === '-') {
string = '-'
ch = this.next('-')
}
while (ch >= '0' && ch <= '9') {
string += ch
ch = this.next()
}
if (ch === '.') {
string += '.'
ch = this.next()
while (ch && ch >= '0' && ch <= '9') {
string += ch
ch = this.next()
}
}
if (ch === 'e' || ch === 'E') {
string += ch
ch = this.next()
if (ch === '-' || ch === '+') {
string += ch
ch = this.next()
}
while (ch >= '0' && ch <= '9') {
string += ch
ch = this.next()
}
}
number = +string
if (!isFinite(number)) {
options.onError(new Error('Bad number: ' + number + ' in ' + string))
} else {
return number
}
}
/**
* Add a property to 'object' that equals the given value.
* @param {Object} object The object to add the value to.
* @param {String} key object[key] is set to the given value.
* @param {mixed} value The value, may be a primitive or a function. If a
* function it is unwrapped as a property.
*/
objectAddValue (object, key, value) {
if (value && value[Node.isExpressionOrIdentifierSymbol]) {
Object.defineProperty(object, key, {
get: () => Node.value_of(value, ...this.currentContextGlobals),
enumerable: true
})
} else if (Array.isArray(value)) {
Object.defineProperty(object, key, {
get: () => value.map(v => Node.value_of(v, ...this.currentContextGlobals)),
enumerable: true
})
} else {
// primitives
object[key] = value
}
}
object () {
let key
let object = {}
let ch = this.ch
if (ch === '{') {
this.next('{')
ch = this.white()
if (ch === '}') {
ch = this.next('}')
return object
}
while (ch) {
if (ch === '"' || ch === "'" || ch === '`') {
key = this.string()
} else {
key = this.name()
}
if (hasOwnProperty(object, key)) {
this.error('Duplicate key "' + key + '"')
}
if (this.white() === ':') {
ch = this.next(':')
this.objectAddValue(object, key, this.expression())
} else {
const objectKeyIsValue = new Identifier(this, key, [])
this.objectAddValue(object, key, objectKeyIsValue)
}
ch = this.white()
if (ch === '}') {
ch = this.next('}')
return object
}
this.next(',')
ch = this.white()
if (ch === '}') {
ch = this.next('}')
return object
}
}
}
this.error('Bad object')
}
/**
* Read up to delim and return the string
* @param {string} delim The delimiter, either ' or "
* @return {string} The string read.
*/
readString (delim) {
let string = ''
let nodes = ['']
let plusOp = operators['+']
let hex
let i
let uffff
let interpolate = delim === '`'
let ch = this.next()
while (ch) {
if (ch === delim) {
ch = this.next()
if (interpolate) { nodes.push(plusOp) }
nodes.push(string)
return nodes
}
if (ch === '\\') {
ch = this.next()
if (ch === 'u') {
uffff = 0
for (i = 0; i < 4; i += 1) {
hex = parseInt(ch = this.next(), 16)
if (!isFinite(hex)) {
break
}
uffff = uffff * 16 + hex
}
string += String.fromCharCode(uffff)
} else if (typeof escapee[ch] === 'string') {
string += escapee[ch]
} else {
break
}
} else if (interpolate && ch === '$') {
ch = this.next()
if (ch === '{') {
this.next('{')
nodes.push(plusOp)
nodes.push(string)
nodes.push(plusOp)
nodes.push(this.expression())
string = ''
// this.next('}');
} else {
string += '$' + ch
}
} else {
string += ch
}
ch = this.next()
}
this.error('Bad string')
}
string () {
var ch = this.ch
if (ch === '"') {
return this.readString('"').join('')
} else if (ch === "'") {
return this.readString("'").join('')
} else if (ch === '`') {
return Node.create_root(this.readString('`'))
}
this.error('Bad string')
}
array () {
let array = []
let ch = this.ch
if (ch === '[') {
ch = this.next('[')
this.white()
if (ch === ']') {
ch = this.next(']')
return array
}
while (ch) {
array.push(this.expression())
ch = this.white()
if (ch === ']') {
ch = this.next(']')
return array
}
this.next(',')
ch = this.white()
}
}
this.error('Bad array')
}
value () {
var ch
this.white()
ch = this.ch
switch (ch) {
case '{': return this.object()
case '[': return this.array()
case '"': case "'": case '`': return this.string()
case '-': return this.number()
default:
return ch >= '0' && ch <= '9' ? this.number() : this.identifier()
}
}
/**
* Get the function for the given operator.
* A `.precedence` value is added to the function, with increasing
* precedence having a higher number.
* @return {function} The function that performs the infix operation
*/
operator (opts) {
let op = ''
let opFn
let ch = this.white()
let isIdentifierChar = Identifier.is_valid_start_char
while (ch) {
if (isIdentifierChar(ch) || ch <= ' ' || ch === '' ||
ch === '"' || ch === "'" || ch === '{' || ch === '(' ||
ch === '`' || ch === ')' || (ch <= '9' && ch >= '0')) {
break
}
if (!opts.not_an_array && ch === '[') {
break
}
op += ch
ch = this.next()
// An infix followed by the prefix e.g. a + @b
// TODO: other prefix unary operators
if (ch === '@') {
break
}
isIdentifierChar = Identifier.is_valid_continue_char
}
if (op !== '') {
if (opts.prefix && op === '-') { op = '&-' }
opFn = operators[op]
if (!opFn) {
this.error("Bad operator: '" + op + "'.")
}
}
return opFn
}
/**
* Filters
* Returns what the Node interprets as an "operator".
* e.g.
* <span data-bind="text: name | fit:20 | uppercase"></span>
*/
filter () {
let ch = this.next()
let args = []
let nextFilter = function (v) { return v }
let name = this.name()
if (!options.filters[name]) {
options.onError('Cannot find filter by the name of: ' + name)
}
ch = this.white()
while (ch) {
if (ch === ':') {
ch = this.next()
args.push(this.expression('|'))
}
if (ch === '|') {
nextFilter = this.filter()
break
}
if (ch === ',') { break }
ch = this.white()
}
var filter = function filter (value, ignored, context, globals, node) {
var argValues = [value]
for (var i = 0, j = args.length; i < j; ++i) {
argValues.push(Node.value_of(args[i], context, globals, node))
}
return nextFilter(options.filters[name].apply(null, argValues))
}
// Lowest precedence.
filter.precedence = 1
return filter
}
/**
* Parse an expression – builds an operator tree, in something like
* Shunting-Yard.
* See: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
*
* @return {function} A function that computes the value of the expression
* when called or a primitive.
*/
expression (filterable) {
let op
let nodes = []
let ch = this.white()
while (ch) {
// unary prefix operators
op = this.operator({ prefix: true })
if (op) {
nodes.push(undefined) // LHS Tree node.
nodes.push(op)
ch = this.white()
}
if (ch === '(') {
this.next()
nodes.push(this.expression())
this.next(')')
} else {
nodes.push(this.value())
}
ch = this.white()
if (ch === ':' || ch === '}' || ch === ',' || ch === ']' ||
ch === ')' || ch === '' || ch === '`' || (ch === '|' && filterable === '|')) {
break
}
// filters
if (ch === '|' && this.lookahead() !== '|' && filterable) {
nodes.push(this.filter())
nodes.push(undefined)
break
}
// infix or postfix operators
op = this.operator({ not_an_array: true })
if (op === operators['?']) {
this.ternary(nodes)
break
} else if (op === operators['.']) {
nodes.push(op)
nodes.push(this.member())
op = null
} else if (op === operators['[']) {
nodes.push(op)
nodes.push(this.expression())
ch = this.next(']')
op = null
} else if (op) {
nodes.push(op)
}
ch = this.white()
if (ch === ']' || (!op && ch === '(')) { break }
}
if (nodes.length === 0) {
return undefined
}
var dereferences = this.dereferences()
if (nodes.length === 1 && !dereferences.length) {
return nodes[0]
}
for (var i = 0, j = dereferences.length; i < j; ++i) {
var deref = dereferences[i]
if (deref.constructor === Arguments) {
nodes.push(operators.call)
} else {
nodes.push(operators['.'])
}
nodes.push(deref)
}
return new Expression(nodes)
}
ternary (nodes) {
var ternary = new Ternary()
ternary.yes = this.expression()
this.next(':')
ternary.no = this.expression()
nodes.push(operators['?'])
nodes.push(ternary)
}
/**
* Parse the arguments to a function, returning an Array.
*
*/
funcArguments () {
let args = []
let ch = this.next('(')
while (ch) {
ch = this.white()
if (ch === ')') {
this.next(')')
return new Arguments(this, args)
} else {
args.push(this.expression())
ch = this.white()
}
if (ch !== ')') { this.next(',') }
}
this.error('Bad arguments to function')
}
/**
* The literal string reference `abc` in an `x.abc` expression.
*/
member () {
let member = ''
let ch = this.white()
let isIdentifierChar = Identifier.is_valid_start_char
while (ch) {
if (!isIdentifierChar(ch)) {
break
}
member += ch
ch = this.next()
isIdentifierChar = Identifier.is_valid_continue_char
}
return member
}
/**
* A dereference applies to an identifer, being either a function
* call "()" or a membership lookup with square brackets "[member]".
* @return {fn or undefined} Dereference function to be applied to the
* Identifier
*/
dereference () {
let member
let ch = this.white()
while (ch) {
if (ch === '(') {
// a(...) function call
return this.funcArguments()
} else if (ch === '[') {
// a[x] membership
this.next('[')
member = this.expression()
this.white()
this.next(']')
return member
} else if (ch === '.') {
// a.x membership
this.next('.')
return this.member()
} else {
break
}
}
}
dereferences () {
let ch = this.white()
let dereferences = []
let deref
while (ch) {
deref = this.dereference()
if (deref !== undefined) {
dereferences.push(deref)
} else {
break
}
}
return dereferences
}
identifier () {
let token = ''
let isIdentifierChar = Identifier.is_valid_start_char
let ch = this.white()
while (ch) {
if (!isIdentifierChar(ch)) {
break
}
token += ch
ch = this.next()
isIdentifierChar = Identifier.is_valid_continue_char
}
switch (token) {
case 'true': return true
case 'false': return false
case 'null': return null
case 'undefined': return void 0
case 'function':
throw new Error('Knockout: Anonymous functions are no longer supported, but `=>` lambdas are.')
// return this.anonymous_fn();
}
return new Identifier(this, token, this.dereferences())
}
readBindings () {
let key
let bindings = {}
let sep
let expr
let ch = this.ch
while (ch) {
key = this.name()
sep = this.white()
if (!sep || sep === ',') {
if (sep) {
ch = this.next(',')
} else {
ch = ''
}
// A "bare" binding e.g. "text"; substitute value of 'null'
// so it becomes "text: null".
bindings[key] = null
} else {
if (key.indexOf('.') !== -1) {
// Namespaced – i.e.
// `attr.css: x` becomes `attr: { css: x }`
// ^^^ - key
key = key.split('.')
bindings[key[0]] = bindings[key[0]] || {}
if (key.length !== 2) {
options.onError('Binding ' + key + ' should have two parts (a.b).')
} else if (bindings[key[0]].constructor !== Object) {
options.onError('Binding ' + key[0] + '.' + key[1] + ' paired with a non-object.')
}
ch = this.next(':')
this.objectAddValue(bindings[key[0]], key[1], this.expression(true))
} else {
ch = this.next(':')
if (bindings[key] && typeof bindings[key] === 'object' && bindings[key].constructor === Object) {
// Extend a namespaced bindings e.g. we've previously seen
// on.x, now we're seeing on: { 'abc' }.
expr = this.expression(true)
if (typeof expr !== 'object' || expr.constructor !== Object) {
options.onError('Expected plain object for ' + key + ' value.')
} else {
extend(bindings[key], expr)
}
} else {
bindings[key] = this.expression(true)
}
}
this.white()
if (this.ch) {
ch = this.next(',')
} else {
ch = ''
}
}
}
return bindings
}
valueAsAccessor (value, context, globals, node) {
if (!value) { return () => value }
if (typeof value === 'function') { return value }
if (value[Node.isExpressionOrIdentifierSymbol]) {
return () => Node.value_of(value, context, globals, node)
}
if (Array.isArray(value)) {
return () => value.map(v => Node.value_of(v, context, globals, node))
}
if (typeof (value) !== 'function') {
return () => clonePlainObjectDeep(value)
}
throw new Error('Value has cannot be converted to accessor: ' + value)
}
/**
* Convert result[name] from a value to a function (i.e. `valueAccessor()`)
* @param {object} result [Map of top-level names to values]
* @return {object} [Map of top-level names to functions]
*
* Accessors may be one of (below) constAccessor, identifierAccessor,
* expressionAccessor, or nodeAccessor.
*/
convertToAccessors (result, context, globals, node) {
objectForEach(result, (name, value) => {
if (value instanceof Identifier) {
// Return a function that, with no arguments returns
// the value of the identifier, otherwise sets the
// value of the identifier to the first given argument.
Object.defineProperty(result, name, {
value: function (optionalValue, options) {
const currentValue = value.get_value(undefined, context, globals, node)
if (arguments.length === 0) { return currentValue }
const unchanged = optionalValue === currentValue
if (options && options.onlyIfChanged && unchanged) { return }
return value.set_value(optionalValue, context, globals)
}
})
} else {
result[name] = this.valueAsAccessor(value, context, globals, node)
}
})
return result
}
preparse (source = '') {
const preparsers = options.bindingStringPreparsers || []
return preparsers.reduce((acc, fn) => fn(acc), source.trim())
}
runParse (source, fn) {
this.text = this.preparse(source)
this.at = 0
this.ch = ' '
try {
var result = fn()
this.white()
if (this.ch) {
this.error('Syntax Error')
}
return result
} catch (e) {
options.onError(e)
}
}
/**
* Get the bindings as name: accessor()
* @param {string} source The binding string to parse.
* @return {object} Map of name to accessor function.
*/
parse (source, context = {}, globals = {}, node) {
if (!source) { return () => null }
this.currentContextGlobals = [context, globals, node]
const parseFn = () => this.readBindings()
const bindingAccessors = this.runParse(source, parseFn)
return this.convertToAccessors(bindingAccessors, context, globals, node)
}
/**
* Return a function that evaluates and returns the result of the expression.
*/
parseExpression (source, context = {}, globals = {}, node) {
if (!source) { return () => '' }
this.currentContextGlobals = [context, globals, node]
const parseFn = () => this.expression(true)
const bindingAccessors = this.runParse(source, parseFn)
return this.valueAsAccessor(bindingAccessors, context, globals, node)
}
} | the_stack |
import { Result, result } from '@expo/results';
import { IEntityClass } from './Entity';
import EntityPrivacyPolicy from './EntityPrivacyPolicy';
import { EntityQueryContext } from './EntityQueryContext';
import ReadonlyEntity from './ReadonlyEntity';
import ViewerContext from './ViewerContext';
export default class EntityAssociationLoader<
TFields,
TID extends NonNullable<TFields[TSelectedFields]>,
TViewerContext extends ViewerContext,
TEntity extends ReadonlyEntity<TFields, TID, TViewerContext, TSelectedFields>,
TSelectedFields extends keyof TFields
> {
constructor(private readonly entity: TEntity) {}
/**
* Load an associated entity identified by a field value of this entity. In a relational database,
* the field in this entity is a foreign key to the ID of the associated entity.
* @param fieldIdentifyingAssociatedEntity - field of this entity containing the ID of the associated entity
* @param associatedEntityClass - class of the associated entity
* @param queryContext - query context in which to perform the load
*/
async loadAssociatedEntityAsync<
TIdentifyingField extends keyof Pick<TFields, TSelectedFields>,
TAssociatedFields,
TAssociatedID extends NonNullable<TAssociatedFields[TAssociatedSelectedFields]>,
TAssociatedEntity extends ReadonlyEntity<
TAssociatedFields,
TAssociatedID,
TViewerContext,
TAssociatedSelectedFields
>,
TAssociatedPrivacyPolicy extends EntityPrivacyPolicy<
TAssociatedFields,
TAssociatedID,
TViewerContext,
TAssociatedEntity,
TAssociatedSelectedFields
>,
TAssociatedSelectedFields extends keyof TAssociatedFields = keyof TAssociatedFields
>(
fieldIdentifyingAssociatedEntity: TIdentifyingField,
associatedEntityClass: IEntityClass<
TAssociatedFields,
TAssociatedID,
TViewerContext,
TAssociatedEntity,
TAssociatedPrivacyPolicy,
TAssociatedSelectedFields
>,
queryContext: EntityQueryContext = this.entity
.getViewerContext()
.getViewerScopedEntityCompanionForClass(associatedEntityClass)
.getQueryContextProvider()
.getQueryContext()
): Promise<
Result<null extends TFields[TIdentifyingField] ? TAssociatedEntity | null : TAssociatedEntity>
> {
const associatedEntityID = this.entity.getField(fieldIdentifyingAssociatedEntity);
if (!associatedEntityID) {
return result(null) as Result<
null extends TFields[TIdentifyingField] ? TAssociatedEntity | null : TAssociatedEntity
>;
}
const loader = this.entity
.getViewerContext()
.getViewerScopedEntityCompanionForClass(associatedEntityClass)
.getLoaderFactory()
.forLoad(queryContext);
return (await loader.loadByIDAsync(associatedEntityID as unknown as TAssociatedID)) as Result<
null extends TFields[TIdentifyingField] ? TAssociatedEntity | null : TAssociatedEntity
>;
}
/**
* Load many entities associated with this entity, often referred to as entites belonging
* to this entity. In a relational database, the field in the foreign entity is a
* foreign key to the ID of this entity. Also commonly referred to as a has many relationship,
* where this entity has many associated entities.
* @param associatedEntityClass - class of the associated entities
* @param associatedEntityFieldContainingThisID - field of associated entity which contains the ID of this entity
* @param queryContext - query context in which to perform the load
*/
async loadManyAssociatedEntitiesAsync<
TAssociatedFields,
TAssociatedID extends NonNullable<TAssociatedFields[TAssociatedSelectedFields]>,
TAssociatedEntity extends ReadonlyEntity<
TAssociatedFields,
TAssociatedID,
TViewerContext,
TAssociatedSelectedFields
>,
TAssociatedPrivacyPolicy extends EntityPrivacyPolicy<
TAssociatedFields,
TAssociatedID,
TViewerContext,
TAssociatedEntity,
TAssociatedSelectedFields
>,
TAssociatedSelectedFields extends keyof TAssociatedFields = keyof TAssociatedFields
>(
associatedEntityClass: IEntityClass<
TAssociatedFields,
TAssociatedID,
TViewerContext,
TAssociatedEntity,
TAssociatedPrivacyPolicy,
TAssociatedSelectedFields
>,
associatedEntityFieldContainingThisID: keyof Pick<TAssociatedFields, TAssociatedSelectedFields>,
queryContext: EntityQueryContext = this.entity
.getViewerContext()
.getViewerScopedEntityCompanionForClass(associatedEntityClass)
.getQueryContextProvider()
.getQueryContext()
): Promise<readonly Result<TAssociatedEntity>[]> {
const thisID = this.entity.getID();
const loader = this.entity
.getViewerContext()
.getViewerScopedEntityCompanionForClass(associatedEntityClass)
.getLoaderFactory()
.forLoad(queryContext);
return await loader.loadManyByFieldEqualingAsync(
associatedEntityFieldContainingThisID,
thisID as any
);
}
/**
* Load an associated entity identified by a field value of this entity. In a relational database,
* the field in this entity is a foreign key to a unique field of the associated entity.
* @param fieldIdentifyingAssociatedEntity - field of this entity containing the value with which to look up associated entity
* @param associatedEntityClass - class of the associated entity
* @param associatedEntityLookupByField - field of associated entity with which to look up the associated entity
* @param queryContext - query context in which to perform the load
*/
async loadAssociatedEntityByFieldEqualingAsync<
TAssociatedFields,
TAssociatedID extends NonNullable<TAssociatedFields[TAssociatedSelectedFields]>,
TAssociatedEntity extends ReadonlyEntity<
TAssociatedFields,
TAssociatedID,
TViewerContext,
TAssociatedSelectedFields
>,
TAssociatedPrivacyPolicy extends EntityPrivacyPolicy<
TAssociatedFields,
TAssociatedID,
TViewerContext,
TAssociatedEntity,
TAssociatedSelectedFields
>,
TAssociatedSelectedFields extends keyof TAssociatedFields = keyof TAssociatedFields
>(
fieldIdentifyingAssociatedEntity: keyof Pick<TFields, TSelectedFields>,
associatedEntityClass: IEntityClass<
TAssociatedFields,
TAssociatedID,
TViewerContext,
TAssociatedEntity,
TAssociatedPrivacyPolicy,
TAssociatedSelectedFields
>,
associatedEntityLookupByField: keyof Pick<TAssociatedFields, TAssociatedSelectedFields>,
queryContext: EntityQueryContext = this.entity
.getViewerContext()
.getViewerScopedEntityCompanionForClass(associatedEntityClass)
.getQueryContextProvider()
.getQueryContext()
): Promise<Result<TAssociatedEntity> | null> {
const associatedFieldValue = this.entity.getField(fieldIdentifyingAssociatedEntity);
if (!associatedFieldValue) {
return null;
}
const loader = this.entity
.getViewerContext()
.getViewerScopedEntityCompanionForClass(associatedEntityClass)
.getLoaderFactory()
.forLoad(queryContext);
return await loader.loadByFieldEqualingAsync(
associatedEntityLookupByField,
associatedFieldValue as any
);
}
/**
* Load many associated entities identified by a field value of this entity. In a relational database,
* the field in this entity refers to a field of the associated entity.
* @param fieldIdentifyingAssociatedEntity - field of this entity containing the value with which to look up associated entities
* @param associatedEntityClass - class of the associated entities
* @param associatedEntityLookupByField - field of associated entities with which to look up the associated entities
* @param queryContext - query context in which to perform the load
*/
async loadManyAssociatedEntitiesByFieldEqualingAsync<
TAssociatedFields,
TAssociatedID extends NonNullable<TAssociatedFields[TAssociatedSelectedFields]>,
TAssociatedEntity extends ReadonlyEntity<
TAssociatedFields,
TAssociatedID,
TViewerContext,
TAssociatedSelectedFields
>,
TAssociatedPrivacyPolicy extends EntityPrivacyPolicy<
TAssociatedFields,
TAssociatedID,
TViewerContext,
TAssociatedEntity,
TAssociatedSelectedFields
>,
TAssociatedSelectedFields extends keyof TAssociatedFields = keyof TAssociatedFields
>(
fieldIdentifyingAssociatedEntity: keyof Pick<TFields, TSelectedFields>,
associatedEntityClass: IEntityClass<
TAssociatedFields,
TAssociatedID,
TViewerContext,
TAssociatedEntity,
TAssociatedPrivacyPolicy,
TAssociatedSelectedFields
>,
associatedEntityLookupByField: keyof Pick<TAssociatedFields, TAssociatedSelectedFields>,
queryContext: EntityQueryContext = this.entity
.getViewerContext()
.getViewerScopedEntityCompanionForClass(associatedEntityClass)
.getQueryContextProvider()
.getQueryContext()
): Promise<readonly Result<TAssociatedEntity>[]> {
const associatedFieldValue = this.entity.getField(fieldIdentifyingAssociatedEntity);
if (!associatedFieldValue) {
return [];
}
const loader = this.entity
.getViewerContext()
.getViewerScopedEntityCompanionForClass(associatedEntityClass)
.getLoaderFactory()
.forLoad(queryContext);
return await loader.loadManyByFieldEqualingAsync(
associatedEntityLookupByField,
associatedFieldValue as any
);
}
/**
* Load an associated entity by folding a sequence of {@link EntityLoadThroughDirective}. At each
* fold step, load an associated entity identified by a field value of the current fold value.
* @param loadDirectives - associated entity load directives instructing each step of the fold
* @param queryContext - query context in which to perform the loads
*/
async loadAssociatedEntityThroughAsync<
TFields2,
TID2 extends NonNullable<TFields2[TSelectedFields2]>,
TEntity2 extends ReadonlyEntity<TFields2, TID2, TViewerContext, TSelectedFields2>,
TPrivacyPolicy2 extends EntityPrivacyPolicy<
TFields2,
TID2,
TViewerContext,
TEntity2,
TSelectedFields2
>,
TSelectedFields2 extends keyof TFields2 = keyof TFields2
>(
loadDirectives: [
EntityLoadThroughDirective<
TViewerContext,
TFields,
TFields2,
TID2,
TEntity2,
TPrivacyPolicy2,
TSelectedFields,
TSelectedFields2
>
],
queryContext?: EntityQueryContext
): Promise<Result<TEntity2> | null>;
/**
* Load an associated entity by folding a sequence of {@link EntityLoadThroughDirective}. At each
* fold step, load an associated entity identified by a field value of the current fold value.
* @param loadDirectives - associated entity load directives instructing each step of the fold
* @param queryContext - query context in which to perform the loads
*/
async loadAssociatedEntityThroughAsync<
TFields2,
TID2 extends NonNullable<TFields2[TSelectedFields2]>,
TEntity2 extends ReadonlyEntity<TFields2, TID2, TViewerContext, TSelectedFields2>,
TPrivacyPolicy2 extends EntityPrivacyPolicy<
TFields2,
TID2,
TViewerContext,
TEntity2,
TSelectedFields2
>,
TFields3,
TID3 extends NonNullable<TFields3[TSelectedFields3]>,
TEntity3 extends ReadonlyEntity<TFields3, TID3, TViewerContext, TSelectedFields3>,
TPrivacyPolicy3 extends EntityPrivacyPolicy<
TFields3,
TID3,
TViewerContext,
TEntity3,
TSelectedFields3
>,
TSelectedFields2 extends keyof TFields2 = keyof TFields2,
TSelectedFields3 extends keyof TFields3 = keyof TFields3
>(
loadDirectives: [
EntityLoadThroughDirective<
TViewerContext,
TFields,
TFields2,
TID2,
TEntity2,
TPrivacyPolicy2,
TSelectedFields,
TSelectedFields2
>,
EntityLoadThroughDirective<
TViewerContext,
TFields2,
TFields3,
TID3,
TEntity3,
TPrivacyPolicy3,
TSelectedFields2,
TSelectedFields3
>
],
queryContext?: EntityQueryContext
): Promise<Result<TEntity3> | null>;
/**
* Load an associated entity by folding a sequence of {@link EntityLoadThroughDirective}. At each
* fold step, load an associated entity identified by a field value of the current fold value.
* @param loadDirectives - associated entity load directives instructing each step of the fold
* @param queryContext - query context in which to perform the loads
*/
async loadAssociatedEntityThroughAsync<
TFields2,
TID2 extends NonNullable<TFields2[TSelectedFields2]>,
TEntity2 extends ReadonlyEntity<TFields2, TID2, TViewerContext, TSelectedFields2>,
TPrivacyPolicy2 extends EntityPrivacyPolicy<
TFields2,
TID2,
TViewerContext,
TEntity2,
TSelectedFields2
>,
TFields3,
TID3 extends NonNullable<TFields3[TSelectedFields3]>,
TEntity3 extends ReadonlyEntity<TFields3, TID3, TViewerContext, TSelectedFields3>,
TPrivacyPolicy3 extends EntityPrivacyPolicy<
TFields3,
TID3,
TViewerContext,
TEntity3,
TSelectedFields3
>,
TFields4,
TID4 extends NonNullable<TFields4[TSelectedFields4]>,
TEntity4 extends ReadonlyEntity<TFields4, TID4, TViewerContext, TSelectedFields4>,
TPrivacyPolicy4 extends EntityPrivacyPolicy<
TFields4,
TID4,
TViewerContext,
TEntity4,
TSelectedFields4
>,
TSelectedFields2 extends keyof TFields2 = keyof TFields2,
TSelectedFields3 extends keyof TFields3 = keyof TFields3,
TSelectedFields4 extends keyof TFields4 = keyof TFields4
>(
loadDirective: [
EntityLoadThroughDirective<
TViewerContext,
TFields,
TFields2,
TID2,
TEntity2,
TPrivacyPolicy2,
TSelectedFields,
TSelectedFields2
>,
EntityLoadThroughDirective<
TViewerContext,
TFields2,
TFields3,
TID3,
TEntity3,
TPrivacyPolicy3,
TSelectedFields2,
TSelectedFields3
>,
EntityLoadThroughDirective<
TViewerContext,
TFields3,
TFields4,
TID4,
TEntity4,
TPrivacyPolicy4,
TSelectedFields3,
TSelectedFields4
>
],
queryContext?: EntityQueryContext
): Promise<Result<TEntity4> | null>;
/**
* Load an associated entity by folding a sequence of {@link EntityLoadThroughDirective}. At each
* fold step, load an associated entity identified by a field value of the current fold value.
* @param loadDirectives - associated entity load directives instructing each step of the fold
* @param queryContext - query context in which to perform the loads
*/
async loadAssociatedEntityThroughAsync(
loadDirectives: EntityLoadThroughDirective<TViewerContext, any, any, any, any, any, any, any>[],
queryContext?: EntityQueryContext
): Promise<Result<ReadonlyEntity<any, any, any, any>> | null>;
async loadAssociatedEntityThroughAsync(
loadDirectives: EntityLoadThroughDirective<TViewerContext, any, any, any, any, any, any, any>[],
queryContext?: EntityQueryContext
): Promise<Result<ReadonlyEntity<any, any, any, any>> | null> {
let currentEntity: ReadonlyEntity<any, any, any, any> = this.entity;
for (const loadDirective of loadDirectives) {
const {
associatedEntityClass,
fieldIdentifyingAssociatedEntity,
associatedEntityLookupByField,
} = loadDirective;
let associatedEntityResult: Result<ReadonlyEntity<any, any, any, any>> | null;
if (associatedEntityLookupByField) {
associatedEntityResult = await currentEntity
.associationLoader()
.loadAssociatedEntityByFieldEqualingAsync(
fieldIdentifyingAssociatedEntity,
associatedEntityClass,
associatedEntityLookupByField,
queryContext
);
} else {
const associatedEntityResultLocal = await currentEntity
.associationLoader()
.loadAssociatedEntityAsync(
fieldIdentifyingAssociatedEntity,
associatedEntityClass,
queryContext
);
if (associatedEntityResultLocal.ok && associatedEntityResultLocal.value === null) {
associatedEntityResult = null;
} else {
associatedEntityResult = associatedEntityResultLocal;
}
}
if (!associatedEntityResult) {
return null;
}
if (!associatedEntityResult.ok) {
return result(associatedEntityResult.reason);
}
currentEntity = associatedEntityResult.value;
}
return result(currentEntity);
}
}
/**
* Instruction for each step of a load-associated-through method.
*/
export interface EntityLoadThroughDirective<
TViewerContext extends ViewerContext,
TFields,
TAssociatedFields,
TAssociatedID extends NonNullable<TAssociatedFields[TAssociatedSelectedFields]>,
TAssociatedEntity extends ReadonlyEntity<
TAssociatedFields,
TAssociatedID,
TViewerContext,
TAssociatedSelectedFields
>,
TAssociatedPrivacyPolicy extends EntityPrivacyPolicy<
TAssociatedFields,
TAssociatedID,
TViewerContext,
TAssociatedEntity,
TAssociatedSelectedFields
>,
TSelectedFields extends keyof TFields = keyof TFields,
TAssociatedSelectedFields extends keyof TAssociatedFields = keyof TAssociatedFields
> {
/**
* Class of entity to load at this step.
*/
associatedEntityClass: IEntityClass<
TAssociatedFields,
TAssociatedID,
TViewerContext,
TAssociatedEntity,
TAssociatedPrivacyPolicy,
TAssociatedSelectedFields
>;
/**
* Field of the current entity with which to load an instance of associatedEntityClass.
*/
fieldIdentifyingAssociatedEntity: keyof Pick<TFields, TSelectedFields>;
/**
* Field by which to load the instance of associatedEntityClass. If not provided, the
* associatedEntityClass instance is fetched by its ID.
*/
associatedEntityLookupByField?: keyof Pick<TAssociatedFields, TAssociatedSelectedFields>;
} | the_stack |
import {
Characteristic, CharacteristicEventTypes, CharacteristicProps, CharacteristicSetCallback, CharacteristicValue, Logger, Service,
SessionIdentifier, WithUUID,
} from 'homebridge';
import { BasicAccessory, ServiceHandler } from '../src/converters/interfaces';
import { DeviceDefinition, DeviceListEntry, ExposesEntry, isDeviceDefinition, isDeviceListEntry, isExposesEntry } from '../src/z2mModels';
import { mock, mockClear, MockProxy } from 'jest-mock-extended';
import { when } from 'jest-when';
import 'jest-chain';
import { BasicServiceCreatorManager } from '../src/converters/creators';
export interface HomebridgeCharacteristicSetCallback {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(value: CharacteristicValue, cb: CharacteristicSetCallback, context?: any, connectionID?: SessionIdentifier): void;
}
export const testJsonDeviceListEntry = (json: string): DeviceListEntry | undefined => {
const output = JSON.parse(json);
expect(isDeviceListEntry(output)).toBeTruthy();
if (isDeviceListEntry(output)) {
expect(isDeviceDefinition(output.definition)).toBeTruthy();
if (isDeviceDefinition(output.definition)) {
expect(output.definition.exposes.length).toBeGreaterThan(0);
const invalidExposes = output.definition.exposes.find(e => !isExposesEntry(e));
expect(invalidExposes).toBeUndefined();
if (invalidExposes !== undefined) {
return undefined;
}
return output;
}
}
return undefined;
};
export const testJsonDeviceDefinition = (json: string): DeviceDefinition | undefined => {
const output = JSON.parse(json);
expect(isDeviceDefinition(output)).toBeTruthy();
if (isDeviceDefinition(output)) {
expect(output.exposes.length).toBeGreaterThan(0);
const invalidExposes = output.exposes.find(e => !isExposesEntry(e));
expect(invalidExposes).toBeUndefined();
if (invalidExposes !== undefined) {
return undefined;
}
return output;
}
return undefined;
};
export const testJsonExposes = (json: string): ExposesEntry[] => {
const output = JSON.parse(json);
expect(Array.isArray(output)).toBeTruthy();
if (Array.isArray(output)) {
expect(output.length).toBeGreaterThan(0);
const invalidExposes = output.find(e => !isExposesEntry(e));
expect(invalidExposes).toBeUndefined();
if (invalidExposes !== undefined) {
return [];
}
return output;
}
return [];
};
class TestCharacteristic {
setFunction?: HomebridgeCharacteristicSetCallback;
public readonly mock: MockProxy<Characteristic> & Characteristic | undefined;
constructor(
readonly topLevelProperty: string,
readonly characteristic: WithUUID<{ new(): Characteristic }> | undefined,
readonly doExpectSet: boolean,
readonly doExpectCheckPropertyExcluded: boolean,
) {
if (characteristic !== undefined) {
this.mock = mock<Characteristic>();
}
}
}
export declare type ServiceIdentifier = string | WithUUID<{ new(): Service }>;
export interface ServiceHandlerContainer {
addExpectedPropertyCheck(property: string): ServiceHandlerContainer;
addExpectedCharacteristic(identifier: string, characteristic: WithUUID<{ new(): Characteristic }>, doExpectSet?: boolean,
property?: string, doExpectCheckPropertyExcluded?: boolean): ServiceHandlerContainer;
checkCharacteristicPropertiesHaveBeenSet(identifier: string, props: Partial<CharacteristicProps>): ServiceHandlerContainer;
checkCharacteristicUpdateValue(identifier: string, value: CharacteristicValue): ServiceHandlerContainer;
checkCharacteristicUpdateValues(expectedUpdates: Map<string, CharacteristicValue>): ServiceHandlerContainer;
checkCharacteristicUpdate(characteristic: WithUUID<{ new(): Characteristic }> | string,
value: CharacteristicValue): ServiceHandlerContainer;
checkCharacteristicUpdates(expectedUpdates: Map<WithUUID<{ new(): Characteristic }> | string,
CharacteristicValue>): ServiceHandlerContainer;
checkNoCharacteristicUpdates(): ServiceHandlerContainer;
callAndCheckHomeKitSetCallback(identifier: string, setValue: CharacteristicValue): ServiceHandlerContainer;
getCharacteristicMock(identifier: string): MockProxy<Characteristic> & Characteristic;
prepareGetCharacteristicMock(property: string): void;
}
class ServiceHandlerTestData implements ServiceHandlerContainer {
serviceHandler?: ServiceHandler;
readonly serviceMock: MockProxy<Service> & Service;
readonly characteristics: Map<string, TestCharacteristic> = new Map<string, TestCharacteristic>();
constructor(readonly serviceUuid: string, readonly subType: string | undefined, readonly serviceIdentifier: string) {
this.serviceMock = mock<Service>();
}
addExpectedPropertyCheck(property: string): ServiceHandlerContainer {
expect(this.characteristics.has(property)).toBeFalsy();
this.characteristics.set(property, new TestCharacteristic(property, undefined, false, true));
return this;
}
addExpectedCharacteristic(identifier: string, characteristic: WithUUID<{ new(): Characteristic }>, doExpectSet = false,
property: string | undefined = undefined, doExpectCheckPropertyExcluded = true): ServiceHandlerContainer {
if (property === undefined) {
property = identifier;
}
expect(this.characteristics.has(identifier)).toBeFalsy();
this.characteristics.set(identifier, new TestCharacteristic(property, characteristic, doExpectSet,
doExpectCheckPropertyExcluded));
return this;
}
checkCharacteristicPropertiesHaveBeenSet(identifier: string, props: Partial<CharacteristicProps>): ServiceHandlerContainer {
const mock = this.getCharacteristicMock(identifier);
expect(mock.setProps)
.toBeCalledTimes(1)
.toBeCalledWith(props);
return this;
}
getCharacteristicMock(identifier: string): MockProxy<Characteristic> & Characteristic {
const characteristicMock = this.characteristics.get(identifier)?.mock;
if (characteristicMock === undefined) {
throw new Error(`Characterstic mock for identifier ${identifier} not found.`);
}
return characteristicMock;
}
prepareGetCharacteristicMock(property: string) {
const mapping = this.characteristics.get(property);
if (mapping === undefined) {
throw new Error(`Unknown property ${property} passed to prepareGetCharacteristicMock`);
}
when(this.serviceMock.getCharacteristic)
.calledWith(mapping.characteristic)
.mockReturnValue(mapping.mock);
}
checkCharacteristicUpdate(characteristic: WithUUID<{ new(): Characteristic }> | string, value: CharacteristicValue):
ServiceHandlerContainer {
return this.checkCharacteristicUpdates(new Map<WithUUID<{ new(): Characteristic }> | string, CharacteristicValue>([
[characteristic, value],
]));
}
checkCharacteristicUpdates(expectedUpdates: Map<WithUUID<{ new(): Characteristic }> | string, CharacteristicValue>):
ServiceHandlerContainer {
expect(this.serviceMock.updateCharacteristic)
.toBeCalledTimes(expectedUpdates.size);
for (const [characteristic, value] of expectedUpdates) {
expect(this.serviceMock.updateCharacteristic)
.toBeCalledWith(characteristic, value);
}
return this;
}
checkCharacteristicUpdateValue(identifier: string, value: CharacteristicValue): ServiceHandlerContainer {
return this.checkCharacteristicUpdateValues(new Map<string, CharacteristicValue>([
[identifier, value],
]));
}
checkCharacteristicUpdateValues(expectedUpdates: Map<string, CharacteristicValue>): ServiceHandlerContainer {
for (const [identifier, value] of expectedUpdates) {
const mock = this.getCharacteristicMock(identifier);
expect(mock.updateValue)
.toBeCalledTimes(1)
.toBeCalledWith(value);
}
return this;
}
checkNoCharacteristicUpdates(): ServiceHandlerContainer {
expect(this.serviceMock.updateCharacteristic)
.not.toBeCalled();
return this;
}
callAndCheckHomeKitSetCallback(identifier: string, setValue: CharacteristicValue): ServiceHandlerContainer {
expect(this.characteristics.has(identifier)).toBeTruthy();
const mapping = this.characteristics.get(identifier);
if (mapping?.setFunction === undefined) {
throw new Error(`No set callback for identifier ${identifier} found.`);
}
const callbackMock = jest.fn();
mapping.setFunction(setValue, callbackMock);
expect(callbackMock)
.toBeCalledTimes(1)
.toBeCalledWith(null);
return this;
}
clearMocks(): void {
mockClear(this.serviceMock);
for (const mapping of this.characteristics.values()) {
if (mapping.mock !== undefined) {
mockClear(mapping.mock);
}
}
}
}
export class ServiceHandlersTestHarness {
private readonly handlers = new Map<string, ServiceHandlerTestData>();
private readonly allowedValues = new Map<string, string[]>();
readonly accessoryMock: MockProxy<BasicAccessory> & BasicAccessory;
constructor() {
this.accessoryMock = mock<BasicAccessory>();
this.accessoryMock.log = mock<Logger>();
// Mock implementations of certain accessory functions
this.accessoryMock.isValueAllowedForProperty
.mockImplementation((property: string, value: string): boolean => {
return this.allowedValues.get(property)?.includes(value) ?? true;
});
this.accessoryMock.getOrAddService
.mockImplementation((service: Service) => {
const handler = [...this.handlers.values()].find(h => h.serviceUuid === service.UUID && h.subType === service.subtype);
expect(handler).toBeDefined();
if (handler) {
return handler.serviceMock;
}
// Next line should NEVER be executed, but needs to be there for the code to be valid.
return service;
});
this.accessoryMock.isServiceHandlerIdKnown
.mockImplementation((id: string): boolean => {
// Ignore all identifiers that have not been registered before
return !this.handlers.has(id);
});
this.accessoryMock.registerServiceHandler
.mockImplementation((serviceHandler: ServiceHandler) => {
// Check service identifier is known and store service handler once
expect(serviceHandler).toBeDefined();
const testHandler = this.handlers.get(serviceHandler.identifier);
expect(testHandler).toBeDefined();
if (testHandler !== undefined) {
expect(testHandler.serviceHandler).toBeUndefined();
testHandler.serviceHandler = serviceHandler;
}
});
}
configureAllowedValues(property: string, values: string[]) {
this.allowedValues.set(property, values);
}
private extractServiceId(id: ServiceIdentifier): string {
if (typeof id === 'string') {
return id;
}
return id.UUID;
}
generateServiceId(serviceType: WithUUID<{ new(): Service }> | string, subType: string | undefined = undefined): string {
let serviceIdentifier = (typeof serviceType === 'string') ? serviceType : serviceType.UUID;
if (subType !== undefined) {
serviceIdentifier += '_' + subType;
}
return serviceIdentifier;
}
getOrAddHandler(serviceType: WithUUID<{ new(): Service }> | string, subType: string | undefined = undefined,
serviceIdentifier: string | undefined = undefined): ServiceHandlerContainer {
// Determine identifier
const serviceUuid = (typeof serviceType === 'string') ? serviceType : serviceType.UUID;
if (serviceIdentifier === undefined) {
serviceIdentifier = this.generateServiceId(serviceType, subType);
}
// Check if handler exists
const existingHandler = this.handlers.get(serviceIdentifier);
if (existingHandler !== undefined) {
return existingHandler;
}
const newHandler = new ServiceHandlerTestData(serviceUuid, subType, serviceIdentifier);
this.handlers.set(serviceIdentifier, newHandler);
return newHandler;
}
callCreators(exposes: ExposesEntry[]) {
BasicServiceCreatorManager.getInstance().createHomeKitEntitiesFromExposes(this.accessoryMock, exposes);
}
prepareCreationMocks(): void {
for (const data of this.handlers.values()) {
for (const mapping of data.characteristics.values()) {
if (mapping.doExpectCheckPropertyExcluded) {
when(this.accessoryMock.isPropertyExcluded)
.calledWith(mapping.topLevelProperty)
.mockReturnValue(false);
}
if (mapping.characteristic !== undefined) {
when(data.serviceMock.getCharacteristic)
.calledWith(mapping.characteristic)
.mockReturnValue(undefined);
when(data.serviceMock.addCharacteristic)
.calledWith(mapping.characteristic)
.mockReturnValue(mapping.mock);
if (mapping.mock !== undefined) {
mapping.mock.on.mockReturnThis();
mapping.mock.setProps.mockReturnThis();
}
}
}
}
}
checkExpectedGetableKeys(keys: string[]) {
// Gather all keys
const actualKeys = [...this.handlers.values()].map(h => h.serviceHandler?.getableKeys ?? []).reduce((a, b) => {
return a.concat(b);
}, []);
// Compare to expectations
expect(actualKeys.sort()).toEqual(keys.sort());
}
checkCreationExpectations(): void {
let expectedCallsToGetOrAddService = 0;
let expectedCallsToRegisterServiceHandler = 0;
for (const handler of this.handlers.values()) {
expect(this.accessoryMock.isServiceHandlerIdKnown)
.toHaveBeenCalledWith(handler.serviceIdentifier);
++expectedCallsToGetOrAddService;
let characteristicCount = 0;
for (const mapping of handler.characteristics.values()) {
if (mapping.characteristic !== undefined) {
characteristicCount += 1;
}
}
expect(handler.serviceMock.getCharacteristic)
.toBeCalledTimes(characteristicCount);
expect(handler.serviceMock.addCharacteristic)
.toBeCalledTimes(characteristicCount);
++expectedCallsToRegisterServiceHandler;
expect(this.accessoryMock.registerServiceHandler.mock.calls.length).toBeGreaterThanOrEqual(expectedCallsToRegisterServiceHandler);
for (const mapping of handler.characteristics.values()) {
if (mapping.doExpectCheckPropertyExcluded) {
expect(this.accessoryMock.isPropertyExcluded)
.toBeCalledWith(mapping.topLevelProperty);
}
if (mapping.characteristic !== undefined) {
expect(handler.serviceMock.getCharacteristic)
.toBeCalledWith(mapping.characteristic);
expect(handler.serviceMock.addCharacteristic)
.toBeCalledWith(mapping.characteristic);
if (mapping.doExpectSet && mapping.mock !== undefined) {
expect(mapping.mock.on)
.toHaveBeenCalledTimes(1)
.toHaveBeenCalledWith(CharacteristicEventTypes.SET, expect.anything());
// Store set callback for future tests
mapping.setFunction = (mapping.mock.on.mock.calls[0][1] as unknown) as HomebridgeCharacteristicSetCallback;
}
}
}
}
expect(this.accessoryMock.getOrAddService)
.toHaveBeenCalledTimes(expectedCallsToGetOrAddService);
expect(this.accessoryMock.registerServiceHandler)
.toHaveBeenCalledTimes(expectedCallsToRegisterServiceHandler);
}
checkSingleUpdateState(json: string, serviceIdentifier: ServiceIdentifier,
characteristic: WithUUID<{ new(): Characteristic }> | string, value: CharacteristicValue, checkOtherHandlersIgnoreThisUpdate = true) {
const map = new Map<WithUUID<{ new(): Characteristic }> | string, CharacteristicValue>();
map.set(characteristic, value);
this.checkUpdateState(json, serviceIdentifier, map, checkOtherHandlersIgnoreThisUpdate);
}
checkUpdateStateIsIgnored(json: string) {
const state = JSON.parse(json);
const noUpdates = new Map<WithUUID<{ new(): Characteristic }> | string, CharacteristicValue>();
for (const handler of this.handlers.values()) {
expect(handler?.serviceHandler).toBeDefined();
handler?.serviceHandler?.updateState(state);
handler?.checkCharacteristicUpdates(noUpdates);
}
}
checkUpdateState(json: string, serviceIdentifier: ServiceIdentifier,
expectedUpdates: Map<WithUUID<{ new(): Characteristic }> | string, CharacteristicValue>, checkOtherHandlersIgnoreThisUpdate = true) {
const state = JSON.parse(json);
const serviceId = this.extractServiceId(serviceIdentifier);
const handler = this.handlers.get(serviceId);
expect(handler).toBeDefined();
expect(handler?.serviceHandler).toBeDefined();
handler?.serviceHandler?.updateState(state);
handler?.checkCharacteristicUpdates(expectedUpdates);
if (checkOtherHandlersIgnoreThisUpdate) {
const noUpdates = new Map<WithUUID<{ new(): Characteristic }> | string, CharacteristicValue>();
for (const [id, otherHandler] of this.handlers) {
if (id === serviceId) {
// already verified
continue;
}
expect(otherHandler?.serviceHandler).toBeDefined();
otherHandler?.serviceHandler?.updateState(state);
otherHandler?.checkCharacteristicUpdates(noUpdates);
}
}
}
checkHomeKitUpdateWithSingleValue(serviceIdentifier: ServiceIdentifier, identifier: string, setValue: CharacteristicValue, value: unknown,
property: string | undefined = undefined) {
if (property === undefined) {
property = identifier;
}
const data = {};
data[property] = value;
this.checkHomeKitUpdate(serviceIdentifier, identifier, setValue, data);
}
checkHomeKitUpdate(serviceIdentifier: ServiceIdentifier, identifier: string, setValue: CharacteristicValue, expectedData: unknown) {
const handler = this.handlers.get(this.extractServiceId(serviceIdentifier));
expect(handler).toBeDefined();
handler?.callAndCheckHomeKitSetCallback(identifier, setValue);
this.checkSetDataQueued(expectedData);
}
checkSetDataQueued(expectedData: unknown) {
expect(this.accessoryMock.queueDataForSetAction)
.toBeCalledTimes(1)
.toBeCalledWith(expectedData);
}
checkNoSetDataQueued() {
expect(this.accessoryMock.queueDataForSetAction)
.not.toBeCalled();
}
checkGetKeysQueued(expectedKeys: string | string[]) {
expect(this.accessoryMock.queueKeyForGetAction)
.toBeCalledTimes(1)
.toBeCalledWith(expectedKeys);
}
checkNoGetKeysQueued() {
expect(this.accessoryMock.queueKeyForGetAction)
.not.toBeCalled();
}
clearMocks(): void {
mockClear(this.accessoryMock);
this.handlers.forEach(h => h.clearMocks());
}
} | the_stack |
import { SelectionVariant } from './common';
import { ResourceIdentifier, ResourceBase, SiteVersionResponse } from './contracts/common';
import { RuntimeMap } from './contracts/runtime-map';
import { QueryMapFeaturesResponse } from './contracts/query';
/**
* Describes a request that takes either a session or username/password pair
*
* @export
* @interface IAuthenticatedRequest
*/
export interface IAuthenticatedRequest {
/**
* The session id
*
* @type {string}
* @memberOf IAuthenticatedRequest
*/
session?: string;
/**
* The username
*
* @type {string}
* @memberOf IAuthenticatedRequest
*/
username?: string;
/**
* The password
*
* @type {string}
* @memberOf IAuthenticatedRequest
*/
password?: string;
}
/**
* Bitmask describing what data to return when creating a runtime map
*
* @export
* @enum {number}
*/
export enum RuntimeMapFeatureFlags {
/**
* Include data about layers and groups
*/
LayersAndGroups = 1,
/**
* Include layer icons
*/
LayerIcons = 2,
/**
* Include data about layer feature sources
*/
LayerFeatureSources = 4
}
/**
* Describes options for creating a runtime map
*
* @export
* @interface ICreateRuntimeMapOptions
* @extends {IAuthenticatedRequest}
*/
export interface ICreateRuntimeMapOptions extends IAuthenticatedRequest {
/**
* The map definition id
*
* @type {ResourceIdentifier}
* @memberOf ICreateRuntimeMapOptions
*/
mapDefinition: ResourceIdentifier;
/**
* A bitmask indicating what data to return
*
* @type {(number | RuntimeMapFeatureFlags)}
* @memberOf ICreateRuntimeMapOptions
*/
requestedFeatures: number | RuntimeMapFeatureFlags;
/**
* If requesting icons, the number of icons per scale range
*
* @type {number}
* @memberOf ICreateRuntimeMapOptions
*/
iconsPerScaleRange?: number;
/**
* The image format for requested icons
*
* @type {("PNG" | "PNG8" | "GIF" | "JPG")}
* @memberOf ICreateRuntimeMapOptions
*/
iconFormat?: "PNG" | "PNG8" | "GIF" | "JPG";
/**
* The width of requested icons
*
* @type {number}
* @memberOf ICreateRuntimeMapOptions
*/
iconWidth?: number;
/**
* The height of requested icons
*
* @type {number}
* @memberOf ICreateRuntimeMapOptions
*/
iconHeight?: number;
/**
* The target map name to assign. Otherwise the map name will be computed from the map definition id
*
* @type {string}
* @memberOf ICreateRuntimeMapOptions
*/
targetMapName?: string;
}
/**
* Describes operations requiring a session id
*
* @export
* @interface ISessionBasedRequest
*/
export interface ISessionBasedRequest {
/**
* The session id
*
* @type {string}
* @memberOf ISessionBasedRequest
*/
session: string;
}
/**
* Describes operations against a runtime map
*
* @export
* @interface IRuntimeMapRequest
* @extends {ISessionBasedRequest}
*/
export interface IRuntimeMapRequest extends ISessionBasedRequest {
/**
* The name of the runtime map
*
* @type {string}
* @memberOf IRuntimeMapRequest
*/
mapname: string;
}
/**
* A bitmask indicating what to return when querying map features
*
* @export
* @enum {number}
*/
export enum QueryFeaturesSet {
/**
* Include attributes of selected features
*/
Attributes = 1,
/**
* Include an inline image of the selected features
*/
InlineSelection = 2,
/**
* Include tooltips for the first matching feature
*/
Tooltip = 4,
/**
* Include hyperlink for the first matching feature
*/
Hyperlink = 8
}
/**
* Options for querying map features
*
* @export
* @interface IQueryMapFeaturesOptions
* @extends {IRuntimeMapRequest}
*/
export interface IQueryMapFeaturesOptions extends IRuntimeMapRequest {
/**
* A comma-seperated list of layer name to restrict the query on. Omit to
* cover all selectable layers
*
* @type {string}
*/
layernames?: string;
/**
* The WKT of the query geometry
*
* @type {string}
*/
geometry?: string;
/**
* The spatial query operator to use with the input geometry
*
* @type {SelectionVariant}
*/
selectionvariant?: SelectionVariant;
/**
* A bitmask containing what features to ask for
*
* @type {QueryFeaturesSet}
*/
requestdata?: QueryFeaturesSet;
/**
* The color of the selection
*
* @type {string}
*/
selectioncolor?: string;
/**
* The image format of the requested selection image
*
* @type {("PNG" | "JPG" | "GIF" | "PNG8")}
*/
selectionformat?: "PNG" | "JPG" | "GIF" | "PNG8";
/**
* The maximum number of features to select. Use -1 for no limit.
*
* @type {number}
*/
maxfeatures?: number;
/**
* 1 = Persist the query selection changes to the current selection set
* 0 = The query selection does not modify the current selection set
*
* @type {number}
*/
persist?: number;
/**
* An optional selection XML string. If specified, the rendering/query will be based off of
* a selection initialized with this selection XML
*/
featurefilter?: string;
layerattributefilter?: number;
}
/**
* Options for describing a runtime map
*
* @export
* @interface IDescribeRuntimeMapOptions
* @extends {IRuntimeMapRequest}
*/
export interface IDescribeRuntimeMapOptions extends IRuntimeMapRequest {
/**
* A bitmask of data to return about a runtime map
*
* @type {(number | RuntimeMapFeatureFlags)}
* @memberOf IDescribeRuntimeMapOptions
*/
requestedFeatures?: number | RuntimeMapFeatureFlags;
/**
* If requesting icons, the number of icons per scale range
*
* @type {number}
* @memberOf IDescribeRuntimeMapOptions
*/
iconsPerScaleRange?: number;
/**
* The image format for requested icons
*
* @type {("PNG" | "PNG8" | "GIF" | "JPG")}
* @memberOf IDescribeRuntimeMapOptions
*/
iconFormat?: "PNG" | "PNG8" | "GIF" | "JPG";
/**
* The width of requested icons
*
* @type {number}
* @memberOf IDescribeRuntimeMapOptions
*/
iconWidth?: number;
/**
* The height of requested icons
*
* @type {number}
* @memberOf IDescribeRuntimeMapOptions
*/
iconHeight?: number;
}
/**
* Provides client services for a MapGuide map viewer
*
* @export
* @interface IMapGuideClient
*/
export interface IMapGuideClient {
/**
* Creates a new MapGuide session
*
* @param {string} username
* @param {string} password
* @returns {Promise<string>}
*/
createSession(username: string, password: string): Promise<string>;
/**
* Retrieves the requested resource
*
* @abstract
* @template T
* @param {string} resourceId
* @returns {PromiseLike<T>}
*/
getResource<T extends ResourceBase>(resourceId: ResourceIdentifier, args?: any): Promise<T>;
/**
* Creates a runtime map from the specified map definition
*
* @abstract
* @param {ICreateRuntimeMapOptions} options
* @returns {PromiseLike<RuntimeMap>}
*/
createRuntimeMap(options: ICreateRuntimeMapOptions): Promise<RuntimeMap>;
/**
* Performs a map selection query on the current map
*
* @abstract
* @param {IQueryMapFeaturesOptions} options
* @returns {PromiseLike<QueryMapFeaturesResponse>}
*/
queryMapFeatures(options: IQueryMapFeaturesOptions): Promise<QueryMapFeaturesResponse>;
/**
* Performs a map selection query on the current map. Only applicable for use with MapGuide
* Open Source 4.0 and higher
*
* @abstract
* @param {IQueryMapFeaturesOptions} options
* @returns {PromiseLike<QueryMapFeaturesResponse>}
*/
queryMapFeatures_v4(options: IQueryMapFeaturesOptions): Promise<QueryMapFeaturesResponse>;
/**
* Describes a runtime map
*
* @abstract
* @param {IDescribeRuntimeMapOptions} options
* @returns {PromiseLike<RuntimeMap>}
*/
describeRuntimeMap(options: IDescribeRuntimeMapOptions): Promise<RuntimeMap>;
/**
* Gets the tile template URL used by the viewer to send tile requests
*
* @param {string} resourceId
* @param {string} groupName
* @param {string} xPlaceholder
* @param {string} yPlaceholder
* @param {string} zPlaceholder
* @returns {string}
*/
getTileTemplateUrl(resourceId: string, groupName: string, xPlaceholder: string, yPlaceholder: string, zPlaceholder: string): string;
}
/**
* An abstract MapGuide service client
*
* @export
* @abstract
* @class RequestBuilder
* @implements {IMapGuideClient}
*/
export abstract class RequestBuilder implements IMapGuideClient {
protected agentUri: string;
constructor(agentUri: string) {
this.agentUri = agentUri;
}
public abstract createSession(username: string, password: string): Promise<string>;
public abstract getServerSessionTimeout(session: string): Promise<number>;
public abstract getResource<T extends ResourceBase>(resourceId: ResourceIdentifier, args?: any): Promise<T>;
public abstract createRuntimeMap(options: ICreateRuntimeMapOptions): Promise<RuntimeMap>;
public abstract queryMapFeatures(options: IQueryMapFeaturesOptions): Promise<QueryMapFeaturesResponse>;
public abstract queryMapFeatures_v4(options: IQueryMapFeaturesOptions): Promise<QueryMapFeaturesResponse>;
public abstract describeRuntimeMap(options: IDescribeRuntimeMapOptions): Promise<RuntimeMap>;
public abstract getTileTemplateUrl(resourceId: string, groupName: string, xPlaceholder: string, yPlaceholder: string, zPlaceholder: string): string;
public abstract getSiteVersion(): Promise<SiteVersionResponse>;
} | the_stack |
import { gzipSync } from 'zlib'
import { defaultConfig } from '../src/config/config'
import { LOCKED_RESOURCE } from '../src/main/job-queues/job-queue-consumer'
import { JobQueueManager } from '../src/main/job-queues/job-queue-manager'
import { ServerInstance, startPluginsServer } from '../src/main/pluginsServer'
import { EnqueuedJob, Hub, LogLevel, PluginsServerConfig } from '../src/types'
import { createHub } from '../src/utils/db/hub'
import { killProcess } from '../src/utils/kill'
import { delay } from '../src/utils/utils'
import { makePiscina } from '../src/worker/piscina'
import { createPosthog, DummyPostHog } from '../src/worker/vm/extensions/posthog'
import { writeToFile } from '../src/worker/vm/extensions/test-utils'
import { resetGraphileSchema } from './helpers/graphile'
import { pluginConfig39 } from './helpers/plugins'
import { resetTestDatabase } from './helpers/sql'
const mS3WrapperInstance = {
upload: jest.fn(),
getObject: jest.fn(),
deleteObject: jest.fn(),
listObjectsV2: jest.fn(),
mockClear: () => {
mS3WrapperInstance.upload.mockClear()
mS3WrapperInstance.getObject.mockClear()
mS3WrapperInstance.deleteObject.mockClear()
mS3WrapperInstance.listObjectsV2.mockClear()
},
}
jest.mock('../src/utils/db/s3-wrapper', () => {
return { S3Wrapper: jest.fn(() => mS3WrapperInstance) }
})
jest.mock('../src/utils/db/sql')
jest.mock('../src/utils/kill')
jest.setTimeout(60000) // 60 sec timeout
const { console: testConsole } = writeToFile
const testCode = `
import { console } from 'test-utils/write-to-file'
export const jobs = {
logReply: (text, meta) => {
console.log('reply', text)
}
}
export async function processEvent (event, { jobs }) {
console.log('processEvent')
if (event.properties?.type === 'runIn') {
jobs.logReply('runIn').runIn(1, 'second')
} else if (event.properties?.type === 'runAt') {
jobs.logReply('runAt').runAt(new Date())
} else if (event.properties?.type === 'runNow') {
jobs.logReply('runNow').runNow()
}
return event
}
`
const createConfig = (config: Partial<PluginsServerConfig>): PluginsServerConfig => ({
...defaultConfig,
WORKER_CONCURRENCY: 2,
LOG_LEVEL: LogLevel.Debug,
...config,
})
async function waitForLogEntries(number: number) {
const timeout = 20000
const start = new Date().valueOf()
while (testConsole.read().length < number) {
await delay(200)
if (new Date().valueOf() - start > timeout) {
console.error(`Did not find ${number} console logs:`, testConsole.read())
throw new Error(`Did not get ${number} console logs within ${timeout / 1000} seconds`)
}
}
}
describe('job queues', () => {
let server: ServerInstance
let posthog: DummyPostHog
beforeEach(async () => {
testConsole.reset()
// reset lock in redis
const [tempHub, closeTempHub] = await createHub()
const redis = await tempHub.redisPool.acquire()
await redis.del(LOCKED_RESOURCE)
await tempHub.redisPool.release(redis)
await closeTempHub()
// reset test code
await resetTestDatabase(testCode)
// try to deflake
await delay(100)
})
afterEach(async () => {
await server?.stop()
})
describe('fs queue', () => {
beforeEach(async () => {
server = await startPluginsServer(createConfig({ JOB_QUEUES: 'fs' }), makePiscina)
posthog = createPosthog(server.hub, pluginConfig39)
})
test('jobs get scheduled with runIn', async () => {
await posthog.capture('my event', { type: 'runIn' })
await waitForLogEntries(2)
expect(testConsole.read()).toEqual([['processEvent'], ['reply', 'runIn']])
})
test('jobs get scheduled with runAt', async () => {
await posthog.capture('my event', { type: 'runAt' })
await waitForLogEntries(2)
expect(testConsole.read()).toEqual([['processEvent'], ['reply', 'runAt']])
})
test('jobs get scheduled with runNow', async () => {
await posthog.capture('my event', { type: 'runNow' })
await waitForLogEntries(2)
expect(testConsole.read()).toEqual([['processEvent'], ['reply', 'runNow']])
})
})
describe('graphile', () => {
async function initTest(
config: Partial<PluginsServerConfig>,
resetSchema = true
): Promise<PluginsServerConfig> {
const createdConfig = createConfig(config)
if (resetSchema) {
await resetGraphileSchema(createdConfig)
}
return createdConfig
}
describe('jobs', () => {
beforeEach(async () => {
const config = await initTest({ JOB_QUEUES: 'graphile' })
server = await startPluginsServer(config, makePiscina)
posthog = createPosthog(server.hub, pluginConfig39)
})
test('graphile job queue', async () => {
await posthog.capture('my event', { type: 'runIn' })
await waitForLogEntries(2)
expect(testConsole.read()).toEqual([['processEvent'], ['reply', 'runIn']])
})
test('polls for jobs in future', async () => {
const DELAY = 3000 // 3s
// return something to be picked up after a few loops (poll interval is 100ms)
const now = Date.now()
const job: EnqueuedJob = {
type: 'pluginJob',
payload: { key: 'value' },
timestamp: now + DELAY,
pluginConfigId: 2,
pluginConfigTeam: 3,
}
server.hub.jobQueueManager.enqueue(job)
const consumedJob: EnqueuedJob = await new Promise((resolve, reject) => {
server.hub.jobQueueManager.startConsumer((consumedJob) => {
resolve(consumedJob[0])
})
})
expect(consumedJob).toEqual(job)
})
})
describe('connection', () => {
test('default connection', async () => {
const config = await initTest({ JOB_QUEUES: 'graphile', JOB_QUEUE_GRAPHILE_URL: '' }, true)
server = await startPluginsServer(config, makePiscina)
posthog = createPosthog(server.hub, pluginConfig39)
await posthog.capture('my event', { type: 'runIn' })
await waitForLogEntries(2)
expect(testConsole.read()).toEqual([['processEvent'], ['reply', 'runIn']])
})
describe('invalid host/domain', () => {
// This crashes the tests as well. So... it, uhm, passes :D.
// The crash only happens when running in Github Actions of course, so hard to debug.
// This mode will not be activated by default, and we will not use it on cloud (yet).
test.skip('crash', async () => {
const config = await initTest(
{
JOB_QUEUES: 'graphile',
JOB_QUEUE_GRAPHILE_URL: 'postgres://0.0.0.0:9212/database',
CRASH_IF_NO_PERSISTENT_JOB_QUEUE: true,
},
false
)
server = await startPluginsServer(config, makePiscina)
await delay(5000)
expect(killProcess).toHaveBeenCalled()
})
test('no crash', async () => {
const config = await initTest(
{
JOB_QUEUES: 'graphile',
JOB_QUEUE_GRAPHILE_URL: 'postgres://0.0.0.0:9212/database',
CRASH_IF_NO_PERSISTENT_JOB_QUEUE: false,
},
false
)
server = await startPluginsServer(config, makePiscina)
posthog = createPosthog(server.hub, pluginConfig39)
await posthog.capture('my event', { type: 'runIn' })
await waitForLogEntries(1)
expect(testConsole.read()).toEqual([['processEvent']])
})
})
})
})
describe('s3 queue', () => {
let jobQueue: JobQueueManager
let hub: Hub
let closeHub: () => Promise<void>
beforeEach(async () => {
mS3WrapperInstance.getObject.mockReturnValueOnce({ Body: 'test' })
;[hub, closeHub] = await createHub(
createConfig({
CRASH_IF_NO_PERSISTENT_JOB_QUEUE: true,
JOB_QUEUES: 's3',
JOB_QUEUE_S3_PREFIX: 'prefix/',
JOB_QUEUE_S3_BUCKET_NAME: 'bucket-name',
JOB_QUEUE_S3_AWS_SECRET_ACCESS_KEY: 'secret key',
JOB_QUEUE_S3_AWS_ACCESS_KEY: 'access key',
JOB_QUEUE_S3_AWS_REGION: 'region',
})
)
})
afterEach(async () => closeHub?.())
test('calls a few functions', async () => {
// calls a few functions to test the connection on init
expect(mS3WrapperInstance.getObject).toBeCalledWith({
Bucket: 'bucket-name',
Key: expect.stringContaining('prefix/CONNTEST/'),
})
expect(mS3WrapperInstance.upload).toBeCalledWith({
Body: 'test',
Bucket: 'bucket-name',
Key: expect.stringContaining('prefix/CONNTEST/'),
})
expect(mS3WrapperInstance.deleteObject).toBeCalledWith({
Bucket: 'bucket-name',
Key: expect.stringContaining('prefix/CONNTEST/'),
})
expect(mS3WrapperInstance.listObjectsV2).toBeCalledWith({
Bucket: 'bucket-name',
MaxKeys: 2,
Prefix: expect.stringContaining('prefix/'),
})
// calls the right functions to enqueue the job
mS3WrapperInstance.mockClear()
const job: EnqueuedJob = {
type: 'pluginJob',
payload: { key: 'value' },
timestamp: 1000000000,
pluginConfigId: 2,
pluginConfigTeam: 3,
}
await hub.jobQueueManager.enqueue(job)
expect(mS3WrapperInstance.upload).toBeCalledWith({
Body: gzipSync(Buffer.from(JSON.stringify(job), 'utf8')),
Bucket: 'bucket-name',
Key: expect.stringContaining('prefix/1970-01-12/19700112-134640.000Z-'),
})
expect(mS3WrapperInstance.getObject).not.toBeCalled()
expect(mS3WrapperInstance.deleteObject).not.toBeCalled()
expect(mS3WrapperInstance.listObjectsV2).not.toBeCalled()
// calls the right functions to read the enqueued job
mS3WrapperInstance.mockClear()
mS3WrapperInstance.listObjectsV2.mockReturnValueOnce({
Contents: [{ Key: `prefix/2020-01-01/20200101-123456.123Z-deadbeef.json.gz` }],
})
mS3WrapperInstance.getObject.mockReturnValueOnce({
Body: gzipSync(Buffer.from(JSON.stringify(job), 'utf8')),
})
const consumedJob: EnqueuedJob = await new Promise((resolve, reject) => {
hub.jobQueueManager.startConsumer((consumedJob) => {
resolve(consumedJob[0])
})
})
expect(consumedJob).toEqual(job)
await delay(10)
expect(mS3WrapperInstance.deleteObject).toBeCalledWith({
Bucket: 'bucket-name',
Key: `prefix/2020-01-01/20200101-123456.123Z-deadbeef.json.gz`,
})
})
test('polls for new jobs', async () => {
const DELAY = 10000 // 10s
// calls the right functions to read the enqueued job
mS3WrapperInstance.mockClear()
// return something to be picked up after a few loops (poll interval is 5s)
const now = Date.now()
const date = new Date(now + DELAY).toISOString()
const [day, time] = date.split('T')
const dayTime = `${day.split('-').join('')}-${time.split(':').join('')}`
const job: EnqueuedJob = {
type: 'pluginJob',
payload: { key: 'value' },
timestamp: now,
pluginConfigId: 2,
pluginConfigTeam: 3,
}
mS3WrapperInstance.listObjectsV2.mockReturnValue({
Contents: [{ Key: `prefix/${day}/${dayTime}-deadbeef.json.gz` }],
})
mS3WrapperInstance.getObject.mockReturnValueOnce({
Body: gzipSync(Buffer.from(JSON.stringify(job), 'utf8')),
})
const consumedJob: EnqueuedJob = await new Promise((resolve, reject) => {
hub.jobQueueManager.startConsumer((consumedJob) => {
resolve(consumedJob[0])
})
})
expect(consumedJob).toEqual(job)
await delay(10)
expect(mS3WrapperInstance.deleteObject).toBeCalledWith({
Bucket: 'bucket-name',
Key: `prefix/${day}/${dayTime}-deadbeef.json.gz`,
})
})
})
}) | the_stack |
'use strict'
// General libraries
import { Algebra, Parser } from 'sparqljs'
import { Consumable } from '../operators/update/consumer'
// pipelining engine
import { Pipeline } from '../engine/pipeline/pipeline'
import { PipelineStage } from '../engine/pipeline/pipeline-engine'
// RDF core classes
import { Bindings, BindingBase } from '../rdf/bindings'
import Dataset from '../rdf/dataset'
// Optimization
import Optimizer from '../optimizer/optimizer'
// Solution modifiers
import ask from '../operators/modifiers/ask'
import construct from '../operators/modifiers/construct'
import select from '../operators/modifiers/select'
// Stage builders
import StageBuilder from './stages/stage-builder'
import AggregateStageBuilder from './stages/aggregate-stage-builder'
import BGPStageBuilder from './stages/bgp-stage-builder'
import BindStageBuilder from './stages/bind-stage-builder'
import DistinctStageBuilder from './stages/distinct-stage-builder'
import FilterStageBuilder from './stages/filter-stage-builder'
import GlushkovStageBuilder from './stages/glushkov-executor/glushkov-stage-builder'
import GraphStageBuilder from './stages/graph-stage-builder'
import MinusStageBuilder from './stages/minus-stage-builder'
import ServiceStageBuilder from './stages/service-stage-builder'
import OptionalStageBuilder from './stages/optional-stage-builder'
import OrderByStageBuilder from './stages/orderby-stage-builder'
import UnionStageBuilder from './stages/union-stage-builder'
import UpdateStageBuilder from './stages/update-stage-builder'
// caching
import { BGPCache, LRUBGPCache } from './cache/bgp-cache'
// utilities
import {
partition,
isNull,
isString,
isUndefined,
some,
sortBy
} from 'lodash'
import ExecutionContext from './context/execution-context'
import ContextSymbols from './context/symbols'
import { CustomFunctions } from '../operators/expressions/sparql-expression'
import { extractPropertyPaths } from './stages/rewritings'
import { extendByBindings, deepApplyBindings, rdf } from '../utils'
const QUERY_MODIFIERS = {
SELECT: select,
CONSTRUCT: construct,
ASK: ask
}
/**
* Output of a physical query execution plan
*/
export type QueryOutput = Bindings | Algebra.TripleObject | boolean
/*
* Class of SPARQL operations that are evaluated by a Stage Builder
*/
export enum SPARQL_OPERATION {
AGGREGATE,
BGP,
BIND,
DISTINCT,
FILTER,
GRAPH,
MINUS,
OPTIONAL,
ORDER_BY,
PROPERTY_PATH,
SERVICE,
UPDATE,
UNION
}
/**
* A PlanBuilder builds a physical query execution plan of a SPARQL query,
* i.e., an iterator that can be consumed to get query results.
* Internally, it implements a Builder design pattern, where various {@link StageBuilder} are used
* for building each part of the query execution plan.
* @author Thomas Minier
* @author Corentin Marionneau
*/
export class PlanBuilder {
private readonly _parser: Parser
private _optimizer: Optimizer
private _stageBuilders: Map<SPARQL_OPERATION, StageBuilder>
private _currentCache: BGPCache | null
/**
* Constructor
* @param _dataset - RDF Dataset used for query execution
* @param _prefixes - Optional prefixes to use during query processing
*/
constructor (
private _dataset: Dataset,
prefixes: any = {},
private _customFunctions?: CustomFunctions) {
this._dataset = _dataset
this._parser = new Parser(prefixes)
this._optimizer = Optimizer.getDefault()
this._currentCache = null
this._stageBuilders = new Map()
// add default stage builders
this.use(SPARQL_OPERATION.AGGREGATE, new AggregateStageBuilder(this._dataset))
this.use(SPARQL_OPERATION.BGP, new BGPStageBuilder(this._dataset))
this.use(SPARQL_OPERATION.BIND, new BindStageBuilder(this._dataset))
this.use(SPARQL_OPERATION.DISTINCT, new DistinctStageBuilder(this._dataset))
this.use(SPARQL_OPERATION.FILTER, new FilterStageBuilder(this._dataset))
this.use(SPARQL_OPERATION.GRAPH, new GraphStageBuilder(this._dataset))
this.use(SPARQL_OPERATION.MINUS, new MinusStageBuilder(this._dataset))
this.use(SPARQL_OPERATION.SERVICE, new ServiceStageBuilder(this._dataset))
this.use(SPARQL_OPERATION.OPTIONAL, new OptionalStageBuilder(this._dataset))
this.use(SPARQL_OPERATION.ORDER_BY, new OrderByStageBuilder(this._dataset))
this.use(SPARQL_OPERATION.PROPERTY_PATH, new GlushkovStageBuilder(this._dataset))
this.use(SPARQL_OPERATION.UNION, new UnionStageBuilder(this._dataset))
this.use(SPARQL_OPERATION.UPDATE, new UpdateStageBuilder(this._dataset))
}
/**
* Set a new {@link Optimizer} uszed to optimize logical SPARQL query execution plans
* @param opt - New optimizer to use
*/
set optimizer (opt: Optimizer) {
this._optimizer = opt
}
/**
* Register a Stage Builder to evaluate a class of SPARQL operations
* @param kind - Class of SPARQL operations handled by the Stage Builder
* @param stageBuilder - New Stage Builder
*/
use (kind: SPARQL_OPERATION, stageBuilder: StageBuilder) {
// complete handshake
stageBuilder.builder = null
stageBuilder.builder = this
this._stageBuilders.set(kind, stageBuilder)
}
/**
* Enable Basic Graph Patterns semantic caching for SPARQL query evaluation.
* The parameter is optional and used to provide your own cache instance.
* If left undefined, the query engine will use a {@link LRUBGPCache} with
* a maximum of 500 items and a max age of 20 minutes.
* @param customCache - (optional) Custom cache instance
*/
useCache (customCache?: BGPCache): void {
if (customCache === undefined) {
this._currentCache = new LRUBGPCache(500, 1200 * 60 * 60)
} else {
this._currentCache = customCache
}
}
/**
* Disable Basic Graph Patterns semantic caching for SPARQL query evaluation.
*/
disableCache (): void {
this._currentCache = null
}
/**
* Build the physical query execution of a SPARQL 1.1 query
* and returns a {@link PipelineStage} or a {@link Consumable} that can be consumed to evaluate the query.
* @param query - SPARQL query to evaluated
* @param options - Execution options
* @return A {@link PipelineStage} or a {@link Consumable} that can be consumed to evaluate the query.
*/
build (query: any, context?: ExecutionContext): PipelineStage<QueryOutput> | Consumable {
// If needed, parse the string query into a logical query execution plan
if (typeof query === 'string') {
query = this._parser.parse(query)
}
if (isNull(context) || isUndefined(context)) {
context = new ExecutionContext()
context.cache = this._currentCache
}
// Optimize the logical query execution plan
query = this._optimizer.optimize(query)
// build physical query execution plan, depending on the query type
switch (query.type) {
case 'query':
return this._buildQueryPlan(query, context)
case 'update':
if (!this._stageBuilders.has(SPARQL_OPERATION.UPDATE)) {
throw new Error('A PlanBuilder cannot evaluate SPARQL UPDATE queries without a StageBuilder for it')
}
return this._stageBuilders.get(SPARQL_OPERATION.UPDATE)!.execute(query.updates, context)
default:
throw new SyntaxError(`Unsupported SPARQL query type: ${query.type}`)
}
}
/**
* Build the physical query execution of a SPARQL query
* @param query - Parsed SPARQL query
* @param options - Execution options
* @param source - Input {@link PipelineStage}
* @return A {@link PipelineStage} that can be consumed to evaluate the query.
*/
_buildQueryPlan (query: Algebra.RootNode, context: ExecutionContext, source?: PipelineStage<Bindings>): PipelineStage<Bindings> {
const engine = Pipeline.getInstance()
if (isNull(source) || isUndefined(source)) {
// build pipeline starting iterator
source = engine.of(new BindingBase())
}
context.setProperty(ContextSymbols.PREFIXES, query.prefixes)
let aggregates: any[] = []
// rewrite a DESCRIBE query into a CONSTRUCT query
if (query.queryType === 'DESCRIBE') {
const template: Algebra.TripleObject[] = []
const where: any = [{
type: 'bgp',
triples: []
}]
query.variables!.forEach((v: any) => {
const triple = rdf.triple(v, `?pred__describe__${v}`, `?obj__describe__${v}`)
template.push(triple)
where[0].triples.push(triple)
})
const construct = {
prefixes: query.prefixes,
from: query.from,
queryType: 'CONSTRUCT',
template,
type: 'query',
where: query.where.concat(where)
}
return this._buildQueryPlan(construct, context, source)
}
// from the begining, dectect any LIMIT/OFFSET modifiers, as they cimpact the caching strategy
context.setProperty(ContextSymbols.HAS_LIMIT_OFFSET, 'limit' in query || 'offset' in query)
// Handles FROM clauses
if (query.from) {
context.defaultGraphs = query.from.default
context.namedGraphs = query.from.named
}
// Handles WHERE clause
let graphIterator: PipelineStage<Bindings>
if (query.where.length > 0) {
graphIterator = this._buildWhere(source, query.where, context)
} else {
graphIterator = engine.of(new BindingBase())
}
// Parse query variable to separate projection & aggregate variables
if ('variables' in query) {
const parts = partition(query.variables, v => isString(v))
aggregates = parts[1]
// add aggregates variables to projection variables
query.variables = parts[0].concat(aggregates.map(agg => (agg as Algebra.Aggregation).variable))
}
// Handles SPARQL aggregations
if ('group' in query || aggregates.length > 0) {
// Handles GROUP BY
graphIterator = this._stageBuilders.get(SPARQL_OPERATION.AGGREGATE)!.execute(graphIterator, query, context, this._customFunctions) as PipelineStage<Bindings>
}
if (aggregates.length > 0) {
// Handles SPARQL aggregation functions
graphIterator = aggregates.reduce((prev: PipelineStage<Bindings>, agg: Algebra.Aggregation) => {
const op = this._stageBuilders.get(SPARQL_OPERATION.BIND)!.execute(prev, agg, this._customFunctions, context)
return op as PipelineStage<Bindings>
}, graphIterator)
}
// Handles ORDER BY
if ('order' in query) {
if (!this._stageBuilders.has(SPARQL_OPERATION.ORDER_BY)) {
throw new Error('A PlanBuilder cannot evaluate SPARQL ORDER BY clauses without a StageBuilder for it')
}
graphIterator = this._stageBuilders.get(SPARQL_OPERATION.ORDER_BY)!.execute(graphIterator, query.order!) as PipelineStage<Bindings>
}
if (!(query.queryType in QUERY_MODIFIERS)) {
throw new Error(`Unsupported SPARQL query type: ${query.queryType}`)
}
graphIterator = QUERY_MODIFIERS[query.queryType](graphIterator, query, context)
// Create iterators for modifiers
if (query.distinct) {
if (!this._stageBuilders.has(SPARQL_OPERATION.DISTINCT)) {
throw new Error('A PlanBuilder cannot evaluate a DISTINCT clause without a StageBuilder for it')
}
graphIterator = this._stageBuilders.get(SPARQL_OPERATION.DISTINCT)!.execute(graphIterator, context) as PipelineStage<Bindings>
}
// Add offsets and limits if requested
if ('offset' in query) {
graphIterator = engine.skip(graphIterator, query.offset!)
}
if ('limit' in query) {
graphIterator = engine.limit(graphIterator, query.limit!)
}
// graphIterator.queryType = query.queryType
return graphIterator
}
/**
* Optimize a WHERE clause and build the corresponding physical plan
* @param source - Input {@link PipelineStage}
* @param groups - WHERE clause to process
* @param options - Execution options
* @return A {@link PipelineStage} used to evaluate the WHERE clause
*/
_buildWhere (source: PipelineStage<Bindings>, groups: Algebra.PlanNode[], context: ExecutionContext): PipelineStage<Bindings> {
groups = sortBy(groups, g => {
switch (g.type) {
case 'graph':
if (rdf.isVariable((g as Algebra.GraphNode).name)) {
return 5
}
return 0
case 'bgp':
return 0
case 'values':
return 3
case 'filter':
return 4
default:
return 1
}
})
// Handle VALUES clauses using query rewriting
if (some(groups, g => g.type === 'values')) {
return this._buildValues(source, groups, context)
}
// merge BGPs on the same level
let newGroups = []
let prec = null
for (let i = 0; i < groups.length; i++) {
let group = groups[i]
if (group.type === 'bgp' && prec !== null && prec.type === 'bgp') {
let lastGroup = newGroups[newGroups.length - 1] as Algebra.BGPNode
lastGroup.triples = lastGroup.triples.concat((group as Algebra.BGPNode).triples)
} else {
newGroups.push(group)
}
prec = groups[i]
}
groups = newGroups
return groups.reduce((source, group) => {
return this._buildGroup(source, group, context)
}, source)
}
/**
* Build a physical plan for a SPARQL group clause
* @param source - Input {@link PipelineStage}
* @param group - SPARQL Group
* @param options - Execution options
* @return A {@link PipelineStage} used to evaluate the SPARQL Group
*/
_buildGroup (source: PipelineStage<Bindings>, group: Algebra.PlanNode, context: ExecutionContext): PipelineStage<Bindings> {
const engine = Pipeline.getInstance()
// Reset flags on the options for child iterators
let childContext = context.clone()
switch (group.type) {
case 'bgp':
if (!this._stageBuilders.has(SPARQL_OPERATION.BGP)) {
throw new Error('A PlanBuilder cannot evaluate a Basic Graph Pattern without a Stage Builder for it')
}
// find possible Property paths
let [classicTriples, pathTriples, tempVariables] = extractPropertyPaths(group as Algebra.BGPNode)
if (pathTriples.length > 0) {
if (!this._stageBuilders.has(SPARQL_OPERATION.PROPERTY_PATH)) {
throw new Error('A PlanBuilder cannot evaluate property paths without a Stage Builder for it')
}
source = this._stageBuilders.get(SPARQL_OPERATION.PROPERTY_PATH)!.execute(source, pathTriples, context) as PipelineStage<Bindings>
}
// delegate remaining BGP evaluation to the dedicated executor
let iter = this._stageBuilders.get(SPARQL_OPERATION.BGP)!.execute(source, classicTriples, childContext) as PipelineStage<Bindings>
// filter out variables added by the rewriting of property paths
if (tempVariables.length > 0) {
iter = engine.map(iter, bindings => {
return bindings.filter(v => tempVariables.indexOf(v) === -1)
})
}
return iter
case 'query':
return this._buildQueryPlan(group as Algebra.RootNode, childContext, source)
case 'graph':
if (!this._stageBuilders.has(SPARQL_OPERATION.GRAPH)) {
throw new Error('A PlanBuilder cannot evaluate a GRAPH clause without a Stage Builder for it')
}
// delegate GRAPH evaluation to an executor
return this._stageBuilders.get(SPARQL_OPERATION.GRAPH)!.execute(source, group as Algebra.GraphNode, childContext) as PipelineStage<Bindings>
case 'service':
if (!this._stageBuilders.has(SPARQL_OPERATION.SERVICE)) {
throw new Error('A PlanBuilder cannot evaluate a SERVICE clause without a Stage Builder for it')
}
return this._stageBuilders.get(SPARQL_OPERATION.SERVICE)!.execute(source, group as Algebra.ServiceNode, childContext) as PipelineStage<Bindings>
case 'group':
return this._buildWhere(source, (group as Algebra.GroupNode).patterns, childContext)
case 'optional':
if (!this._stageBuilders.has(SPARQL_OPERATION.OPTIONAL)) {
throw new Error('A PlanBuilder cannot evaluate an OPTIONAL clause without a Stage Builder for it')
}
return this._stageBuilders.get(SPARQL_OPERATION.OPTIONAL)!.execute(source, group, childContext) as PipelineStage<Bindings>
case 'union':
if (!this._stageBuilders.has(SPARQL_OPERATION.UNION)) {
throw new Error('A PlanBuilder cannot evaluate an UNION clause without a Stage Builder for it')
}
return this._stageBuilders.get(SPARQL_OPERATION.UNION)!.execute(source, group, childContext) as PipelineStage<Bindings>
case 'minus':
if (!this._stageBuilders.has(SPARQL_OPERATION.MINUS)) {
throw new Error('A PlanBuilder cannot evaluate a MINUS clause without a Stage Builder for it')
}
return this._stageBuilders.get(SPARQL_OPERATION.MINUS)!.execute(source, group, childContext) as PipelineStage<Bindings>
case 'filter':
if (!this._stageBuilders.has(SPARQL_OPERATION.FILTER)) {
throw new Error('A PlanBuilder cannot evaluate a FILTER clause without a Stage Builder for it')
}
return this._stageBuilders.get(SPARQL_OPERATION.FILTER)!.execute(source, group, this._customFunctions, childContext) as PipelineStage<Bindings>
case 'bind':
if (!this._stageBuilders.has(SPARQL_OPERATION.BIND)) {
throw new Error('A PlanBuilder cannot evaluate a BIND clause without a Stage Builder for it')
}
return this._stageBuilders.get(SPARQL_OPERATION.BIND)!.execute(source, (group as Algebra.BindNode), this._customFunctions, childContext) as PipelineStage<Bindings>
default:
throw new Error(`Unsupported SPARQL group pattern found in query: ${group.type}`)
}
}
/**
* Build a {@link PipelineStage} which evaluates a SPARQL query with VALUES clause(s).
* It rely on a query rewritiing approach:
* ?s ?p ?o . VALUES ?s { :1 :2 } becomes {:1 ?p ?o BIND(:1 AS ?s)} UNION {:2 ?p ?o BIND(:2 AS ?s)}
* @param source - Input {@link PipelineStage}
* @param groups - Query body, i.e., WHERE clause
* @param options - Execution options
* @return A {@link PipelineStage} which evaluates a SPARQL query with VALUES clause(s)
*/
_buildValues (source: PipelineStage<Bindings>, groups: Algebra.PlanNode[], context: ExecutionContext): PipelineStage<Bindings> {
let [ values, others ] = partition(groups, g => g.type === 'values')
const bindingsLists = values.map(g => (g as Algebra.ValuesNode).values)
// for each VALUES clause
const iterators = bindingsLists.map(bList => {
// for each value to bind in the VALUES clause
const unionBranches = bList.map(b => {
const bindings = BindingBase.fromObject(b)
// BIND each group with the set of bindings and then evaluates it
const temp = others.map(g => deepApplyBindings(g, bindings))
return extendByBindings(this._buildWhere(source, temp, context), bindings)
})
return Pipeline.getInstance().merge(...unionBranches)
})
// Users may use more than one VALUES clause
if (iterators.length > 1) {
return Pipeline.getInstance().merge(...iterators)
}
return iterators[0]
}
} | the_stack |
import { mocked } from 'ts-jest/utils';
import { getBreakpoint as getBreakpoint_ } from '../../../lib/detect';
import fastdom from '../../../lib/fastdom-promise';
import { mediator as fakeMediator } from '../../../lib/mediator';
import { commercialFeatures } from '../../common/modules/commercial/commercial-features';
import { isUserLoggedIn as isUserLoggedIn_ } from '../../common/modules/identity/api';
import { _, initCommentAdverts } from './comment-adverts';
import { addSlot } from './dfp/add-slot';
import type { Advert } from './dfp/Advert';
import { getAdvertById as getAdvertById_ } from './dfp/get-advert-by-id';
import { refreshAdvert as refreshAdvert_ } from './dfp/load-advert';
// Mock advert type by overwriting slot property with only one function for defining size mapping
// This avoids having to set the rest of the slot properties that are unnecessary for the tests
type MockAdvert = Omit<Advert, 'slot'> & {
slot: {
defineSizeMapping: (asm: googletag.SizeMappingArray) => googletag.Slot;
};
};
// Workaround to fix issue where dataset is missing from jsdom, and solve the
// 'cannot set property [...] which has only a getter' TypeError
Object.defineProperty(HTMLElement.prototype, 'dataset', {
writable: true,
value: {},
});
jest.mock('../../../lib/config', () => ({ page: {}, get: () => false }));
jest.mock('./dfp/add-slot', () => ({
addSlot: jest.fn(),
}));
jest.mock('./dfp/load-advert', () => ({
refreshAdvert: jest.fn(),
}));
jest.mock('./dfp/get-advert-by-id', () => ({
getAdvertById: jest.fn(),
}));
jest.mock('../../../lib/detect', () => ({
getBreakpoint: jest.fn(),
}));
jest.mock('../../common/modules/commercial/commercial-features', () => ({
commercialFeatures: {
commentAdverts: true,
},
}));
jest.mock('../../common/modules/identity/api', () => ({
isUserLoggedIn: jest.fn(),
}));
const { createCommentSlots, runSecondStage, maybeUpgradeSlot } = _;
const commercialFeaturesMock = commercialFeatures;
const isUserLoggedIn = isUserLoggedIn_;
const getAdvertById = getAdvertById_;
const getBreakpoint = getBreakpoint_;
const refreshAdvert = refreshAdvert_;
const mockHeight = (height: number) => {
// this is an issue with fastdom's typing of measure: () => Promise<void>
jest.spyOn(fastdom, 'measure').mockReturnValue(
Promise.resolve(height) as unknown as Promise<void>,
);
};
const generateInnerHtmlWithAdSlot = () => {
document.body.innerHTML = `
<div class="js-comments">
<div class="content__main-column">
<div class="js-discussion__ad-slot">
<div id="dfp-ad--comments"
class="js-ad-slot ad-slot ad-slot--comments js-sticky-mpu
data-mobile="1,1|2,2|300,250|300,274|fluid"
data-desktop="1,1|2,2|300,250|300,274|fluid">
</div>
</div>
</div>
</div>`;
};
const createTestAdvert = (testAdvert: Partial<MockAdvert>): Advert =>
({ ...testAdvert } as Advert);
const getElement = (selector: string): Element =>
document.querySelector(selector) as Element;
describe('createCommentSlots', () => {
beforeEach(() => {
mocked(isUserLoggedIn).mockReturnValue(false);
commercialFeaturesMock.commentAdverts = true;
document.body.innerHTML = `<div class="js-comments">
<div class="content__main-column">
<div class="js-discussion__ad-slot"></div></div></div>`;
});
afterEach(() => {
document.body.innerHTML = '';
jest.resetAllMocks();
fakeMediator.removeAllListeners();
});
it('should return an ad slot with the correct sizes', () => {
const commentMpu = createCommentSlots(false)[0];
const commentDmpu = createCommentSlots(true)[0];
expect(commentMpu.getAttribute('data-desktop')).toBe(
'1,1|2,2|300,250|300,274|620,1|620,350|550,310|fluid',
);
expect(commentMpu.getAttribute('data-mobile')).toBe(
'1,1|2,2|300,197|300,250|300,274|fluid',
);
expect(commentDmpu.getAttribute('data-desktop')).toBe(
'1,1|2,2|300,250|300,274|620,1|620,350|550,310|fluid|300,600|160,600',
);
expect(commentDmpu.getAttribute('data-mobile')).toBe(
'1,1|2,2|300,197|300,250|300,274|fluid',
);
});
it('should add js-sticky-mpu to the class list', () => {
const commentMpu = createCommentSlots(false)[0];
const commentDmpu = createCommentSlots(true)[0];
expect(commentMpu.classList).toContain('js-sticky-mpu');
expect(commentDmpu.classList).toContain('js-sticky-mpu');
});
});
describe('maybeUpgradeSlot', () => {
beforeEach(() => {
generateInnerHtmlWithAdSlot();
});
afterEach(() => {
document.body.innerHTML = '';
jest.resetAllMocks();
});
it('should upgrade the MPU to a DMPU where necessary', () => {
const advert = createTestAdvert({
sizes: { desktop: [[300, 250]] },
slot: { defineSizeMapping: jest.fn() },
});
expect(advert.sizes.desktop).toEqual([[300, 250]]);
maybeUpgradeSlot(advert, getElement('.js-discussion__ad-slot'));
expect(advert.sizes.desktop).toEqual([
[300, 250],
[300, 600],
[160, 600],
]);
expect(advert.slot.defineSizeMapping).toHaveBeenCalledTimes(1);
});
it('should not alter the slot if the slot is already a DMPU', () => {
const advert = createTestAdvert({
sizes: {
desktop: [
[160, 600],
[300, 250],
[300, 600],
],
},
slot: { defineSizeMapping: jest.fn() },
});
expect(advert.sizes.desktop).toEqual([
[160, 600],
[300, 250],
[300, 600],
]);
maybeUpgradeSlot(advert, getElement('.js-discussion__ad-slot'));
expect(advert.sizes.desktop).toEqual([
[160, 600],
[300, 250],
[300, 600],
]);
expect(advert.slot.defineSizeMapping).toHaveBeenCalledTimes(0);
});
});
describe('runSecondStage', () => {
beforeEach(() => {
generateInnerHtmlWithAdSlot();
});
afterEach(() => {
document.body.innerHTML = '';
jest.resetAllMocks();
});
it('should upgrade a MPU to DMPU and immediately refresh the slot', () => {
const adSlotContainer = getElement('.js-discussion__ad-slot');
const commentMainColumn = getElement(
'.js-comments .content__main-column',
);
const advert = createTestAdvert({
sizes: { desktop: [[300, 250]] },
slot: { defineSizeMapping: jest.fn() },
});
mocked(getAdvertById).mockReturnValue(advert);
runSecondStage(commentMainColumn, adSlotContainer);
expect(advert.slot.defineSizeMapping).toHaveBeenCalledTimes(1);
expect(mocked(getAdvertById).mock.calls).toEqual([
['dfp-ad--comments'],
]);
expect(refreshAdvert).toHaveBeenCalledTimes(1);
});
it('should not upgrade a DMPU yet still immediately refresh the slot', () => {
const adSlotContainer = getElement('.js-discussion__ad-slot');
const commentMainColumn = getElement(
'.js-comments .content__main-column',
);
const advert = createTestAdvert({
sizes: { desktop: [[300, 250]] },
slot: { defineSizeMapping: jest.fn() },
});
mocked(getAdvertById).mockReturnValue(advert);
runSecondStage(commentMainColumn, adSlotContainer);
expect(advert.slot.defineSizeMapping).toHaveBeenCalledTimes(1);
expect(mocked(getAdvertById).mock.calls).toEqual([
['dfp-ad--comments'],
]);
expect(refreshAdvert).toHaveBeenCalledTimes(1);
});
});
describe('initCommentAdverts', () => {
beforeEach(() => {
mocked(isUserLoggedIn).mockReturnValue(false);
commercialFeaturesMock.commentAdverts = true;
document.body.innerHTML = `<div class="js-comments">
<div class="content__main-column">
<div class="js-discussion__ad-slot"></div></div></div>`;
});
afterEach(() => {
document.body.innerHTML = '';
jest.resetAllMocks();
fakeMediator.removeAllListeners();
});
it('should return false if commentAdverts are switched off', (done) => {
commercialFeaturesMock.commentAdverts = false;
void initCommentAdverts().then((result) => {
expect(result).toBe(false);
done();
});
});
it('should return false if there is no comments ad slot container', (done) => {
document.body.innerHTML = `<div class="js-comments">
<div class="content__main-column"></div></div>`;
void initCommentAdverts().then((result) => {
expect(result).toBe(false);
done();
});
});
it('should return false if on mobile', (done) => {
document.body.innerHTML = `<div class="js-comments">
<div class="content__main-column"></div></div>`;
mocked(getBreakpoint).mockReturnValue('mobile');
void initCommentAdverts().then((result) => {
expect(result).toBe(false);
done();
});
});
it('should insert a DMPU slot if there is enough space', (done) => {
mockHeight(800); // at 800px we insert a DMPU regardless
void initCommentAdverts().then(() => {
fakeMediator.emit('modules:comments:renderComments:rendered');
fakeMediator.once('page:commercial:comments', () => {
const adSlot = getElement('.js-ad-slot');
expect(addSlot).toHaveBeenCalledTimes(1);
expect(adSlot.getAttribute('data-desktop')).toBe(
'1,1|2,2|300,250|300,274|620,1|620,350|550,310|fluid|300,600|160,600',
);
done();
});
});
});
it('should insert a DMPU slot if there is space, and the user is logged in', (done) => {
mockHeight(600); // at 600px we can insert a DMPU if the user is logged in
mocked(isUserLoggedIn).mockReturnValue(true);
void initCommentAdverts().then(() => {
fakeMediator.emit('modules:comments:renderComments:rendered');
fakeMediator.once('page:commercial:comments', () => {
const adSlot = getElement('.js-ad-slot');
expect(addSlot).toHaveBeenCalledTimes(1);
expect(adSlot.getAttribute('data-desktop')).toBe(
'1,1|2,2|300,250|300,274|620,1|620,350|550,310|fluid|300,600|160,600',
);
done();
});
});
});
it('should insert an MPU if the user is logged in, and the DMPU will not fit', (done) => {
mockHeight(300); // at 300px we can insert an MPU if the user is logged in
mocked(isUserLoggedIn).mockReturnValue(true);
void initCommentAdverts().then(() => {
fakeMediator.emit('modules:comments:renderComments:rendered');
fakeMediator.once('page:commercial:comments', () => {
const adSlot = getElement('.js-ad-slot');
expect(addSlot).toHaveBeenCalledTimes(1);
expect(adSlot.getAttribute('data-desktop')).toBe(
'1,1|2,2|300,250|300,274|620,1|620,350|550,310|fluid',
);
done();
});
});
});
it('should otherwise set the EventListener that can insert the slot', (done) => {
const spyOn = jest.spyOn(fakeMediator, 'on');
mockHeight(300);
void initCommentAdverts()
.then((result) => {
fakeMediator.emit('modules:comments:renderComments:rendered');
expect(result).toBe(true);
})
.then(() => {
expect(spyOn.mock.calls[0]).toEqual(
expect.arrayContaining([
'discussion:comments:get-more-replies',
]),
);
done();
});
});
it('should always set the EventListener', (done) => {
const spyOn = jest.spyOn(fakeMediator, 'on');
mockHeight(800);
void initCommentAdverts()
.then((result) => {
fakeMediator.emit('modules:comments:renderComments:rendered');
expect(result).toBe(true);
})
.then(() => {
expect(spyOn.mock.calls[0]).toEqual(
expect.arrayContaining([
'discussion:comments:get-more-replies',
]),
);
done();
});
});
}); | the_stack |
import { getEle } from "../../../utility/dom/getEle";
import { addClass } from "../../../utility/dom/addClass";
import { removeClass } from "../../../utility/dom/removeClass";
import { getAllEle } from "../../../utility/dom/getAllEle";
import { getAttr } from "../../../utility/dom/getAttr";
/**
* BUG1: 无法在ondrop内部直接使用`e.dataTransfer.files`获取文件列表, 需要自定义数组, 再遍历一遍;
* BUG2: ondrag和onclick无法共存, 导致无法追加自定义样式, 只需监听onmouseup, 并在其中自行调用`label`标签的click方法 - `label.click()`;
*/
export interface IDraggerUploadProps {
container?: string;
onChangeHook?: (e: Event) => void;
onBeforeUploadHook?: (file: File, fileList: File[]) => boolean | Promise<File | undefined>;
onUploadClickHook?: (file: File, FileList: File[]) => boolean | Promise<any>;
onPreviewClickHook?: (file: File, fileList: File[]) => void;
onRemoveClickHook?: (file: File, fileList: File[]) => void;
onUploadClickSuccessHook?: (file: File, fileList: File[]) => void;
onUploadClickFailHook?: (file: File, fileList: File[]) => void;
};
export interface IDraggerUploadState {
files: File[];
oContainer: HTMLDivElement;
oLabel: HTMLLabelElement;
oInput: HTMLInputElement;
oShowList: HTMLUListElement;
}
export class DraggerUpload {
public static readonly defaultProps: IDraggerUploadProps = {
container: 'body',
};
public constructor(
props: IDraggerUploadProps,
) {
this.__init__(props);
}
public readonly state: IDraggerUploadState = {
files: [],
oContainer: document.createElement('div'),
oLabel: document.createElement('label'),
oInput: document.createElement('input'),
oShowList: document.createElement('ul'),
};
private __init__(props: IDraggerUploadProps): void {
this._initProps(props);
this._initDOM();
this._initStyle();
this._initCommonEle();
this.handleDragUpload();
this.handleClickUpload();
}
private _initProps(
props: IDraggerUploadProps,
): void {
for (const key in props) {
if (props.hasOwnProperty(key)) {
const value = Reflect.get(props, key);
Reflect.set(DraggerUpload.defaultProps, key, value);
}
}
}
private _initDOM(): void {
this.handleMountDOM(this.handleCreateDOM());
}
private _initStyle(): void {
this.handleMountStyle(this.handleCreateStyle());
}
/**
* 初始化一些常用的变量
*/
private _initCommonEle(): void {
const oContainer = getEle('.ddzy-upload-drag-container') as HTMLDivElement;
const oLabel = getEle('.ddzy-upload-drag-main-content') as HTMLLabelElement;
const oInput = getEle('.ddzy-upload-drag-main-input') as HTMLInputElement;
const oShowList = getEle('.ddzy-upload-show-list') as HTMLUListElement;
this.state.oContainer = oContainer;
this.state.oLabel = oLabel;
this.state.oInput = oInput;
this.state.oShowList = oShowList;
}
private handleCreateDOM(): string {
let html: string = `
<div id="ddzy-upload-wrapper">
<div class="ddzy-upload-main">
<!-- 拖拽容器 -->
<div class="ddzy-upload-drag-container" draggable="true">
<div class="ddzy-upload-drag-main">
<input id="ddzy-upload-drag-main-input" class="ddzy-upload-drag-main-input" type="file" multiple="true" accept="image/jpg, image/jpeg, image/gif, image/png, image/ico" style="display: none;" />
<label for="ddzy-upload-drag-main-input" class="ddzy-upload-drag-main-content">
<div class="ddzy-upload-drag-icon-box">
<svg class="icon" aria-hidden="true">
<use xlink:href="#icon-upload"></use>
</svg>
</div>
<div class="ddzy-upload-drag-title-box">
<h3>Click or Drag to upload</h3>
</div>
<div class="ddzy-upload-drag-description-box">
<p>Support mutiple files but only image</p>
</div>
</label>
</div>
</div>
<!-- 文件列表 -->
<div class="ddzy-upload-show-container">
<div class="ddzy-upload-show-content">
<ul class="ddzy-upload-show-list">
</ul>
</div>
</div>
</div>
</div>
`;
return html;
}
private handleMountDOM(text: string): void {
const {
container,
} = DraggerUpload.defaultProps;
const mountWrapper = getEle(container as string);
if (mountWrapper) {
mountWrapper.innerHTML += text;
} else {
throw new TypeError('Please enter an existing selector.');
}
}
private handleCreateStyle(): string {
let css: string = `
body, ul, li, p, h3 {
margin: 0;
padding: 0;
}
ul {
list-style-type: none;
}
label {
display: block;
cursor: pointer;
}
#ddzy-upload-wrapper {
height: 100%;
}
#ddzy-upload-wrapper .ddzy-upload-main {
height: 100%;
user-select: none;
cursor: pointer;
}
/* 拖拽上传部分 */
#ddzy-upload-wrapper .ddzy-upload-drag-container {
border: 1px dashed #ccc;
background-color: #f9f9f9;
cursor: pointer;
transition: all .3s ease;
}
#ddzy-upload-wrapper .ddzy-upload-drag-container:hover {
border-color: #1890ff;
}
#ddzy-upload-wrapper .ddzy-upload-drag-main {
pointer-events: none;
}
#ddzy-upload-wrapper .ddzy-upload-drag-main-content {
padding: 0.5rem;
text-align: center;
}
#ddzy-upload-wrapper .ddzy-upload-drag-icon-box {
margin-top: 0.5rem;
}
#ddzy-upload-wrapper .ddzy-upload-drag-title-box {
margin-top: 1.375rem;
}
#ddzy-upload-wrapper .ddzy-upload-drag-description-box {
margin-top: 0.625rem;
margin-bottom: 1rem;
}
#ddzy-upload-wrapper .ddzy-upload-drag-icon-box svg {
color: #1890ff;
min-width: 2.5rem;
min-height: 2.5rem;
}
#ddzy-upload-wrapper .ddzy-upload-drag-title-box h3 {
color: #888;
}
#ddzy-upload-wrapper .ddzy-upload-drag-description-box p {
color: #999;
font-size: 0.875rem;
}
/* 文件列表部分 */
#ddzy-upload-wrapper .ddzy-upload-show-container {
margin-top: 0.5rem;
}
#ddzy-upload-wrapper .ddzy-upload-show-content {
}
#ddzy-upload-wrapper .ddzy-upload-show-list {
}
#ddzy-upload-wrapper .ddzy-upload-show-item {
display: flex;
margin-top: 0.5rem;
padding: 0.25rem 0.5rem;
border: 1px solid #ddd;
color: #666;
transition: all .3s ease;
}
#ddzy-upload-wrapper .ddzy-upload-show-item:hover {
background-color: #f3f4f5;
}
#ddzy-upload-wrapper .ddzy-upload-show-item svg:hover {
color: #1890ff;
}
#ddzy-upload-wrapper .ddzy-upload-show-action-box {
flex: 8;
}
#ddzy-upload-wrapper .ddzy-upload-show-action {
}
#ddzy-upload-wrapper .ddzy-upload-show-action > span {
display: inline-block;
}
#ddzy-upload-wrapper .ddzy-upload-show-action-preview {
margin-left: 0.5rem;
}
#ddzy-upload-wrapper .ddzy-upload-show-action-send {
margin-left: 0.25rem;
}
#ddzy-upload-wrapper .ddzy-upload-show-action-name {
margin-left: 1rem;
}
#ddzy-upload-wrapper .ddzy-upload-show-action-loading {
}
#ddzy-upload-wrapper .ddzy-upload-show-close-box {
flex: 1;
}
#ddzy-upload-wrapper .ddzy-upload-show-close {
text-align: right;
}
/* Animation */
@keyframes showItemLoading {
0% {
transform: rotate(0);
}
100% {
transform: rotate(360deg);
}
}
/* Active classes */
#ddzy-upload-wrapper .ddzy-upload-drag-container-active {
border-color: #1890ff;
filter: blur(1px);
}
#ddzy-upload-wrapper .ddzy-upload-show-item-in-animate {
transition: none;
opacity: 0;
transform: translateX(100%);
}
#ddzy-upload-wrapper .ddzy-upload-show-item-out-animate {
transform: translateX(-100%);
opacity: 0;
}
#ddzy-upload-wrapper .ddzy-upload-show-action-loading-active {
animation: showItemLoading .5s linear infinite;
}
#ddzy-upload-wrapper .ddzy-upload-show-action-loading-success {
animation: none;
color: #52c41a;
}
#ddzy-upload-wrapper .ddzy-upload-show-action-loading-faild {
animation: none;
color: #f5222d;
}
`;
return css;
}
private handleMountStyle(text: string): void {
let oStyle = document.querySelector('style');
if (oStyle) {
oStyle.innerText += `
/* Create by DraggerUpload */
${text}
`;
}
else {
oStyle = document.createElement('style') as HTMLStyleElement;
oStyle.innerText += oStyle.innerText += `
/* Create by DraggerUpload */
${text}
`;;
document.head.appendChild(oStyle);
}
}
private handleDragEnter(): void {
const {
oContainer,
} = this.state;
addClass(oContainer, 'ddzy-upload-drag-container-active');
}
private handleDragLeave(): void {
const {
oContainer,
} = this.state;
removeClass(oContainer, 'ddzy-upload-drag-container-active');
}
/**
* 处理单项列表进场动画
*/
private handleLocalItemAnimateIn(): void {
const oShowItems = getAllEle('.ddzy-upload-show-item') as ArrayLike<HTMLLIElement>;
const oShowItem = oShowItems[oShowItems.length - 1];
// ! [Bug-fix] 解决多文件上传至本地时, 只显示最后一个文件的问题
Array.from(oShowItems).forEach((v) => {
v === oShowItem
? (addClass(v, 'ddzy-upload-show-item-in-animate'))
: (removeClass(v, 'ddzy-upload-show-item-in-animate'));
});
setTimeout(() => {
removeClass(oShowItem, 'ddzy-upload-show-item-in-animate');
}, 0);
}
/**
* 处理单项列表出场动画
*/
private handleLocalItemAnimateOut(
currentItem: HTMLLIElement,
): void {
const { oShowList } = this.state;
addClass(currentItem, 'ddzy-upload-show-item-out-animate');
setTimeout(() => {
oShowList.removeChild(currentItem);
}, 300);
}
/**
* 处理本地列表项移除
*/
private handleLocalItemRemove(): void {
const oShowItems = getAllEle('.ddzy-upload-show-item') as ArrayLike<HTMLLIElement>;
const {
onRemoveClickHook,
} = DraggerUpload.defaultProps;
const {
files,
} = this.state;
Array.from(oShowItems).forEach((li) => {
const oShowItemCloseBtn = li
.getElementsByClassName('ddzy-upload-show-close')[0]
.firstElementChild as SVGAElement;
oShowItemCloseBtn.addEventListener('click', () => {
const index: number = Number(getAttr(li, 'data-index'));
const file: File = files[index];
// ? 执行移除钩子
onRemoveClickHook && onRemoveClickHook(file, files);
this.handleLocalItemAnimateOut(li);
})
})
}
/**
* 处理本地列表项预览
*/
private handleLocalItemPreview(): void {
const oShowItems = getAllEle('.ddzy-upload-show-item') as ArrayLike<HTMLLIElement>;
const { files } = this.state;
const { onPreviewClickHook } = DraggerUpload.defaultProps;
Array.from(oShowItems).forEach((li) => {
const oShowItemPreviewBtn = li
.getElementsByClassName('ddzy-upload-show-action-preview')[0] as HTMLSpanElement;
oShowItemPreviewBtn.addEventListener('click', () => {
// ? 根据当前点击的li的下标找到对应的file
const index: number = Number(getAttr(li, 'data-index'));
const file: File = files[index];
// ? 执行预览钩子
onPreviewClickHook && onPreviewClickHook(file, files);
});
})
}
/**
* 处理成功上传至服务器
*/
private handleLocalItemSendSuccess(
showItem: HTMLLIElement,
file: File,
fileList: File[],
): void {
const {
onUploadClickSuccessHook,
} = DraggerUpload.defaultProps;
const oShowItemLoadingBtn = showItem
.getElementsByClassName('ddzy-upload-show-action-loading')[0] as HTMLSpanElement;
// ? 处理成功上传至服务器时的loading状态
addClass(oShowItemLoadingBtn, 'ddzy-upload-show-action-loading-success');
// ? 执行成功上传至服务器的钩子
onUploadClickSuccessHook && onUploadClickSuccessHook(file, fileList);
}
/**
* 处理上传至服务器失败
*/
private handleLocalItemSendFaild(
showItem: HTMLLIElement,
file: File,
fileList: File[],
): void {
const {
onUploadClickFailHook,
} = DraggerUpload.defaultProps;
const oShowItemLoadingBtn = showItem
.getElementsByClassName('ddzy-upload-show-action-loading')[0] as HTMLSpanElement;
// ? 处理上传至服务器失败时的loading状态
addClass(oShowItemLoadingBtn, 'ddzy-upload-show-action-loading-faild');
// ? 执行上传至服务器失败的钩子
onUploadClickFailHook && onUploadClickFailHook(file, fileList);
}
/**
* 处理本地列表项上传至服务器
*/
private handleLocalItemSend(): void {
const oShowItems = getAllEle('.ddzy-upload-show-item') as ArrayLike<HTMLLIElement>;
const { files } = this.state;
const { onUploadClickHook } = DraggerUpload.defaultProps;
Array.from(oShowItems).forEach((li) => {
const oShowItemSendBtn = li
.getElementsByClassName('ddzy-upload-show-action-send')[0]
.firstElementChild as SVGAElement;
const oShowItemLoadingBtn = li
.getElementsByClassName('ddzy-upload-show-action-loading')[0] as HTMLSpanElement;
oShowItemSendBtn.addEventListener('click', () => {
const index: number = Number(getAttr(li, 'data-index'));
const file: File = files[index];
// ? 处理上传时的loading状态
addClass(oShowItemLoadingBtn, 'ddzy-upload-show-action-loading-active');
// ? 执行上传钩子
if (onUploadClickHook) {
const result = onUploadClickHook(file, files);
if (result instanceof Promise) {
result
.then(() => {
// ? 成功上传至远程服务器
this.handleLocalItemSendSuccess(li, file, files);
})
.catch(() => {
// ? 上传远程服务器失败
this.handleLocalItemSendFaild(li, file, files);
})
} else {
if (result) {
this.handleLocalItemSendSuccess(li, file, files);
} else {
this.handleLocalItemSendFaild(li, file, files);
}
}
}
});
})
}
/**
* 处理本地展示的单项列表相关(入场、预览、上传、移除、出场...)
*/
private handleLocalItem(): void {
this.handleLocalItemAnimateIn();
this.handleLocalItemRemove();
this.handleLocalItemPreview();
this.handleLocalItemSend();
}
/**
* 处理添加至本地预览列表
* @param file 单个文件对象
*/
private handleAppendToShow(file: File): void {
const { oShowList } = this.state;
const { name } = file;
const text = `
<li class="ddzy-upload-show-item" data-index=${oShowList.children.length}>
<div class="ddzy-upload-show-action-box">
<div class="ddzy-upload-show-action">
<span class="ddzy-upload-show-action-loading">
<svg class="icon" aria-hidden="true" data-index=${oShowList.children.length}>
<use xlink:href="#icon-Loading"></use>
</svg>
</span>
<span class="ddzy-upload-show-action-name" title="图片名称">
${name}
</span>
<span class="ddzy-upload-show-action-preview" title="预览">
<svg class="icon" aria-hidden="true" data-index=${oShowList.children.length}>
<use xlink:href="#icon-eye"></use>
</svg>
</span>
<span class="ddzy-upload-show-action-send" title="上传">
<svg class="icon" aria-hidden="true" data-index=${oShowList.children.length}>
<use xlink:href="#icon-upload1"></use>
</svg>
</span>
</div>
</div>
<div class="ddzy-upload-show-close-box">
<div class="ddzy-upload-show-close" title="移除">
<svg class="icon" aria-hidden="true" data-index=${oShowList.children.length}>
<use xlink:href="#icon-et-wrong"></use>
</svg>
</div>
</div>
</li>
`;
oShowList.innerHTML += text;
this.handleLocalItem();
}
/**
* 处理添加至文件数组, 后续会用到
* @param file 单个文件对象
*/
private handleAppendToFiles(file: File): void {
this.state.files.push(file);
}
/**
* 处理文件上传前的钩子, 根据`onBeforeUploadHook`返回true或resolve来添加至本地列表, 反之不添加
* @param file 单个文件对象
* @param files 文件列表
*/
private handleBeforeUploadHook(file: File, files: FileList): void {
const {
onBeforeUploadHook,
} = DraggerUpload.defaultProps;
if (onBeforeUploadHook) {
const result = onBeforeUploadHook(file, Array.from(files));
if (result instanceof Promise) {
result
.then((newFile) => {
if (newFile instanceof File) {
this.handleAppendToFiles(newFile);
this.handleAppendToShow(newFile);
} else {
this.handleAppendToFiles(file);
this.handleAppendToShow(file);
}
})
.catch(() => { })
} else {
if (result) {
this.handleAppendToFiles(file);
this.handleAppendToShow(file);
}
}
} else {
this.handleAppendToFiles(file);
this.handleAppendToShow(file);
}
}
private handleDrop(e: DragEvent): void {
const {
onChangeHook,
} = DraggerUpload.defaultProps;
const {
oContainer,
} = this.state;
const dataTransfer = e.dataTransfer as DataTransfer;
// ? 执行文件更改钩子
onChangeHook && onChangeHook(e);
removeClass(oContainer, 'ddzy-upload-drag-container-active');
Array.from(dataTransfer.files).forEach((file) => {
this.handleBeforeUploadHook(file, dataTransfer.files);
});
}
private handleChange(e: Event): void {
const {
onChangeHook,
} = DraggerUpload.defaultProps;
const target = e.target as HTMLInputElement;
const fileList = target.files as FileList;
// ? 执行文件更改钩子
onChangeHook && onChangeHook(e);
Array.from(fileList).forEach((file) => {
this.handleBeforeUploadHook(file, fileList);
});
}
/**
* 处理拖拽形式上传到本地
*/
private handleDragUpload(): void {
const { oContainer } = this.state;
// ? 解决浏览器默认打开预览窗口
document.addEventListener('dragover', (e) => {
e.preventDefault();
});
document.addEventListener('drop', (e) => {
e.preventDefault();
});
oContainer.addEventListener('dragenter', () => {
this.handleDragEnter();
});
oContainer.addEventListener('dragleave', () => {
this.handleDragLeave();
});
oContainer.addEventListener('drop', (e) => {
this.handleDrop(e);
});
}
/**
* 处理点击上传到本地
*/
private handleClickUpload(): void {
const {
oContainer,
oLabel,
oInput,
} = this.state;
// ? 解决ondrag和onclick冲突, 导致无法弹起文件选框的问题
oContainer.addEventListener('mouseup', () => {
oLabel.click();
});
oInput.addEventListener('change', (e) => {
this.handleChange(e);
});
}
} | the_stack |
import type * as ESTree from "estree"
import type { RuleListener, RuleModule, PartialRuleModule } from "../types"
import type { RegExpVisitor } from "regexpp/visitor"
import type {
CapturingGroup,
Element,
Node,
Pattern,
Quantifier,
} from "regexpp/ast"
import { RegExpParser, visitRegExpAST } from "regexpp"
import { CALL, CONSTRUCT, ReferenceTracker } from "eslint-utils"
import type { Rule, AST, SourceCode } from "eslint"
import { getStringIfConstant } from "./ast-utils"
import type { ReadonlyFlags } from "regexp-ast-analysis"
import { toCache } from "regexp-ast-analysis"
import type { CharSet } from "refa"
import { JS } from "refa"
import type { UsageOfPattern } from "./get-usage-of-pattern"
import { getUsageOfPattern } from "./get-usage-of-pattern"
import {
dereferenceOwnedVariable,
getStringValueRange,
isRegexpLiteral,
isStringLiteral,
} from "./ast-utils/utils"
import type { PatternRange } from "./ast-utils/pattern-source"
import { PatternSource } from "./ast-utils/pattern-source"
import type { CapturingGroupReference } from "./extract-capturing-group-references"
import { extractCapturingGroupReferences } from "./extract-capturing-group-references"
import { createTypeTracker } from "./type-tracker"
export * from "./unicode"
type RegExpContextBase = {
/**
* Creates SourceLocation from the given regexp node
* @see getRegexpLocation
*
* @param regexpNode The regexp node to report.
* @param offsets The report location offsets.
* @returns The SourceLocation
*/
getRegexpLocation: (
regexpNode: PatternRange,
offsets?: [number, number],
) => AST.SourceLocation
/**
* Creates SourceLocation of the regexp flags
*/
getFlagsLocation: () => AST.SourceLocation
/**
* Creates SourceLocation of the regexp flag
*/
getFlagLocation: (flag: string) => AST.SourceLocation
/**
* Creates a new fix that replaces the given node with a given string.
*
* The string will automatically be escaped if necessary.
* @see fixReplaceNode
*/
fixReplaceNode: (
regexpNode: Node,
replacement: string | (() => string | null),
) => (fixer: Rule.RuleFixer) => Rule.Fix | null
/**
* Creates a new fix that replaces the given quantifier (but not the quantified
* element) with a given string.
*
* This will not change the greediness of the quantifier.
* @see fixReplaceQuant
*/
fixReplaceQuant: (
quantifier: Quantifier,
replacement: string | Quant | (() => string | Quant | null),
) => (fixer: Rule.RuleFixer) => Rule.Fix | null
fixReplaceFlags: (
newFlags: string | (() => string | null),
includePattern?: boolean,
) => (fixer: Rule.RuleFixer) => Rule.Fix[] | Rule.Fix | null
/**
* Returns the usage of pattern.
*/
getUsageOfPattern: () => UsageOfPattern
/**
* Returns the capturing group references
*/
getCapturingGroupReferences: (options?: {
strictTypes?: boolean // default true
}) => CapturingGroupReference[]
/**
* Returns a list of all capturing groups in the order of their numbers.
*/
getAllCapturingGroups: () => CapturingGroup[]
pattern: string
patternAst: Pattern
patternSource: PatternSource
flags: Required<ReadonlyFlags>
}
export type RegExpContextForLiteral = {
node: ESTree.RegExpLiteral
flagsString: string
ownsFlags: true
regexpNode: ESTree.RegExpLiteral
} & RegExpContextBase
export type RegExpContextForSource = {
node: ESTree.Expression
flagsString: string | null
ownsFlags: boolean
regexpNode: ESTree.CallExpression
} & RegExpContextBase
export type RegExpContext = RegExpContextForLiteral | RegExpContextForSource
type UnparsableRegExpContextBase = {
node: ESTree.Expression
regexpNode: ESTree.RegExpLiteral | ESTree.CallExpression
flags: Required<ReadonlyFlags>
flagsString: string | null
ownsFlags: boolean
/**
* Creates SourceLocation of the regexp flags
*/
getFlagsLocation: () => AST.SourceLocation
/**
* Creates SourceLocation of the regexp flag
*/
getFlagLocation: (flag: string) => AST.SourceLocation
fixReplaceFlags: (
newFlags: string | (() => string | null),
includePattern?: boolean,
) => (fixer: Rule.RuleFixer) => Rule.Fix[] | Rule.Fix | null
}
export type RegExpContextForInvalid = {
pattern: string
patternSource: PatternSource
error: SyntaxError
} & UnparsableRegExpContextBase
export type RegExpContextForUnknown = {
pattern: null
patternSource: null
} & UnparsableRegExpContextBase
export type UnparsableRegExpContext =
| RegExpContextForInvalid
| RegExpContextForUnknown
type ParsableRegexpRule = {
createLiteralVisitor?: (
context: RegExpContextForLiteral,
) => RegExpVisitor.Handlers
createSourceVisitor?: (
context: RegExpContextForSource,
) => RegExpVisitor.Handlers
}
type UnparsableRegexpRule = {
visitInvalid?: (context: RegExpContextForInvalid) => void
visitUnknown?: (context: RegExpContextForUnknown) => void
}
type RegexpRule = ParsableRegexpRule & UnparsableRegexpRule
const regexpRules = new WeakMap<ESTree.Program, RegexpRule[]>()
export const FLAG_GLOBAL = "g"
export const FLAG_DOTALL = "s"
export const FLAG_IGNORECASE = "i"
export const FLAG_MULTILINE = "m"
export const FLAG_STICKY = "y"
export const FLAG_UNICODE = "u"
const flagsCache = new Map<string, ReadonlyFlags>()
/**
* Given some flags, this will return a parsed flags object.
*
* Non-standard flags will be ignored.
*/
export function parseFlags(flags: string): ReadonlyFlags {
let cached = flagsCache.get(flags)
if (cached === undefined) {
cached = {
dotAll: flags.includes(FLAG_DOTALL),
global: flags.includes(FLAG_GLOBAL),
ignoreCase: flags.includes(FLAG_IGNORECASE),
multiline: flags.includes(FLAG_MULTILINE),
sticky: flags.includes(FLAG_STICKY),
unicode: flags.includes(FLAG_UNICODE),
}
flagsCache.set(flags, cached)
}
return cached
}
/**
* Define the rule.
* @param ruleName ruleName
* @param rule rule module
*/
export function createRule(
ruleName: string,
rule: PartialRuleModule,
): RuleModule {
return {
meta: {
...rule.meta,
docs: {
...rule.meta.docs,
url: `https://ota-meshi.github.io/eslint-plugin-regexp/rules/${ruleName}.html`,
ruleId: `regexp/${ruleName}`,
ruleName,
},
},
create: rule.create as never,
}
}
type DefineRegexpVisitorRule = UnparsableRegexpRule &
(
| ParsableRegexpRule
| {
createVisitor: (context: RegExpContext) => RegExpVisitor.Handlers
}
)
/**
* Define the RegExp visitor rule.
*/
export function defineRegexpVisitor(
context: Rule.RuleContext,
rule: DefineRegexpVisitorRule,
): RuleListener {
const programNode = context.getSourceCode().ast
let visitor: RuleListener
let rules = regexpRules.get(programNode)
if (!rules) {
rules = []
regexpRules.set(programNode, rules)
visitor = buildRegexpVisitor(context, rules, () => {
regexpRules.delete(programNode)
})
} else {
visitor = {}
}
let createLiteralVisitor = undefined
let createSourceVisitor = undefined
if ("createVisitor" in rule) {
createLiteralVisitor = rule.createVisitor
createSourceVisitor = rule.createVisitor
} else {
createLiteralVisitor = rule.createLiteralVisitor
createSourceVisitor = rule.createSourceVisitor
}
rules.push({
createLiteralVisitor,
createSourceVisitor,
visitInvalid: rule.visitInvalid,
visitUnknown: rule.visitUnknown,
})
return visitor
}
/** Build RegExp visitor */
function buildRegexpVisitor(
context: Rule.RuleContext,
rules: RegexpRule[],
programExit: (node: ESTree.Program) => void,
): RuleListener {
const parser = new RegExpParser()
/**
* Verify a given regular expression.
* @param patternNode The regular expression pattern to verify.
* @param flags The flags of the regular expression.
*/
function verify(
patternNode: ESTree.Expression,
flagsNode: ESTree.Expression | null,
regexpNode: ESTree.RegExpLiteral | ESTree.CallExpression,
patternSource: PatternSource | null,
flagsString: string | null,
ownsFlags: boolean,
createVisitor: (helpers: RegExpContextBase) => RegExpVisitor.Handlers,
) {
const flags = parseFlags(flagsString || "")
if (!patternSource) {
visitUnknownForRules(rules, {
pattern: null,
patternSource: null,
...buildUnparsableRegExpContextBase({
patternSource,
patternNode,
regexpNode,
context,
flags,
flagsString,
flagsNode,
ownsFlags,
}),
})
return
}
let parsedPattern
try {
parsedPattern = parser.parsePattern(
patternSource.value,
0,
patternSource.value.length,
flags.unicode,
)
} catch (error: unknown) {
if (error instanceof SyntaxError) {
// regex with syntax error
visitInvalidForRules(rules, {
pattern: patternSource.value,
patternSource,
error,
...buildUnparsableRegExpContextBase({
patternSource,
patternNode,
regexpNode,
context,
flags,
flagsString,
flagsNode,
ownsFlags,
}),
})
}
return
}
const helpers = buildRegExpContextBase({
patternSource,
regexpNode,
flagsNode,
context,
flags,
parsedPattern,
})
visitRegExpAST(parsedPattern, createVisitor(helpers))
}
const ownedRegExpLiterals = new Set<ESTree.RegExpLiteral>()
return {
"Program:exit": programExit,
Literal(node: ESTree.Literal) {
if (!isRegexpLiteral(node) || ownedRegExpLiterals.has(node)) {
return
}
const flagsString = node.regex.flags
const patternSource = PatternSource.fromRegExpLiteral(context, node)
verify(
node,
node,
node,
patternSource,
flagsString,
true,
(base) => {
return createLiteralVisitorFromRules(rules, {
node,
flagsString,
ownsFlags: true,
regexpNode: node,
...base,
})
},
)
},
Program() {
const tracker = new ReferenceTracker(context.getScope())
// Iterate calls of RegExp.
// E.g., `new RegExp()`, `RegExp()`, `new window.RegExp()`,
// `const {RegExp: a} = window; new a()`, etc...
const regexpDataList: {
call: ESTree.CallExpression
patternNode: ESTree.Expression
patternSource: PatternSource | null
flagsNode: ESTree.Expression | null
flagsString: string | null
ownsFlags: boolean
}[] = []
for (const { node } of tracker.iterateGlobalReferences({
RegExp: { [CALL]: true, [CONSTRUCT]: true },
})) {
const newOrCall = node as ESTree.CallExpression
const args = newOrCall.arguments as (
| ESTree.Expression
| ESTree.SpreadElement
| undefined
)[]
const [patternArg, flagsArg] = args
if (!patternArg || patternArg.type === "SpreadElement") {
continue
}
const patternSource = PatternSource.fromExpression(
context,
patternArg,
)
// avoid double reporting
patternSource
?.getOwnedRegExpLiterals()
.forEach((n) => ownedRegExpLiterals.add(n))
let flagsNode = null
let flagsString = null
let ownsFlags = false
if (flagsArg) {
if (flagsArg.type !== "SpreadElement") {
flagsNode = dereferenceOwnedVariable(context, flagsArg)
flagsString = getStringIfConstant(context, flagsNode)
ownsFlags = isStringLiteral(flagsNode)
}
} else {
if (patternSource && patternSource.regexpValue) {
flagsString = patternSource.regexpValue.flags
ownsFlags = Boolean(patternSource.regexpValue.ownedNode)
flagsNode = patternSource.regexpValue.ownedNode
} else {
flagsString = ""
ownsFlags = true
}
}
regexpDataList.push({
call: newOrCall,
patternNode: patternArg,
patternSource,
flagsNode,
flagsString,
ownsFlags,
})
}
for (const {
call,
patternNode,
patternSource,
flagsNode,
flagsString,
ownsFlags,
} of regexpDataList) {
verify(
patternNode,
flagsNode,
call,
patternSource,
flagsString,
ownsFlags,
(base) => {
return createSourceVisitorFromRules(rules, {
node: patternNode,
flagsString,
ownsFlags,
regexpNode: call,
...base,
})
},
)
}
},
}
}
/** Create a visitor handler from the given rules */
function createLiteralVisitorFromRules(
rules: Iterable<RegexpRule>,
context: RegExpContextForLiteral,
): RegExpVisitor.Handlers {
const handlers: RegExpVisitor.Handlers[] = []
for (const rule of rules) {
if (rule.createLiteralVisitor) {
handlers.push(rule.createLiteralVisitor(context))
}
}
return composeRegExpVisitors(handlers)
}
/** Create a visitor handler from the given rules */
function createSourceVisitorFromRules(
rules: Iterable<RegexpRule>,
context: RegExpContextForSource,
): RegExpVisitor.Handlers {
const handlers: RegExpVisitor.Handlers[] = []
for (const rule of rules) {
if (rule.createSourceVisitor) {
handlers.push(rule.createSourceVisitor(context))
}
}
return composeRegExpVisitors(handlers)
}
/** Calls a visit function for all the given rules */
function visitInvalidForRules(
rules: Iterable<RegexpRule>,
context: RegExpContextForInvalid,
): void {
for (const rule of rules) {
rule.visitInvalid?.(context)
}
}
/** Calls a visit function for all the given rules */
function visitUnknownForRules(
rules: Iterable<RegexpRule>,
context: RegExpContextForUnknown,
): void {
for (const rule of rules) {
rule.visitUnknown?.(context)
}
}
/** Returns a single visitor handler that executes all the given handlers. */
function composeRegExpVisitors(
handlers: Iterable<RegExpVisitor.Handlers>,
): RegExpVisitor.Handlers {
const handler: RegExpVisitor.Handlers = {}
for (const visitor of handlers) {
const entries = Object.entries(visitor) as [
keyof RegExpVisitor.Handlers,
RegExpVisitor.Handlers[keyof RegExpVisitor.Handlers],
][]
for (const [key, fn] of entries) {
const orig = handler[key]
if (orig) {
handler[key] = (
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- ignore
node: any,
) => {
orig(node)
fn!(node)
}
} else {
// @ts-expect-error -- ignore
handler[key] = fn
}
}
}
return handler
}
/**
* Composite all given visitors.
*/
export function compositingVisitors(
visitor: RuleListener,
...visitors: RuleListener[]
): RuleListener {
for (const v of visitors) {
for (const key in v) {
const orig = visitor[key]
if (orig) {
visitor[key] = (...args: unknown[]) => {
// @ts-expect-error -- ignore
orig(...args)
// @ts-expect-error -- ignore
v[key](...args)
}
} else {
visitor[key] = v[key]
}
}
}
return visitor
}
/**
* Build RegExpContextBase
*/
function buildRegExpContextBase({
patternSource,
regexpNode,
flagsNode,
context,
flags,
parsedPattern,
}: {
patternSource: PatternSource
regexpNode: ESTree.CallExpression | ESTree.RegExpLiteral
flagsNode: ESTree.Expression | null
context: Rule.RuleContext
flags: ReadonlyFlags
parsedPattern: Pattern
}): RegExpContextBase {
const sourceCode = context.getSourceCode()
let cacheUsageOfPattern: UsageOfPattern | null = null
const cacheCapturingGroupReferenceMap = new Map<
boolean /* strictTypes */,
CapturingGroupReference[]
>()
let cacheAllCapturingGroups: CapturingGroup[] | null = null
return {
getRegexpLocation: (range, offsets) => {
if (offsets) {
return patternSource.getAstLocation({
start: range.start + offsets[0],
end: range.start + offsets[1],
})
}
return patternSource.getAstLocation(range)
},
getFlagsLocation: () =>
getFlagsLocation(sourceCode, regexpNode, flagsNode),
getFlagLocation: (flag) =>
getFlagLocation(sourceCode, regexpNode, flagsNode, flag),
fixReplaceNode: (node, replacement) => {
return fixReplaceNode(patternSource, node, replacement)
},
fixReplaceQuant: (qNode, replacement) => {
return fixReplaceQuant(patternSource, qNode, replacement)
},
fixReplaceFlags: (newFlags, includePattern) => {
return fixReplaceFlags(
patternSource,
regexpNode,
flagsNode,
newFlags,
includePattern ?? true,
)
},
getUsageOfPattern: () =>
(cacheUsageOfPattern ??= getUsageOfPattern(regexpNode, context)),
getCapturingGroupReferences: (options?: {
strictTypes?: boolean // default true
}) => {
const strictTypes = Boolean(options?.strictTypes ?? true)
const cacheCapturingGroupReference =
cacheCapturingGroupReferenceMap.get(strictTypes)
if (cacheCapturingGroupReference) {
return cacheCapturingGroupReference
}
const countOfCapturingGroup =
getAllCapturingGroupsWithCache().length
const capturingGroupReferences = [
...extractCapturingGroupReferences(
regexpNode,
flags,
createTypeTracker(context),
countOfCapturingGroup,
context,
{ strictTypes },
),
]
cacheCapturingGroupReferenceMap.set(
strictTypes,
capturingGroupReferences,
)
return capturingGroupReferences
},
getAllCapturingGroups: getAllCapturingGroupsWithCache,
pattern: parsedPattern.raw,
patternAst: parsedPattern,
patternSource,
flags: toCache(flags),
}
/** Returns a list of all capturing groups in the order of their numbers. */
function getAllCapturingGroupsWithCache(): CapturingGroup[] {
return (cacheAllCapturingGroups ??=
getAllCapturingGroups(parsedPattern))
}
}
/**
* Build UnparsableRegExpContextBase
*/
function buildUnparsableRegExpContextBase({
patternSource,
patternNode,
regexpNode,
context,
flags: originalFlags,
flagsString,
flagsNode,
ownsFlags,
}: {
patternSource: PatternSource | null
patternNode: ESTree.Expression
regexpNode: ESTree.CallExpression | ESTree.RegExpLiteral
context: Rule.RuleContext
flags: ReadonlyFlags
flagsString: string | null
flagsNode: ESTree.Expression | null
ownsFlags: boolean
}): UnparsableRegExpContextBase {
const sourceCode = context.getSourceCode()
const flags = toCache(originalFlags)
return {
regexpNode,
node: patternNode,
flags,
flagsString,
ownsFlags,
getFlagsLocation: () =>
getFlagsLocation(sourceCode, regexpNode, flagsNode),
getFlagLocation: (flag) =>
getFlagLocation(sourceCode, regexpNode, flagsNode, flag),
fixReplaceFlags: (newFlags, includePattern) => {
return fixReplaceFlags(
patternSource,
regexpNode,
flagsNode,
newFlags,
includePattern ?? true,
)
},
}
}
export function getFlagsRange(flagsNode: ESTree.RegExpLiteral): AST.Range
export function getFlagsRange(
flagsNode: ESTree.Expression | null,
): AST.Range | null
/**
* Creates source range of the flags of the given regexp node
* @param flagsNode The expression that contributes the flags.
*/
export function getFlagsRange(
flagsNode: ESTree.Expression | null,
): AST.Range | null {
if (!flagsNode) {
return null
}
if (isRegexpLiteral(flagsNode)) {
return [
flagsNode.range![1] - flagsNode.regex.flags.length,
flagsNode.range![1],
]
}
if (isStringLiteral(flagsNode)) {
return [flagsNode.range![0] + 1, flagsNode.range![1] - 1]
}
return null
}
/**
* Creates SourceLocation of the flags of the given regexp node
* @param sourceCode The ESLint source code instance.
* @param regexpNode The node to report.
*/
export function getFlagsLocation(
sourceCode: SourceCode,
regexpNode: ESTree.CallExpression | ESTree.RegExpLiteral,
flagsNode: ESTree.Expression | null,
): AST.SourceLocation {
const range = getFlagsRange(flagsNode)
if (range == null) {
return flagsNode?.loc ?? regexpNode.loc!
}
if (range[0] === range[1]) {
range[0]--
}
return {
start: sourceCode.getLocFromIndex(range[0]),
end: sourceCode.getLocFromIndex(range[1]),
}
}
/**
* Creates source range of the given flag in the given flags node
* @param flagsNode The expression that contributes the flags.
*/
function getFlagRange(
sourceCode: SourceCode,
flagsNode: ESTree.Expression | null,
flag: string,
): AST.Range | null {
if (!flagsNode || !flag) {
return null
}
if (isRegexpLiteral(flagsNode)) {
const index = flagsNode.regex.flags.indexOf(flag)
if (index === -1) {
return null
}
const start = flagsNode.range![1] - flagsNode.regex.flags.length + index
return [start, start + 1]
}
if (isStringLiteral(flagsNode)) {
const index = flagsNode.value.indexOf(flag)
if (index === -1) {
return null
}
return getStringValueRange(sourceCode, flagsNode, index, index + 1)
}
return null
}
/**
* Creates source location of the given flag in the given flags node
* @param flagsNode The expression that contributes the flags.
*/
function getFlagLocation(
sourceCode: SourceCode,
regexpNode: ESTree.CallExpression | ESTree.RegExpLiteral,
flagsNode: ESTree.Expression | null,
flag: string,
): AST.SourceLocation {
const range = getFlagRange(sourceCode, flagsNode, flag)
if (range == null) {
return flagsNode?.loc ?? regexpNode.loc!
}
return {
start: sourceCode.getLocFromIndex(range[0]),
end: sourceCode.getLocFromIndex(range[1]),
}
}
/**
* Creates a new fix that replaces the given node with a given string.
*
* The string will automatically be escaped if necessary.
*/
function fixReplaceNode(
patternSource: PatternSource,
regexpNode: Node,
replacement: string | (() => string | null),
) {
return (fixer: Rule.RuleFixer): Rule.Fix | null => {
const range = patternSource.getReplaceRange(regexpNode)
if (range == null) {
return null
}
let text
if (typeof replacement === "string") {
text = replacement
} else {
text = replacement()
if (text == null) {
return null
}
}
return range.replace(fixer, text)
}
}
/**
* Creates a new fix that replaces the given quantifier (but not the quantified
* element) with a given string.
*
* This will not change the greediness of the quantifier.
*/
function fixReplaceQuant(
patternSource: PatternSource,
quantifier: Quantifier,
replacement: string | Quant | (() => string | Quant | null),
) {
return (fixer: Rule.RuleFixer): Rule.Fix | null => {
let text
if (typeof replacement !== "function") {
text = replacement
} else {
text = replacement()
if (text == null) {
return null
}
}
const offset = getQuantifierOffsets(quantifier)
if (typeof text !== "string") {
if (
text.greedy !== undefined &&
text.greedy !== quantifier.greedy
) {
// we also change the greediness of the quantifier
offset[1] += 1
}
text = quantToString(text)
}
const range = patternSource.getReplaceRange({
start: quantifier.start + offset[0],
end: quantifier.start + offset[1],
})
if (range == null) {
return null
}
return range.replace(fixer, text)
}
}
/**
* Returns a new fixer that replaces the current flags with the given flags.
*
* @param includePattern Whether the whole pattern is to be included in the fix.
*
* Fixes that change the pattern generally assume that the flags don't change,
* so changing the flags should conflict with all pattern fixes.
*/
function fixReplaceFlags(
patternSource: PatternSource | null,
regexpNode: ESTree.CallExpression | ESTree.RegExpLiteral,
flagsNode: ESTree.Expression | null,
replacement: string | (() => string | null),
includePattern: boolean,
) {
return (fixer: Rule.RuleFixer): Rule.Fix[] | Rule.Fix | null => {
let newFlags
if (typeof replacement === "string") {
newFlags = replacement
} else {
newFlags = replacement()
if (newFlags == null) {
return null
}
}
if (!/^[a-z]*$/iu.test(newFlags)) {
// make sure that escaping isn't necessary
return null
}
if (includePattern && isRegexpLiteral(regexpNode)) {
return fixer.replaceText(
regexpNode,
`/${regexpNode.regex.pattern}/${newFlags}`,
)
}
// eslint-disable-next-line one-var -- x
let flagsFix
if (isRegexpLiteral(regexpNode)) {
flagsFix = fixer.replaceTextRange(
getFlagsRange(regexpNode),
newFlags,
)
} else if (flagsNode) {
const range = getFlagsRange(flagsNode)
if (range == null) {
return null
}
flagsFix = fixer.replaceTextRange(range, newFlags)
} else {
// If the RegExp call doesn't have a flags argument, we'll add it
if (regexpNode.arguments.length !== 1) {
return null
}
const end = regexpNode.range![1]
flagsFix = fixer.replaceTextRange(
[end - 1, end],
`, "${newFlags}")`,
)
}
if (!includePattern) {
return flagsFix
}
// pattern fix
if (!patternSource) {
return null
}
const patternRange = patternSource.getReplaceRange({
start: 0,
end: patternSource.value.length,
})
if (patternRange == null) {
return null
}
const patternFix = patternRange.replace(fixer, patternSource.value)
return [patternFix, flagsFix]
}
}
/**
* Get the offsets of the given quantifier
*/
export function getQuantifierOffsets(qNode: Quantifier): [number, number] {
const startOffset = qNode.element.end - qNode.start
const endOffset = qNode.raw.length - (qNode.greedy ? 0 : 1)
return [startOffset, endOffset]
}
export interface Quant {
min: number
max: number
greedy?: boolean
}
/**
* Returns the string representation of the given quantifier.
*/
export function quantToString(quant: Readonly<Quant>): string {
if (
quant.max < quant.min ||
quant.min < 0 ||
!Number.isInteger(quant.min) ||
!(Number.isInteger(quant.max) || quant.max === Infinity)
) {
throw new Error(
`Invalid quantifier { min: ${quant.min}, max: ${quant.max} }`,
)
}
let value
if (quant.min === 0 && quant.max === 1) {
value = "?"
} else if (quant.min === 0 && quant.max === Infinity) {
value = "*"
} else if (quant.min === 1 && quant.max === Infinity) {
value = "+"
} else if (quant.min === quant.max) {
value = `{${quant.min}}`
} else if (quant.max === Infinity) {
value = `{${quant.min},}`
} else {
value = `{${quant.min},${quant.max}}`
}
if (quant.greedy === false) {
return `${value}?`
}
return value
}
/**
* Returns a regexp literal source of the given char set or char.
*/
export function toCharSetSource(
charSetOrChar: CharSet | number,
flags: ReadonlyFlags,
): string {
let charSet
if (typeof charSetOrChar === "number") {
charSet = JS.createCharSet([charSetOrChar], flags)
} else {
charSet = charSetOrChar
}
return JS.toLiteral(
{
type: "Concatenation",
elements: [{ type: "CharacterClass", characters: charSet }],
},
{ flags },
).source
}
/* eslint-disable complexity -- X( */
/**
* Returns whether the concatenation of the two string might create new escape
* sequences or elements.
*/
export function mightCreateNewElement(
/* eslint-enable complexity -- X( */
before: string,
after: string,
): boolean {
// control
// \cA
if (before.endsWith("\\c") && /^[a-z]/iu.test(after)) {
return true
}
// hexadecimal
// \xFF \uFFFF
if (
/(?:^|[^\\])(?:\\{2})*\\(?:x[\dA-Fa-f]?|u[\dA-Fa-f]{0,3})$/u.test(
before,
) &&
/^[\da-f]/iu.test(after)
) {
return true
}
// unicode
// \u{FFFF}
if (
(/(?:^|[^\\])(?:\\{2})*\\u$/u.test(before) &&
/^\{[\da-f]*(?:\}[\s\S]*)?$/iu.test(after)) ||
(/(?:^|[^\\])(?:\\{2})*\\u\{[\da-f]*$/u.test(before) &&
/^(?:[\da-f]+\}?|\})/iu.test(after))
) {
return true
}
// octal
// \077 \123
if (
(/(?:^|[^\\])(?:\\{2})*\\0[0-7]?$/u.test(before) &&
/^[0-7]/u.test(after)) ||
(/(?:^|[^\\])(?:\\{2})*\\[1-7]$/u.test(before) && /^[0-7]/u.test(after))
) {
return true
}
// backreference
// \12 \k<foo>
if (
(/(?:^|[^\\])(?:\\{2})*\\[1-9]\d*$/u.test(before) &&
/^\d/u.test(after)) ||
(/(?:^|[^\\])(?:\\{2})*\\k$/u.test(before) && after.startsWith("<")) ||
/(?:^|[^\\])(?:\\{2})*\\k<[^<>]*$/u.test(before)
) {
return true
}
// property
// \p{L} \P{L}
if (
(/(?:^|[^\\])(?:\\{2})*\\p$/iu.test(before) &&
/^\{[\w=]*(?:\}[\s\S]*)?$/u.test(after)) ||
(/(?:^|[^\\])(?:\\{2})*\\p\{[\w=]*$/iu.test(before) &&
/^[\w=]+(?:\}[\s\S]*)?$|^\}/u.test(after))
) {
return true
}
// quantifier
// {1} {2,} {2,3}
if (
(/(?:^|[^\\])(?:\\{2})*\{\d*$/u.test(before) &&
/^[\d,}]/u.test(after)) ||
(/(?:^|[^\\])(?:\\{2})*\{\d+,$/u.test(before) &&
/^(?:\d+(?:\}|$)|\})/u.test(after)) ||
(/(?:^|[^\\])(?:\\{2})*\{\d+,\d*$/u.test(before) &&
after.startsWith("}"))
) {
return true
}
return false
}
/**
* Check the siblings to see if the regex doesn't change when unwrapped.
*/
export function canUnwrapped(node: Element, text: string): boolean {
let textBefore, textAfter
const parent = node.parent
if (parent.type === "Alternative") {
textBefore = parent.raw.slice(0, node.start - parent.start)
textAfter = parent.raw.slice(node.end - parent.start)
} else if (parent.type === "Quantifier") {
const alt = parent.parent
textBefore = alt.raw.slice(0, node.start - alt.start)
textAfter = alt.raw.slice(node.end - alt.start)
} else {
return true
}
return (
!mightCreateNewElement(textBefore, text) &&
!mightCreateNewElement(text, textAfter)
)
}
/**
* Returns whether the given raw of a character literal is an octal escape
* sequence.
*/
export function isOctalEscape(raw: string): boolean {
return /^\\[0-7]{1,3}$/u.test(raw)
}
/**
* Returns whether the given raw of a character literal is a control escape
* sequence.
*/
export function isControlEscape(raw: string): boolean {
return /^\\c[A-Za-z]$/u.test(raw)
}
/**
* Returns whether the given raw of a character literal is a hexadecimal escape
* sequence.
*/
export function isHexadecimalEscape(raw: string): boolean {
return /^\\x[\dA-Fa-f]{2}$/u.test(raw)
}
/**
* Returns whether the given raw of a character literal is a unicode escape
* sequence.
*/
export function isUnicodeEscape(raw: string): boolean {
return /^\\u[\dA-Fa-f]{4}$/u.test(raw)
}
/**
* Returns whether the given raw of a character literal is a unicode code point
* escape sequence.
*/
export function isUnicodeCodePointEscape(raw: string): boolean {
return /^\\u\{[\dA-Fa-f]{1,8}\}$/u.test(raw)
}
export enum EscapeSequenceKind {
octal = "octal",
control = "control",
hexadecimal = "hexadecimal",
unicode = "unicode",
unicodeCodePoint = "unicode code point",
}
/**
* Returns which escape sequence kind was used for the given raw of a character literal.
*/
export function getEscapeSequenceKind(raw: string): EscapeSequenceKind | null {
if (!raw.startsWith("\\")) {
return null
}
if (isOctalEscape(raw)) {
return EscapeSequenceKind.octal
}
if (isControlEscape(raw)) {
return EscapeSequenceKind.control
}
if (isHexadecimalEscape(raw)) {
return EscapeSequenceKind.hexadecimal
}
if (isUnicodeEscape(raw)) {
return EscapeSequenceKind.unicode
}
if (isUnicodeCodePointEscape(raw)) {
return EscapeSequenceKind.unicodeCodePoint
}
return null
}
/**
* Returns whether the given raw of a character literal is a hexadecimal escape
* sequence, a unicode escape sequence, or a unicode code point escape sequence.
*/
export function isUseHexEscape(raw: string): boolean {
const kind = getEscapeSequenceKind(raw)
return (
kind === EscapeSequenceKind.hexadecimal ||
kind === EscapeSequenceKind.unicode ||
kind === EscapeSequenceKind.unicodeCodePoint
)
}
/**
* Returns whether the given raw of a character literal is an octal escape
* sequence, a control escape sequence, a hexadecimal escape sequence, a unicode
* escape sequence, or a unicode code point escape sequence.
*/
export function isEscapeSequence(raw: string): boolean {
return Boolean(getEscapeSequenceKind(raw))
}
/** Returns a list of all capturing groups in the order of their numbers. */
function getAllCapturingGroups(pattern: Pattern): CapturingGroup[] {
const groups: CapturingGroup[] = []
visitRegExpAST(pattern, {
onCapturingGroupEnter(group) {
groups.push(group)
},
})
// visitRegExpAST given no guarantees in which order nodes are visited.
// Sort the list to guarantee order.
groups.sort((a, b) => a.start - b.start)
return groups
} | the_stack |
import { AjaxFlowInteralNode, CombErr, FlowOutNode } from '../core';
import { IRcloneServer, PostFlow } from './post-flow';
import { NoopAuthFlowSupNode } from './noop-auth-flow';
// update schema: npm run build:schemas
export interface IRcloneOptionsDlna {
/**
* specify which IP address and port the server should listen on.
* eg `1.2.3.4:8000` or `:8080` to listen to all IPs.
*/
ListenAddr?: ':7979' | string;
/**
* choose the friendly server name,
* which is by default "rclone (hostname)
*/
FriendlyName?: '' | string;
/** enable additional debug logging of all UPNP traffic. */
LogTrace?: false | boolean;
}
export interface IRcloneOptionsFilter {
/** Delete files on dest excluded from sync */
DeleteExcluded?: false | boolean;
/** Add a file-filtering rule */
FilterRule?: null | string[];
/** Read filtering patterns from a file (use - to read from stdin) */
FilterFrom?: null | string[];
/** Exclude files matching pattern */
ExcludeRule?: null | string[];
/** Read exclude patterns from file (use - to read from stdin) */
ExcludeFrom?: null | string[];
/** Exclude directories if filename is present */
ExcludeFile?: '' | string;
/** Include files matching pattern */
IncludeRule?: null | string[];
/** Read include patterns from file (use - to read from stdin) */
IncludeFrom?: null | string[];
/** Read list of source-file names from file (use - to read from stdin) */
FilesFrom?: null | string[];
/** Read list of source-file names from file without any processing of lines (use - to read from stdin) */
FilesFromRaw?: null | string[];
/**
* Only transfer files older than this in s or suffix ms|s|m|h|d|w|M|y
*/
MinAge?: number;
/**
* Only transfer files younger than this in s or suffix ms|s|m|h|d|w|M|y
*/
MaxAge?: number;
/** Only transfer files bigger than this in k or suffix b|k|M|G */
MinSize?: -1 | number;
/** Only transfer files smaller than this in k or suffix b|k|M|G */
MaxSize?: -1 | number;
/** Ignore case in filters (case insensitive) */
IgnoreCase?: false | boolean;
}
export interface IRcloneOptionsFtp {
/** IPaddress:Port or :Port to bind server to. */
ListenAddr?: 'localhost:2121' | string;
/** Public IP address to advertise for passive connections. */
PublicIP?: '' | string;
/** Passive port range to use. */
PassivePorts?: '30000-32000' | string;
/**
* User name for authentication.
* single username for basic auth if not using Htpasswd
*/
BasicUser?: 'anonymous' | string;
/**
* Password for BasicUser authentication.
* (empty value allow every password)
*/
BasicPass?: '' | string;
}
export interface IRcloneOptionsHttp {
/**
* Port to listen on
* Use --addr to specify which IP address and port
* the server should listen on,
* eg --addr 1.2.3.4:8000 or --addr :8080 to listen to all IPs.
* By default it only listens on localhost.
* You can use port :0 to let the OS choose an available port.
*
* If you set --addr to listen on a public or LAN accessible IP address
* then using Authentication is advised - see the next section for info.
*/
ListenAddr?: 'localhost:8080' | string;
/**
* prefix to strip from URLs
* --baseurl controls the URL prefix that rclone serves from.
* By default rclone will serve from the root.
* If you used --baseurl "/rclone" then rclone would serve from a URL
* starting with "/rclone/".
* This is useful if you wish to proxy rclone serve.
* Rclone automatically inserts leading and trailing "/" on --baseurl,
* so --baseurl "rclone", --baseurl "/rclone" and --baseurl "/rclone/"
* are all treated identically.
*/
BaseURL?: '' | string;
/**
* Timeout for server reading data
* Note that this is the total time for a transfer.
*/
ServerReadTimeout?: 3600000000000 | number;
/**
* Timeout for server writing data
* Note that this is the total time for a transfer.
*/
ServerWriteTimeout?: 3600000000000 | number;
/**
* Maximum size of request header
* --max-header-bytes controls the maximum number of bytes the server will
* accept in the HTTP header.
*/
MaxHeaderBytes?: 4096 | number;
/** SSL PEM key (concatenation of certificate and CA certificate) */
SslCert?: '' | string;
/** SSL PEM Private key */
SslKey?: '' | string;
/** Client certificate authority to verify clients with */
ClientCA?: '' | string;
/**
* htpasswd file - if not provided no authentication is done
* This is in standard apache format and supports MD5, SHA1 and BCrypt for basic
* authentication. Bcrypt is recommended.
* To create an htpasswd file:
*
* touch htpasswd
* htpasswd -B htpasswd user
* htpasswd -B htpasswd anotherUser
*
* The password file can be updated while rclone is running.
*/
HtPasswd?: '' | string;
/** realm for authentication */
Realm?: 'rclone' | string;
/** single username for basic auth if not using Htpasswd */
BasicUser?: 'admin' | string;
/** password for BasicUser */
BasicPass?: 'admin' | string;
/**
* User specified template
* --template allows a user to specify a custom markup template for http
* and webdav serve functions. The server exports the following markup
* to be used within the template to server pages:
*
* | Parameter | Description |
* | :---------- | :---------- |
* | .Name | The full path of a file/directory. |
* | .Title | Directory listing of .Name |
* | .Sort | The current sort used. This is changeable via ?sort= parameter |
* | | Sort Options: namedirfist,name,size,time (default namedirfirst) |
* | .Order | The current ordering used. This is changeable via ?order= parameter |
* | | Order Options: asc,desc (default asc) |
* | .Query | Currently unused. |
* | .Breadcrumb | Allows for creating a relative navigation |
* |-- .Link | The relative to the root link of the Text. |
* |-- .Text | The Name of the directory. |
* | .Entries | Information about a specific file/directory. |
* |-- .URL | The 'url' of an entry. |
* |-- .Leaf | Currently same as 'URL' but intended to be 'just' the name. |
* |-- .IsDir | Boolean for if an entry is a directory or not. |
* |-- .Size | Size in Bytes of the entry. |
* |-- .ModTime | The UTC timestamp of an entry. |
*/
Template?: '' | string;
}
export interface IRcloneOptionsLog {
/** Log everything to this file */
File?: '' | string;
/** Comma separated list of log format options */
Format?: 'date,time' | string;
/** Use Syslog for logging */
UseSyslog?: false | boolean;
/** Facility for syslog, eg KERN,USER,... */
SyslogFacility?: 'DAEMON' | string;
}
export interface IRcloneOptionsMain {
/**
* Log level DEBUG|INFO|NOTICE|ERROR
*
* Log levels. These are the syslog levels of which we only use a
* subset.
*
* 0 LOG_EMERG system is unusable
* 1 LOG_ALERT action must be taken immediately
* 2 LOG_CRIT critical conditions
* 3 LOG_ERR error conditions
* 4 LOG_WARNING warning conditions
* 5 LOG_NOTICE normal, but significant, condition
* 6 LOG_INFO informational message
* 7 LOG_DEBUG debug-level message
*/
LogLevel?: 7 | number;
/**
* Log level to show --stats output DEBUG|INFO|NOTICE|ERROR
*
* Log levels. These are the syslog levels of which we only use a
* subset.
*
* 0 LOG_EMERG system is unusable
* 1 LOG_ALERT action must be taken immediately
* 2 LOG_CRIT critical conditions
* 3 LOG_ERR error conditions
* 4 LOG_WARNING warning conditions
* 5 LOG_NOTICE normal, but significant, condition
* 6 LOG_INFO informational message
* 7 LOG_DEBUG debug-level message
*/
StatsLogLevel?: 6 | number;
/** Use json log format. */
UseJSONLog?: false | boolean;
/** Do a trial run with no permanent changes */
DryRun?: false | boolean;
/** Skip based on checksum (if available) & size, not mod-time & size */
CheckSum?: false | boolean;
/** Skip based on size only, not mod-time or checksum */
SizeOnly?: false | boolean;
/** Don't skip files that match size and time - transfer all files */
IgnoreTimes?: false | boolean;
/** Skip all files that exist on destination */
IgnoreExisting?: false | boolean;
/** delete even if there are I/O errors */
IgnoreErrors?: false | boolean;
/** Max time diff to be considered the same */
ModifyWindow?: 1 | number;
/** Number of checkers to run in parallel. */
Checkers?: 8 | number;
/** Number of file transfers to run in parallel. */
Transfers?: 4 | number;
/** Connect timeout */
ConnectTimeout?: 60000000000 | number;
/** IO idle timeout */
Timeout?: 300000000000 | number;
/** Timeout when using expect / 100-continue in HTTP */
ExpectContinueTimeout?: 1000000000 | number;
/** List of items to dump from: headers,bodies,requests,responses,auth,filters,goroutines,openfiles */
Dump?: 0 | number;
/** Do not verify the server SSL certificate. Insecure. */
InsecureSkipVerify?: false | boolean;
/**
* the possible delete modes in the config
* DeleteModeOff DeleteMode = iota
* 0 DeleteModeBefore
* 1 DeleteModeDuring
* 2 DeleteModeAfter
* 3 DeleteModeOnly
*/
DeleteMode?: 3 | number;
/** When synchronizing, limit the number of deletes */
MaxDelete?: -1 | number;
/** When synchronizing, track file renames and do a server side move if possible */
TrackRenames?: false | boolean;
/** Strategies to use when synchronizing using track-renames hash|modtime */
TrackRenamesStrategy?: 'hash' | 'modtime';
/** Number of low level retries to do. */
LowLevelRetries?: 10 | number;
/** Skip files that are newer on the destination. */
UpdateOlder?: false | boolean;
/** Don't set Accept-Encoding: gzip. */
NoGzip?: false | boolean;
/** If set limits the recursion depth to this. */
MaxDepth?: -1 | number;
/** Ignore size when skipping use mod-time or checksum */
IgnoreSize?: false | boolean;
/** Skip post copy check of checksums. */
IgnoreChecksum?: false | boolean;
/** Ignore case when synchronizing */
IgnoreCaseSync?: false | boolean;
/** Don't traverse destination file system on copy. */
NoTraverse?: false | boolean;
/** Don't check the destination, copy regardless. */
NoCheckDest?: false | boolean;
/** Don't update destination mod-time if files identical. */
NoUpdateModTime?: false | boolean;
DataRateUnit?: 'bytes' | string;
/** Include additional server-side path during comparison. */
CompareDest?: '' | string;
/** Implies --compare-dest but also copies files from path into destination. */
CopyDest?: '' | string;
/** Make backups into hierarchy based in DIR. */
BackupDir?: '' | string;
/** Suffix to add to changed files. */
Suffix?: '' | string;
/** Preserve the extension when using --suffix. */
SuffixKeepExtension?: false | boolean;
/** Use recursive list if available. Uses more memory but fewer transactions. */
UseListR?: false | boolean;
/** In memory buffer size when reading files for each --transfer. */
BufferSize?: 16777216 | number;
/** */
BwLimit?: null | boolean | string | number;
/** Bandwidth limit in kBytes/s, or use suffix b|k|M|G or a full timetable. */
TPSLimit?: 0 | number;
/** Max burst of transactions for --tpslimit. */
TPSLimitBurst?: 1 | number;
/** Local address to bind to for outgoing connections, IPv4, IPv6 or name. */
BindAddr?: '' | string;
/** Disable a comma separated list of features. Use help to see a list. */
DisableFeatures?: null | boolean | string | number;
/** Set the user-agent to a specified string. The default is rclone/ version */
UserAgent?: 'rclone/v1.51.0-DEV' | string;
/** Do not modify files. Fail if existing files have been modified. */
Immutable?: false | boolean;
/** If enabled, do not request console confirmation. */
AutoConfirm?: false | boolean;
/**
* Cutoff for switching to chunked upload if file size is unknown.
* Upload starts after reaching cutoff or when file ends.
*/
StreamingUploadCutoff?: 102400 | number;
/** Max file name length in stats. 0 for no limit */
StatsFileNameLength?: 45 | number;
/** Allow prompt for password for encrypted configuration. */
AskPassword?: true | boolean;
/** Command for supplying password for encrypted configuration. */
PasswordCommand?: null | boolean | string | number;
/** Use server modified time instead of object metadata */
UseServerModTime?: false | boolean;
/** Maximum size of data to transfer. */
MaxTransfer?: -1 | number;
/** Maximum duration rclone will transfer data for. */
MaxDuration?: 0 | number;
/**
* Mode to stop transfers when reaching the max transfer limit HARD|SOFT|CAUTIOUS
* 0 Hard
* 1 Soft
* 2 Cautious
*/
CutoffMode?: 0 | number;
/** Maximum number of objects in sync or check backlog. */
MaxBacklog?: 10000 | number;
/** Maximum number of stats groups to keep in memory. On max oldest is discarded. */
MaxStatsGroups?: 1000 | number;
/** Make the stats fit on one line. */
StatsOneLine?: false | boolean;
/**
* If we want a date prefix at all
* Enables --stats-one-line and add current date/time prefix.
*/
StatsOneLineDate?: false | boolean;
/**
* If we want to customize the prefix
* Enables --stats-one-line-date and uses custom formatted date.
* Enclose date string in double quotes (\").
* See https://golang.org/pkg/time/#Time.Format
*/
StatsOneLineDateFormat?: '' | string;
/**
* Set appropriate exit code if no files transferred
* Sets exit code 9 if no files are transferred, useful in scripts
*/
ErrorOnNoTransfer?: false | boolean;
/** Show progress during transfer. */
Progress?: false | boolean;
/** Enable session cookiejar. */
Cookie?: false | boolean;
/** Use mmap allocator (see docs). */
UseMmap?: false | boolean;
/**
* Client Side CA
* CA certificate used to verify servers
*/
CaCert?: '' | string;
/**
* Client Side Cert
* Client SSL certificate (PEM) for mutual TLS auth
*/
ClientCert?: '' | string;
/**
* Client Side Key
* Client SSL private key (PEM) for mutual TLS auth
*/
ClientKey?: '' | string;
/** Use multi-thread downloads for files above this size. */
MultiThreadCutoff?: 262144000 | number;
/** Max number of streams to use for multi-thread downloads. */
MultiThreadStreams?: 4 | number;
/**
* whether MultiThreadStreams was set (set in fs/config/configflags)
*/
MultiThreadSet?: false | boolean;
/**
* Instructions on how to order the transfers, eg 'size,descending'
*/
OrderBy?: '' | string;
/** Set HTTP header for upload transactions */
UploadHeaders?: null | string[];
/** Set HTTP header for download transactions */
DownloadHeaders?: null | string[];
/** Set HTTP header for all transactions */
Headers?: null | string[];
}
export interface IRcloneOptionsRc {
/** equal to rc-http */
HTTPOptions?: IRcloneOptionsHttp;
/** Enable the remote control server. */
Enabled?: true | boolean;
/** Enable the serving of remote objects. */
Serve?: true | boolean;
/** Path to local files to serve on the HTTP server. */
Files?: '' | string;
/** Don't require auth for certain methods. */
NoAuth?: false | boolean;
/** Launch WebGUI on localhost */
WebUI?: false | boolean;
/** Check and update to latest version of web gui */
WebGUIUpdate?: false | boolean;
/** Force update to latest version of web gui */
WebGUIForceUpdate?: false | boolean;
/** Don't open the browser automatically */
WebGUINoOpenBrowser?: false | boolean;
/** URL to fetch the releases for webgui. */
WebGUIFetchURL?:
| 'https://api.github.com/repos/rclone/rclone-webui-react/releases/latest'
| string;
/** Set the allowed origin for CORS. */
AccessControlAllowOrigin?: '*' | string;
/** Enable prometheus metrics on /metrics */
EnableMetrics?: false | boolean;
/** expire finished async jobs older than this value */
JobExpireDuration?: 60000000000 | number;
/** interval to check for expired async jobs */
JobExpireInterval?: 10000000000 | number;
}
export interface IRcloneOptionsSftp {
/**
* Port to listen on
* IPaddress:Port or :Port to bind server to.
*/
ListenAddr?: 'localhost:2022' | string;
/**
* Paths to private host keys
* SSH private host key file (Can be multi-valued, leave blank to auto generate)
*/
HostKeys?: null | string[];
/**
* Path to authorized keys file
*/
AuthorizedKeys?: '~/.ssh/authorized_keys' | string;
/**
* single username
* User name for authentication.
*/
User?: '' | string;
/**
* password for user
* Password for authentication.
*/
Pass?: '' | string;
/** Allow connections with no authentication if set. */
NoAuth?: false | boolean;
}
export interface IRcloneOptionsVfs {
/**
* don't allow seeking if set
* Don't allow seeking in files.
*/
NoSeek?: false | boolean;
/**
* don't check checksums if set
* Don't compare checksums on up/download.
*/
NoChecksum?: false | boolean;
/**
* if set VFS is read only
* Mount read-only.
*/
ReadOnly?: false | boolean;
/**
* Don't read/write the modification time (can speed things up).
*/
NoModTime?: false | boolean;
/**
* how long to consider directory listing cache valid
* Time to cache directory entries for.
*/
DirCacheTime?: 300000000000 | number;
/**
* Time to wait between polling for changes.
* Must be smaller than dir-cache-time.
* Only on supported remotes.
* Set to 0 to disable.
*/
PollInterval?: 60000000000 | number;
/** */
Umask?: 18 | number;
/** */
UID?: 1000 | number;
/** */
GID?: 1000 | number;
/**
* Directory permissions
*/
DirPerms?: 511 | number;
/**
* File permissions
*/
FilePerms?: 438 | number;
/**
* if > 0 read files in chunks
* Read the source objects in chunks.
*/
ChunkSize?: 134217728 | number;
/**
* if > ChunkSize double the chunk size after each chunk until reached
* If greater than --vfs-read-chunk-size,
* double the chunk size after each chunk read,
* until the limit is reached.
* 'off' is unlimited.
*/
ChunkSizeLimit?: -1 | number;
/**
* Cache mode off|minimal|writes|full
* 0 "off" cache nothing - return errors for writes which can't be satisfied
* 1 "minimal" cache only the minimum, eg read/write opens
* 2 "writes" cache all files opened with write intent
* 3 "full" cache all files opened in any mode
*/
CacheMode?: 0 | number;
/**
* Max age of objects in the cache.
*/
CacheMaxAge?: 3600000000000 | number;
/**
* Max total size of objects in the cache.
*/
CacheMaxSize?: -1 | number;
/**
* Interval to poll the cache for stale objects.
*/
CachePollInterval?: 60000000000 | number;
/**
* If a file name not found, find a case insensitive match.
*/
CaseInsensitive?: false | boolean;
/**
* Time to wait for in-sequence write before giving error.
*/
WriteWait?: 1000000000 | number;
/**
* Time to wait for in-sequence read before seeking.
*/
ReadWait?: 5000000 | number;
}
export interface IRcloneOptions {
/** DLNA serving options. */
dlna?: IRcloneOptionsDlna;
/** configures the filter */
filter?: IRcloneOptionsFilter;
/**
* options for the ftp Server
*/
ftp?: IRcloneOptionsFtp;
/**
* options for the http Server
*/
http?: IRcloneOptionsHttp;
/**
* options for the logger
*/
log?: IRcloneOptionsLog;
/** filesystem config options */
main?: IRcloneOptionsMain;
/**
* options for the remote control server
*/
rc?: IRcloneOptionsRc;
/** same as rc.HTTPOptions */
'rc-http'?: IRcloneOptionsHttp;
/** options for the Sftp Server */
sftp?: IRcloneOptionsSftp;
/** options for creating the vfs */
vfs?: IRcloneOptionsVfs;
}
export interface OptionsGetFlowOutNode extends FlowOutNode {
options: IRcloneOptions;
}
export interface OptionsGetFlowSupNode extends OptionsGetFlowOutNode, NoopAuthFlowSupNode {}
export abstract class OptionsGetFlow extends PostFlow<IRcloneServer, OptionsGetFlowOutNode> {
// public prerequest$: Observable<CombErr<IRcloneServer>>;
protected cmd = 'options/get';
protected cacheSupport = false;
protected params = {};
protected reconstructAjaxResult(x: CombErr<AjaxFlowInteralNode>): CombErr<OptionsGetFlowOutNode> {
if (x[1].length !== 0) return [{}, x[1]] as any;
const rsp = x[0].ajaxRsp.response;
return [{ options: rsp }, []];
}
}
/**
* access deeply nested properties without assertion
*/
export function NestedGet(obj: unknown, ...path: (string | number)[]) {
return path.reduce(
(pre, cur) => (pre && typeof pre[cur] !== 'undefined' ? pre[cur] : undefined),
obj
);
} | the_stack |
import {render as renderLit, Template, nothing} from 'lit-html';
import {CompiledTemplate, CompiledTemplateResult} from 'lit-html';
import {parse, Parser, EvalAstFactory} from 'jexpr';
import type {Expression, Scope} from 'jexpr/lib/eval';
import {_Σ} from 'lit-html/private-ssr-support.js';
const {AttributePart, PropertyPart, BooleanAttributePart, EventPart} = _Σ;
const astFactory = new EvalAstFactory();
const expressionCache = new Map<string, Expression | undefined>();
const toCamelCase = (s: string) =>
s.replace(/-(-|\w)/g, (_, p1: string) => p1.toUpperCase());
/**
* Gets the value from a string that contains a delimted expression: {{ ... }}
*/
const getSingleValue = (s: string, model: any) => {
let ast = expressionCache.get(s);
if (ast === undefined) {
if (expressionCache.has(s)) {
return undefined;
}
s = s.trim();
if (s.startsWith('{{') && s.endsWith('}}')) {
const expression = s.substring(2, s.length - 2).trim();
ast = new Parser(expression, astFactory).parse();
expressionCache.set(s, ast);
}
}
return ast?.evaluate(model);
};
export interface TemplateFunction {
(model: object): unknown;
}
/**
* A Renderer is responsible for rendering a block call, like
* <template name="foo">
*/
// TODO: rename to BlockRenderer?
export interface Renderer {
(model: any, handlers: TemplateHandlers, renderers: Renderers): unknown;
}
export interface Renderers {
[name: string]: Renderer;
}
/**
* A TemplateHandlers is responsible for rendering control flow like
* <template type="if" if="{{x}}">
*/
export type TemplateHandler = (
template: HTMLTemplateElement,
model: object,
handlers: TemplateHandlers,
renderers: Renderers
) => unknown;
export interface TemplateHandlers {
[name: string]: TemplateHandler;
}
export const ifHandler: TemplateHandler = (
template: HTMLTemplateElement,
model: object,
handlers: TemplateHandlers,
renderers: Renderers
) => {
const ifAttribute = template.getAttribute('if');
if (ifAttribute !== null && getSingleValue(ifAttribute, model)) {
return evaluateTemplate(template, model, handlers, renderers);
}
return undefined;
};
export const repeatHandler: TemplateHandler = (
template: HTMLTemplateElement,
model: object,
handlers: TemplateHandlers,
renderers: Renderers
) => {
const repeatAttribute = template.getAttribute('repeat');
if (repeatAttribute !== null) {
const items = getSingleValue(repeatAttribute, model);
if (!items[Symbol.iterator]) {
return nothing;
}
const litTemplate = getLitTemplate(template);
let index = -1;
const result = [];
for (const item of items) {
index++;
const itemModel = Object.create(model);
itemModel.item = item;
itemModel.index = index;
itemModel['this'] = model['this'] ?? model;
const values = litTemplate.parts.map((part) =>
part.update(itemModel, handlers, renderers)
);
const templateResult: CompiledTemplateResult = {
_$litType$: litTemplate,
values,
};
result.push(templateResult);
}
return result;
}
return undefined;
};
export const defaultHandlers = <TemplateHandlers>{
if: ifHandler,
repeat: repeatHandler,
};
/**
* @returns {Function} a template function of the form (model) => TemplateResult
*/
export const prepareTemplate = (
template: HTMLTemplateElement,
handlers: TemplateHandlers = defaultHandlers,
renderers: Renderers = {},
superTemplate?: HTMLTemplateElement
): TemplateFunction => {
const litTemplate = getLitTemplate(template);
const templateRenderers = litTemplate.renderers;
if (superTemplate) {
const superLitTemplate = getLitTemplate(superTemplate);
const superRenderers = superLitTemplate.renderers;
const superCallRenderer = templateRenderers['super'];
if (superCallRenderer !== undefined) {
// Explicit super call
// render the sub template with:
renderers = {
// sub template's own renderes
...templateRenderers,
// passed-in renderers
...renderers,
// a super call renderer
super: (model, handlers, renderers) => {
// This renderer delegates to the super block in the sub template,
// which in turn delegates back to the super renderer below, but with
// the inner blocks of the super call.
// when the super call goes, render with:
renderers = {
// super template's own blocks
...superRenderers,
// passed-in renderers
...renderers,
// sub template's overrides will be added by the inner super call
super: (model, handlers, renderers) => {
return evaluateTemplate(
superTemplate,
model,
handlers,
renderers
);
},
};
return superCallRenderer(model, handlers, renderers);
},
};
} else {
// Implicit super call
// Wrap the whole template in an implicit super call by rendering the
// super template first, but using the block renderers from this template.
// Render the super template with:
renderers = {
// super template's own blocks
...superRenderers,
// sub template's overrides
...templateRenderers,
// passed-in renderers
...renderers,
};
template = superTemplate;
}
} else {
// No super call
renderers = {
...renderers,
...templateRenderers,
};
}
return (model) => evaluateTemplate(template, model, handlers, renderers);
};
export interface RenderOptions {
renderers?: Renderers;
extends?: HTMLTemplateElement;
}
/**
* Renders a template element containing a Stampino template.
*
* This is a convenience function wrapper around:
*
* ```
* import {render} from 'lit';
* const templateFn = prepareTemplate(templateEl);
* render(templateFn(model), container);
* ```
*/
export const render = (
template: HTMLTemplateElement,
container: HTMLElement,
model: any,
handlers: TemplateHandlers = defaultHandlers
) => {
const litTemplate = prepareTemplate(template, handlers);
renderLit(litTemplate(model), container);
};
/**
* Evaluates the given template and returns its result
*
* @param template
* @param model
* @param handlers
* @param renderers
* @returns
*/
export const evaluateTemplate = (
template: HTMLTemplateElement,
model: any,
handlers: TemplateHandlers = defaultHandlers,
renderers: Renderers = {}
) => {
const litTemplate = getLitTemplate(template);
const values: Array<unknown> = [];
for (const part of litTemplate.parts) {
const value = part.update(model, handlers, renderers);
if (part.type === 1) {
values.push(...(value as Iterable<unknown>));
} else {
values.push(value);
}
}
const templateResult: CompiledTemplateResult = {
_$litType$: litTemplate,
values,
};
return templateResult;
};
type TemplatePart = Template['parts'][0];
type StampinoTemplatePart = TemplatePart & {
update: PartUpdater;
};
type PartUpdater = (
model: object,
handlers: TemplateHandlers,
blocks: Renderers
) => unknown;
interface StampinoTemplate extends CompiledTemplate {
parts: Array<StampinoTemplatePart>;
renderers: Renderers;
}
const litTemplateCache = new Map<HTMLTemplateElement, StampinoTemplate>();
export const getLitTemplate = (
template: HTMLTemplateElement
): StampinoTemplate => {
let litTemplate = litTemplateCache.get(template);
if (litTemplate === undefined) {
litTemplateCache.set(template, (litTemplate = makeLitTemplate(template)));
}
return litTemplate;
};
const makeLitTemplate = (template: HTMLTemplateElement): StampinoTemplate => {
const litTemplate: StampinoTemplate = {
h: (undefined as unknown) as TrustedHTML,
el: template.cloneNode(true) as HTMLTemplateElement,
parts: [],
renderers: {},
};
const walker = document.createTreeWalker(
litTemplate.el!.content,
NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT
);
let node: Node | null = walker.currentNode;
let nodeIndex = -1;
const elementsToRemove = [];
while ((node = walker.nextNode()) !== null) {
if (node.nodeType === Node.ELEMENT_NODE) {
nodeIndex++;
const element = node as Element;
if (element.tagName === 'TEMPLATE') {
const type = element.getAttribute('type');
const name = element.getAttribute('name');
if (type !== null || name !== null) {
element.parentNode!.insertBefore(document.createComment(''), element);
elementsToRemove.push(element);
let update: PartUpdater;
if (type !== null) {
// This is a control-flow call, like if/repeat
update = (
model: object,
handlers: TemplateHandlers,
renderers: Renderers
) => {
const handler = handlers[type];
return handler?.(
element as HTMLTemplateElement,
model,
handlers,
renderers
);
};
} else {
// This is a named block
if (name === 'super') {
litTemplate.renderers['super'] = (
model: any,
handlers: TemplateHandlers,
renderers: Renderers
) => {
// Instead of rendering this block, delegate to a passed in
// 'super' renderer which will actually render the late-bound
// super template. We pass that renderer the child blocks from
// this block for block overrides.
const superRenderer = renderers['super'];
const superCallTemplate = getLitTemplate(
element as HTMLTemplateElement
);
renderers = {
...renderers,
...superCallTemplate.renderers,
};
return superRenderer(model, handlers, renderers);
};
} else {
// The renderer renders the contents of the named block
litTemplate.renderers[name!] = (
model: any,
handlers: TemplateHandlers,
renderers: Renderers
) => {
return evaluateTemplate(
element as HTMLTemplateElement,
model,
handlers,
renderers
);
};
}
// The updater runs when the template is evaluated and functions as
// a template _call_. It looks for a named renderer, which might be
// the renderer function above if the block is not overridden.
update = (
model: object,
handlers: TemplateHandlers,
renderers: Renderers
) => {
const renderer = renderers[name!];
return renderer?.(model, handlers, renderers);
};
}
litTemplate.parts.push({
type: 2, // text binding
index: nodeIndex,
update,
});
}
} else {
const attributeNames = element.getAttributeNames();
for (const attributeName of attributeNames) {
const attributeValue = element.getAttribute(attributeName)!;
// TODO: use alternative to negative lookbehind
// (but it's so convenient!)
const splitValue = attributeValue.split(
/(?<!\\){{(.*?)(?:(?<!\\)}})/g
);
if (splitValue.length === 1) {
continue;
}
element.removeAttribute(attributeName);
let name = attributeName;
let ctor = AttributePart;
const prefix = attributeName[0];
if (prefix === '.') {
name = toCamelCase(attributeName.substring(1));
ctor = PropertyPart;
} else if (prefix === '?') {
name = attributeName.substring(1);
ctor = BooleanAttributePart;
} else if (prefix === '@') {
name = toCamelCase(attributeName.substring(1));
ctor = EventPart;
}
const strings = [splitValue[0]];
const exprs: Array<Expression> = [];
for (let i = 1; i < splitValue.length; i += 2) {
const exprText = splitValue[i];
exprs.push(parse(exprText, astFactory) as Expression);
strings.push(splitValue[i + 1]);
}
litTemplate.parts.push({
type: 1, // attribute binding
index: nodeIndex,
name,
strings,
ctor,
update: (
model: object,
_handlers: TemplateHandlers,
_renderers: Renderers
) => {
return exprs.map((expr) => expr.evaluate(model));
},
});
}
}
} else if (node.nodeType === Node.TEXT_NODE) {
const textNode = node as Text;
const text = textNode.textContent!;
const strings = text.split(/(?<!\\){{(.*?)(?:(?<!\\)}})/g);
if (strings.length > 1) {
textNode.textContent = strings[0].replace('\\{{', '{{');
} else {
// TODO: do this better
textNode.textContent = text.replace('\\{{', '{{');
}
for (let i = 1; i < strings.length; i += 2) {
const exprText = strings[i];
const expr = parse(exprText, astFactory) as Expression;
litTemplate.parts.push({
type: 2,
index: ++nodeIndex,
update: (model: unknown, _handlers: TemplateHandlers) =>
expr.evaluate(model as Scope),
});
const newTextNode = new Text(strings[i + 1].replace('\\{{', '{{'));
textNode.parentNode!.insertBefore(newTextNode, textNode.nextSibling);
textNode.parentNode!.insertBefore(
document.createComment(''),
textNode.nextSibling
);
// This TreeWalker isn't configured to walk comment nodes, but this
// node will be returned next time through the loop. This is the easiest
// way to get the walker to proceed to the next successor after the
// marker, even when the marker doesn't have a nextSibling
walker.currentNode = newTextNode;
}
}
}
for (const e of elementsToRemove) {
e.remove();
}
return litTemplate;
}; | the_stack |
import {TypedEventNode} from './_Base';
import {NodeContext} from '../../poly/NodeContext';
import {BaseNodeType} from '../_Base';
import {BaseParamType} from '../../params/_Base';
import {VisibleIfParamOptions, ParamOptions} from '../../params/utils/OptionsController';
import {EventContext} from '../../scene/utils/events/_BaseEventsController';
import {RaycastCPUController} from './utils/raycast/CPUController';
import {CPUIntersectWith, CPU_INTERSECT_WITH_OPTIONS} from './utils/raycast/CpuConstants';
import {RaycastGPUController} from './utils/raycast/GPUController';
import {AttribType, ATTRIBUTE_TYPES, AttribTypeMenuEntries} from '../../../core/geometry/Constant';
import {EventConnectionPoint, EventConnectionPointType} from '../utils/io/connections/Event';
import {ParamType} from '../../poly/ParamType';
const TIMESTAMP = 1000.0 / 60.0;
enum RaycastMode {
CPU = 'cpu',
GPU = 'gpu',
}
const RAYCAST_MODES: Array<RaycastMode> = [RaycastMode.CPU, RaycastMode.GPU];
function visible_for_cpu(options: VisibleIfParamOptions = {}): ParamOptions {
options['mode'] = RAYCAST_MODES.indexOf(RaycastMode.CPU);
return {visibleIf: options};
}
function visible_for_cpu_geometry(options: VisibleIfParamOptions = {}): ParamOptions {
options['mode'] = RAYCAST_MODES.indexOf(RaycastMode.CPU);
options['intersectWith'] = CPU_INTERSECT_WITH_OPTIONS.indexOf(CPUIntersectWith.GEOMETRY);
return {visibleIf: options};
}
function visible_for_cpu_plane(options: VisibleIfParamOptions = {}): ParamOptions {
options['mode'] = RAYCAST_MODES.indexOf(RaycastMode.CPU);
options['intersectWith'] = CPU_INTERSECT_WITH_OPTIONS.indexOf(CPUIntersectWith.PLANE);
return {visibleIf: options};
}
function visible_for_gpu(options: VisibleIfParamOptions = {}): ParamOptions {
options['mode'] = RAYCAST_MODES.indexOf(RaycastMode.GPU);
return {visibleIf: options};
}
export enum TargetType {
SCENE_GRAPH = 'scene graph',
NODE = 'node',
}
export const TARGET_TYPES: TargetType[] = [TargetType.SCENE_GRAPH, TargetType.NODE];
import {NodeParamsConfig, ParamConfig} from '../utils/params/ParamsConfig';
import {Poly} from '../../Poly';
class RaycastParamsConfig extends NodeParamsConfig {
/** @param defines if the ray detection is done on the CPU or GPU (GPU being currently experimental) */
mode = ParamConfig.INTEGER(RAYCAST_MODES.indexOf(RaycastMode.CPU), {
menu: {
entries: RAYCAST_MODES.map((name, value) => {
return {
name,
value,
};
}),
},
});
//
//
// COMMON
//
//
/** @param mouse coordinates (0,0) being the center of the screen, (-1,-1) being the bottom left corner and (1,1) being the top right corner */
mouse = ParamConfig.VECTOR2([0, 0], {cook: false});
/** @param by default the ray is sent from the current camera, but this allows to set another camera */
overrideCamera = ParamConfig.BOOLEAN(0);
/** @param by default the ray is sent from the current camera, but this allows to set a custom ray */
overrideRay = ParamConfig.BOOLEAN(0, {
visibleIf: {
mode: RAYCAST_MODES.indexOf(RaycastMode.CPU),
overrideCamera: 1,
},
});
/** @param the camera to override to */
camera = ParamConfig.OPERATOR_PATH('/perspective_camera1', {
nodeSelection: {
context: NodeContext.OBJ,
},
dependentOnFoundNode: false,
visibleIf: {
overrideCamera: 1,
overrideRay: 0,
},
});
/** @param the ray origin */
rayOrigin = ParamConfig.VECTOR3([0, 0, 0], {
visibleIf: {
overrideCamera: 1,
overrideRay: 1,
},
});
/** @param the ray direction */
rayDirection = ParamConfig.VECTOR3([0, 0, 1], {
visibleIf: {
overrideCamera: 1,
overrideRay: 1,
},
});
//
//
// GPU
//
//
/** @param the material to use on the scene for GPU detection */
material = ParamConfig.OPERATOR_PATH('/MAT/mesh_basic_builder1', {
nodeSelection: {
context: NodeContext.MAT,
},
dependentOnFoundNode: false,
callback: (node: BaseNodeType, param: BaseParamType) => {
RaycastGPUController.PARAM_CALLBACK_update_material(node as RaycastEventNode);
},
...visible_for_gpu(),
});
/** @param the current pixel value being read */
pixelValue = ParamConfig.VECTOR4([0, 0, 0, 0], {
cook: false,
...visible_for_gpu(),
});
/** @param the value threshold for which a hit is detected */
hitThreshold = ParamConfig.FLOAT(0.5, {
cook: false,
...visible_for_gpu(),
});
//
//
// CPU
//
//
/** @param defines the hit it tested against geometry or just a plane */
intersectWith = ParamConfig.INTEGER(CPU_INTERSECT_WITH_OPTIONS.indexOf(CPUIntersectWith.GEOMETRY), {
menu: {
entries: CPU_INTERSECT_WITH_OPTIONS.map((name, value) => {
return {name, value};
}),
},
...visible_for_cpu(),
});
/** @param threshold used to test hit with points */
pointsThreshold = ParamConfig.FLOAT(1, {
range: [0, 100],
rangeLocked: [true, false],
...visible_for_cpu(),
});
//
//
// CPU PLANE
//
//
/** @param plane direction if the hit is tested against a plane */
planeDirection = ParamConfig.VECTOR3([0, 1, 0], {
...visible_for_cpu_plane(),
});
/** @param plane offset if the hit is tested against a plane */
planeOffset = ParamConfig.FLOAT(0, {
...visible_for_cpu_plane(),
});
//
//
// CPU GEOMETRY
//
//
targetType = ParamConfig.INTEGER(0, {
menu: {
entries: TARGET_TYPES.map((name, value) => {
return {name, value};
}),
},
...visible_for_cpu_geometry(),
});
/** @param node whose objects to test hit against, when testing against geometries */
targetNode = ParamConfig.NODE_PATH('', {
nodeSelection: {
context: NodeContext.OBJ,
},
dependentOnFoundNode: false,
callback: (node: BaseNodeType, param: BaseParamType) => {
RaycastCPUController.PARAM_CALLBACK_update_target(node as RaycastEventNode);
},
...visible_for_cpu_geometry({targetType: TARGET_TYPES.indexOf(TargetType.NODE)}),
});
/** @param objects to test hit against, when testing against geometries */
objectMask = ParamConfig.STRING('*geo1*', {
callback: (node: BaseNodeType, param: BaseParamType) => {
RaycastCPUController.PARAM_CALLBACK_update_target(node as RaycastEventNode);
},
...visible_for_cpu_geometry({targetType: TARGET_TYPES.indexOf(TargetType.SCENE_GRAPH)}),
});
/** @param prints which objects are targeted by this node, for debugging */
printFoundObjectsFromMask = ParamConfig.BUTTON(null, {
callback: (node: BaseNodeType, param: BaseParamType) => {
RaycastCPUController.PARAM_CALLBACK_print_resolve(node as RaycastEventNode);
},
...visible_for_cpu_geometry({targetType: TARGET_TYPES.indexOf(TargetType.SCENE_GRAPH)}),
});
/** @param toggle to hit if tested against children */
traverseChildren = ParamConfig.BOOLEAN(true, {
callback: (node: BaseNodeType, param: BaseParamType) => {
RaycastCPUController.PARAM_CALLBACK_update_target(node as RaycastEventNode);
},
...visible_for_cpu_geometry(),
separatorAfter: true,
});
//
//
// POSITION (common between plane and geo intersection)
//
//
/** @param toggle on to set the param to the hit position */
tpositionTarget = ParamConfig.BOOLEAN(0, {
cook: false,
...visible_for_cpu(),
});
/** @param this will be set to the hit position */
position = ParamConfig.VECTOR3([0, 0, 0], {
cook: false,
...visible_for_cpu({tpositionTarget: 0}),
});
/** @param this parameter will be set to the hit position */
positionTarget = ParamConfig.PARAM_PATH('', {
cook: false,
...visible_for_cpu({tpositionTarget: 1}),
paramSelection: ParamType.VECTOR3,
computeOnDirty: true,
});
/** @param toggle on to set the param to the mouse velocity (experimental) */
tvelocity = ParamConfig.BOOLEAN(0, {
cook: false,
// callback: (node: BaseNodeType, param: BaseParamType) => {
// RaycastCPUVelocityController.PARAM_CALLBACK_update_timer(node as RaycastEventNode);
// },
});
/** @param toggle on to set the param to the mouse velocity */
tvelocityTarget = ParamConfig.BOOLEAN(0, {
cook: false,
...visible_for_cpu({tvelocity: 1}),
});
/** @param this will be set to the mouse velocity */
velocity = ParamConfig.VECTOR3([0, 0, 0], {
cook: false,
...visible_for_cpu({tvelocity: 1, tvelocityTarget: 0}),
});
/** @param this will be set to the mouse velocity */
velocityTarget = ParamConfig.PARAM_PATH('', {
cook: false,
...visible_for_cpu({tvelocity: 1, tvelocityTarget: 1}),
paramSelection: ParamType.VECTOR3,
computeOnDirty: true,
});
//
//
// GEO ATTRIB
//
//
/** @param for geometry hit tests, a vertex attribute can be read */
geoAttribute = ParamConfig.BOOLEAN(0, visible_for_cpu_geometry());
/** @param geometry vertex attribute to read */
geoAttributeName = ParamConfig.STRING('id', {
cook: false,
...visible_for_cpu_geometry({geoAttribute: 1}),
});
/** @param type of attribute */
geoAttributeType = ParamConfig.INTEGER(ATTRIBUTE_TYPES.indexOf(AttribType.NUMERIC), {
menu: {
entries: AttribTypeMenuEntries,
},
...visible_for_cpu_geometry({geoAttribute: 1}),
});
/** @param attribute value for float */
geoAttributeValue1 = ParamConfig.FLOAT(0, {
cook: false,
...visible_for_cpu_geometry({
geoAttribute: 1,
geoAttributeType: ATTRIBUTE_TYPES.indexOf(AttribType.NUMERIC),
}),
});
/** @param attribute value for string */
geoAttributeValues = ParamConfig.STRING('', {
...visible_for_cpu_geometry({
geoAttribute: 1,
geoAttributeType: ATTRIBUTE_TYPES.indexOf(AttribType.STRING),
}),
});
}
const ParamsConfig = new RaycastParamsConfig();
export class RaycastEventNode extends TypedEventNode<RaycastParamsConfig> {
paramsConfig = ParamsConfig;
static type() {
return 'raycast';
}
static readonly INPUT_TRIGGER = 'trigger';
static readonly INPUT_MOUSE = 'mouse';
static readonly INPUT_UPDATE_OBJECTS = 'updateObjects';
static readonly INPUT_TRIGGER_VEL_RESET = 'triggerVelReset';
static readonly OUTPUT_HIT = 'hit';
static readonly OUTPUT_MISS = 'miss';
public readonly cpuController: RaycastCPUController = new RaycastCPUController(this);
public readonly gpuController: RaycastGPUController = new RaycastGPUController(this);
initializeNode() {
this.io.inputs.setNamedInputConnectionPoints([
new EventConnectionPoint(
RaycastEventNode.INPUT_TRIGGER,
EventConnectionPointType.BASE,
this._process_trigger_event_throttled.bind(this)
),
new EventConnectionPoint(
RaycastEventNode.INPUT_MOUSE,
EventConnectionPointType.MOUSE,
this._process_mouse_event.bind(this)
),
new EventConnectionPoint(
RaycastEventNode.INPUT_UPDATE_OBJECTS,
EventConnectionPointType.BASE,
this._process_trigger_update_objects.bind(this)
),
new EventConnectionPoint(
RaycastEventNode.INPUT_TRIGGER_VEL_RESET,
EventConnectionPointType.BASE,
this._process_trigger_vel_reset.bind(this)
),
]);
this.io.outputs.setNamedOutputConnectionPoints([
new EventConnectionPoint(RaycastEventNode.OUTPUT_HIT, EventConnectionPointType.BASE),
new EventConnectionPoint(RaycastEventNode.OUTPUT_MISS, EventConnectionPointType.BASE),
]);
}
trigger_hit(context: EventContext<MouseEvent>) {
this.dispatchEventToOutput(RaycastEventNode.OUTPUT_HIT, context);
}
trigger_miss(context: EventContext<MouseEvent>) {
this.dispatchEventToOutput(RaycastEventNode.OUTPUT_MISS, context);
}
private _process_mouse_event(context: EventContext<MouseEvent>) {
if (this.pv.mode == RAYCAST_MODES.indexOf(RaycastMode.CPU)) {
this.cpuController.updateMouse(context);
} else {
this.gpuController.updateMouse(context);
}
}
private _last_event_processed_at = -1;
private _process_trigger_event_throttled(context: EventContext<MouseEvent>) {
const previous = this._last_event_processed_at;
const performance = Poly.performance.performanceManager();
const now = performance.now();
this._last_event_processed_at = now;
const delta = now - previous;
if (delta < TIMESTAMP) {
setTimeout(() => {
this._process_trigger_event(context);
}, TIMESTAMP - delta);
} else {
this._process_trigger_event(context);
}
}
private _process_trigger_event(context: EventContext<MouseEvent>) {
if (this.pv.mode == RAYCAST_MODES.indexOf(RaycastMode.CPU)) {
this.cpuController.processEvent(context);
} else {
this.gpuController.processEvent(context);
}
}
private _process_trigger_update_objects(context: EventContext<MouseEvent>) {
if (this.pv.mode == RAYCAST_MODES.indexOf(RaycastMode.CPU)) {
this.cpuController.update_target();
}
}
private _process_trigger_vel_reset(context: EventContext<MouseEvent>) {
if (this.pv.mode == RAYCAST_MODES.indexOf(RaycastMode.CPU)) {
this.cpuController.velocity_controller.reset();
}
}
} | the_stack |
import * as React from "react";
import { useState, useEffect } from "react";
import { IManageAppsProps } from "../ManageApps/IManageAppsProps";
import { IManageAppsState } from "../ManageApps/IManageAppsState";
import MaterialTable, { Icons, MTableHeader } from "material-table";
import dataservices from "../../../../services/dataservices";
import * as strings from "PersonalAppsWebPartStrings";
import { IconPicker } from "../../../../controls/iconPicker";
import {
FontIcon,
TextField,
Spinner,
SpinnerSize,
SpinnerType,
Panel,
PanelType,
Text,
Label,
MessageBar,
MessageBarType,
PrimaryButton,
DefaultButton
} from "office-ui-fabric-react";
import Check from "@material-ui/icons/Check";
import ChevronLeft from "@material-ui/icons/ChevronLeft";
import ChevronRight from "@material-ui/icons/ChevronRight";
import Clear from "@material-ui/icons/Clear";
import DeleteOutline from "@material-ui/icons/DeleteOutline";
import Edit from "@material-ui/icons/Edit";
import FilterList from "@material-ui/icons/FilterList";
import FirstPage from "@material-ui/icons/FirstPage";
import LastPage from "@material-ui/icons/LastPage";
import Remove from "@material-ui/icons/Remove";
import SaveAlt from "@material-ui/icons/SaveAlt";
import Search from "@material-ui/icons/Search";
import ViewColumn from "@material-ui/icons/ViewColumn";
import { initializeIcons } from "office-ui-fabric-react/lib/Icons";
import { IListItem } from "./IListItem";
import { Paper, CircularProgress } from "@material-ui/core";
import styles from "./ManageApps.module.scss";
initializeIcons();
const tableIcons: Icons = {
Add: React.forwardRef((props, ref) => (
<FontIcon iconName="AppIconDefaultAdd" style={{ fontWeight: 700 }} />
)),
Check: React.forwardRef((props, ref) => <Check />),
Clear: React.forwardRef((props, ref) => <Clear />),
Delete: React.forwardRef((props, ref) => <FontIcon iconName="Delete" style={{fontSize: 20}} />),
DetailPanel: React.forwardRef((props, ref) => <ChevronRight />),
Edit: React.forwardRef((props, ref) => <FontIcon iconName="Edit" style={{fontSize: 20}} />),
Export: React.forwardRef((props, ref) => <SaveAlt />),
Filter: React.forwardRef((props, ref) => <FilterList />),
FirstPage: React.forwardRef((props, ref) => <FirstPage />),
LastPage: React.forwardRef((props, ref) => <LastPage />),
NextPage: React.forwardRef((props, ref) => <ChevronRight />),
PreviousPage: React.forwardRef((props, ref) => <ChevronLeft />),
ResetSearch: React.forwardRef((props, ref) => <Clear />),
Search: React.forwardRef((props, ref) => <Search />),
SortArrow: React.forwardRef((props, ref) => (
<FontIcon iconName="Sort" style={{ marginLeft: 5 }} />
)),
ThirdStateCheck: React.forwardRef((props, ref) => <Remove />),
ViewColumn: React.forwardRef((props, ref) => <ViewColumn />)
};
export function ManageApps(appProps: IManageAppsProps) {
const [isLoading, setIsLoading] = useState(false);
const [changeData, setChangeData] = useState(false);
const [hasError, setHasError] = useState(false);
const [errorMessage, setErrorMessage] = useState("");
const [showPanel, setShowPanel] = useState(appProps.showPanel);
const [isSaving, setIsSaving] = useState(false);
const [state, setState] = useState({
columns: [
{
title: "Name ",
field: "name",
editComponent: props => (
<TextField
underlined
required
placeholder="Enter name here"
onGetErrorMessage={(newValue: string) => {
return newValue.trim().length > 0 ? "" : "Please enter name";
}}
validateOnFocusOut
validateOnLoad={false}
value={props.value}
onChange={(event: React.FormEvent<HTMLInputElement>, newValue) => {
props.onChange(newValue);
}}
/>
)
},
{
title: "Derscription",
field: "description",
editComponent: props => (
<TextField
underlined
required
placeholder="Enter description here"
validateOnFocusOut
validateOnLoad={false}
onGetErrorMessage={(newValue: string) => {
return newValue.trim().length > 0
? ""
: "Please enter Description";
}}
value={props.value}
onChange={(event: React.FormEvent<HTMLInputElement>, newValue) => {
props.onChange(newValue);
}}
/>
)
},
{
title: "Url",
field: "url",
editComponent: props => (
<TextField
underlined
required
placeholder="Enter URL here"
onGetErrorMessage={(newValue: string) => {
try {
const _URL = new URL(newValue);
return "";
} catch (error) {
return "Please enter valid Url";
}
}}
validateOnFocusOut
validateOnLoad={false}
value={props.value}
onChange={(event: React.FormEvent<HTMLInputElement>, newValue) => {
props.onChange(newValue);
}}
/>
)
},
{
title: "Icon",
field: "iconName",
render: rowData => (
<FontIcon
iconName={rowData.iconName}
style={{ width: 24, height: 24, fontSize: 24 }}
/>
),
editComponent: props => (
<div style={{ display: "Flex", flexDirection: "row" }}>
{" "}
<FontIcon
iconName={props.value}
style={{ width: 24, height: 24, fontSize: 24, marginRight: 7 }}
/>
<IconPicker
buttonLabel={" Select icon"}
currentIcon={props.value}
onSave={(iconName: string) => {
props.onChange(iconName);
}}
/>
</div>
)
}
],
data: appProps.Apps
});
// Load Schema Extension Data
useEffect(() => {
(async () => {
// Get Tenant Property with id of Extension Id to check if exists or needs to create
})();
});
// Cancel command
const _onDismiss = async () => {
appProps.onDismiss(state.data, false);
};
// Save command
const _onSave = async () => {
try {
setIsSaving(true);
const _result: microsoftgraph.OpenTypeExtension = await dataservices.createOrUpdateUserApps(
state.data
);
console.log("extention created or updated", _result);
appProps.onDismiss(state.data, true);
} catch (error) {
setHasError(true);
setErrorMessage(error.message);
}
};
// Render Panel commands
const _onRenderFooterContent = () => (
<div
style={{
display: "flex",
justifyContent: "flex-end",
width: "100%",
marginBottom: 35
}}
>
<PrimaryButton
onClick={_onSave}
disabled={isSaving}
style={{ marginRight: 7, width: 100 }}
>
{isSaving ? (
<Spinner size={SpinnerSize.xSmall}></Spinner>
) : (
strings.SaveLabelButtom
)}
</PrimaryButton>
<DefaultButton style={{ width: 100 }} onClick={_onDismiss}>
{strings.CancelLabelButton}
</DefaultButton>
</div>
);
return (
<Panel
isOpen={showPanel}
onDismiss={_onDismiss}
type={PanelType.custom}
customWidth="888px"
closeButtonAriaLabel="Close"
headerText="My Apps"
onRenderFooterContent={_onRenderFooterContent}
isFooterAtBottom={true}
>
<div style={{ marginTop: 20, marginBottom: 25 }}>
<Text variant="large" block>
Please add links for your favorite apps
</Text>
</div>
{hasError && (
<MessageBar messageBarType={MessageBarType.error}>
{errorMessage}
</MessageBar>
)}
{isLoading ? (
<Spinner size={SpinnerSize.medium} />
) : (
<div style={{ height: "100%" }}>
<MaterialTable
title="My Apps"
isLoading={false}
columns={state.columns}
components={{
OverlayLoading: props => (
<div className={styles.overlay}><CircularProgress /></div>
),
Container: props => (
<Paper
{...props}
elevation={0}
classes={{ root: styles.MuiPaperRoot }}
/>
)
}}
data={state.data}
icons={tableIcons}
options={{
paging: true,
showTitle:false,
searchFieldAlignment:'left',
pageSize: 7,
pageSizeOptions: [],
search: true,
minBodyHeight: "100%"
}}
editable={{
onRowAdd: (newData: IListItem) =>
new Promise(resolve => {
setTimeout(() => {
resolve();
setChangeData(true);
setState(prevState => {
const data = [...prevState.data];
data.push(newData);
return { ...prevState, data };
});
}, 600);
}),
onRowUpdate: (newData, oldData) =>
new Promise(resolve => {
setTimeout(() => {
resolve();
if (oldData) {
setChangeData(true);
setState(prevState => {
const data = [...prevState.data];
data[data.indexOf(oldData)] = newData;
return { ...prevState, data };
});
}
}, 600);
}),
onRowDelete: oldData =>
new Promise(resolve => {
setTimeout(() => {
resolve();
setChangeData(true);
setState(prevState => {
const data = [...prevState.data];
data.splice(data.indexOf(oldData), 1);
return { ...prevState, data };
});
}, 600);
})
}}
/>
</div>
)}
</Panel>
);
} | the_stack |
import '@polymer/iron-autogrow-textarea/iron-autogrow-textarea';
import '../../shared/gr-account-link/gr-account-link';
import '../../shared/gr-autocomplete/gr-autocomplete';
import '../../shared/gr-button/gr-button';
import '../../shared/gr-overlay/gr-overlay';
import '../gr-confirm-delete-item-dialog/gr-confirm-delete-item-dialog';
import {getBaseUrl} from '../../../utils/url-util';
import {GrOverlay} from '../../shared/gr-overlay/gr-overlay';
import {
GroupId,
AccountId,
AccountInfo,
GroupInfo,
GroupName,
} from '../../../types/common';
import {
AutocompleteQuery,
AutocompleteSuggestion,
} from '../../shared/gr-autocomplete/gr-autocomplete';
import {
fireAlert,
firePageError,
fireTitleChange,
} from '../../../utils/event-util';
import {getAppContext} from '../../../services/app-context';
import {ErrorCallback} from '../../../api/rest';
import {assertNever} from '../../../utils/common-util';
import {GrButton} from '../../shared/gr-button/gr-button';
import {fontStyles} from '../../../styles/gr-font-styles';
import {formStyles} from '../../../styles/gr-form-styles';
import {sharedStyles} from '../../../styles/shared-styles';
import {subpageStyles} from '../../../styles/gr-subpage-styles';
import {tableStyles} from '../../../styles/gr-table-styles';
import {LitElement, css, html} from 'lit';
import {customElement, property, query, state} from 'lit/decorators';
const SUGGESTIONS_LIMIT = 15;
const SAVING_ERROR_TEXT =
'Group may not exist, or you may not have ' + 'permission to add it';
const URL_REGEX = '^(?:[a-z]+:)?//';
export enum ItemType {
MEMBER = 'member',
INCLUDED_GROUP = 'includedGroup',
}
declare global {
interface HTMLElementTagNameMap {
'gr-group-members': GrGroupMembers;
}
}
@customElement('gr-group-members')
export class GrGroupMembers extends LitElement {
@query('#overlay') protected overlay!: GrOverlay;
@property({type: String})
groupId?: GroupId;
@state() protected groupMemberSearchId?: number;
@state() protected groupMemberSearchName?: string;
@state() protected includedGroupSearchId?: string;
@state() protected includedGroupSearchName?: string;
@state() protected loading = true;
/* private but used in test */
@state() groupName?: GroupName;
@state() protected groupMembers?: AccountInfo[];
/* private but used in test */
@state() includedGroups?: GroupInfo[];
/* private but used in test */
@state() itemName?: string;
@state() protected itemType?: ItemType;
@state() protected queryMembers?: AutocompleteQuery;
@state() protected queryIncludedGroup?: AutocompleteQuery;
/* private but used in test */
@state() groupOwner = false;
@state() protected isAdmin = false;
/* private but used in test */
@state() itemId?: AccountId | GroupId;
private readonly restApiService = getAppContext().restApiService;
constructor() {
super();
this.queryMembers = input => this.getAccountSuggestions(input);
this.queryIncludedGroup = input => this.getGroupSuggestions(input);
}
override connectedCallback() {
super.connectedCallback();
this.loadGroupDetails();
fireTitleChange(this, 'Members');
}
static override get styles() {
return [
fontStyles,
formStyles,
sharedStyles,
subpageStyles,
tableStyles,
css`
.input {
width: 15em;
}
gr-autocomplete {
width: 20em;
}
a {
color: var(--primary-text-color);
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
th {
border-bottom: 1px solid var(--border-color);
font-weight: var(--font-weight-bold);
text-align: left;
}
.canModify #groupMemberSearchInput,
.canModify #saveGroupMember,
.canModify .deleteHeader,
.canModify .deleteColumn,
.canModify #includedGroupSearchInput,
.canModify #saveIncludedGroups,
.canModify .deleteIncludedHeader,
.canModify #saveIncludedGroups {
display: none;
}
`,
];
}
override render() {
return html`
<div
class="main gr-form-styles ${this.isAdmin || this.groupOwner
? ''
: 'canModify'}"
>
<div id="loading" class=${this.loading ? 'loading' : ''}>
Loading...
</div>
<div id="loadedContent" class=${this.loading ? 'loading' : ''}>
<h1 id="Title" class="heading-1">${this.groupName}</h1>
<div id="form">
<h3 id="members" class="heading-3">Members</h3>
<fieldset>
<span class="value">
<gr-autocomplete
id="groupMemberSearchInput"
.text=${this.groupMemberSearchName}
.value=${this.groupMemberSearchId}
.query=${this.queryMembers}
placeholder="Name Or Email"
@text-changed=${this.handleGroupMemberTextChanged}
@value-changed=${this.handleGroupMemberValueChanged}
>
</gr-autocomplete>
</span>
<gr-button
id="saveGroupMember"
?disabled=${!this.groupMemberSearchId}
@click=${this.handleSavingGroupMember}
>
Add
</gr-button>
<table id="groupMembers">
<tbody>
<tr class="headerRow">
<th class="nameHeader">Name</th>
<th class="emailAddressHeader">Email Address</th>
<th class="deleteHeader">Delete Member</th>
</tr>
</tbody>
<tbody>
${this.groupMembers?.map((member, index) =>
this.renderGroupMember(member, index)
)}
</tbody>
</table>
</fieldset>
<h3 id="includedGroups" class="heading-3">Included Groups</h3>
<fieldset>
<span class="value">
<gr-autocomplete
id="includedGroupSearchInput"
.text=${this.includedGroupSearchName}
.value=${this.includedGroupSearchId}
.query=${this.queryIncludedGroup}
placeholder="Group Name"
@text-changed=${this.handleIncludedGroupTextChanged}
@value-changed=${this.handleIncludedGroupValueChanged}
>
</gr-autocomplete>
</span>
<gr-button
id="saveIncludedGroups"
?disabled=${!this.includedGroupSearchId}
@click=${this.handleSavingIncludedGroups}
>
Add
</gr-button>
<table id="includedGroups">
<tbody>
<tr class="headerRow">
<th class="groupNameHeader">Group Name</th>
<th class="descriptionHeader">Description</th>
<th class="deleteIncludedHeader">Delete Group</th>
</tr>
</tbody>
<tbody>
${this.includedGroups?.map((group, index) =>
this.renderIncludedGroup(group, index)
)}
</tbody>
</table>
</fieldset>
</div>
</div>
</div>
<gr-overlay id="overlay" with-backdrop>
<gr-confirm-delete-item-dialog
class="confirmDialog"
.item=${this.itemName}
.itemTypeName=${this.computeItemTypeName(this.itemType)}
@confirm=${this.handleDeleteConfirm}
@cancel=${this.handleConfirmDialogCancel}
></gr-confirm-delete-item-dialog>
</gr-overlay>
`;
}
private renderGroupMember(member: AccountInfo, index: number) {
return html`
<tr>
<td class="nameColumn">
<gr-account-link .account=${member}></gr-account-link>
</td>
<td>${member.email}</td>
<td class="deleteColumn">
<gr-button
class="deleteMembersButton"
data-index=${index}
@click=${this.handleDeleteMember}
>
Delete
</gr-button>
</td>
</tr>
`;
}
private renderIncludedGroup(group: GroupInfo, index: number) {
return html`
<tr>
<td class="nameColumn">${this.renderIncludedGroupHref(group)}</td>
<td>${group.description}</td>
<td class="deleteColumn">
<gr-button
class="deleteIncludedGroupButton"
data-index=${index}
@click=${this.handleDeleteIncludedGroup}
>
Delete
</gr-button>
</td>
</tr>
`;
}
private renderIncludedGroupHref(group: GroupInfo) {
if (group.url) {
return html`
<a href=${this.computeGroupUrl(group.url)} rel="noopener">
${group.name}
</a>
`;
}
return group.name;
}
/* private but used in test */
loadGroupDetails() {
if (!this.groupId) return;
const promises: Promise<void>[] = [];
const errFn: ErrorCallback = response => {
firePageError(response);
};
return this.restApiService
.getGroupConfig(this.groupId, errFn)
.then(config => {
if (!config || !config.name) {
return Promise.resolve();
}
this.groupName = config.name;
promises.push(
this.restApiService.getIsAdmin().then(isAdmin => {
this.isAdmin = !!isAdmin;
})
);
promises.push(
this.restApiService.getIsGroupOwner(this.groupName).then(isOwner => {
this.groupOwner = !!isOwner;
})
);
promises.push(
this.restApiService.getGroupMembers(this.groupName).then(members => {
this.groupMembers = members;
})
);
promises.push(
this.restApiService
.getIncludedGroup(this.groupName)
.then(includedGroup => {
this.includedGroups = includedGroup;
})
);
return Promise.all(promises).then(() => {
this.loading = false;
});
});
}
/* private but used in test */
computeGroupUrl(url?: string) {
if (!url) return;
const r = new RegExp(URL_REGEX, 'i');
if (r.test(url)) {
return url;
}
// For GWT compatibility
if (url.startsWith('#')) {
return getBaseUrl() + url.slice(1);
}
return getBaseUrl() + url;
}
/* private but used in test */
handleSavingGroupMember() {
if (!this.groupName) {
return Promise.reject(new Error('group name undefined'));
}
return this.restApiService
.saveGroupMember(this.groupName, this.groupMemberSearchId as AccountId)
.then(config => {
if (!config || !this.groupName) {
return;
}
this.restApiService.getGroupMembers(this.groupName).then(members => {
this.groupMembers = members;
});
this.groupMemberSearchName = '';
this.groupMemberSearchId = undefined;
});
}
/* private but used in test */
handleDeleteConfirm() {
if (!this.groupName) {
return Promise.reject(new Error('group name undefined'));
}
this.overlay.close();
if (this.itemType === ItemType.MEMBER) {
return this.restApiService
.deleteGroupMember(this.groupName, this.itemId! as AccountId)
.then(itemDeleted => {
if (itemDeleted.status === 204 && this.groupName) {
this.restApiService
.getGroupMembers(this.groupName)
.then(members => {
this.groupMembers = members;
});
}
});
} else if (this.itemType === ItemType.INCLUDED_GROUP) {
return this.restApiService
.deleteIncludedGroup(this.groupName, this.itemId! as GroupId)
.then(itemDeleted => {
if (
(itemDeleted.status === 204 || itemDeleted.status === 205) &&
this.groupName
) {
this.restApiService
.getIncludedGroup(this.groupName)
.then(includedGroup => {
this.includedGroups = includedGroup;
});
}
});
}
return Promise.reject(new Error('Unrecognized item type'));
}
/* private but used in test */
computeItemTypeName(itemType?: ItemType): string {
if (itemType === undefined) return '';
switch (itemType) {
case ItemType.INCLUDED_GROUP:
return 'Included Group';
case ItemType.MEMBER:
return 'Member';
default:
assertNever(itemType, 'unknown item type: ${itemType}');
}
}
private handleConfirmDialogCancel() {
this.overlay.close();
}
private handleDeleteMember(e: Event) {
if (!this.groupMembers) return;
const el = e.target as GrButton;
const index = Number(el.getAttribute('data-index')!);
const keys = this.groupMembers[index];
const item =
keys.username || keys.name || keys.email || keys._account_id?.toString();
if (!item) return;
this.itemName = item;
this.itemId = keys._account_id;
this.itemType = ItemType.MEMBER;
this.overlay.open();
}
/* private but used in test */
handleSavingIncludedGroups() {
if (!this.groupName || !this.includedGroupSearchId) {
return Promise.reject(
new Error('group name or includedGroupSearchId undefined')
);
}
return this.restApiService
.saveIncludedGroup(
this.groupName,
this.includedGroupSearchId.replace(/\+/g, ' ') as GroupId,
(errResponse, err) => {
if (errResponse) {
if (errResponse.status === 404) {
fireAlert(this, SAVING_ERROR_TEXT);
return errResponse;
}
throw Error(errResponse.statusText);
}
throw err;
}
)
.then(config => {
if (!config || !this.groupName) {
return;
}
this.restApiService
.getIncludedGroup(this.groupName)
.then(includedGroup => {
this.includedGroups = includedGroup;
});
this.includedGroupSearchName = '';
this.includedGroupSearchId = '';
});
}
private handleDeleteIncludedGroup(e: Event) {
if (!this.includedGroups) return;
const el = e.target as GrButton;
const index = Number(el.getAttribute('data-index')!);
const keys = this.includedGroups[index];
const id = decodeURIComponent(keys.id).replace(/\+/g, ' ') as GroupId;
const name = keys.name;
const item = name || id;
if (!item) return;
this.itemName = item;
this.itemId = id;
this.itemType = ItemType.INCLUDED_GROUP;
this.overlay.open();
}
/* private but used in test */
getAccountSuggestions(input: string) {
if (input.length === 0) {
return Promise.resolve([]);
}
return this.restApiService
.getSuggestedAccounts(input, SUGGESTIONS_LIMIT)
.then(accounts => {
if (!accounts) return [];
const accountSuggestions = [];
for (const account of accounts) {
let nameAndEmail;
if (account.email !== undefined) {
nameAndEmail = `${account.name} <${account.email}>`;
} else {
nameAndEmail = account.name;
}
accountSuggestions.push({
name: nameAndEmail,
value: account._account_id?.toString(),
});
}
return accountSuggestions;
});
}
/* private but used in test */
getGroupSuggestions(input: string) {
return this.restApiService.getSuggestedGroups(input).then(response => {
const groups: AutocompleteSuggestion[] = [];
for (const [name, group] of Object.entries(response ?? {})) {
groups.push({name, value: decodeURIComponent(group.id)});
}
return groups;
});
}
private handleGroupMemberTextChanged(e: CustomEvent) {
if (this.loading) return;
this.groupMemberSearchName = e.detail.value;
}
private handleGroupMemberValueChanged(e: CustomEvent) {
if (this.loading) return;
this.groupMemberSearchId = e.detail.value;
}
private handleIncludedGroupTextChanged(e: CustomEvent) {
if (this.loading) return;
this.includedGroupSearchName = e.detail.value;
}
private handleIncludedGroupValueChanged(e: CustomEvent) {
if (this.loading) return;
this.includedGroupSearchId = e.detail.value;
}
} | the_stack |
import * as assert from 'assert'
import {
hashLeftRight,
hash5,
stringifyBigInts,
unstringifyBigInts,
} from './'
type Leaf = BigInt
type Root = BigInt
type PathElements = BigInt[][]
type Indices = number[]
interface MerkleProof {
pathElements: PathElements;
indices: Indices;
depth: number;
root: BigInt;
leaf: Leaf;
}
const deepCopyBigIntArray = (arr: BigInt[]) => {
return arr.map((x) => BigInt(x.toString()))
}
/*
* An incremental Merkle tree which conforms to the implementation in
* IncrementalQuinTree.sol. It supports 2 or 5 elements per leaf.
*/
class IncrementalQuinTree {
// The number of leaves per node
public leavesPerNode: number
// The tree depth
public depth: number
// The default value for empty leaves
public zeroValue: BigInt
// The tree root
public root: BigInt
// The the smallest empty leaf index
public nextIndex: number
// All leaves in the tree
public leaves: Leaf[] = []
// Contains the zero value per level. i.e. zeros[0] is zeroValue,
// zeros[1] is the hash of leavesPerNode zeros, and so on.
public zeros: BigInt[] = []
// Caches values needed for efficient appends.
public filledSubtrees: BigInt[][] = []
// Caches values needed to compute Merkle paths.
public filledPaths: any = {}
// The hash function to use
public hashFunc: (leaves: BigInt[]) => BigInt
constructor (
_depth: number,
_zeroValue: BigInt | number,
_leavesPerNode: number | BigInt = 5,
) {
// This class supports either 2 leaves per node, or 5 leaves per node.
// 5 is largest number of inputs which circomlib's Poseidon EVM hash
// function implementation provides for.
// TODO: modify this to support 3 or 4 leaves per node
this.leavesPerNode = Number(_leavesPerNode)
assert(this.leavesPerNode === 2 || this.leavesPerNode === 5)
this.depth = Number(_depth)
this.nextIndex = 0
this.zeroValue = BigInt(_zeroValue)
// Set this.hashFunc depending on the number of leaves per node
if (this.leavesPerNode === 2) {
// Uses PoseidonT3 under the hood, which accepts 2 inputs
this.hashFunc = (inputs: BigInt[]) => {
return hashLeftRight(inputs[0], inputs[1])
}
} else {
// Uses PoseidonT6 under the hood, which accepts up to 5 inputs
this.hashFunc = hash5
}
this.zeros = []
this.filledSubtrees = []
let currentLevelHash = this.zeroValue
// Calculate intermediate values
for (let i = 0; i < this.depth; i++) {
if (i < this.depth - 1) {
this.filledPaths[i] = []
}
this.zeros.push(currentLevelHash)
const z: BigInt[] = []
for (let j = 0; j < this.leavesPerNode; j ++) {
z.push(this.zeros[i])
}
this.filledSubtrees.push(z)
currentLevelHash = this.hash(z)
}
// Calculate the root
this.root = this.hash(this.filledSubtrees[this.depth - 1])
}
/*
* Insert a leaf into the Merkle tree
* @param _value The value to insert. This may or may not already be
* hashed.
*/
public insert(
_value: Leaf,
) {
// Ensure that _value is a BigInt
_value = BigInt(_value)
// A node is one level above the leaf
// m is the leaf's relative position within its node
let m = this.nextIndex % this.leavesPerNode
// Zero out the level in filledSubtrees
if (m === 0) {
for (let j = 1; j < this.filledSubtrees[0].length; j ++) {
this.filledSubtrees[0][j] = this.zeros[0]
}
}
this.filledSubtrees[0][m] = _value
let currentIndex = this.nextIndex
for (let i = 1; i < this.depth; i++) {
// currentIndex is the leaf or node's absolute index
currentIndex = Math.floor(currentIndex / this.leavesPerNode)
// m is the leaf's relative position within its node
m = currentIndex % this.leavesPerNode
// Zero out the level
if (m === 0) {
for (let j = 1; j < this.filledSubtrees[i].length; j ++) {
this.filledSubtrees[i][j] = this.zeros[i]
}
}
const hashed = this.hash(this.filledSubtrees[i - 1])
this.filledSubtrees[i][m] = hashed
if (this.filledPaths[i - 1].length <= currentIndex) {
this.filledPaths[i - 1].push(hashed)
} else {
this.filledPaths[i - 1][currentIndex] = hashed
}
}
this.leaves.push(_value)
this.nextIndex ++
this.root = this.hash(
this.filledSubtrees[this.filledSubtrees.length - 1],
)
}
/*
* Update the leaf at the specified index with the given value.
*/
public update(
_index: number,
_value: Leaf,
) {
if (_index >= this.nextIndex || _index >= this.leaves.length) {
throw new Error('The leaf index specified is too large')
}
_value = BigInt(_value)
const temp = this.leaves
temp[_index] = _value
this.leaves[_index] = _value
const newTree = new IncrementalQuinTree(
this.depth,
this.zeroValue,
this.leavesPerNode,
)
for (let i = 0; i < temp.length; i++) {
newTree.insert(temp[i])
}
this.leaves = newTree.leaves
this.zeros = newTree.zeros
this.filledSubtrees = newTree.filledSubtrees
this.filledPaths = newTree.filledPaths
this.root = newTree.root
this.nextIndex = newTree.nextIndex
}
/*
* Returns the leaf value at the given index
*/
public getLeaf(_index: number): Leaf {
return this.leaves[_index]
}
/* Generates a Merkle proof from a leaf to the root.
*/
public genMerklePath(_index: number): MerkleProof {
if (_index < 0) {
throw new Error('The leaf index must be greater than 0')
}
if (_index >= this.nextIndex || _index >= this.leaves.length) {
throw new Error('The leaf index is too large')
}
const pathElements: BigInt[][] = []
const indices: number[] = [_index % this.leavesPerNode]
let r = Math.floor(_index / this.leavesPerNode)
for (let i = 0; i < this.depth; i ++) {
const s: BigInt[] = []
if (i === 0) {
// Get a slice of leaves, padded with zeros
const leafStartIndex = _index - (_index % this.leavesPerNode)
const leafEndIndex = leafStartIndex + this.leavesPerNode
for (let j = leafStartIndex; j < leafEndIndex; j ++) {
if (j < this.leaves.length) {
s.push(this.leaves[j])
} else {
s.push(this.zeros[i])
}
}
} else {
for (let j = 0; j < this.leavesPerNode; j ++) {
const x = r * this.leavesPerNode + j
if (this.filledPaths[i - 1].length <= x) {
s.push(this.zeros[i])
} else {
const e = this.filledPaths[i - 1][x]
s.push(e)
}
}
}
const p = r % this.leavesPerNode
pathElements.push(s)
if (i < this.depth - 1) {
indices.push(p)
}
r = Math.floor(r /this.leavesPerNode)
}
// Remove the commitments to elements which are the leaves per level
const newPe: BigInt[][] = [[]]
const firstIndex = _index % this.leavesPerNode
for (let i = 0; i < pathElements[0].length; i ++) {
if (i !== firstIndex) {
newPe[0].push(pathElements[0][i])
}
}
for (let i = 1; i < pathElements.length; i ++) {
const level: BigInt[] = []
for (let j = 0; j < pathElements[i].length; j ++) {
if (j !== indices[i]) {
level.push(pathElements[i][j])
}
}
newPe.push(level)
}
return {
pathElements: newPe,
indices,
depth: this.depth,
root: this.root,
leaf: this.leaves[_index],
}
}
public static verifyMerklePath(
_proof: MerkleProof,
_hashFunc: (leaves: BigInt[]) => BigInt,
): boolean {
assert (_proof.pathElements)
const pathElements = _proof.pathElements
// Validate the proof format
assert (_proof.indices)
for (let i = 0; i < _proof.depth; i ++) {
assert(pathElements[i])
assert(_proof.indices[i] != undefined)
}
// Hash the first level
const firstLevel: BigInt[] = pathElements[0].map(BigInt)
firstLevel.splice(Number(_proof.indices[0]), 0, _proof.leaf)
let currentLevelHash: BigInt = _hashFunc(firstLevel)
// Verify the proof
for (let i = 1; i < pathElements.length; i ++) {
const level: BigInt[] = pathElements[i].map(BigInt)
level.splice(Number(_proof.indices[i]), 0, currentLevelHash)
currentLevelHash = _hashFunc(level)
}
return currentLevelHash === _proof.root
}
/* Deep-copies this object
*/
public copy(): IncrementalQuinTree {
const newTree = new IncrementalQuinTree(
this.depth,
this.zeroValue,
this.leavesPerNode,
)
newTree.leaves = deepCopyBigIntArray(this.leaves)
newTree.zeros = deepCopyBigIntArray(this.zeros)
newTree.root = this.root
newTree.nextIndex = this.nextIndex
newTree.filledSubtrees = this.filledSubtrees.map(deepCopyBigIntArray)
newTree.filledPaths = unstringifyBigInts(JSON.parse(
JSON.stringify(stringifyBigInts(this.filledPaths))
))
return newTree
}
public hash(_leaves: BigInt[]): BigInt {
if (this.leavesPerNode > 2) {
while (_leaves.length < 5) {
_leaves.push(this.zeroValue)
}
}
return this.hashFunc(_leaves)
}
}
export {
IncrementalQuinTree,
} | the_stack |
/// <reference types="geojson" />
// ----------------------------------------------------------------------
// Shared Interfaces and Types
// ----------------------------------------------------------------------
/**
* A basic geometry for a sphere, which is supported by d3-geo
* beyond the GeoJSON geometries.
*/
export interface GeoSphere {
type: 'Sphere';
}
/**
* Type Alias for GeoJSON Geometry Object and GeoSphere additional
* geometry supported by d3-geo
*/
export type GeoGeometryObjects = GeoJSON.GeometryObject | GeoSphere;
/**
* A GeoJSON-style GeometryCollection which supports GeoJSON geometry objects
* and additionally GeoSphere
*/
export interface ExtendedGeometryCollection<GeometryType extends GeoGeometryObjects> {
type: string;
bbox?: number[];
crs?: GeoJSON.CoordinateReferenceSystem;
geometries: GeometryType[];
}
/**
* A GeoJSON-style Feature which support features built on GeoJSON GeometryObjects
* or GeoSphere
*/
export interface ExtendedFeature<GeometryType extends GeoGeometryObjects, Properties> extends GeoJSON.GeoJsonObject {
geometry: GeometryType;
properties: Properties;
id?: string;
}
/**
* A GeoJSON-style FeatureCollection which supports GeoJSON features
* and features built on GeoSphere
*/
export interface ExtendedFeatureCollection<FeatureType extends ExtendedFeature<GeoGeometryObjects, any>> extends GeoJSON.GeoJsonObject {
features: FeatureType[];
}
/**
* Type Alias for permissible objects which can be used with d3-geo
* methods
*/
export type GeoPermissibleObjects = GeoGeometryObjects | ExtendedGeometryCollection<GeoGeometryObjects> | ExtendedFeature<GeoGeometryObjects, any> | ExtendedFeatureCollection<ExtendedFeature<GeoGeometryObjects, any>>;
// ----------------------------------------------------------------------
// Spherical Math
// ----------------------------------------------------------------------
/**Returns the spherical area of the specified GeoJSON feature in steradians. */
export function geoArea(feature: ExtendedFeature<GeoGeometryObjects, any>): number;
export function geoArea(feature: ExtendedFeatureCollection<ExtendedFeature<GeoGeometryObjects, any>>): number;
export function geoArea(feature: GeoGeometryObjects): number;
export function geoArea(feature: ExtendedGeometryCollection<GeoGeometryObjects>): number;
/**Returns the spherical bounding box for the specified GeoJSON feature. The bounding box is represented by a two-dimensional array: [[left, bottom], [right, top]], where left is the minimum longitude, bottom is the minimum latitude, right is maximum longitude, and top is the maximum latitude. All coordinates are given in degrees. */
export function geoBounds(feature: ExtendedFeature<GeoGeometryObjects, any>): [[number, number], [number, number]];
export function geoBounds(feature: ExtendedFeatureCollection<ExtendedFeature<GeoGeometryObjects, any>>): [[number, number], [number, number]];
export function geoBounds(feature: GeoGeometryObjects): [[number, number], [number, number]];
export function geoBounds(feature: ExtendedGeometryCollection<GeoGeometryObjects>): [[number, number], [number, number]];
/**Returns the spherical centroid of the specified GeoJSON feature. See also path.centroid, which computes the projected planar centroid.*/
export function geoCentroid(feature: ExtendedFeature<GeoGeometryObjects, any>): [number, number];
export function geoCentroid(feature: ExtendedFeatureCollection<ExtendedFeature<GeoGeometryObjects, any>>): [number, number];
export function geoCentroid(feature: GeoGeometryObjects): [number, number];
export function geoCentroid(feature: ExtendedGeometryCollection<GeoGeometryObjects>): [number, number];
/**Returns the great-arc distance in radians between the two points a and b. Each point must be specified as a two-element array [longitude, latitude] in degrees. */
export function geoDistance(a: [number, number], b: [number, number]): number;
/**Returns the great-arc length of the specified GeoJSON feature in radians.*/
export function geoLength(feature: ExtendedFeature<GeoGeometryObjects, any>): number;
export function geoLength(feature: ExtendedFeatureCollection<ExtendedFeature<GeoGeometryObjects, any>>): number;
export function geoLength(feature: GeoGeometryObjects): number;
export function geoLength(feature: ExtendedGeometryCollection<GeoGeometryObjects>): number;
/**Returns an interpolator function given two points a and b. Each point must be specified as a two-element array [longitude, latitude] in degrees. */
export function geoInterpolate(a: [number, number], b: [number, number]): (t: number) => [number, number];
export interface GeoRotation {
(point: [number, number]): [number, number];
invert(point: [number, number]): [number, number];
}
/**Returns a rotation function for the given angles, which must be a two- or three-element array of numbers [lambda, phi, gamma] specifying the rotation angles in degrees about each spherical axis. */
export function geoRotation(angles: [number, number] | [number, number, number]): GeoRotation;
// ----------------------------------------------------------------------
// Spherical Shapes
// ----------------------------------------------------------------------
// geoCircle ============================================================
export interface GeoCircleGenerator<This, Datum> {
/**Returns a new GeoJSON geometry object of type “Polygon” approximating a circle on the surface of a sphere, with the current center, radius and precision. */
(this: This, d?: Datum, ...args: any[]): GeoJSON.Polygon;
center(): ((this: This, d: Datum, ...args: any[]) => [number, number]);
center(center: [number, number]): this;
center(center: ((this: This, d: Datum, ...args: any[]) => [number, number])): this;
radius(): ((this: This, d: Datum, ...args: any[]) => number);
radius(radius: number): this;
radius(radius: ((this: This, d: Datum, ...args: any[]) => number)): this;
precision(): ((this: This, d: Datum, ...args: any[]) => number);
precision(precision: number): this;
precision(precision: (this: This, d: Datum, ...args: any[]) => number): this;
}
export function geoCircle(): GeoCircleGenerator<any, any>;
export function geoCircle<Datum>(): GeoCircleGenerator<any, Datum>;
export function geoCircle<This, Datum>(): GeoCircleGenerator<This, Datum>;
// geoGraticule ============================================================
export interface GeoGraticuleGenerator {
/**Returns a GeoJSON MultiLineString geometry object representing all meridians and parallels for this graticule. */
(): GeoJSON.MultiLineString;
lines(): GeoJSON.LineString[];
outline(): GeoJSON.Polygon;
extent(): [[number, number], [number, number]];
extent(extent: [[number, number], [number, number]]): this;
extentMajor(): [[number, number], [number, number]];
extentMajor(extent: [[number, number], [number, number]]): this;
extentMinor(): [[number, number], [number, number]];
extentMinor(extent: [[number, number], [number, number]]): this;
step(): [number, number];
step(step: [number, number]): this;
stepMajor(): [number, number];
stepMajor(step: [number, number]): this;
stepMinor(): [number, number];
stepMinor(step: [number, number]): this;
precision(): number;
precision(angle: number): this;
}
export function geoGraticule(): GeoGraticuleGenerator;
// ----------------------------------------------------------------------
// Projections
// ----------------------------------------------------------------------
export interface GeoStream {
lineEnd(): void;
lineStart(): void;
point(x: number, y: number, z?: number): void;
polygonEnd(): void;
polygonStart(): void;
sphere?(): void;
}
export interface GeoStreamWrapper {
stream(stream: GeoStream): GeoStream;
}
export interface GeoRawProjection {
(longitude: number, latitude: number): [number, number];
invert?(x: number, y: number): [number, number];
}
export interface GeoProjection extends GeoStreamWrapper {
/**Returns a new array x, y representing the projected point of the given point. The point must be specified as a two-element array [longitude, latitude] in degrees. */
(point: [number, number]): [number, number] | null;
center(): [number, number];
center(point: [number, number]): this;
clipAngle(): number | null;
clipAngle(angle: null): this;
clipAngle(angle: number): this;
clipExtent(): [[number, number], [number, number]] | null;
clipExtent(extent: null): this;
clipExtent(extent: [[number, number], [number, number]]): this;
/**Sets the projection’s scale and translate to fit the specified GeoJSON object in the center of the given extent. */
fitExtent(extent: [[number, number], [number, number]], object: ExtendedFeature<GeoGeometryObjects, any>): this;
fitExtent(extent: [[number, number], [number, number]], object: ExtendedFeatureCollection<ExtendedFeature<GeoGeometryObjects, any>>): this;
fitExtent(extent: [[number, number], [number, number]], object: GeoGeometryObjects): this;
fitExtent(extent: [[number, number], [number, number]], object: ExtendedGeometryCollection<GeoGeometryObjects>): this;
/**A convenience method for projection.fitExtent where the top-left corner of the extent is [0,0]. */
fitSize(size: [number, number], object: ExtendedFeature<GeoGeometryObjects, any>): this;
fitSize(size: [number, number], object: ExtendedFeatureCollection<ExtendedFeature<GeoGeometryObjects, any>>): this;
fitSize(size: [number, number], object: GeoGeometryObjects): this;
fitSize(size: [number, number], object: ExtendedGeometryCollection<GeoGeometryObjects>): this;
/**Returns a new array [longitude, latitude] in degrees representing the unprojected point of the given projected point. */
invert?(point: [number, number]): [number, number] | null;
precision(): number;
precision(precision: number): this;
rotate(): [number, number, number];
rotate(angles: [number, number] | [number, number, number]): this;
scale(): number;
scale(scale: number): this;
translate(): [number, number];
translate(point: [number, number]): this;
}
export interface GeoConicProjection extends GeoProjection {
parallels(value: [number, number]): this;
parallels(): [number, number];
}
// geoPath ==============================================================
export interface GeoContext {
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void;
beginPath(): void;
closePath(): void;
lineTo(x: number, y: number): void;
moveTo(x: number, y: number): void;
}
export interface GeoPath<This, DatumObject extends GeoPermissibleObjects> {
(this: This, object: DatumObject, ...args: any[]): string;
area(object: DatumObject): number;
bounds(object: DatumObject): [[number, number], [number, number]];
centroid(object: DatumObject): [number, number];
context<C extends GeoContext>(): C | null;
context(context: GeoContext | null): this;
/**
* Get the current projection. The generic parameter can be used to cast the result to the
* correct, known type of the projection, e.g. GeoProjection or GeoConicProjection. Otherwise,
* the return type defaults to the minimum type requirement for a projection which
* can be passed into a GeoPath.
*/
projection<P extends GeoConicProjection | GeoProjection | GeoStreamWrapper>(): P | null;
/**
* Set the projection to the identity projection
*/
projection(projection: null): this;
/**
* Set the projection to be used with the geo path generator.
*/
projection(projection: GeoProjection): this;
/**
* Set the projection to be used with the geo path generator to a custom projection.
* Custom projections must minimally contain a stream method.
*/
projection(projection: GeoStreamWrapper): this;
pointRadius(): (this: This, object: DatumObject, ...args: any[]) => number;
pointRadius(value: number): this;
pointRadius(value: (this: This, object: DatumObject, ...args: any[]) => number): this;
}
export function geoPath(): GeoPath<any, GeoPermissibleObjects>;
export function geoPath<DatumObject extends GeoPermissibleObjects>(): GeoPath<any, DatumObject>;
export function geoPath<This, DatumObject extends GeoPermissibleObjects>(): GeoPath<This, DatumObject>;
// Raw Projections ========================================================
export function geoAzimuthalEqualAreaRaw(): GeoRawProjection;
export function geoAzimuthalEquidistantRaw(): GeoRawProjection;
export function geoConicConformalRaw(phi0: number, phi1: number): GeoRawProjection;
export function geoConicEqualAreaRaw(phi0: number, phi1: number): GeoRawProjection;
export function geoConicEquidistantRaw(phi0: number, phi1: number): GeoRawProjection;
export function geoEquirectangularRaw(): GeoRawProjection;
export function geoGnomonicRaw(): GeoRawProjection;
export function geoMercatorRaw(): GeoRawProjection;
export function geoOrthographicRaw(): GeoRawProjection;
export function geoStereographicRaw(): GeoRawProjection;
export function geoTransverseMercatorRaw(): GeoRawProjection;
// geoProjection ==========================================================
export function geoProjection(project: GeoRawProjection): GeoProjection;
// geoProjectionMutator ====================================================
export function geoProjectionMutator(factory: (...args: any[]) => GeoRawProjection): () => GeoProjection;
// Pre-Defined Projections =================================================
export function geoAlbers(): GeoConicProjection;
export function geoAlbersUsa(): GeoProjection;
export function geoAzimuthalEqualArea(): GeoProjection;
export function geoAzimuthalEquidistant(): GeoProjection;
export function geoConicConformal(): GeoConicProjection;
export function geoConicEqualArea(): GeoConicProjection;
export function geoConicEquidistant(): GeoConicProjection;
export function geoEquirectangular(): GeoProjection;
export function geoGnomonic(): GeoProjection;
export function geoMercator(): GeoProjection;
export function geoOrthographic(): GeoProjection;
export function geoStereographic(): GeoProjection;
export function geoTransverseMercator(): GeoProjection;
// geoClipExtent =============================================================
export interface GeoExtent {
extent(): [[number, number], [number, number]];
extent(extent: [[number, number], [number, number]]): this;
stream(stream: GeoStream): GeoStream;
}
export function geoClipExtent(): GeoExtent;
// ----------------------------------------------------------------------
// Projection Streams
// ----------------------------------------------------------------------
// geoTransform(...) ====================================================
export interface GeoTransformPrototype {
lineEnd?(this: this & { stream: GeoStream }): void;
lineStart?(this: this & { stream: GeoStream }): void;
point?(this: this & { stream: GeoStream }, x: number, y: number, z?: number): void;
polygonEnd?(this: this & { stream: GeoStream }): void;
polygonStart?(this: this & { stream: GeoStream }): void;
sphere?(this: this & { stream: GeoStream }): void;
}
// TODO: Review whether GeoStreamWrapper should be included into return value union type, i.e. ({ stream: (s: GeoStream) => (T & GeoStream & GeoStreamWrapper)})?
// It probably should be omitted for purposes of this API. The stream method added to (T & GeoStream) is more of a private member used internally to
// implement the Transform factory
export function geoTransform<T extends GeoTransformPrototype>(prototype: T): { stream: (s: GeoStream) => (T & GeoStream) };
// geoStream(...) =======================================================
export function geoStream(object: ExtendedFeature<GeoGeometryObjects, any>, stream: GeoStream): void;
export function geoStream(object: ExtendedFeatureCollection<ExtendedFeature<GeoGeometryObjects, any>>, stream: GeoStream): void;
export function geoStream(object: GeoGeometryObjects, stream: GeoStream): void;
export function geoStream(object: ExtendedGeometryCollection<GeoGeometryObjects>, stream: GeoStream): void; | the_stack |
import apiLooper from '../apiLooper'
import { BigNumber } from 'bignumber.js'
import * as bitcoin from 'bitcoinjs-lib'
import typeforce from 'swap.app/util/typeforce'
import constants from 'common/helpers/constants'
import DEFAULT_CURRENCY_PARAMETERS from 'common/helpers/constants/DEFAULT_CURRENCY_PARAMETERS'
// Use front API config
import { default as TESTNET } from '../../../front/config/testnet/api'
import { default as MAINNET } from '../../../front/config/mainnet/api'
const DUST = 546
const getBitpay = (network) => {
return {
name: `apiBitpay`,
servers: (network === `MAINNET`)
? MAINNET.bitpay
: TESTNET.bitpay
}
}
const getCore = () => {
return bitcoin
}
const getBlockcypher = (network) => {
return {
name: `apiBlockcypher`,
servers: (network === `MAINNET`)
? MAINNET.blockcypher
: TESTNET.blockcypher
}
}
const fetchBalance = (options) => {
const {
address,
withUnconfirmed,
apiBitpay,
cacheResponse,
NETWORK,
} = options
return apiLooper.get(apiBitpay || getBitpay(NETWORK), `/address/${address}/balance/`, {
cacheResponse,
checkStatus: (answer) => {
try {
if (answer && answer.balance !== undefined) return true
} catch (error) {
console.error('Utils - btc - fetch balance: ', error)
}
return false
},
inQuery: {
delay: 500,
name: `bitpay`,
},
}).then((answer: any) => {
const {
balance,
unconfirmed,
} = answer
if (withUnconfirmed) {
return {
balance: new BigNumber(balance).dividedBy(1e8).toNumber(),
unconfirmed: new BigNumber(unconfirmed).dividedBy(1e8).toNumber(),
}
} else {
return new BigNumber(balance).dividedBy(1e8).toNumber()
}
})
}
const fetchTx = (options) => {
const {
hash,
apiBitpay,
cacheResponse,
NETWORK,
} = options
return apiLooper.get(apiBitpay || getBitpay(NETWORK), `/tx/${hash}`, {
cacheResponse,
checkStatus: (answer) => {
try {
if (answer && answer.fee !== undefined) return true
} catch (e) { /* */ }
return false
},
inQuery: {
delay: 500,
name: `bitpay`,
},
}).then(({ fee, ...rest }) => ({
fees: new BigNumber(fee).dividedBy(1e8).toNumber(),
...rest,
}
))
}
// @ToDo - Make interface - fetchTxInfo общая для всех блокчейнов - она возврашет сведенные данные определенного типа
const fetchTxInfo = (options) : any => {
const {
hash,
apiBitpay,
cacheResponse,
hasAdminFee,
NETWORK,
} = options
return new Promise(async (callback, txinfoReject) => {
let baseTxInfo: any | boolean = false // @ToDo - make interface for baseTxInfo api answer
let txCoins: any | boolean = false // @ToDo - make interface for txCoins api answer
try {
baseTxInfo = await fetchTx({
hash,
apiBitpay,
cacheResponse,
NETWORK,
})
} catch (error) {
console.error('Fail fetch tx info', error)
txinfoReject(error)
return
}
try {
txCoins = await apiLooper.get(apiBitpay || getBitpay(NETWORK), `/tx/${hash}/coins`, {
cacheResponse,
/* checkStatus */
inQuery: {
delay: 500,
name: `bitpay`,
},
})
} catch (error) {
console.error('Failt fetch tx coin info', error)
txinfoReject(error)
}
let receiverAddress = null
let afterBalance = txCoins && txCoins.inputs && txCoins.inputs[1]
? new BigNumber(txCoins.inputs[1].value).dividedBy(1e8).toNumber()
: null
let adminOutput = []
let adminFee : number | boolean = false
let afterOutput = []
if (!txCoins || !txCoins.inputs || !txCoins.outputs) {
console.error('tx coin info empty')
txinfoReject('tx coin info empty')
}
const senderAddress = txCoins && txCoins.inputs ? txCoins.inputs[0].address : null
const amount = new BigNumber(txCoins.outputs[0].value).dividedBy(1e8).toNumber()
if (hasAdminFee) {
adminOutput = txCoins.outputs.filter((out) => {
return (
out.address === hasAdminFee.address
&& !(new BigNumber(out.value).eq(amount))
)
})
}
/*
// @ToDo - need fix
if (txCoins && txCoins.outputs) {
afterOutput = txCoins.outputs.filter(({ address }) => {
return (
address !== hasAdminFee.address
)
})
}
*/
if (afterOutput.length) {
//@ts-ignore: strictNullChecks
afterBalance = new BigNumber(afterOutput[0].value).dividedBy(1e8).toNumber()
}
if (adminOutput.length) {
//@ts-ignore: strictNullChecks
adminFee = new BigNumber(adminOutput[0].value).dividedBy(1e8).toNumber()
}
if (txCoins && txCoins.outputs && txCoins.outputs[0]) {
receiverAddress = txCoins.outputs[0].address
}
// @ToDo - Интерфейс этой функции
const txInfo = {
txid: baseTxInfo.txid,
amount,
afterBalance,
senderAddress,
confirmed: !!(baseTxInfo.confirmations),
confirmations: baseTxInfo.confirmations,
receiverAddress,
minerFee: baseTxInfo.fees,
adminFee,
minerFeeCurrency: 'BTC',
outputs: txCoins.outputs.map((output) => ({
...output,
amount: new BigNumber(output.value).dividedBy(1e8).toNumber(),
})),
inputs: txCoins.inputs.map((input) => ({
...input,
amount: new BigNumber(input.value).dividedBy(1e8).toNumber(),
})),
fees: baseTxInfo.fees,
size: baseTxInfo.size,
}
callback( txInfo )
})
}
export interface IBtcUnspent {
address: string,
amount: number,
confirmations: number,
height: number,
satoshis: number,
scriptPubKey: string,
txid: string,
vout: number,
spentTxid: string,
}
// @To-do - make interface - ответ этой функции общий для все блокчейнов
const fetchUnspents = (options): Promise<IBtcUnspent[]> => {
const {
address,
apiBitpay,
cacheResponse,
NETWORK,
} = options
return new Promise((resolve, reject) => {
apiLooper.get(
apiBitpay || getBitpay(NETWORK),
`/address/${address}?unspent=true&limit=1000000`,
{
cacheResponse: (cacheResponse || 5000),
inQuery: {
delay: 500,
name: `bitpay`,
},
}
).then((answer: any) => {
resolve(answer.map((txInfo, index) => {
return {
address,
amount: new BigNumber(txInfo.value).dividedBy(1e8).toNumber(),
confirmations: txInfo.confirmations,
height: txInfo.mintHeight,
satoshis: txInfo.value,
scriptPubKey: txInfo.script,
txid: txInfo.mintTxid,
vout: txInfo.mintIndex,
spentTxid: txInfo.spentTxid,
}
}))
}).catch((error) => {
console.error('btc fetchUnspents error', error)
reject(error)
})
})
}
interface IPrepareUnspentsOptions {
amount: number,
unspents: IBtcUnspent[],
}
/**
* Processes the UTXO for the specified amount (in satoshi)
**/
const prepareUnspents = (options: IPrepareUnspentsOptions): Promise<IBtcUnspent[]> => {
const {
amount,
unspents,
} = options
return new Promise((resolve, reject) => {
const needAmount = new BigNumber(amount).multipliedBy(1e8).plus(DUST)
// Sorting all unspent inputs from minimum amount to maximum
const sortedUnspents: IBtcUnspent[] = unspents.sort((a: IBtcUnspent, b: IBtcUnspent) => {
return (new BigNumber(a.satoshis).isEqualTo(b.satoshis))
? 0
: (new BigNumber(a.satoshis).isGreaterThan(b.satoshis))
? 1
: -1
})
// let's try to find one unspent input which will enough for all commission
//@ts-ignore: strictNullChecks
let oneUnspent: IBtcUnspent = null
sortedUnspents.forEach((unspent: IBtcUnspent) => {
if (oneUnspent === null
&& new BigNumber(unspent.satoshis).isGreaterThanOrEqualTo(needAmount)
) {
oneUnspent = unspent
return false
}
})
// if we didn't find one unspent then we're looking for
// all unspent inputs which will enough (from min to max)
if (oneUnspent === null) {
let calcedAmount = new BigNumber(0)
const usedUnspents: IBtcUnspent[] = sortedUnspents.filter((unspent: IBtcUnspent) => {
if (calcedAmount.isGreaterThanOrEqualTo(needAmount)) {
return false
} else {
calcedAmount = calcedAmount.plus(unspent.satoshis)
return true
}
})
resolve(usedUnspents)
} else {
resolve([oneUnspent])
}
})
}
// @ToDo - интерфейс - возврашет объект { txid }
const broadcastTx = (options): any => {
const {
txRaw,
apiBitpay,
apiBlocyper,
onBroadcastError,
NETWORK,
} = options
return new Promise(async (resolve, reject) => {
let answer : any | boolean = false // @ToDo - make interface for api answer
try {
answer = await apiLooper.post(apiBitpay || getBitpay(NETWORK), `/tx/send`, {
body: {
rawTx: txRaw,
},
reportErrors: (error) => {
console.log('BitPay broadcastTx error', error)
return true
},
inQuery: {
delay: 500,
name: `bitpay`,
},
})
} catch (bitpayError) {
console.log('BitPay broadcastTx error', bitpayError)
if (onBroadcastError instanceof Function) {
if (onBroadcastError(bitpayError)) reject()
}
}
if (answer && answer.txid) {
resolve({ txid: answer.txid })
return
}
if (!answer || !answer.txid) {
// use blockcryper
try {
const bcAnswer : any | boolean = await apiLooper.post(apiBlocyper || getBlockcypher(NETWORK), `/txs/push`, {
body: {
tx: txRaw,
},
reportErrors: (error) => {
if (error
&& error.res
&& error.res.res
&& error.res.res.statusMessage
&& error.res.res.statusMessage === `Conflict`
) {
reject(`Conflict`)
return false
} else {
if (error
&& error.res
&& error.res.body
&& error.res.body.error
) {
reject(error.res.body.error)
return false
}
}
return true
},
inQuery: {
delay: 500,
name: `blocyper`,
},
})
if (bcAnswer
&& bcAnswer.tx
&& bcAnswer.tx.hash) {
resolve({
txid: bcAnswer.tx.hash,
})
} else {
reject(`Cant decode answer`)
}
} catch (blocyperError) {
if (onBroadcastError instanceof Function) {
if (onBroadcastError(blocyperError)) reject(``)
} else {
reject(``)
}
}
}
})
}
/*
Проверяет списание со скрипта - последняя транзакция выхода
Возвращает txId, адресс и сумму
*/
const checkWithdraw = (options) => {
const {
scriptAddress,
apiBitpay,
NETWORK,
} = options
const url = `/address/${scriptAddress}/txs/`
return apiLooper.get(apiBitpay || getBitpay(NETWORK), url, {
checkStatus: (answer) => {
try {
if (answer && answer.length !== undefined) return true
} catch (e) { /* */ }
return false
},
inQuery: {
delay: 500,
name: `bitpay`,
},
}).then(async (txs: any) => {
// has two or more txs on script
if ((txs.length >= 1)
&& txs[0].mintTxid
&& txs[0].spentTxid
) {
try {
const spendTxInfo = await fetchTxInfo({
hash: txs[0].spentTxid,
apiBitpay
})
return {
address: spendTxInfo.receiverAddress,
txid: txs[0].spentTxid,
amount: new BigNumber(txs[0].value).dividedBy(1e8).toNumber(),
}
} catch (e) {
console.error('Fail check Withdraw for ', scriptAddress, e)
}
}
return false
})
}
const fetchTxInputScript = (options) => {
const {
txId,
cacheResponse,
apiBlocyper,
NETWORK,
} = options
return apiLooper.get(apiBlocyper || getBlockcypher(NETWORK), `/txs/${txId}?includeHex=true`, {
cacheResponse,
checkStatus: (answer) => {
try {
if (answer && answer.hex !== undefined) return true
} catch (e) {}
return false
},
inQuery: {
delay: 500,
name: `blocyper`,
},
}).then((inInfo: any) => {
if (inInfo
&& inInfo.inputs
&& inInfo.inputs.length === 1
) {
return bitcoin.script.toASM(
//@ts-ignore: strictNullChecks
bitcoin.script.decompile(
Buffer.from(inInfo.inputs[0].script, 'hex')
)
)
}
return false
})
}
const fetchTxRaw = (options) => {
const {
txId,
cacheResponse,
apiBlocyper,
NETWORK,
} = options
return apiLooper.get(apiBlocyper || getBlockcypher(NETWORK), `/txs/${txId}?includeHex=true`, {
cacheResponse,
checkStatus: (answer) => {
try {
if (answer && answer.hex !== undefined) return true
} catch (e) {}
return false
},
inQuery: {
delay: 500,
name: `blocyper`,
},
}).then(({ hex }) => hex)
}
const getTransactionBlocyper = (options) => {
const {
address,
ownAddress,
ownType,
myWallets,
network,
apiBlocyper,
NETWORK,
} = options
return new Promise((resolve) => {
const type = (ownType) || 'btc'
const checkAddress = (address || ownAddress)
const url = `/addrs/${checkAddress}/full?txlimit=1000000`
apiLooper.get(
apiBlocyper || getBlockcypher(NETWORK),
url,
{
cacheResponse: 10*1000,
inQuery: {
delay: 500,
name: `blocyper`,
},
}
).then((answer: any) => {
if (answer
&& answer.txs
) {
const transactions = answer.txs.map((item) => {
const hasOurInputs = item.inputs.filter((input) => {
return (input.addresses[0] === checkAddress)
})
const direction = hasOurInputs.length ? `out` : `in`
const isSelf = direction === 'out'
&& item.outputs.filter((output) => {
const currentAddress = output.addresses[0]
return currentAddress === checkAddress
}).length === item.outputs.length
let value = isSelf
? item.fees
: item.outputs.filter((output) => {
const currentAddress = output.addresses[0]
return direction === 'in'
? (currentAddress === checkAddress)
: (currentAddress !== checkAddress)
})[0].value
return({
type,
hash: item.hash,
canEdit: (myWallets.indexOf(checkAddress) !== -1),
confirmations: item.confirmations,
value: new BigNumber(value).dividedBy(1e8).toNumber(),
date: Date.parse(
(item.confirmations)
? item.confirmed
: item.received
),
direction: isSelf ? 'self' : direction,
})
})
resolve(transactions)
} else {
resolve([])
}
})
.catch((e) => {
console.error('Get btc txs Error', e)
resolve([])
})
})
}
/**
Draft - взято из фронта, там не используется
Но нужно реализовать
игноры - явные ошибки - есть зависимости от фронта shared/actions/btc
Ситауация такая - когда insight обновил свое апи, в быстром режиме нужно было
восстанавливать фронт - эта функция должна использоваться для получения списка
все транзакций на странице "История", но из-за изменений в их апи, быстрее было
использовать блокрипер - в этой функции есть проблемы с получением адресов получателя-отправителя
**/
const getTransactionBitcore = (options) => {
const {
address,
ownType,
myWallets,
network,
apiBitpay,
NETWORK,
} = options
return new Promise(async (resolve) => {
// @ts-ignore
const myAllWallets = getAllMyAddresses()
// @ts-ignore
let { user: { btcData: { address: userAddress } } } = getState()
// @ts-ignore
address = address || userAddress
const type = (ownType) || 'btc'
// @ts-ignore
if (!typeforce.isCoinAddress.BTC(address)) {
resolve([])
}
const blockInfo = await apiLooper.get(apiBitpay || getBitpay(NETWORK), `/block/tip`, {
/* cache */
/* query */
})
console.log('blockInfo', blockInfo)
const url = `/address/${address}/txs`
return apiLooper.get(apiBitpay, url, {
checkStatus: (answer) => {
try {
if (answer && answer.txs !== undefined) return true
} catch (e) { /* */ }
return false
},
inQuery: {
delay: 500,
name: `bitpay`,
},
}).then((res: any) => {
const transactions = res.txs.map((item) => {
const direction = item.vin[0].addr !== address ? 'in' : 'out'
const isSelf = direction === 'out'
&& item.vout.filter((item) => {
const voutAddrBuf = Buffer.from(item.scriptPubKey.hex, 'hex')
const currentAddress = bitcoin.address.fromOutputScript(voutAddrBuf, network)
return currentAddress === address
}).length === item.vout.length
return({
type,
hash: item.txid,
canEdit: (myWallets.indexOf(address) !== -1),
confirmations: item.confirmations,
value: isSelf
? item.fees
: item.vout.filter((item) => {
const voutAddrBuf = Buffer.from(item.scriptPubKey.hex, 'hex')
const currentAddress = bitcoin.address.fromOutputScript(voutAddrBuf, network)
return direction === 'in'
? (currentAddress === address)
: (currentAddress !== address)
})[0].value,
date: item.time * 1000,
direction: isSelf ? 'self' : direction,
})
})
resolve(transactions)
}).catch((error) => {
console.error(error)
resolve([])
})
})
}
const getFeesRateBlockcypher = async ({ NETWORK }) => {
const defaultRate = DEFAULT_CURRENCY_PARAMETERS.btc.rate
const defaultApiSpeeds = {
slow: defaultRate.slow,
normal: defaultRate.normal,
fast: defaultRate.fast,
custom: 50 * 1024,
}
let apiResult
try {
// api returns sotoshi in 1 kb
apiResult = await apiLooper
.get(getBlockcypher(NETWORK), ``, {
cacheResponse: 10*60*1000,
cacheOnFail: true,
inQuery: {
delay: 500,
name: `blocyper`,
},
} )
} catch (err) {
console.error({ info: err })
return defaultApiSpeeds
}
const apiRate = {
slow: apiResult.low_fee_per_kb,
normal: apiResult.medium_fee_per_kb,
fast: apiResult.high_fee_per_kb,
custom: 50 * 1024,
}
return apiRate;
}
enum Network {
mainnet = "mainnet",
testnet = "testnet",
}
enum AddressType {
p2pkh = "P2PKH",
p2sh = "P2SH",
p2wpkh = "P2WPKH",
p2wsh = "P2WSH",
}
const addressTypes: { [key: number]: { type: AddressType, network: Network } } = {
0x00: {
type: AddressType.p2pkh,
network: Network.mainnet,
},
0x6f: {
type: AddressType.p2pkh,
network: Network.testnet,
},
0x05: {
type: AddressType.p2sh,
network: Network.mainnet,
},
0xc4: {
type: AddressType.p2sh,
network: Network.testnet,
},
};
const getAddressType = (address: string) => {
const prefix = address.substr(0, 2)
let data
let addressType
if (prefix === 'bc' || prefix === 'tb') {
const { data: benchVersion } = bitcoin.address.fromBech32(address)
data = benchVersion
addressType = data.length === 20 ? AddressType.p2wpkh : AddressType.p2wsh
return addressType
} else {
const { version } = bitcoin.address.fromBase58Check(address)
let { type } = addressTypes[version]
if (!type) {
type = AddressType.p2pkh
console.warn(`Unknown version '${version}' for address '${address}'.`)
}
return addressType = type || AddressType.p2pkh
}
}
// getByteCount({'MULTISIG-P2SH:2-4':45},{'P2PKH':1}) Means "45 inputs of P2SH Multisig and 1 output of P2PKH"
// getByteCount({'P2PKH':1,'MULTISIG-P2SH:2-3':2},{'P2PKH':2}) means "1 P2PKH input and 2 Multisig P2SH (2 of 3) inputs along with 2 P2PKH outputs"
const getByteCount = (inputs, outputs) => {
const { TRANSACTION } = constants
let totalWeight = 0
let hasWitness = false
let inputCount = 0
let outputCount = 0
// assumes compressed pubkeys in all cases.
const types = {
'inputs': {
'MULTISIG-P2SH': TRANSACTION.MULTISIG_P2SH_IN_SIZE * 4,
'MULTISIG-P2WSH': TRANSACTION.MULTISIG_P2WSH_IN_SIZE + (41 * 4),
'MULTISIG-P2SH-P2WSH': TRANSACTION.MULTISIG_P2SH_P2WSH_IN_SIZE + (76 * 4),
'P2PKH': TRANSACTION.P2PKH_IN_SIZE * 4,
'P2WPKH': TRANSACTION.P2WPKH_IN_SIZE + (41 * 4),
'P2SH-P2WPKH': TRANSACTION.P2SH_P2WPKH_IN_SIZE + (64 * 4),
},
'outputs': {
'P2SH': TRANSACTION.P2SH_OUT_SIZE * 4,
'P2PKH': TRANSACTION.P2PKH_OUT_SIZE * 4,
'P2WPKH': TRANSACTION.P2WPKH_OUT_SIZE * 4,
'P2WSH': TRANSACTION.P2WSH_OUT_SIZE * 4,
},
}
const checkUInt53 = (n) => {
if (n < 0 || n > Number.MAX_SAFE_INTEGER || n % 1 !== 0) throw new RangeError('value out of range')
}
const varIntLength = (number) => {
checkUInt53(number)
return (
number < 0xfd ? 1
: number <= 0xffff ? 3
: number <= 0xffffffff ? 5
: 9
)
}
Object.keys(inputs).forEach((key) => {
checkUInt53(inputs[key])
if (key.slice(0, 8) === 'MULTISIG') {
// ex. "MULTISIG-P2SH:2-3" would mean 2 of 3 P2SH MULTISIG
const keyParts = key.split(':')
if (keyParts.length !== 2) throw new Error(`invalid input: ${key}`)
const newKey = keyParts[0]
const mAndN = keyParts[1].split('-').map((item) => parseInt(item))
totalWeight += types.inputs[newKey] * inputs[key]
const multiplyer = (newKey === 'MULTISIG-P2SH') ? 4 : 1
totalWeight += ((73 * mAndN[0]) + (34 * mAndN[1])) * multiplyer * inputs[key]
} else {
totalWeight += types.inputs[key] * inputs[key]
}
inputCount += inputs[key]
if (key.indexOf('W') >= 0) hasWitness = true
})
Object.keys(outputs).forEach((key) => {
checkUInt53(outputs[key])
totalWeight += types.outputs[key] * outputs[key]
outputCount += outputs[key]
})
if (hasWitness) totalWeight += 2
totalWeight += 8 * 4
totalWeight += varIntLength(inputCount) * 4
totalWeight += varIntLength(outputCount) * 4
return Math.ceil(totalWeight / 4)
}
type CalculateTxSizeParams = {
txIn?: number
txOut?: number
method?: string
fixed?: boolean
toAddress?: string
serviceFee?: {
address: any
min: any
fee: any
} | any
address?: string
}
const calculateTxSize = async (params: CalculateTxSizeParams) => {
let {
txIn,
txOut,
method = 'send',
fixed,
toAddress,
serviceFee,
address,
} = params
const { TRANSACTION } = constants
const defaultTxSize = DEFAULT_CURRENCY_PARAMETERS.btc.size[method]
let txSize = defaultTxSize
if (fixed) {
return txSize
}
const fromAddressType = address ? getAddressType(address) : "P2PKH";
// general formula
// (<one input size> × <number of inputs>) + (<one output size> × <number of outputs>) + <tx size>
//@ts-ignore: strictNullChecks
if (txIn > 0) {
txSize =
//@ts-ignore: strictNullChecks
txIn * TRANSACTION[`${fromAddressType}_IN_SIZE`] +
//@ts-ignore: strictNullChecks
txOut * TRANSACTION.P2PKH_OUT_SIZE +
//@ts-ignore: strictNullChecks
(TRANSACTION.TX_SIZE + txIn - txOut)
}
if (method === 'send_multisig') {
let outputs = {
'P2SH': 1,
}
const toAddressType = toAddress ? getAddressType(toAddress) : "P2PKH";
outputs[toAddressType] = ++outputs[toAddressType] || 1;
if (serviceFee) {
const adminAddressType = getAddressType(serviceFee.address);
outputs[adminAddressType] = ++outputs[adminAddressType] || 1;
}
txSize = getByteCount(
{ 'MULTISIG-P2SH:2-2': 1 },
outputs
)
}
if (method === 'send_2fa') {
let outputs = {
'P2SH': 1,
}
const toAddressType = toAddress ? getAddressType(toAddress) : "P2PKH";
outputs[toAddressType] = ++outputs[toAddressType] || 1;
if (serviceFee) {
const adminAddressType = getAddressType(serviceFee.address);
outputs[adminAddressType] = ++outputs[adminAddressType] || 1;
}
txSize = getByteCount(
{ 'MULTISIG-P2SH:2-3': txIn },
outputs
)
}
console.group('Common > utils > coin >%c btc > calculateTxSize', 'color: green;')
console.log('params: ', params)
console.log('txSize: ', txSize)
console.groupEnd()
return txSize
}
const estimateFeeRateBLOCKCYPHER = (options) => {
const {
speed = 'fast',
NETWORK,
} = options
const _speed = (() => {
switch (speed) {
case 'fast': return 'high_fee_per_kb'
case 'normal': return 'medium_fee_per_kb'
case 'slow': return 'low_fee_per_kb'
default: return 'medium_fee_per_kb'
}
})()
// 10 minuts cache
// query request
return apiLooper
.get(getBlockcypher(NETWORK), ``, {
cacheResponse: 10*60*1000,
cacheOnFail: true,
inQuery: {
delay: 500,
name: `blocyper`,
},
} )
//@ts-ignore: strictNullChecks
.then(info => Number(info[_speed]))
}
const estimateFeeRate = async (options) => {
const { speed } = options;
const defaultRate = DEFAULT_CURRENCY_PARAMETERS.btc.rate
try {
return await estimateFeeRateBLOCKCYPHER(options)
} catch (err) {
console.error(`EstimateFeeError: BLOCKCYPHER_API ${err.message}, get default rate...`)
return defaultRate[speed]
}
}
const estimateFeeValue = async (options) => {
const {
feeRate: _feeRate,
inSatoshis,
speed,
address,
amount,
toAddress,
method,
txSize: _txSize,
swapUTXOMethod,
serviceFee,
fixed,
moreInfo,
NETWORK,
} = options
let calculatedFeeValue
const SATOSHI_TO_BITCOIN_RATIO = 0.000_000_01
if (!_txSize && !address) {
calculatedFeeValue = new BigNumber(constants.TRANSACTION.DUST_SAT).multipliedBy(1e-8)
} else {
let unspents = await fetchUnspents({
address,
NETWORK,
})
// if user have some amount then try to find "better" UTXO for this
if (amount) {
unspents = await prepareUnspents({ amount, unspents })
}
// one input for output from the script when swapping
const txIn = unspents.length
// 2 = recipient input + sender input (for a residue)
// 3 = the same inputs like higher + input for admin fee
let txOut = serviceFee
? method === 'send'
? 3
: 2
: 2
if (method === 'swap' && swapUTXOMethod === 'withdraw') {
txOut = 1
}
const txSize = _txSize || await calculateTxSize({
fixed,
address,
toAddress,
method,
txIn,
txOut,
serviceFee
})
const feeRate = _feeRate || await estimateFeeRate({ speed, NETWORK })
calculatedFeeValue = BigNumber.maximum(
constants.TRANSACTION.DUST_SAT,
new BigNumber(feeRate)
.multipliedBy(txSize)
.div(1024)
.dp(0, BigNumber.ROUND_HALF_EVEN),
)
if (moreInfo) {
const moreInfoResponse = {
fee: calculatedFeeValue.multipliedBy(SATOSHI_TO_BITCOIN_RATIO).toNumber(),
satoshis: calculatedFeeValue.toNumber(),
txSize,
feeRate,
unspents,
}
return moreInfoResponse
}
}
const finalFeeValue = inSatoshis
? calculatedFeeValue.toString()
: calculatedFeeValue.multipliedBy(SATOSHI_TO_BITCOIN_RATIO).toString()
console.group('Common > coin >%c btc > estimateFeeValue', 'color: green;')
console.log('fee value: ', finalFeeValue)
console.groupEnd()
return finalFeeValue
}
const prepareFees = async ({
amount,
serviceFee,
feeValue,
speed,
method = 'send',
from,
to,
NETWORK,
}) => {
let feeFromAmount: number | BigNumber = new BigNumber(0)
if (serviceFee) {
const {
fee: adminFee,
min: adminFeeMinValue,
} = serviceFee
const adminFeeMin = new BigNumber(adminFeeMinValue)
feeFromAmount = new BigNumber(adminFee).dividedBy(100).multipliedBy(amount)
if (adminFeeMin.isGreaterThan(feeFromAmount)) feeFromAmount = adminFeeMin
feeFromAmount = feeFromAmount.multipliedBy(1e8).integerValue() // Admin fee in satoshi
}
feeFromAmount = feeFromAmount.toNumber()
try {
feeValue = feeValue ?
new BigNumber(feeValue).multipliedBy(1e8).toNumber() :
await estimateFeeValue({
inSatoshis: true,
speed,
method,
address: from,
toAddress: to,
amount,
serviceFee,
})
} catch (eFee) {
return { message: `Fail estimate fee ` + eFee.message }
}
let unspents = []
try {
//@ts-ignore: strictNullChecks
unspents = await fetchUnspents({address: from, NETWORK})
} catch (eUnspents) {
return { message: `Fail fetch unspents `+ eUnspents.message}
}
const toAmount = amount
amount = new BigNumber(amount).multipliedBy(1e8).plus(feeValue).plus(feeFromAmount).multipliedBy(1e-8).toNumber()
try {
//@ts-ignore: strictNullChecks
unspents = await prepareUnspents({ unspents, amount })
} catch (eUnspents) {
return { message: `Fail prepare unspents `+ eUnspents.message}
}
const fundValue = new BigNumber(toAmount).multipliedBy(1e8).integerValue().toNumber()
const totalUnspent = unspents.reduce((summ, { satoshis }) => summ + satoshis, 0)
const skipValue = totalUnspent - fundValue - feeValue - feeFromAmount
return {
fundValue,
skipValue,
feeFromAmount,
unspents,
}
}
const prepareRawTx = async (params) => {
const {
from,
to,
fundValue,
skipValue,
serviceFee,
feeFromAmount,
method = 'send',
unspents,
privateKey,
publicKeys = [Buffer.from('')],
network,
NETWORK
} = params
const psbt = new bitcoin.Psbt({network})
psbt.addOutput({
address: to,
value: fundValue,
})
if (skipValue > 546) {
psbt.addOutput({
address: from,
value: skipValue
})
}
if (serviceFee) {
psbt.addOutput({
address: serviceFee.address,
value: feeFromAmount,
})
}
const keyPair = bitcoin.ECPair.fromWIF(privateKey, network)
const hasOneSignature = !['send_2fa', 'send_multisig'].includes(method)
if (hasOneSignature) {
for (let i = 0; i < unspents.length; i++) {
const { txid, vout } = unspents[i]
let rawTx = ''
try {
rawTx = await fetchTxRaw({ txId: txid, cacheResponse: 5000, NETWORK })
} catch (eFetchTxRaw) {
return { message: `Fail fetch tx raw `+ txid + `(`+eFetchTxRaw.message+`)` }
}
psbt.addInput({
hash: txid,
index: vout,
nonWitnessUtxo: Buffer.from(rawTx, 'hex'),
})
}
psbt.signAllInputs(keyPair)
psbt.finalizeAllInputs()
return psbt.extractTransaction().toHex();
}
const p2ms = bitcoin.payments.p2ms({
m: 2,
n: publicKeys.length,
pubkeys: publicKeys.map((key) => Buffer.from(key)),
network,
})
for (let i = 0; i < unspents.length; i++) {
const { txid, vout } = unspents[i]
let rawTx = ''
try {
rawTx = await fetchTxRaw({ txId: txid, cacheResponse: 5000, NETWORK })
} catch (eFetchTxRaw) {
return { message: `Fail fetch tx raw `+ txid + `(`+eFetchTxRaw.message+`)` }
}
psbt.addInput({
hash: txid,
index: vout,
redeemScript: p2ms.output,
nonWitnessUtxo: Buffer.from(rawTx, 'hex'),
})
}
psbt.signAllInputs(keyPair)
return psbt.toHex()
}
export default {
fetchBalance,
fetchTx,
fetchTxInfo,
fetchUnspents,
broadcastTx,
checkWithdraw,
fetchTxRaw,
getTransactionBlocyper,
getFeesRateBlockcypher,
estimateFeeValue,
estimateFeeRate,
calculateTxSize,
getCore,
prepareFees,
prepareRawTx,
prepareUnspents,
fetchTxInputScript,
} | the_stack |
import stream = require("stream");
import * as zlib from "zlib";
import * as restm from 'typed-rest-client/RestClient';
import * as httpm from 'typed-rest-client/HttpClient';
import VsoBaseInterfaces = require('./interfaces/common/VsoBaseInterfaces');
import FileContainerApiBase = require("./FileContainerApiBase");
import FileContainerInterfaces = require("./interfaces/FileContainerInterfaces");
import vsom = require('./VsoClient');
export interface IFileContainerApi extends FileContainerApiBase.IFileContainerApiBase {
createItem(contentStream: NodeJS.ReadableStream, uncompressedLength: number, containerId: number, itemPath: string, scope: string, options: any): Promise<FileContainerInterfaces.FileContainerItem>;
getItem(containerId: number, scope?: string, itemPath?: string, downloadFileName?: string): Promise<restm.IRestResponse<NodeJS.ReadableStream>>;
}
export class FileContainerApi extends FileContainerApiBase.FileContainerApiBase implements IFileContainerApi {
constructor(baseUrl: string, handlers: VsoBaseInterfaces.IRequestHandler[], options?: VsoBaseInterfaces.IRequestOptions) {
super(baseUrl, handlers, options);
}
/**
* @param {number} containerId
* @param {string} scope
* @param {string} itemPath
* @param {string} downloadFileName
*/
public async getItem(
containerId: number,
scope?: string,
itemPath?: string,
downloadFileName?: string
): Promise<restm.IRestResponse<NodeJS.ReadableStream>> {
return new Promise<restm.IRestResponse<NodeJS.ReadableStream>>(async (resolve, reject) => {
let routeValues: any = {
containerId: containerId
};
let queryValues: any = {
scope: scope,
itemPath: itemPath,
'$format': "OctetStream",
downloadFileName: downloadFileName
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"4.0-preview.4",
"Container",
"e4f5c81e-e250-447b-9fef-bd48471bea5e",
routeValues,
queryValues);
let url: string = verData.requestUrl;
let options: restm.IRequestOptions = this.createRequestOptions('application/octet-stream', verData.apiVersion);
let res = await this.http.get(url);
let rres: restm.IRestResponse<NodeJS.ReadableStream> = <restm.IRestResponse<NodeJS.ReadableStream>>{};
let statusCode = res.message.statusCode;
rres.statusCode = statusCode;
// not found leads to null obj returned
if (statusCode == httpm.HttpCodes.NotFound) {
resolve(rres);
}
if (statusCode > 299) {
let msg;
// if exception/error in body, attempt to get better error
let contents = await res.readBody();
let obj;
if (contents && contents.length > 0) {
obj = JSON.parse(contents);
if (options && options.responseProcessor) {
rres.result = options.responseProcessor(obj);
}
else {
rres.result = obj;
}
}
if (obj && obj.message) {
msg = obj.message;
}
else {
msg = "Failed request: (" + statusCode + ") " + res.message.url;
}
reject(new Error(msg));
}
else {
// if the response is gzipped, unzip it
if (res.message.headers["content-encoding"] === "gzip") {
let unzipStream = zlib.createGunzip();
res.message.pipe(unzipStream);
rres.result = unzipStream;
}
else {
rres.result = res.message;
}
resolve(rres);
}
}
catch (err) {
reject(err);
}
});
}
public createItem(contentStream: NodeJS.ReadableStream, uncompressedLength: number, containerId: number, itemPath: string, scope: string, options: any): Promise<FileContainerInterfaces.FileContainerItem> {
return new Promise<FileContainerInterfaces.FileContainerItem>((resolve, reject) => {
let chunkStream = new ChunkStream(this, uncompressedLength, containerId, itemPath, scope, options);
chunkStream.on('finish', () => {
resolve(chunkStream.getItem());
});
contentStream.pipe(chunkStream);
});
}
// used by ChunkStream
public _createItem(
customHeaders: VsoBaseInterfaces.IHeaders,
contentStream: NodeJS.ReadableStream,
containerId: number,
itemPath: string,
scope: string,
onResult: (err: any, statusCode: number, Container: FileContainerInterfaces.FileContainerItem) => void
): void {
var routeValues: any = {
containerId: containerId
};
var queryValues: any = {
itemPath: itemPath,
scope: scope,
};
customHeaders = customHeaders || {};
customHeaders["Content-Type"] = "";
this.vsoClient.getVersioningData("4.0-preview.4", "Container", "e4f5c81e-e250-447b-9fef-bd48471bea5e", routeValues, queryValues)
.then((versioningData: vsom.ClientVersioningData) => {
var url: string = versioningData.requestUrl;
var serializationData = { responseTypeMetadata: FileContainerInterfaces.TypeInfo.FileContainerItem, responseIsCollection: false };
let options: restm.IRequestOptions = this.createRequestOptions('application/octet-stream',
versioningData.apiVersion);
options.additionalHeaders = customHeaders;
this.rest.uploadStream<FileContainerInterfaces.FileContainerItem>('PUT', url, contentStream, options)
.then((res: restm.IRestResponse<FileContainerInterfaces.FileContainerItem>) => {
let ret = this.formatResponse(res.result,
FileContainerInterfaces.TypeInfo.FileContainerItem,
false);
onResult(null, res.statusCode, ret);
})
.catch((err) => {
onResult(err, err.statusCode, null);
});
}, (error) => {
onResult(error, error.statusCode, null);
});
}
}
class ChunkStream extends stream.Writable {
private static ChunkSize: number = (16 * 1024 * 1024);
private _options: any;
private _api: FileContainerApi;
private _buffer: Buffer = new Buffer(ChunkStream.ChunkSize);
private _length: number = 0;
private _startRange: number = 0;
private _bytesToSend: number = 0;
private _totalReceived: number = 0;
private _uncompressedLength: number;
private _containerId: number;
private _itemPath: string;
private _scope: string;
private _item: FileContainerInterfaces.FileContainerItem;
constructor(api: FileContainerApi, uncompressedLength: number, containerId: number, itemPath: string, scope: string, options: any) {
super();
this._api = api;
this._options = options || {};
this._uncompressedLength = uncompressedLength;
this._containerId = containerId;
this._itemPath = itemPath;
this._scope = scope;
this._bytesToSend = this._options.isGzipped ? this._options.compressedLength : uncompressedLength;
}
_write(data: Buffer | string, encoding: string, callback: Function): void {
let chunk: Buffer = <Buffer>data;
if (!chunk) {
if (this._length == 0) {
callback();
}
else {
// last chunk
this._sendChunk(callback);
}
return;
}
let newBuffer: Buffer = null;
if (this._length + chunk.length > ChunkStream.ChunkSize) {
// overflow
let overflowPosition: number = chunk.length - (ChunkStream.ChunkSize - this._length);
chunk.copy(this._buffer, this._length, 0, overflowPosition);
this._length += overflowPosition;
newBuffer = chunk.slice(overflowPosition);
}
else {
chunk.copy(this._buffer, this._length, 0, chunk.length);
this._length += chunk.length;
}
this._totalReceived += chunk.length;
if (this._length >= ChunkStream.ChunkSize || this._totalReceived >= this._bytesToSend) {
this._sendChunk(callback, newBuffer);
}
else {
callback();
}
}
private _sendChunk(callback: Function, newBuffer?: Buffer) {
let endRange = this._startRange + this._length;
let headers = {
"Content-Range": "bytes " + this._startRange + "-" + (endRange - 1) + "/" + this._bytesToSend,
"Content-Length": this._length
};
if (this._options.isGzipped) {
headers["Accept-Encoding"] = "gzip";
headers["Content-Encoding"] = "gzip";
headers["x-tfs-filelength"] = this._uncompressedLength;
}
this._startRange = endRange;
this._api._createItem(headers, new BufferStream(this._buffer, this._length), this._containerId, this._itemPath, this._scope, (err: any, statusCode: number, item: FileContainerInterfaces.FileContainerItem) => {
if (newBuffer) {
this._length = newBuffer.length;
newBuffer.copy(this._buffer);
}
else {
this._length = 0;
}
this._item = item;
callback(err);
});
}
public getItem(): FileContainerInterfaces.FileContainerItem {
return this._item;
}
}
class BufferStream extends stream.Readable {
private _buffer: Buffer;
private _position: number = 0;
private _length: number = 0;
constructor(buffer: Buffer, length: number) {
super();
this._buffer = buffer;
this._length = length;
}
_read(size: number): void {
if (this._position >= this._length) {
this.push(null);
return;
}
let end: number = Math.min(this._position + size, this._length);
this.push(this._buffer.slice(this._position, end));
this._position = end;
}
} | the_stack |
import { Component, EventHandler, Collection, Property, Event, EmitType, formatUnit, INotifyPropertyChanged, NotifyPropertyChanges } from '@syncfusion/ej2-base';
import { ChildProperty, addClass, removeClass, setStyleAttribute, attributes, getUniqueID, compile, Complex, getInstance, L10n } from '@syncfusion/ej2-base';
import { append, closest, isNullOrUndefined, remove, classList, Touch, SwipeEventArgs, KeyboardEvents, KeyboardEventArgs, BaseEventArgs } from '@syncfusion/ej2-base';
import { Button } from '@syncfusion/ej2-buttons';
import { CarouselModel, CarouselItemModel, CarouselAnimationSettingsModel } from './carousel-model';
// Constant variables
const CLS_CAROUSEL: string = 'e-carousel';
const CLS_ACTIVE: string = 'e-active';
const CLS_RTL: string = 'e-rtl';
const CLS_ITEMS: string = 'e-carousel-items';
const CLS_ITEM: string = 'e-carousel-item';
const CLS_PREVIOUS: string = 'e-previous';
const CLS_NEXT: string = 'e-next';
const CLS_PREV_ICON: string = 'e-previous-icon';
const CLS_NEXT_ICON: string = 'e-next-icon';
const CLS_NAVIGATORS: string = 'e-carousel-navigators';
const CLS_INDICATORS: string = 'e-carousel-indicators';
const CLS_INDICATOR_BARS: string = 'e-indicator-bars';
const CLS_INDICATOR_BAR: string = 'e-indicator-bar';
const CLS_INDICATOR: string = 'e-indicator';
const CLS_ICON: string = 'e-icons';
const CLS_PLAY_PAUSE: string = 'e-play-pause';
const CLS_PLAY_ICON: string = 'e-play-icon';
const CLS_PAUSE_ICON: string = 'e-pause-icon';
const CLS_PREV_BUTTON: string = 'e-previous-button';
const CLS_NEXT_BUTTON: string = 'e-next-button';
const CLS_PLAY_BUTTON: string = 'e-play-button';
const CLS_FLAT: string = 'e-flat';
const CLS_ROUND: string = 'e-round';
const CLS_HOVER_ARROWS: string = 'e-hover-arrows';
const CLS_HOVER: string = 'e-carousel-hover';
const CLS_TEMPLATE: string = 'e-template';
const CLS_SLIDE_ANIMATION: string = 'e-carousel-slide-animation';
const CLS_FADE_ANIMATION: string = 'e-carousel-fade-animation';
const CLS_CUSTOM_ANIMATION: string = 'e-carousel-custom-animation';
const CLS_PREV_SLIDE: string = 'e-prev';
const CLS_NEXT_SLIDE: string = 'e-next';
const CLS_TRANSITION_START: string = 'e-transition-start';
const CLS_TRANSITION_END: string = 'e-transition-end';
/**
* Specifies the direction of previous/next button navigations in carousel.
*
* * `Previous` - To determine the previous direction of carousel item transition.
* * `Next` - To determine the next direction of carousel item transition.
*/
export type CarouselSlideDirection = 'Previous' | 'Next';
/**
* Specifies the state of navigation buttons displayed in carousel.
*
* * `Hidden` - Navigation buttons are hidden.
* * `Visible` - Navigation buttons are visible.
* * `VisibleOnHover` - Navigation buttons are visible only when we hover the carousel.
*/
export type CarouselButtonVisibility = 'Hidden' | 'Visible' | 'VisibleOnHover';
/**
* Specifies the animation effects of carousel slide.
*
* * `None` - The carousel item transition happens without animation.
* * `Slide` - The carousel item transition happens with slide animation.
* * `Fade` - The Carousel item transition happens with fade animation.
*/
export type CarouselAnimationEffect = 'None' | 'Fade' | 'Slide';
/** An interface that holds details when changing the slide. */
export interface SlideChangingEventArgs extends BaseEventArgs {
/** Specifies the index of current slide. */
currentIndex: number;
/** Specifies the element of current slide. */
currentSlide: HTMLElement;
/** Specifies the index of slide to be changed. */
nextIndex: number;
/** Specifies the element of slide to be changed. */
nextSlide: HTMLElement;
/** Specifies whether the slide transition occur through swiping or not. */
isSwiped: boolean;
/** Specifies the slide direction in which transition occurs. */
slideDirection: CarouselSlideDirection;
/** Specifies whether the slide transition should occur or not. */
cancel: boolean;
}
/** An interface that holds details once slide change done. */
export interface SlideChangedEventArgs extends BaseEventArgs {
/** Specifies the index of current slide. */
currentIndex: number;
/** Specifies the element of current slide. */
currentSlide: HTMLElement;
/** Specifies the index of slide from which it changed. */
previousIndex: number;
/** Specifies the element of slide from which it changed. */
previousSlide: HTMLElement;
/** Specifies whether the slide transition done through swiping or not. */
isSwiped: boolean;
/** Specifies the slide direction in which transition occurred. */
slideDirection: CarouselSlideDirection;
}
/** Specifies the carousel individual item. */
export class CarouselItem extends ChildProperty<CarouselItem> {
/**
* Accepts single/multiple classes (separated by a space) to be used for individual carousel item customization.
*
* @default null
*/
@Property()
public cssClass: string;
/**
* Accepts the interval duration in milliseconds for individual carousel item transition.
*
* @default null
*/
@Property()
public interval: number;
/**
* Accepts the template for individual carousel item.
*
* @default null
*/
@Property()
public template: string;
/**
* Accepts HTML attributes/custom attributes to add in individual carousel item.
*
* @default null
*/
@Property()
public htmlAttributes: Record<string, string>;
}
/** Specifies the animation configuration for carousel items. */
export class CarouselAnimationSettings extends ChildProperty<CarouselAnimationSettings> {
/**
* Specifies the type of animation. The possible values for this property as follows
* * None
* * Slide
* * Fade
*
* @default 'Slide'
*/
@Property('Slide')
public effect: CarouselAnimationEffect;
/**
* Specifies the custom animation effect.
*
* @default null
*/
@Property()
public customEffect: string;
}
@NotifyPropertyChanges
export class Carousel extends Component<HTMLElement> implements INotifyPropertyChanged {
private autoSlideInterval: any;
private slideItems: any[];
private touchModule: Touch;
private keyModule: KeyboardEvents;
private keyConfigs: Record<string, string>;
private slideChangedEventArgs: SlideChangedEventArgs;
private localeObj: L10n;
/**
* Allows defining the collection of carousel item to be displayed on the Carousel.
*
* @default []
*/
@Collection<CarouselItemModel>([], CarouselItem)
public items: CarouselItemModel[];
/**
* Specifies the animation setting for the carousel component.
*
* @default { effect: 'Slide', customEffect: null }
*/
@Complex<CarouselAnimationSettingsModel>({}, CarouselAnimationSettings)
public animation: CarouselAnimationSettingsModel;
/**
* Accepts the template for previous navigation button.
*
* @default null
*/
@Property()
public previousButtonTemplate: string;
/**
* Accepts the template for next navigation button.
*
* @default null
*/
@Property()
public nextButtonTemplate: string;
/**
* Accepts the template for indicator buttons.
*
* @default null
*/
@Property()
public indicatorsTemplate: string;
/**
* Accepts the template for play/pause button.
*
* @default null
*/
@Property()
public playButtonTemplate: string;
/**
* Accepts single/multiple classes (separated by a space) to be used for carousel customization.
*
* @default null
*/
@Property()
public cssClass: string;
/**
* Specifies the datasource for the carousel items.
*
* @isdatamanager false
* @default []
*/
@Property([])
public dataSource: Record<string, any>[];
/**
* Specifies the template option for carousel items.
*
* @default null
*/
@Property()
public itemTemplate: string;
/**
* Specifies index of the current carousel item.
*
* @default 0
*/
@Property(0)
public selectedIndex: number;
/**
* Specifies the width of the Carousel in pixels/number/percentage. The number value is considered as pixels.
*
* @default '100%'
*/
@Property('100%')
public width: string | number;
/**
* Specifies the height of the Carousel in pixels/number/percentage. The number value is considered as pixels.
*
* @default '100%'
*/
@Property('100%')
public height: string | number;
/**
* Specifies the interval duration in milliseconds for carousel item transition.
*
* @default 5000
*/
@Property(5000)
public interval: number;
/**
* Defines whether the slide transition is automatic or manual.
*
* @default true
*/
@Property(true)
public autoPlay: boolean;
/**
* Defines whether the slide transitions loop end or not. When set to false, the transition stops at last slide.
*
* @default true
*/
@Property(true)
public loop: boolean;
/**
* Defines whether to show play button or not.
*
* @default false
*/
@Property(false)
public showPlayButton: boolean;
/**
* Defines whether to enable swipe action in touch devices or not.
*
* @default true
*/
@Property(true)
public enableTouchSwipe: boolean;
/**
* Defines whether to show the indicator positions or not. The indicator positions allow to know the current slide position of the carousel component.
*
* @default true
*/
@Property(true)
public showIndicators: boolean;
/**
* Defines how to show the previous, next and play pause buttons visibility. The possible values for this property as follows
* * Hidden
* * Visible
* * VisibleOnHover
*
* @default 'Visible'
*/
@Property('Visible')
public buttonsVisibility: CarouselButtonVisibility;
/**
* Accepts HTML attributes/custom attributes to add in individual carousel item.
*
* @default null
*/
@Property()
public htmlAttributes: Record<string, string>;
/**
* The event will be fired before the slide change.
*
* @event slideChanging
*/
@Event()
public slideChanging: EmitType<SlideChangingEventArgs>;
/**
* The event will be fired after the slide changed.
*
* @event slideChanged
*/
@Event()
public slideChanged: EmitType<SlideChangedEventArgs>;
/**
* Constructor for creating the Carousel widget
*
* @param {CarouselModel} options Accepts the carousel model properties to initiate the rendering
* @param {string | HTMLElement} element Accepts the DOM element reference
*/
constructor(options?: CarouselModel, element?: string | HTMLElement) {
super(options, <HTMLElement | string>element);
}
protected getModuleName(): string {
return CLS_CAROUSEL.replace('e-', '');
}
protected getPersistData(): string {
return this.addOnPersist(['selectedIndex']);
}
protected preRender(): void {
this.keyConfigs = {
home: 'home',
end: 'end',
space: 'space',
moveLeft: 'leftarrow',
moveRight: 'rightarrow',
moveUp: 'uparrow',
moveDown: 'downarrow'
};
const defaultLocale: Record<string, any> = {
nextSlide: 'Next slide',
of: 'of',
pauseSlideTransition: 'Pause slide transition',
playSlideTransition: 'Play slide transition',
previousSlide: 'Previous slide',
slide: 'Slide',
slideShow: 'Slide show'
};
this.localeObj = new L10n(this.getModuleName(), defaultLocale, this.locale);
}
protected render(): void {
this.initialize();
this.renderSlides();
this.renderNavigators();
this.renderPlayButton();
this.renderIndicators();
this.applyAnimation();
this.wireEvents();
}
public onPropertyChanged(newProp: CarouselModel, oldProp: CarouselModel): void {
let target: Element;
for (const prop of Object.keys(newProp)) {
switch (prop) {
case 'animation':
for (const propName of Object.keys(newProp.animation)) {
if (propName === 'customEffect' && !isNullOrUndefined(oldProp.animation.customEffect)) {
removeClass([this.element.querySelector(`.${CLS_ITEMS}`)], oldProp.animation.customEffect);
}
}
this.applyAnimation();
break;
case 'cssClass':
classList(this.element, [newProp.cssClass], [oldProp.cssClass]);
break;
case 'selectedIndex':
this.setActiveSlide(this.selectedIndex, oldProp.selectedIndex > this.selectedIndex ? 'Previous' : 'Next');
this.autoSlide();
break;
case 'htmlAttributes':
if (!isNullOrUndefined(this.htmlAttributes)) {
this.setHtmlAttributes(this.htmlAttributes, this.element);
}
break;
case 'enableTouchSwipe':
if (!this.enableTouchSwipe && this.touchModule) {
this.touchModule.destroy();
}
if (this.element.querySelector(`.${CLS_ITEMS}`)) {
this.renderTouchActions();
}
break;
case 'loop':
if (this.loop && isNullOrUndefined(this.autoSlideInterval)) {
this.applySlideInterval();
}
this.handleNavigatorsActions(this.selectedIndex);
break;
case 'enableRtl':
if (this.enableRtl) {
addClass([this.element], CLS_RTL);
} else {
removeClass([this.element], CLS_RTL);
}
break;
case 'buttonsVisibility':
target = this.element.querySelector(`.${CLS_NAVIGATORS}`);
if (target) {
switch (this.buttonsVisibility) {
case 'Hidden':
this.resetTemplates(['previousButtonTemplate', 'nextButtonTemplate']);
remove(target);
break;
case 'VisibleOnHover':
addClass([].slice.call(target.childNodes), CLS_HOVER_ARROWS);
break;
case 'Visible':
removeClass([].slice.call(target.childNodes), CLS_HOVER_ARROWS);
break;
}
} else {
this.renderNavigators();
this.renderPlayButton();
}
break;
case 'width':
setStyleAttribute(this.element, { 'width': formatUnit(this.width) });
break;
case 'height':
setStyleAttribute(this.element, { 'height': formatUnit(this.height) });
break;
case 'autoPlay':
if (this.showPlayButton && isNullOrUndefined(this.playButtonTemplate)) {
this.playButtonClickHandler(null, true);
}
this.autoSlide();
break;
case 'interval':
this.autoSlide();
break;
case 'showIndicators':
target = this.element.querySelector(`.${CLS_INDICATORS}`);
if (!this.showIndicators && target) {
this.resetTemplates(['indicatorsTemplate']);
remove(target);
}
this.renderIndicators();
break;
case 'showPlayButton':
target = this.element.querySelector(`.${CLS_PLAY_PAUSE}`);
if (!this.showPlayButton && target) {
remove(target);
this.resetTemplates(['playButtonTemplate']);
}
this.renderPlayButton();
break;
case 'items':
case 'dataSource':
target = this.element.querySelector(`.${CLS_ITEMS}`);
if (target) {
this.resetTemplates(['itemTemplate']);
remove(target);
}
this.renderSlides();
break;
}
}
}
private initialize(): void {
const carouselClasses: string[] = [];
if (this.cssClass) {
carouselClasses.push(this.cssClass);
}
if (this.enableRtl) {
carouselClasses.push(CLS_RTL);
}
addClass([this.element], carouselClasses);
setStyleAttribute(this.element, { 'width': formatUnit(this.width), 'height': formatUnit(this.height) });
attributes(this.element, { 'tabindex': '0', 'aria-roledescription': 'carousel', 'aria-label': this.localeObj.getConstant('slideShow') });
if (!isNullOrUndefined(this.htmlAttributes)) {
this.setHtmlAttributes(this.htmlAttributes, this.element);
}
}
private renderSlides(): void {
const itemsContainer: HTMLElement = this.createElement('div', { className: CLS_ITEMS, attrs: { 'aria-live': this.autoPlay ? 'off' : 'polite' } });
this.element.appendChild(itemsContainer);
if (this.items.length > 0) {
this.slideItems = this.items as Record<string, any>[];
this.items.forEach((item: CarouselItemModel, index: number) => {
this.renderSlide(item, item.template, index, itemsContainer);
});
} else if (this.dataSource.length > 0) {
this.slideItems = this.dataSource;
this.dataSource.forEach((item: Record<string, any>, index: number) => {
this.renderSlide(item, this.itemTemplate, index, itemsContainer);
});
}
this.renderTemplates();
this.autoSlide();
this.renderTouchActions();
this.renderKeyboardActions();
}
private renderSlide(item: Record<string, any>, itemTemplate: string, index: number, container: HTMLElement): void {
const itemEle: HTMLElement = this.createElement('div', {
id: getUniqueID('carousel_item'),
className: `${CLS_ITEM} ${item.cssClass ? item.cssClass : ''} ${this.selectedIndex === index ? CLS_ACTIVE : ''}`,
attrs: {
'aria-hidden': this.selectedIndex === index ? 'false' : 'true', 'data-index': index.toString(),
'aria-role': 'group', 'aria-roledescription': 'slide'
}
});
if (!isNullOrUndefined(item.htmlAttributes)) {
this.setHtmlAttributes(item.htmlAttributes, itemEle);
}
const templateId: string = this.element.id + '_template';
const template: HTMLElement[] = this.templateParser(itemTemplate)(item, this, 'itemTemplate', templateId, false);
append(template, itemEle);
container.appendChild(itemEle);
}
private renderNavigators(): void {
if (this.buttonsVisibility === 'Hidden') {
return;
}
const navigators: HTMLElement = this.createElement('div', { className: CLS_NAVIGATORS });
const itemsContainer: HTMLElement = this.element.querySelector(`.${CLS_ITEMS}`) as HTMLElement;
itemsContainer.insertAdjacentElement('afterend', navigators);
this.renderNavigatorButton('Previous');
this.renderNavigatorButton('Next');
this.renderTemplates();
}
private renderNavigatorButton(direction: CarouselSlideDirection): void {
const buttonContainer: HTMLElement = this.createElement('div', {
className: (direction === 'Previous' ? CLS_PREVIOUS : CLS_NEXT) + ' ' + (this.buttonsVisibility === 'VisibleOnHover' ? CLS_HOVER_ARROWS : ''),
attrs: { 'aria-label': this.localeObj.getConstant(direction === 'Previous' ? 'previousSlide' : 'nextSlide') }
});
if (direction === 'Previous' && this.previousButtonTemplate) {
addClass([buttonContainer], CLS_TEMPLATE);
const templateId: string = this.element.id + '_previousButtonTemplate';
const template: HTMLElement[] = this.templateParser(this.previousButtonTemplate)({ type: 'Previous' }, this, 'previousButtonTemplate', templateId, false);
append(template, buttonContainer);
} else if (direction === 'Next' && this.nextButtonTemplate) {
addClass([buttonContainer], CLS_TEMPLATE);
const templateId: string = this.element.id + '_nextButtonTemplate';
const template: HTMLElement[] = this.templateParser(this.nextButtonTemplate)({ type: 'Next' }, this, 'nextButtonTemplate', templateId, false);
append(template, buttonContainer);
} else {
const button: HTMLElement = this.createElement('button');
const buttonObj: Button = new Button({
cssClass: CLS_FLAT + ' ' + CLS_ROUND + ' ' + (direction === 'Previous' ? CLS_PREV_BUTTON : CLS_NEXT_BUTTON),
iconCss: CLS_ICON + ' ' + (direction === 'Previous' ? CLS_PREV_ICON : CLS_NEXT_ICON),
enableRtl: this.enableRtl,
disabled: !this.loop && this.selectedIndex === (direction === 'Previous' ? 0 : this.slideItems.length - 1)
});
buttonObj.appendTo(button);
buttonContainer.appendChild(button);
}
this.element.querySelector('.' + CLS_NAVIGATORS).appendChild(buttonContainer);
EventHandler.add(buttonContainer, 'click', this.navigatorClickHandler, this);
}
private renderPlayButton(): void {
if (this.buttonsVisibility === 'Hidden' || !this.showPlayButton) {
return;
}
const playPauseWrap: HTMLElement = this.createElement('div', {
className: CLS_PLAY_PAUSE + ' ' + (this.buttonsVisibility === 'VisibleOnHover' ? CLS_HOVER_ARROWS : '')
});
if (this.playButtonTemplate) {
addClass([playPauseWrap], CLS_TEMPLATE);
const templateId: string = this.element.id + '_playButtonTemplate';
const template: HTMLElement[] = this.templateParser(this.playButtonTemplate)({}, this, 'playButtonTemplate', templateId, false);
append(template, playPauseWrap);
} else {
const playButton: HTMLElement = this.createElement('button', {
attrs: { 'aria-label': this.localeObj.getConstant(this.autoPlay ? 'pauseSlideTransition' : 'playSlideTransition') }
});
const isLastSlide: boolean = this.selectedIndex === this.slideItems.length - 1 && !this.loop;
const buttonObj: Button = new Button({
cssClass: CLS_FLAT + ' ' + CLS_ROUND + ' ' + CLS_PLAY_BUTTON,
iconCss: CLS_ICON + ' ' + (this.autoPlay && !isLastSlide ? CLS_PAUSE_ICON : CLS_PLAY_ICON),
isToggle: true,
enableRtl: this.enableRtl
});
if (isLastSlide) {
this.setProperties({ autoPlay: false }, true);
playButton.setAttribute('aria-label', this.localeObj.getConstant('playSlideTransition'));
const itemsContainer: HTMLElement = this.element.querySelector(`.${CLS_ITEMS}`) as HTMLElement;
itemsContainer.setAttribute('aria-live', 'polite');
}
buttonObj.appendTo(playButton);
playPauseWrap.appendChild(playButton);
}
const navigators: Element = this.element.querySelector(`.${CLS_NAVIGATORS}`);
navigators.insertBefore(playPauseWrap, navigators.lastElementChild);
this.renderTemplates();
EventHandler.add(playPauseWrap, 'click', this.playButtonClickHandler, this);
}
private renderIndicators(): void {
if (!this.showIndicators) {
return;
}
const indicatorWrap: HTMLElement = this.createElement('div', { className: CLS_INDICATORS });
const indicatorBars: HTMLElement = this.createElement('div', { className: CLS_INDICATOR_BARS });
indicatorWrap.appendChild(indicatorBars);
if (this.slideItems) {
this.slideItems.forEach((item: Record<string, any>, index: number) => {
const indicatorBar: HTMLElement = this.createElement('div', {
className: CLS_INDICATOR_BAR + ' ' + (this.selectedIndex === index ? CLS_ACTIVE : ''),
attrs: { 'data-index': index.toString(), 'aria-current': this.selectedIndex === index ? 'true' : 'false' }
});
if (this.indicatorsTemplate) {
addClass([indicatorBar], CLS_TEMPLATE);
const templateId: string = this.element.id + '_indicatorsTemplate';
const template: HTMLElement[] = this.templateParser(this.indicatorsTemplate)({ index: index, selectedIndex: this.selectedIndex }, this, 'indicatorsTemplate', templateId, false);
append(template, indicatorBar);
} else {
const indicator: HTMLElement = this.createElement('button', { className: CLS_INDICATOR });
indicatorBar.appendChild(indicator);
indicator.appendChild(this.createElement('div', {
attrs: {
'aria-label': this.localeObj.getConstant('slide') + ' ' + (index + 1) + ' ' + this.localeObj.getConstant('of') + ' ' + this.slideItems.length
}
}));
const buttonObj: Button = new Button({ cssClass: 'e-flat e-small' });
buttonObj.appendTo(indicator);
}
indicatorBars.appendChild(indicatorBar);
EventHandler.add(indicatorBar, 'click', this.indicatorClickHandler, this);
});
}
this.element.appendChild(indicatorWrap);
}
private renderKeyboardActions(): void {
this.keyModule = new KeyboardEvents(this.element, { keyAction: this.keyHandler.bind(this), keyConfigs: this.keyConfigs });
}
private renderTouchActions(): void {
if (!this.enableTouchSwipe) {
return;
}
this.touchModule = new Touch(this.element, { swipe: this.swipeHandler.bind(this) });
}
private applyAnimation(): void {
const animationTarget: HTMLElement = this.element.querySelector(`.${CLS_ITEMS}`) as HTMLElement;
removeClass([animationTarget], [CLS_CUSTOM_ANIMATION, CLS_FADE_ANIMATION, CLS_SLIDE_ANIMATION]);
if (this.animation.customEffect) {
addClass([animationTarget], [CLS_CUSTOM_ANIMATION, this.animation.customEffect]);
} else if (this.animation.effect !== 'None') {
addClass([animationTarget], this.animation.effect === 'Fade' ? CLS_FADE_ANIMATION : CLS_SLIDE_ANIMATION);
}
}
private autoSlide(): void {
this.resetSlideInterval();
this.applySlideInterval();
}
private autoSlideChange(): void {
const activeSlide: HTMLElement = this.element.querySelector(`.${CLS_ACTIVE}`) as HTMLElement;
if (isNullOrUndefined(activeSlide)) { return; }
const activeIndex: number = parseInt(activeSlide.dataset.index, 10);
if (!this.loop && activeIndex === this.slideItems.length - 1) {
this.resetSlideInterval();
} else {
const index: number = (activeIndex + 1) % this.slideItems.length;
if (!this.element.classList.contains(CLS_HOVER)) {
this.setActiveSlide(index, 'Next');
}
this.autoSlide();
}
}
private applySlideInterval(): void {
if (!this.autoPlay || this.element.classList.contains(CLS_HOVER)) {
return;
}
let itemInterval: number = this.interval;
if (this.items.length > 0 && !isNullOrUndefined(this.items[this.selectedIndex].interval)) {
itemInterval = this.items[this.selectedIndex].interval;
}
this.autoSlideInterval = setInterval(() => this.autoSlideChange(), itemInterval);
}
private resetSlideInterval(): void {
clearInterval(this.autoSlideInterval);
this.autoSlideInterval = null;
}
private getSlideIndex(direction: CarouselSlideDirection): number {
let currentIndex: number = this.selectedIndex;
if (direction === 'Previous') {
currentIndex--;
if (currentIndex < 0) {
currentIndex = this.slideItems.length - 1;
}
} else {
currentIndex++;
if (currentIndex === this.slideItems.length) {
currentIndex = 0;
}
}
return currentIndex;
}
private setActiveSlide(currentIndex: number, direction: CarouselSlideDirection, isSwiped: boolean = false): void {
if (this.element.querySelectorAll(`.${CLS_ITEM}.${CLS_PREV_SLIDE},.${CLS_ITEM}.${CLS_NEXT_SLIDE}`).length > 0) {
return;
}
const allSlides: HTMLElement[] = [].slice.call(this.element.querySelectorAll(`.${CLS_ITEM}`));
const activeSlide: HTMLElement = this.element.querySelector(`.${CLS_ITEM}.${CLS_ACTIVE}`);
if (isNullOrUndefined(activeSlide) && this.showIndicators) {
const activeIndicator: HTMLElement = this.element.querySelector(`.${CLS_INDICATOR_BAR}.${CLS_ACTIVE}`) as HTMLElement;
const activeIndex: number = parseInt(activeIndicator.dataset.index, 10);
addClass([allSlides[activeIndex]], CLS_ACTIVE);
return;
} else if (isNullOrUndefined(activeSlide)) {
addClass([allSlides[currentIndex]], CLS_ACTIVE);
return;
}
const activeIndex: number = parseInt(activeSlide.dataset.index, 10);
const currentSlide: HTMLElement = allSlides[currentIndex];
const eventArgs: SlideChangingEventArgs = {
currentIndex: activeIndex,
nextIndex: currentIndex,
currentSlide: activeSlide,
nextSlide: currentSlide,
slideDirection: direction,
isSwiped: isSwiped,
cancel: false
};
this.trigger('slideChanging', eventArgs, (args: SlideChangingEventArgs) => {
if (args.cancel) {
return;
}
this.setProperties({ selectedIndex: currentIndex }, true);
attributes(args.currentSlide, { 'aria-hidden': 'true' });
attributes(args.nextSlide, { 'aria-hidden': 'false' });
const slideIndicators: HTMLElement[] = [].slice.call(this.element.querySelectorAll(`.${CLS_INDICATOR_BAR}`));
if (slideIndicators.length > 0) {
attributes(slideIndicators[activeIndex], { 'aria-current': 'false' });
attributes(slideIndicators[currentIndex], { 'aria-current': 'true' });
removeClass(slideIndicators, CLS_ACTIVE);
addClass([slideIndicators[currentIndex]], CLS_ACTIVE);
}
this.slideChangedEventArgs = {
currentIndex: args.nextIndex,
previousIndex: args.currentIndex,
currentSlide: args.nextSlide,
previousSlide: args.currentSlide,
slideDirection: direction,
isSwiped: isSwiped
};
let slideHeight: number;
if (this.animation.customEffect) {
if (direction === 'Previous') {
addClass([args.nextSlide], CLS_NEXT_SLIDE);
addClass([args.currentSlide], CLS_PREV_SLIDE);
} else {
addClass([args.currentSlide], CLS_PREV_SLIDE);
addClass([args.nextSlide], CLS_NEXT_SLIDE);
}
} else if (this.animation.effect === 'Slide') {
if (direction === 'Previous') {
addClass([args.nextSlide], CLS_PREV_SLIDE);
slideHeight = args.nextSlide.offsetHeight;
addClass([args.currentSlide, args.nextSlide], CLS_TRANSITION_END);
} else {
addClass([args.nextSlide], CLS_NEXT_SLIDE);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
slideHeight = args.nextSlide.offsetHeight;
addClass([args.currentSlide, args.nextSlide], CLS_TRANSITION_START);
}
} else if (this.animation.effect === 'Fade') {
removeClass([args.currentSlide], CLS_ACTIVE);
addClass([args.nextSlide], CLS_ACTIVE);
} else {
this.onTransitionEnd();
}
this.handleNavigatorsActions(currentIndex);
});
}
private onTransitionEnd(): void {
if (this.slideChangedEventArgs) {
addClass([this.slideChangedEventArgs.currentSlide], CLS_ACTIVE);
removeClass([this.slideChangedEventArgs.previousSlide], CLS_ACTIVE);
this.trigger('slideChanged', this.slideChangedEventArgs, () => {
removeClass(this.element.querySelectorAll(`.${CLS_ITEM}`), [CLS_PREV_SLIDE, CLS_NEXT_SLIDE, CLS_TRANSITION_START, CLS_TRANSITION_END]);
this.slideChangedEventArgs = null;
});
}
}
private setHtmlAttributes(attribute: Record<string, string>, element: HTMLElement): void {
const keys: string[] = Object.keys(attribute);
for (const key of keys) {
if (key === 'class') {
addClass([element], attribute[key]);
} else {
element.setAttribute(key, attribute[key]);
}
}
}
private templateParser(template: string): Function {
if (template) {
try {
if (document.querySelectorAll(template).length) {
return compile(document.querySelector(template).innerHTML.trim());
} else {
return compile(template);
}
} catch (error) {
return compile(template);
}
}
return undefined;
}
private getNavigatorState(target: HTMLElement, isPrevious: boolean): boolean {
const button: HTMLElement = target.querySelector(`.${isPrevious ? CLS_PREV_BUTTON : CLS_NEXT_BUTTON}`) as HTMLElement;
if (button) {
const buttonObj: Button = getInstance(button, Button) as Button;
return buttonObj.disabled;
}
return false;
}
private navigatorClickHandler(e: Event): void {
const target: HTMLElement = e.currentTarget as HTMLElement;
const isDisabled: boolean = this.getNavigatorState(target, target.classList.contains(CLS_PREVIOUS));
if (isDisabled) { return; }
const direction: CarouselSlideDirection = target.classList.contains(CLS_PREVIOUS) ? 'Previous' : 'Next';
this.setActiveSlide(this.getSlideIndex(direction), direction);
this.autoSlide();
}
private indicatorClickHandler(e: Event): void {
const target: HTMLElement = closest(e.target as Element, `.${CLS_INDICATOR_BAR}`) as HTMLElement;
const index: number = parseInt(target.dataset.index, 10);
if (this.selectedIndex !== index) {
this.setActiveSlide(index, this.selectedIndex > index ? 'Previous' : 'Next');
this.autoSlide();
}
}
private playButtonClickHandler(e: Event, isPropertyChange: boolean = false): void {
const playButton: HTMLElement = this.element.querySelector(`.${CLS_PLAY_BUTTON}`) as HTMLElement;
if (playButton) {
const buttonObj: Button = getInstance(playButton, Button) as Button;
if (!isPropertyChange) {
this.setProperties({ autoPlay: !this.autoPlay }, true);
}
playButton.setAttribute('aria-label', this.localeObj.getConstant(this.autoPlay ? 'pauseSlideTransition' : 'playSlideTransition'));
buttonObj.iconCss = CLS_ICON + ' ' + (this.autoPlay ? CLS_PAUSE_ICON : CLS_PLAY_ICON);
buttonObj.dataBind();
const itemsContainer: HTMLElement = this.element.querySelector(`.${CLS_ITEMS}`) as HTMLElement;
itemsContainer.setAttribute('aria-live', this.autoPlay ? 'off' : 'polite');
if (this.autoPlay && !this.loop && this.selectedIndex === this.slideItems.length - 1) {
this.setActiveSlide(0, 'Next');
}
this.autoSlide();
}
}
private keyHandler(e: KeyboardEventArgs): void {
let direction: CarouselSlideDirection;
let slideIndex: number;
let isSlideTransition: boolean = false;
const target: HTMLElement = e.target as HTMLElement;
e.preventDefault();
switch (e.action) {
case 'space':
if (this.showIndicators && target.classList.contains(CLS_INDICATOR)) {
target.click();
} else if (target.classList.contains(CLS_CAROUSEL) || target.classList.contains(CLS_PLAY_BUTTON)) {
this.playButtonClickHandler(e);
} else if (target.classList.contains(CLS_NEXT_BUTTON)) {
this.next();
} else if (target.classList.contains(CLS_PREV_BUTTON)) {
this.prev();
}
break;
case 'end':
slideIndex = this.slideItems.length - 1;
direction = 'Next';
isSlideTransition = true;
break;
case 'home':
slideIndex = 0;
direction = 'Previous';
isSlideTransition = true;
break;
case 'moveUp':
case 'moveLeft':
case 'moveDown':
case 'moveRight':
if (this.showIndicators && isNullOrUndefined(this.indicatorsTemplate)) {
this.element.focus();
}
direction = (e.action === 'moveUp' || e.action === 'moveLeft') ? 'Previous' : 'Next';
slideIndex = this.getSlideIndex(direction);
isSlideTransition = !this.isSuspendSlideTransition(slideIndex, direction);
break;
}
if (isSlideTransition) {
this.setActiveSlide(slideIndex, direction);
this.autoSlide();
isSlideTransition = false;
}
}
private swipeHandler(e: SwipeEventArgs): void {
if (this.element.classList.contains(CLS_HOVER)) {
return;
}
const direction: CarouselSlideDirection = (e.swipeDirection === 'Right') ? 'Previous' : 'Next';
const slideIndex: number = this.getSlideIndex(direction);
if (!this.isSuspendSlideTransition(slideIndex, direction)) {
this.setActiveSlide(slideIndex, direction, true);
this.autoSlide();
}
}
private isSuspendSlideTransition(index: number, direction: CarouselSlideDirection): boolean {
return !this.loop && (direction === 'Next' && index === 0 || direction === 'Previous' && index === this.slideItems.length - 1);
}
private handleNavigatorsActions(index: number): void {
if (this.buttonsVisibility === 'Hidden') {
return;
}
if (this.showPlayButton) {
const playButton: HTMLElement = this.element.querySelector(`.${CLS_PLAY_BUTTON}`) as HTMLElement;
const isLastSlide: boolean = this.selectedIndex === this.slideItems.length - 1 && !this.loop;
let isButtonUpdate: boolean = isNullOrUndefined(this.playButtonTemplate) && playButton && isLastSlide;
if (isNullOrUndefined(this.playButtonTemplate) && playButton && !isLastSlide) {
isButtonUpdate = !playButton.classList.contains(CLS_ACTIVE);
}
if (isButtonUpdate) {
this.setProperties({ autoPlay: !isLastSlide }, true);
playButton.setAttribute('aria-label', this.localeObj.getConstant(this.autoPlay ? 'pauseSlideTransition' : 'playSlideTransition'));
const itemsContainer: HTMLElement = this.element.querySelector(`.${CLS_ITEMS}`) as HTMLElement;
itemsContainer.setAttribute('aria-live', this.autoPlay ? 'off' : 'polite');
const buttonObj: Button = getInstance(playButton, Button) as Button;
buttonObj.iconCss = CLS_ICON + ' ' + (this.autoPlay ? CLS_PAUSE_ICON : CLS_PLAY_ICON);
buttonObj.dataBind();
}
}
const prevButton: HTMLElement = this.element.querySelector(`.${CLS_PREV_BUTTON}`) as HTMLElement;
if (prevButton && isNullOrUndefined(this.previousButtonTemplate)) {
const buttonObj: Button = getInstance(prevButton, Button) as Button;
buttonObj.disabled = !this.loop && index === 0;
buttonObj.dataBind();
}
const nextButton: HTMLElement = this.element.querySelector(`.${CLS_NEXT_BUTTON}`) as HTMLElement;
if (nextButton && isNullOrUndefined(this.nextButtonTemplate)) {
const buttonObj: Button = getInstance(nextButton, Button) as Button;
buttonObj.disabled = !this.loop && index === this.slideItems.length - 1;
buttonObj.dataBind();
}
}
private onHoverActions(e: Event): void {
const navigator: HTMLElement = this.element.querySelector(`.${CLS_NAVIGATORS}`);
switch (e.type) {
case 'mouseenter':
if (this.buttonsVisibility === 'VisibleOnHover' && navigator) {
removeClass([].slice.call(navigator.childNodes), CLS_HOVER_ARROWS);
}
addClass([this.element], CLS_HOVER);
break;
case 'mouseleave':
if (this.buttonsVisibility === 'VisibleOnHover' && navigator) {
addClass([].slice.call(navigator.childNodes), CLS_HOVER_ARROWS);
}
removeClass([this.element], CLS_HOVER);
break;
}
this.autoSlide();
}
private onFocusActions(e: Event): void {
switch (e.type) {
case 'focusin':
addClass([this.element], CLS_HOVER);
break;
case 'focusout':
removeClass([this.element], CLS_HOVER);
break;
}
this.autoSlide();
}
private destroyButtons(): void {
const buttonCollections: HTMLElement[] = [].slice.call(this.element.querySelectorAll('.e-control.e-btn'));
for (const button of buttonCollections) {
const instance: Button = getInstance(button, Button) as Button;
if (instance) {
instance.destroy();
}
}
}
private wireEvents(): void {
EventHandler.add(this.element, 'focusin focusout', this.onFocusActions, this);
EventHandler.add(this.element, 'mouseenter mouseleave', this.onHoverActions, this);
EventHandler.add(this.element.firstElementChild, 'animationend', this.onTransitionEnd, this);
EventHandler.add(this.element.firstElementChild, 'transitionend', this.onTransitionEnd, this);
}
private unWireEvents(): void {
const indicators: HTMLElement[] = [].slice.call(this.element.querySelectorAll(`.${CLS_INDICATOR_BAR}`));
indicators.forEach((indicator: Element) => {
EventHandler.remove(indicator, 'click', this.indicatorClickHandler);
});
const navigators: HTMLElement[] = [].slice.call(this.element.querySelectorAll(`.${CLS_PREVIOUS},.${CLS_NEXT}`));
navigators.forEach((navigator: HTMLElement) => {
EventHandler.remove(navigator, 'click', this.navigatorClickHandler);
});
const playIcon: Element = this.element.querySelector(`.${CLS_PLAY_PAUSE}`);
if (playIcon) {
EventHandler.remove(playIcon, 'click', this.playButtonClickHandler);
}
EventHandler.remove(this.element.firstElementChild, 'animationend', this.onTransitionEnd);
EventHandler.remove(this.element.firstElementChild, 'transitionend', this.onTransitionEnd);
EventHandler.clearEvents(this.element);
}
/**
* Method to transit from the current slide to the previous slide.
*
* @returns {void}
*/
public prev(): void {
if (!this.loop && this.selectedIndex === 0) {
return;
}
const index: number = (this.selectedIndex === 0) ? this.slideItems.length - 1 : this.selectedIndex - 1;
this.setActiveSlide(index, 'Previous');
this.autoSlide();
}
/**
* Method to transit from the current slide to the next slide.
*
* @returns {void}
*/
public next(): void {
if (!this.loop && this.selectedIndex === this.slideItems.length - 1) {
return;
}
const index: number = (this.selectedIndex === this.slideItems.length - 1) ? 0 : this.selectedIndex + 1;
this.setActiveSlide(index, 'Next');
this.autoSlide();
}
/**
* Method to play the slides programmatically.
*
* @returns {void}
*/
public play(): void {
const playIcon: Element = this.element.querySelector(`.${CLS_PLAY_ICON}`);
if (this.showPlayButton && playIcon) {
classList(playIcon, [CLS_PAUSE_ICON], [CLS_PLAY_ICON]);
const playButton: HTMLElement = this.element.querySelector(`.${CLS_PLAY_BUTTON}`) as HTMLElement;
playButton.setAttribute('aria-label', this.localeObj.getConstant('pauseSlideTransition'));
}
this.setProperties({ autoPlay: true }, true);
const itemsContainer: HTMLElement = this.element.querySelector(`.${CLS_ITEMS}`) as HTMLElement;
itemsContainer.setAttribute('aria-live', 'off');
this.applySlideInterval();
}
/**
* Method to pause the slides programmatically.
*
* @returns {void}
*/
public pause(): void {
const pauseIcon: Element = this.element.querySelector(`.${CLS_PAUSE_ICON}`);
if (this.showPlayButton && pauseIcon) {
const playButton: HTMLElement = this.element.querySelector(`.${CLS_PLAY_BUTTON}`) as HTMLElement;
playButton.setAttribute('aria-label', this.localeObj.getConstant('playSlideTransition'));
classList(pauseIcon, [CLS_PLAY_ICON], [CLS_PAUSE_ICON]);
}
this.setProperties({ autoPlay: false }, true);
const itemsContainer: HTMLElement = this.element.querySelector(`.${CLS_ITEMS}`) as HTMLElement;
itemsContainer.setAttribute('aria-live', 'off');
this.resetSlideInterval();
}
/**
* Method to render react and angular templates
*
* @returns {void}
* @private
*/
private renderTemplates(): void {
if ((this as any).isAngular || (this as any).isReact) {
this.renderReactTemplates();
}
}
/**
* Method to reset react and angular templates
*
* @param {string[]} templates Accepts the template ID
* @returns {void}
* @private
*/
private resetTemplates(templates?: string[]): void {
if ((this as any).isAngular || (this as any).isReact) {
this.clearTemplate(templates);
}
}
/**
* Method for destroy the carousel component.
*
* @returns {void}
*/
public destroy(): void {
this.resetTemplates();
if (this.touchModule) {
this.touchModule.destroy();
this.touchModule = null;
}
this.keyModule.destroy();
this.keyModule = null;
this.resetSlideInterval();
this.destroyButtons();
this.unWireEvents();
[].slice.call(this.element.children).forEach((ele: HTMLElement) => { this.element.removeChild(ele); });
removeClass([this.element], [CLS_CAROUSEL, this.cssClass, CLS_RTL]);
['tabindex', 'role', 'style'].forEach((attr: string): void => { this.element.removeAttribute(attr); });
super.destroy();
}
} | the_stack |
import { service, inject } from 'spryly';
import { Server } from '@hapi/hapi';
import * as _get from 'lodash.get';
import * as ip from 'ip';
import {
arch as osArch,
platform as osPlatform,
release as osRelease,
cpus as osCpus,
totalmem as osTotalMem,
freemem as osFreeMem,
loadavg as osLoadAvg
} from 'os';
import { LoggingService } from './logging';
import { ConfigService } from './config';
import { StateService } from './state';
import { Mqtt } from 'azure-iot-device-mqtt';
import {
ModuleClient,
Message,
DeviceMethodRequest,
DeviceMethodResponse
} from 'azure-iot-device';
import { healthCheckInterval, HealthState } from './health';
import { bind, defer, emptyObj } from '../utils';
export interface ISystemProperties {
cpuModel: string;
cpuCores: number;
cpuUsage: number;
totalMemory: number;
freeMemory: number;
}
export const IoTCentralDeviceFieldIds = {
Property: {
Manufacturer: 'manufacturer',
Model: 'model',
SwVersion: 'swVersion',
OsName: 'osName',
ProcessorArchitecture: 'processorArchitecture',
ProcessorManufacturer: 'processorManufacturer',
TotalStorage: 'totalStorage',
TotalMemory: 'totalMemory',
GpuProcessor: 'gpuProcessor'
}
};
interface IVideoStreamInput {
cameraId: string;
videoStreamUrl: string;
}
interface IDetectionSettings {
wpDemoMode: boolean;
wpAIModelProvider: string;
wpCustomVisionModelUrl: string;
wpPrimaryDetectionClass: string;
wpSecondaryDetectionClass: string;
}
interface IVideoStreamInputSettings {
wpVideoStreamInput1: IVideoStreamInput;
wpVideoStreamInput2: IVideoStreamInput;
wpVideoStreamInput3: IVideoStreamInput;
wpVideoStreamInput4: IVideoStreamInput;
}
export enum ModuleState {
Inactive = 'inactive',
Active = 'active'
}
export enum PipelineState {
Inactive = 'inactive',
Active = 'active'
}
export enum AIModelProvider {
DeepStream = 'DeepStream',
CustomVision = 'CustomVision'
}
export enum RestartDeviceCommandParams {
Timeout = 'cmpRestartDeviceTimeout'
}
export const ModuleInfoFieldIds = {
Telemetry: {
SystemHeartbeat: 'tlSystemHeartbeat',
PrimaryDetectionCount: 'tlPrimaryDetectionCount',
SecondaryDetectionCount: 'tlSecondaryDetectionCount',
Inference: 'tlInference',
FreeMemory: 'tlFreeMemory',
InferenceRate: 'tlInferenceRate',
PrimaryDetectionClass: 'tlPrimaryDetectionClass',
SecondaryDetectionClass: 'tlSecondaryDetectionClass'
},
State: {
ModuleState: 'stModuleState',
PipelineState: 'stPipelineState'
},
Event: {
VideoStreamProcessingStarted: 'evVideoStreamProcessingStarted',
VideoStreamProcessingStopped: 'evVideoStreamProcessingStopped',
ChangeVideoModel: 'evChangeVideoModel',
DeviceRestart: 'evDeviceRestart'
},
Setting: {
DemoMode: 'wpDemoMode',
AIModelProvider: 'wpAIModelProvider',
CustomVisionModelUrl: 'wpCustomVisionModelUrl',
PrimaryDetectionClass: 'wpPrimaryDetectionClass',
SecondaryDetectionClass: 'wpSecondaryDetectionClass',
VideoStreamInput1: 'wpVideoStreamInput1',
VideoStreamInput2: 'wpVideoStreamInput2',
VideoStreamInput3: 'wpVideoStreamInput3',
VideoStreamInput4: 'wpVideoStreamInput4'
},
Property: {
RtspVideoUrl: 'rpRtspVideoUrl',
VideoTaggingClientUrl: 'rpVideoTaggingClientUrl'
},
Command: {
RestartDeepStream: 'cmRestartDeepStream',
RestartDevice: 'cmRestartDevice'
}
};
const defaultInferenceThrottle: number = 500;
@service('iotCentral')
export class IoTCentralService {
@inject('$server')
private server: Server;
@inject('logger')
private logger: LoggingService;
@inject('config')
private config: ConfigService;
@inject('state')
private state: StateService;
private serviceInitializing: boolean = true;
private healthState = HealthState.Good;
private measurementsSentInternal: number = 0;
private deferredStart = defer();
private iotcDeviceIdInternal: string = '';
private iotcModuleIdInternal: string = '';
private iotcClient: any = null;
private iotcDeviceTwin: any = null;
private iotcClientConnected: boolean = false;
private iotcTelemetryThrottleTimer: number = Date.now();
private inferenceThrottle: number = defaultInferenceThrottle;
private inferenceRateCount: number = 0;
private pipelineState: boolean = false;
private detectionSettingsInternal: IDetectionSettings = {
wpDemoMode: true,
wpAIModelProvider: 'CustomVision',
wpCustomVisionModelUrl: '',
wpPrimaryDetectionClass: 'person',
wpSecondaryDetectionClass: 'car'
};
private videoStreamInputSettingsInternal: IVideoStreamInputSettings = {
wpVideoStreamInput1: {
cameraId: '',
videoStreamUrl: ''
},
wpVideoStreamInput2: {
cameraId: '',
videoStreamUrl: ''
},
wpVideoStreamInput3: {
cameraId: '',
videoStreamUrl: ''
},
wpVideoStreamInput4: {
cameraId: '',
videoStreamUrl: ''
}
};
private moduleIpAddress: string = '127.0.0.1';
public get measurementsSent() {
return this.measurementsSentInternal;
}
public get iotcDeviceId() {
return this.iotcDeviceIdInternal;
}
public get iotcModuleId() {
return this.iotcModuleIdInternal;
}
public get detectionSettings() {
return this.detectionSettingsInternal;
}
public get videoStreamInputSettings() {
return this.videoStreamInputSettingsInternal;
}
public async init(): Promise<void> {
this.logger.log(['IoTCentral', 'info'], 'initialize');
this.server.method({ name: 'iotCentral.connectToIoTCentral', method: this.connectToIoTCentral });
this.measurementsSentInternal = 0;
this.iotcDeviceIdInternal = this.config.get('IOTEDGE_DEVICEID') || '';
this.iotcModuleIdInternal = this.config.get('IOTEDGE_MODULEID') || '';
this.inferenceThrottle = this.config.get('inferenceThrottle') || defaultInferenceThrottle;
this.moduleIpAddress = ip.address() || '127.0.0.1';
}
public async getHealth(): Promise<number> {
let healthState = HealthState.Good;
await this.sendMeasurement({
[ModuleInfoFieldIds.Telemetry.InferenceRate]: this.inferenceRateCount / (healthCheckInterval || 1)
});
this.inferenceRateCount = 0;
try {
const systemProperties = await this.getSystemProperties();
const freeMemory = _get(systemProperties, 'freeMemory') || 0;
await this.sendMeasurement({ [ModuleInfoFieldIds.Telemetry.FreeMemory]: freeMemory });
// TODO:
// Find the right threshold for this metric
if (freeMemory === 0) {
healthState = HealthState.Critical;
}
}
catch (ex) {
this.logger.log(['IoTCentralService', 'error'], `Error calling systemProperties: ${ex.message}`);
healthState = HealthState.Critical;
}
if (this.healthState < HealthState.Good) {
healthState = this.healthState;
}
return healthState;
}
@bind
public async connectToIoTCentral(): Promise<void> {
let result = true;
try {
this.logger.log(['IoTCentralService', 'info'], `Starting client connection sequence...`);
result = await this.connectIotcClient();
await this.deferredStart.promise;
this.logger.log(['IoTCentralService', 'info'], `Finished client connection sequence...`);
}
catch (ex) {
result = false;
this.logger.log(['IoTCentralService', 'error'], `Exception during IoT Central device provsioning: ${ex.message}`);
}
this.healthState = result === true ? HealthState.Good : HealthState.Critical;
this.serviceInitializing = false;
}
public async connectIotcClient(): Promise<boolean> {
let result = true;
let connectionStatus = `IoT Central successfully connected device: ${this.iotcDeviceIdInternal}`;
if (this.iotcClient) {
await this.iotcClient.close();
this.iotcClient = null;
}
try {
this.logger.log(['IoTCentralService', 'info'], `IOTEDGE_WORKLOADURI: ${this.config.get('IOTEDGE_WORKLOADURI')}`);
this.logger.log(['IoTCentralService', 'info'], `IOTEDGE_DEVICEID: ${this.config.get('IOTEDGE_DEVICEID')}`);
this.logger.log(['IoTCentralService', 'info'], `IOTEDGE_MODULEID: ${this.config.get('IOTEDGE_MODULEID')}`);
this.logger.log(['IoTCentralService', 'info'], `IOTEDGE_MODULEGENERATIONID: ${this.config.get('IOTEDGE_MODULEGENERATIONID')}`);
this.logger.log(['IoTCentralService', 'info'], `IOTEDGE_IOTHUBHOSTNAME: ${this.config.get('IOTEDGE_IOTHUBHOSTNAME')}`);
this.logger.log(['IoTCentralService', 'info'], `IOTEDGE_AUTHSCHEME: ${this.config.get('IOTEDGE_AUTHSCHEME')}`);
// tslint:disable-next-line:prefer-conditional-expression
if (_get(process.env, 'LOCAL_DEBUG') === '1') {
this.iotcClient = ModuleClient.fromConnectionString(this.config.get('iotCentralHubConnectionString') || '', Mqtt);
}
else {
this.iotcClient = await ModuleClient.fromEnvironment(Mqtt);
}
}
catch (ex) {
this.logger.log(['IoTCentralService', 'error'], `Failed to instantiate client interface from configuraiton: ${ex.message}`);
}
if (!this.iotcClient) {
result = false;
}
if (result === true) {
try {
await this.iotcClient.open();
this.logger.log(['IoTCentralService', 'info'], `Client is connected`);
this.iotcClient.on('inputMessage', this.onHandleDownstreamMessages);
this.iotcClient.on('error', this.onIotcClientError);
this.iotcClient.onMethod(ModuleInfoFieldIds.Command.RestartDeepStream, this.iotcClientRestartDeepStream);
this.iotcClient.onMethod(ModuleInfoFieldIds.Command.RestartDevice, this.iotcClientRestartDevice);
this.iotcDeviceTwin = await this.iotcClient.getTwin();
this.iotcDeviceTwin.on('properties.desired', this.onHandleModuleProperties);
this.iotcClientConnected = true;
const systemProperties = await this.getSystemProperties();
const deviceProperties = {
...this.state.iotCentral.properties,
[IoTCentralDeviceFieldIds.Property.OsName]: osPlatform() || '',
[IoTCentralDeviceFieldIds.Property.SwVersion]: osRelease() || '',
[IoTCentralDeviceFieldIds.Property.ProcessorArchitecture]: osArch() || '',
[IoTCentralDeviceFieldIds.Property.ProcessorManufacturer]: 'NVIDIA',
[IoTCentralDeviceFieldIds.Property.TotalMemory]: systemProperties.totalMemory,
[ModuleInfoFieldIds.Property.RtspVideoUrl]: `rtsp://${this.moduleIpAddress}:8554/ds-test`,
[ModuleInfoFieldIds.Property.VideoTaggingClientUrl]: `http://${this.moduleIpAddress}:3000`
};
this.logger.log(['IoTCentralService', 'info'], `Updating device properties: ${JSON.stringify(deviceProperties, null, 4)}`);
await this.updateDeviceProperties(deviceProperties);
}
catch (ex) {
connectionStatus = `IoT Central connection error: ${ex.message}`;
this.logger.log(['IoTCentralService', 'error'], connectionStatus);
result = false;
}
}
return result;
}
public async sendInferenceData(inferenceTelemetryData: any) {
if (!inferenceTelemetryData || !this.iotcClientConnected) {
return;
}
try {
await this.sendMeasurement(inferenceTelemetryData);
}
catch (ex) {
this.logger.log(['IoTCentralService', 'error'], `sendInferenceData: ${ex.message}`);
}
}
@bind
public async sendMeasurement(data: any): Promise<void> {
if (!data || !this.iotcClientConnected) {
return;
}
try {
const iotcMessage = new Message(JSON.stringify(data));
await this.iotcClient.sendEvent(iotcMessage);
if (_get(process.env, 'DEBUG_TELEMETRY') === '1') {
this.logger.log(['IoTCentralService', 'info'], `sendEvent: ${JSON.stringify(data, null, 4)}`);
}
for (const key in data) {
if (!data.hasOwnProperty(key)) {
continue;
}
this.measurementsSentInternal++;
}
}
catch (ex) {
this.logger.log(['IoTCentralService', 'error'], `sendMeasurement: ${ex.message}`);
}
}
public async updateDeviceProperties(properties: any): Promise<void> {
if (!properties || !this.iotcClientConnected) {
return;
}
try {
await new Promise((resolve, reject) => {
this.iotcDeviceTwin.properties.reported.update(properties, (error) => {
if (error) {
return reject(error);
}
return resolve();
});
});
this.logger.log(['IoTCentralService', 'info'], `Module live properties updated: ${JSON.stringify(properties, null, 4)}`);
}
catch (ex) {
this.logger.log(['IoTCentralService', 'error'], `Error while updating client properties: ${ex.message}`);
}
}
public async getSystemProperties(): Promise<ISystemProperties> {
const cpus = osCpus();
const cpuUsageSamples = osLoadAvg();
return {
cpuModel: Array.isArray(cpus) ? cpus[0].model : 'NVIDIA',
cpuCores: Array.isArray(cpus) ? cpus.length : 0,
cpuUsage: cpuUsageSamples[0],
totalMemory: osTotalMem() / 1024,
freeMemory: osFreeMem() / 1024
};
}
public async setPipelineState(pipelineState: PipelineState) {
const newPipelineState = pipelineState === PipelineState.Active ? true : false;
if (newPipelineState !== this.pipelineState) {
await this.sendMeasurement({
[ModuleInfoFieldIds.State.PipelineState]: pipelineState
});
}
this.pipelineState = newPipelineState;
}
@bind
private async onHandleDownstreamMessages(inputName, message) {
// this.logger.log(['IoTCentralService', 'info'], `Received downstream message: ${JSON.stringify(message, null, 4)}`);
await this.setPipelineState(PipelineState.Active);
this.inferenceRateCount++;
try {
await this.iotcClient.complete(message);
if (inputName === 'dsmessages') {
const messageData = message.getBytes().toString('utf8');
await this.processDeepStreamInference(messageData);
}
else {
this.logger.log(['IoTCentralService', 'warning'], `Warning: received routed message for unknown input: ${inputName}`);
}
}
catch (ex) {
this.logger.log(['IoTCentralService', 'error'], `Error while handling downstream message: ${ex.message}`);
}
}
@bind
private async onHandleModuleProperties(desiredChangedSettings: any) {
try {
this.logger.log(['IoTCentralService', 'info'], `desiredPropsDelta:\n${JSON.stringify(desiredChangedSettings, null, 4)}`);
const patchedProperties = {};
let needRestart = false;
for (const setting in desiredChangedSettings) {
if (!desiredChangedSettings.hasOwnProperty(setting)) {
continue;
}
if (setting === '$version') {
continue;
}
let changedSettingResult;
switch (setting) {
case ModuleInfoFieldIds.Setting.DemoMode:
case ModuleInfoFieldIds.Setting.AIModelProvider:
case ModuleInfoFieldIds.Setting.CustomVisionModelUrl:
changedSettingResult = await this.moduleSettingChange(setting, _get(desiredChangedSettings, `${setting}`));
needRestart = true;
break;
case ModuleInfoFieldIds.Setting.PrimaryDetectionClass:
case ModuleInfoFieldIds.Setting.SecondaryDetectionClass:
changedSettingResult = await this.moduleSettingChange(setting, _get(desiredChangedSettings, `${setting}`));
break;
case ModuleInfoFieldIds.Setting.VideoStreamInput1:
case ModuleInfoFieldIds.Setting.VideoStreamInput2:
case ModuleInfoFieldIds.Setting.VideoStreamInput3:
case ModuleInfoFieldIds.Setting.VideoStreamInput4:
changedSettingResult = await this.moduleSettingChange(setting, _get(desiredChangedSettings, `${setting}`));
needRestart = true;
break;
default:
this.logger.log(['IoTCentralService', 'error'], `Received desired property change for unknown setting '${setting}'`);
break;
}
if (_get(changedSettingResult, 'status') === true) {
patchedProperties[setting] = changedSettingResult.value;
}
}
if (!this.serviceInitializing && !emptyObj(patchedProperties)) {
await this.updateDeviceProperties(patchedProperties);
if (needRestart) {
await this.server.methods.module.updateDSConfiguration();
await this.server.methods.device.restartDockerImage();
}
}
}
catch (ex) {
this.logger.log(['IoTCentralService', 'error'], `Exception while handling desired properties: ${ex.message}`);
}
this.deferredStart.resolve();
}
private async moduleSettingChange(setting: string, value: any): Promise<any> {
this.logger.log(['IoTCentralService', 'info'], `Handle module setting change for '${setting}': ${typeof value === 'object' && value !== null ? JSON.stringify(value, null, 4) : value}`);
const result = {
value: undefined,
status: true
};
switch (setting) {
case ModuleInfoFieldIds.Setting.DemoMode:
case ModuleInfoFieldIds.Setting.AIModelProvider:
case ModuleInfoFieldIds.Setting.CustomVisionModelUrl:
case ModuleInfoFieldIds.Setting.PrimaryDetectionClass:
case ModuleInfoFieldIds.Setting.SecondaryDetectionClass:
result.value = this.detectionSettings[setting] = value || '';
break;
case ModuleInfoFieldIds.Setting.VideoStreamInput1:
case ModuleInfoFieldIds.Setting.VideoStreamInput2:
case ModuleInfoFieldIds.Setting.VideoStreamInput3:
case ModuleInfoFieldIds.Setting.VideoStreamInput4:
result.value = this.videoStreamInputSettings[setting] = value;
break;
default:
this.logger.log(['IoTCentralService', 'info'], `Unknown module setting change request '${setting}'`);
result.status = false;
}
return result;
}
private async processDeepStreamInference(messageData: any) {
if (!messageData || !this.iotcClientConnected || ((Date.now() - this.iotcTelemetryThrottleTimer) < this.inferenceThrottle)) {
return;
}
this.iotcTelemetryThrottleTimer = Date.now();
if (_get(process.env, 'DEBUG_ROUTING_DATA') === '1') {
this.logger.log(['IoTCentralService', 'info'], `Processing downstream data`);
this.logger.log(['IoTCentralService', 'info'], `messageData: ${messageData}`);
}
const messageJson = JSON.parse(messageData);
const cameraId = _get(messageJson, 'sensorId') || 'Unknown';
const detections = _get(messageJson, 'objects') || [];
let primaryDetectionCount = 0;
let secondaryDetectionCount = 0;
for (const detection of detections) {
const detectionFields = detection.split('|');
const detectionClass = (detectionFields[5] || 'Unknown').trim();
const inferenceData = {
[ModuleInfoFieldIds.Telemetry.Inference]: {
cameraId,
trackingId: detectionFields[0] || 'Unknown',
className: detectionClass,
roi: {
left: Number(detectionFields[1] || 0),
top: Number(detectionFields[2] || 0),
right: Number(detectionFields[3] || 0),
bottom: Number(detectionFields[4] || 0)
}
}
};
if (detectionClass.toUpperCase() === this.detectionSettings.wpPrimaryDetectionClass.toUpperCase()) {
++primaryDetectionCount;
await this.sendInferenceData(inferenceData);
}
else if (detectionClass.toUpperCase() === this.detectionSettings.wpSecondaryDetectionClass.toUpperCase()) {
++secondaryDetectionCount;
await this.sendInferenceData(inferenceData);
}
}
if (primaryDetectionCount > 0) {
await this.sendMeasurement({
[ModuleInfoFieldIds.Telemetry.PrimaryDetectionCount]: primaryDetectionCount
});
}
if (secondaryDetectionCount > 0) {
await this.sendMeasurement({
[ModuleInfoFieldIds.Telemetry.SecondaryDetectionCount]: secondaryDetectionCount
});
}
}
@bind
// @ts-ignore (commandRequest)
private async iotcClientRestartDeepStream(commandRequest: DeviceMethodRequest, commandResponse: DeviceMethodResponse) {
this.logger.log(['IoTCentralService', 'info'], `${ModuleInfoFieldIds.Command.RestartDeepStream} command received`);
try {
await commandResponse.send(200);
}
catch (ex) {
this.logger.log(['IoTCentralService', 'error'], `Error sending response for ${ModuleInfoFieldIds.Command.RestartDeepStream} command: ${ex.message}`);
}
await this.server.methods.device.restartDeepStream();
}
@bind
// @ts-ignore (commandResponse)
private async iotcClientRestartDevice(commandRequest: DeviceMethodRequest, commandResponse: DeviceMethodResponse) {
this.logger.log(['IoTCentralService', 'info'], `${ModuleInfoFieldIds.Command.RestartDevice} command received`);
try {
await commandResponse.send(200);
}
catch (ex) {
this.logger.log(['IoTCentralService', 'error'], `Error sending response for ${ModuleInfoFieldIds.Command.RestartDevice} command: ${ex.message}`);
}
const timeout = _get(commandRequest, `payload.${RestartDeviceCommandParams.Timeout}`);
await this.server.methods.device.restartDevice(timeout, 'RestartDevice command received');
}
@bind
private onIotcClientError(error: Error) {
this.logger.log(['IoTCentralService', 'error'], `Client connection error: ${error.message}`);
this.healthState = HealthState.Critical;
}
} | the_stack |
import * as _ from 'lodash';
import * as parseType from 'strapi-utils/lib/parse-type';
import { DocumentReference, FieldValue, Timestamp } from '@google-cloud/firestore';
import type { FirestoreConnectorModel } from '../model';
import { DeepReference } from '../db/deep-reference';
import { FlatReferenceShape, MorphReferenceShape, Reference } from '../db/reference';
import { StatusError } from '../utils/status-error';
import type { StrapiAttribute } from '../types';
import { getComponentModel } from '../utils/components';
import { MorphReference } from '../db/morph-reference';
import { updateComponentsMetadata } from '../utils/components-indexing';
import { NormalReference } from '../db/normal-reference';
import { FieldOperation } from '../db/field-operation';
import { VirtualReference } from '../db/virtual-reference';
export class CoercionError extends StatusError {
constructor(message: string) {
super(message, 400);
}
}
export interface CoerceOpts {
editMode?: 'create' | 'update'
timestamp?: Date
}
/**
* Attempts to coerce the data to the correct types based on the
* given model schema, builds `Reference` instances for relations, and generates
* index metadata for components.
*
* Designed to both coerce from user input, or rehydrate from Firestore.
*/
export function coerceToModel<T extends object>(model: FirestoreConnectorModel<T>, id: string | undefined, data: unknown, fieldPath: string | null | undefined, opts: CoerceOpts): T {
const obj = coerceModelRecursive(model, data, fieldPath, opts);
// If fieldPath is provided then this is a partial update map
// and this is not the root object
if (!fieldPath) {
// Set the document ID
if (id) {
_.set(obj, model.primaryKey, id);
}
// Assign timestamps
if (model.timestamps && opts.editMode) {
const now = opts.timestamp || new Date();
const [createdAtKey, updatedAtKey] = model.timestamps;
_.set(obj, updatedAtKey, now);
if (opts.editMode === 'create') {
_.set(obj, createdAtKey, now);
} else {
_.unset(obj, createdAtKey);
}
}
// Generate metadata only for edits (to Firestore)
if (opts.editMode) {
updateComponentsMetadata(model, obj);
}
}
return obj;
}
function fallbackCoerceOrCopy(value: any, opts: CoerceOpts): any {
const result = coerceAttrToModel(undefined, value, opts);
if (result === value) {
// If coercion returned the same object then we return undefined
// to that cloneDeepWith handles the copying
// We need this in order to copy root object etc
return undefined;
}
return result;
}
function coerceModelRecursive<T extends object>(model: FirestoreConnectorModel<T>, data: unknown, parentPath: string | null | undefined, opts: CoerceOpts) {
return _.cloneDeepWith(data, (value, key) => {
const path = [parentPath, key].filter(Boolean).join('.');
if (!path) {
// Root object, pass through
// Perform basic coercion
// E.g. this handles document-level FieldOperation.delete()
// for flattened collections
return fallbackCoerceOrCopy(value, opts);
}
const attr = model.attributes[path];
if (!attr && _.isPlainObject(value)) {
if (key) {
return coerceModelRecursive(model, value, path, opts);
} else {
// Stop infinite recursion
// Perform basic coercion of necessary types
return fallbackCoerceOrCopy(value, opts);
}
}
return coerceAttrToModel(attr, value, opts);
});
}
/**
* Coerces a given attribute value to out of the value stored in Firestore to the
* value expected by the given attribute schema.
*/
export function coerceAttrToModel(attr: StrapiAttribute | undefined, value: unknown, opts: CoerceOpts): unknown {
if (Array.isArray(value) && attr?.isMeta) {
// Meta attributes are arrays, so we need to coerce the value recursively
return value.map(v => coerceAttrToModel(attr, v, opts));
}
// Coerce values inside FieldOperation
if (value instanceof FieldOperation) {
return value.coerceWith(v => coerceAttrToModel(attr, v, opts));
}
// Cannot operate on FieldValue
if (value instanceof FieldValue) {
strapi.log.warn(
'Cannot coerce instances of FieldValue, which may result in incorrect data types being ' +
'written to Firestore. Recommend to use FieldOperation equivalent instead.'
);
return value;
}
// Firestore returns Timestamp for all Date values
if (value instanceof Timestamp) {
return value.toDate();
}
// Restore number fields back
// Because Firestore returns BigInt for all integer values
// Do this by default for all BigInt unless the attribute is specifically a BigInt
// BigInt fields will come out as native BigInt but will be serialised to JSON as a string
if ((typeof value === 'bigint') && (!attr || (attr.type !== 'biginteger'))) {
return Number(value);
}
// Don't coerce unknown fields further
if (!attr) {
return value;
}
// Allow null or undefined on any type
if ((value === null) || (value === undefined)) {
return value;
}
// Recursively coerce components
// type == 'component'
if (attr.component) {
const componentModel = getComponentModel(attr.component);
if (Array.isArray(value)) {
// Generate ID if setting dictates
return value.map(v => coerceToModel(componentModel, getIdOrAuto(componentModel, v), v, null, opts));
} else {
if (value) {
if (typeof value !== 'object') {
return fault(opts, 'Invalid value provided. Component must be an array or an object.');
}
// Generate ID if setting dictates
return coerceToModel(componentModel, getIdOrAuto(componentModel, value), value!, null, opts);
} else {
return null;
}
}
}
// Recursively coerce dynamiczone
// type == 'dynamiczone'
if (attr.components) {
if (Array.isArray(value)) {
return value.map(v => {
// Generate ID if setting dictates
const componentModel = getComponentModel(v.__component);
return coerceToModel(componentModel, getIdOrAuto(componentModel, v), v, null, opts);
});
} else {
if (value) {
if (typeof value !== 'object') {
return fault(opts, 'Invalid value provided. Component must be an array or an object.');
}
// Generate ID if setting dictates
const componentModel = getComponentModel((value as any).__component);
return coerceToModel(componentModel, getIdOrAuto(componentModel, value), value!, null, opts);
} else {
return null;
}
}
}
if (attr.type) {
const v = value;
const err = () => fault(opts, `Invalid value provided. Could not coerce to type "${attr.type}" from value "${v}".`);
switch (attr.type) {
case 'integer':
case 'float':
case 'decimal':
if (typeof value !== 'number') {
value = Number(value);
if (Number.isNaN(value)) {
return err();
}
}
break;
case 'biginteger':
if (typeof value !== 'bigint') {
try {
value = BigInt(value as any);
} catch {
return err();
}
}
break;
case 'string':
case 'text':
case 'richtext':
case 'email':
case 'password':
case 'enumeration':
case 'uid':
if (typeof value !== 'string') {
value = (value as any)?.toString();
}
break;
case 'json':
try {
value = ((typeof value === 'string') && value.startsWith('{'))
? JSON.parse(value)
: value;
} catch {
return err();
}
break;
case 'boolean':
case 'date':
case 'time':
case 'datetime':
case 'timestamp':
default:
// These types can be handled by built-in Strapi utils
value = parseType({ type: attr.type, value });
break;
}
} else {
// Convert reference ID to document reference if it is one
const target = attr.model || attr.collection;
if (target) {
const assocModel = strapi.db.getModel(target, attr.plugin);
if (assocModel) {
// Convert DeepReference instances to a string value
// that can be serialised to Firestore
if (Array.isArray(value)) {
value = value.map(v => {
return coerceToReference(v, assocModel, opts);
});
} else {
return coerceToReference(value, assocModel, opts);
}
}
}
}
// References will come out as references unchanged
// but will be serialised to JSON as path string value
// Strings will come out as strings unchanged
// Arrays will come out as arrays
return value;
}
/**
* Coerces a value to a `Reference` if it is one.
*/
function coerceToReference<T extends object = object>(value: any, to: FirestoreConnectorModel<T> | undefined, opts: CoerceOpts): Reference<T> | null {
if ((value === undefined) || (value === null)) {
return null;
}
if (value instanceof Reference) {
return value;
}
if (value instanceof DocumentReference) {
// When deserialised from Firestore it comes without any converters
// We want to get the appropriate converters so we reinstantiate it
return reinstantiateReference(value, undefined, to, opts);
}
if ((typeof value === 'object')
&& ('ref' in value)
&& (value.ref instanceof DocumentReference)) {
// Coerce from ReferenceShape
// i.e. the Firestore representation of DeepReference and MorphReference
const obj: FlatReferenceShape<T> | MorphReferenceShape<T> = value;
let id: string | undefined
if ('id' in obj) {
if (!obj.id || (typeof obj.id !== 'string')) {
return fault(opts, 'Malformed polymorphic reference: `id` must be a string');
}
id = obj.id;
}
const ref = reinstantiateReference(obj.ref, id, to, opts);
if (!ref) {
return ref;
}
if ('filter' in obj) {
if ((obj.filter !== null) && (!obj.filter || (typeof obj.filter !== 'string'))) {
return fault(opts, 'Malformed polymorphic reference: `filter` must be a string');
}
return new MorphReference(ref, obj.filter);
} else {
return ref;
}
}
if (typeof value === 'object') {
// Coerce from the incoming Strapi API representation of
// morph references
// This isn't really documented
const {
ref: targetModelName,
source: plugin,
refId: id,
field,
} = value;
if ((typeof targetModelName === 'string')
&& (typeof id === 'string')
&& (!plugin || (typeof plugin === 'string'))
&& (!field || (typeof field === 'string'))) {
const targetModel = strapi.db.getModel(targetModelName, plugin);
if (!targetModel) {
return fault(opts, `The model "${targetModelName}" with plugin "${plugin}" in polymorphic relation could not be found`)
}
return new MorphReference(targetModel.db.doc(id), field);
}
}
const path: string = (typeof value === 'string')
? value
: (to ? to.getPK(value) : value.id);
if (path && (typeof path === 'string')) {
const lastSep = path.lastIndexOf('/');
if (lastSep === -1) {
// No path separators so it is just an ID
if (to) {
return to.db.doc(path);
} else {
return fault(opts, `Polymorphic reference must be fully qualified. Got the ID segment only.`);
}
}
// TODO:
// Remove this string parsing behaviour before stable release
// DeepReference is no longer serialised to string
// this is for alpha support only
// It must be an absolute deep reference path
// Verify that the path actually refers to the target model
const id = path.slice(lastSep + 1);
if (id) {
if (to) {
const deepRef = to.db.doc(id);
if (deepRef.path !== _.trim(path, '/')) {
return fault(opts, `Reference is pointing to the wrong model. Expected "${deepRef.path}", got "${id}".`);
}
return deepRef;
} else {
const collection = _.trim(path.slice(0, lastSep), '/');
const model = strapi.db.getModelByCollectionName(collection);
if (!model) {
return fault(opts, `The model referred to by "${collection}" doesn't exist`);
}
return model.db.doc(id);
}
}
}
return fault(opts, `Value could not be coerced to a reference: "${JSON.stringify(value)}"`);
}
/**
* When deserialised from Firestore, references comes without any converters.
* Re-instantiates the reference via the target model so that it comes
* loaded with the appropriate converter.
*/
function reinstantiateReference<T extends object>(value: DocumentReference<T | { [id: string]: T }>, id: string | undefined, to: FirestoreConnectorModel<T> | undefined, opts: CoerceOpts): NormalReference<T> | DeepReference<T> | VirtualReference<T> | null {
if (to) {
const newRef = to.db.doc(id || value.id);
if (newRef.parent.path !== value.parent.path) {
return fault(opts, `Reference is pointing to the wrong model. Expected "${newRef.path}", got "${value.path}".`);
}
return newRef;
} else {
const model = strapi.db.getModelByCollectionName(value.parent.path);
if (!model) {
return fault(opts, `The model referred to by "${value.parent.path}" doesn't exist`);
}
return model.db.doc(value.id);
}
}
function getIdOrAuto(model: FirestoreConnectorModel, value: any): string | undefined {
if (model.options.ensureComponentIds) {
// Ensure there is a guaranteed ID
return _.get(value, model.primaryKey) || model.db.autoId();
} else {
// Don't delete it if it already exists
return _.get(value, model.primaryKey);
}
}
function fault({ editMode }: CoerceOpts, message: string): null {
if (editMode) {
throw new CoercionError(message);
} else {
strapi.log.warn(message);
return null;
}
} | the_stack |
import { TypeAssertion,
ObjectAssertion,
AdditionalPropsMember,
ValidationContext,
ErrorMessages } from '../types';
import { validate,
getType } from '../validator';
import { compile } from '../compiler';
import { serialize,
deserialize } from '../serializer';
describe("compiler-8", function() {
const myMessages: ErrorMessages = {
invalidDefinition: ':invalidDefinition: %{name} %{parentType}',
required: ':required: %{name} %{parentType}',
typeUnmatched: ':typeUnmatched: %{name} %{parentType} %{expectedType}',
additionalPropUnmatched: ':additionalPropUnmatched %{name} %{parentType}',
repeatQtyUnmatched: ':repeatQtyUnmatched: %{name} %{parentType} %{repeatQty}',
sequenceUnmatched: ':sequenceUnmatched: %{name} %{parentType}',
valueRangeUnmatched: ':valueRangeUnmatched: %{name} %{parentType} %{minValue} %{maxValue}',
valuePatternUnmatched: ':valuePatternUnmatched: %{name} %{parentType} %{pattern}',
valueLengthUnmatched: ':valueLengthUnmatched: %{name} %{parentType} %{minLength} %{maxLength}',
valueUnmatched: ':valueUnmatched: %{name} %{parentType} %{expectedValue}',
};
function mkmsgobj(s: string): ErrorMessages {
const m: ErrorMessages = {
invalidDefinition: s + myMessages.invalidDefinition,
required: s + myMessages.required,
typeUnmatched: s + myMessages.typeUnmatched,
repeatQtyUnmatched: s + myMessages.repeatQtyUnmatched,
sequenceUnmatched: s + myMessages.sequenceUnmatched,
valueRangeUnmatched: s + myMessages.valueRangeUnmatched,
valuePatternUnmatched: s + myMessages.valuePatternUnmatched,
valueLengthUnmatched: s + myMessages.valueLengthUnmatched,
valueUnmatched: s + myMessages.valueUnmatched,
};
return m;
}
function mkmsg(s: string): string {
return JSON.stringify(mkmsgobj(s));
}
it("compiler-error-reporting-reporter-2-1", function() {
// no tests (single type test pattern of compiler-error-reporting-reporter-1-1)
});
it("compiler-error-reporting-reporter-2-2", function() {
const schemas = [compile(`
@msg(${mkmsg('A')})
export type A = string;
`), compile(`
export type A = @msg(${mkmsg('A')}) string;
`)];
for (const schema of schemas) {
const ctx: Partial<ValidationContext> = {
checkAll: true,
schema,
};
expect(validate(1, getType(schema, 'A'), ctx)).toEqual(null);
expect(ctx.errors).toEqual([{
code: 'TypeUnmatched',
message: 'A:typeUnmatched: ? A string',
dataPath: 'A',
constraints: {},
value: 1,
}]);
}
});
it("compiler-error-reporting-reporter-2-2b", function() {
const schemas = [compile(`
@msg(${mkmsg('A')})
export type A = string;
`), compile(`
export type A = @msg(${mkmsg('A')}) string;
`)];
for (const schema of schemas) {
const ctx: Partial<ValidationContext> = {
checkAll: true,
schema,
};
expect(validate([1], getType(schema, 'A'), ctx)).toEqual(null);
expect(ctx.errors).toEqual([{
code: 'TypeUnmatched',
message: 'A:typeUnmatched: ? A string', // TODO:
dataPath: 'A',
constraints: {},
}]);
}
});
it("compiler-error-reporting-reporter-2-2c", function() {
const schemas = [compile(`
@msg(${mkmsg('A')})
export type A = string[];
`), compile(`
export type A = @msg(${mkmsg('A')}) (string[]);
`)];
for (const schema of schemas) {
const ctx: Partial<ValidationContext> = {
checkAll: true,
schema,
};
expect(validate('1', getType(schema, 'A'), ctx)).toEqual(null);
expect(ctx.errors).toEqual([{
code: 'TypeUnmatched',
message: 'A:typeUnmatched: ? A (repeated string)', // TODO:
dataPath: 'A',
constraints: {},
value: '1',
}]);
}
});
it("compiler-error-reporting-reporter-2-2d", function() {
const schemas = [compile(`
@msg(${mkmsg('A')})
export type A = string[];
`), compile(`
export type A = @msg(${mkmsg('A')}) (string[]);
`)];
for (const schema of schemas) {
const ctx: Partial<ValidationContext> = {
checkAll: true,
schema,
};
expect(validate([1], getType(schema, 'A'), ctx)).toEqual(null);
expect(ctx.errors).toEqual([{
code: 'TypeUnmatched',
message: '"repeated item of ?" of "A" should be type "string".', // TODO: custom error message is ignored
dataPath: 'A.(0:repeated)',
constraints: {},
value: 1,
}]);
}
});
it("compiler-error-reporting-reporter-2-2e", function() {
const schemas = [compile(`
@msg(${mkmsg('A')})
export type A = [string];
`), compile(`
export type A = @msg(${mkmsg('A')}) [string];
`)];
for (const schema of schemas) {
const ctx: Partial<ValidationContext> = {
checkAll: true,
schema,
};
expect(validate('1', getType(schema, 'A'), ctx)).toEqual(null);
expect(ctx.errors).toEqual([{
code: 'TypeUnmatched',
message: 'A:typeUnmatched: ? A (sequence)', // TODO:
dataPath: 'A',
constraints: {},
value: '1',
}]);
}
});
it("compiler-error-reporting-reporter-2-2f", function() {
const schemas = [compile(`
@msg(${mkmsg('A')})
export type A = [string];
`), compile(`
export type A = @msg(${mkmsg('A')}) [string];
`)];
for (const schema of schemas) {
const ctx: Partial<ValidationContext> = {
checkAll: true,
schema,
};
expect(validate([1], getType(schema, 'A'), ctx)).toEqual(null);
expect(ctx.errors).toEqual([{
code: 'TypeUnmatched',
message: '"sequence item of ?" of "A" should be type "string".', // TODO: custom error message is ignored
dataPath: 'A.(0:sequence)',
constraints: {},
value: 1,
}]);
}
});
it("compiler-error-reporting-reporter-2-3", function() {
const schemas = [compile(`
@msg(${mkmsg('A')})
export type A =
@range(3, 5)
number;
`), compile(`
export type A =
@msg(${mkmsg('A')})
@range(3, 5)
number;
`)];
for (const schema of schemas) {
const ctx: Partial<ValidationContext> = {
checkAll: true,
schema,
};
expect(validate(1, getType(schema, 'A'), ctx)).toEqual(null);
expect(ctx.errors).toEqual([{
code: 'ValueRangeUnmatched',
message: 'A:valueRangeUnmatched: ? A 3 5', // TODO:
dataPath: 'A',
constraints: {minValue: 3, maxValue: 5},
value: 1,
}]);
}
});
it("compiler-error-reporting-reporter-2-4", function() {
const schemas = [compile(`
@msg(${mkmsg('A')})
export type A =
@minLength(3) @maxLength(5)
string;
`), compile(`
export type A =
@msg(${mkmsg('A')})
@minLength(3) @maxLength(5)
string;
`)];
for (const schema of schemas) {
const ctx: Partial<ValidationContext> = {
checkAll: true,
schema,
};
expect(validate('1', getType(schema, 'A'), ctx)).toEqual(null);
expect(ctx.errors).toEqual([{
code: 'ValueLengthUnmatched',
message: 'A:valueLengthUnmatched: ? A 3 5',
dataPath: 'A',
constraints: {minLength: 3, maxLength: 5},
value: '1',
}]);
}
});
it("compiler-error-reporting-reporter-2-5", function() {
const schemas = [compile(`
@msg(${mkmsg('A')})
export type A =
@match(/^[0-9]+$/)
string;
`), compile(`
export type A =
@msg(${mkmsg('A')})
@match(/^[0-9]+$/)
string;
`)];
for (const schema of schemas) {
for (const ty of [getType(deserialize(serialize(schema)), 'A'), getType(schema, 'A')]) {
const ctx: Partial<ValidationContext> = {
checkAll: true,
schema,
};
expect(validate('A', ty, ctx)).toEqual(null);
expect(ctx.errors).toEqual([{
code: 'ValuePatternUnmatched',
message: 'A:valuePatternUnmatched: ? A /^[0-9]+$/',
dataPath: 'A',
constraints: {pattern: '/^[0-9]+$/'},
value: 'A',
}]);
}
}
});
it("compiler-error-reporting-reporter-2-5b", function() {
const schemas = [compile(`
@msg(${mkmsg('A')})
export type A =
@match(/^[0-9]+$/gi)
string;
`), compile(`
export type A =
@msg(${mkmsg('A')})
@match(/^[0-9]+$/gi)
string;
`)];
for (const schema of schemas) {
for (const ty of [getType(deserialize(serialize(schema)), 'A'), getType(schema, 'A')]) {
const ctx: Partial<ValidationContext> = {
checkAll: true,
schema,
};
expect(validate('A', ty, ctx)).toEqual(null);
expect(ctx.errors).toEqual([{
code: 'ValuePatternUnmatched',
message: 'A:valuePatternUnmatched: ? A /^[0-9]+$/gi',
dataPath: 'A',
constraints: {pattern: '/^[0-9]+$/gi'},
value: 'A',
}]);
}
}
});
it("compiler-error-reporting-reporter-2-6", function() {
const schemas = [compile(`
@msg(${mkmsg('A')})
export type A =
5;
`), compile(`
export type A =
@msg(${mkmsg('A')})
5;
`)];
for (const schema of schemas) {
const ctx: Partial<ValidationContext> = {
checkAll: true,
schema,
};
expect(validate(4, getType(schema, 'A'), ctx)).toEqual(null);
expect(ctx.errors).toEqual([{
code: 'ValueUnmatched',
message: 'A:valueUnmatched: ? A 5',
dataPath: 'A',
constraints: {},
value: 4,
}]);
}
});
it("compiler-error-reporting-reporter-2-7a", function() {
const schemas = [compile(`
@msg(${mkmsg('A')})
export type A =
[...<string,3..5>];
`), compile(`
export type A =
@msg(${mkmsg('A')})
[...<string,3..5>];
`)];
for (const schema of schemas) {
const ctx: Partial<ValidationContext> = {
checkAll: true,
schema,
};
expect(validate([1], getType(schema, 'A'), ctx)).toEqual(null);
expect(ctx.errors).toEqual([{
code: 'TypeUnmatched', // TODO: expect SequenceUnmatched?
message: '"sequence item of ?" of "A" should be type "string".', // TODO: custom error message is ignored
dataPath: 'A.(0:sequence)',
constraints: {min: 3, max: 5},
}]);
}
});
it("compiler-error-reporting-reporter-2-7b", function() {
const schemas = [compile(`
@msg(${mkmsg('A')})
export type A =
[...<string,3..5>];
`), compile(`
export type A =
@msg(${mkmsg('A')})
[...<string,3..5>];
`)];
for (const schema of schemas) {
const ctx: Partial<ValidationContext> = {
checkAll: true,
schema,
};
expect(validate(['1', '2'], getType(schema, 'A'), ctx)).toEqual(null);
expect(ctx.errors).toEqual([{
code: 'RepeatQtyUnmatched',
message: '"sequence item of ?" of "A" should repeat 3..5 times.', // TODO: custom error message is ignored
dataPath: 'A.(2:sequence)',
constraints: {min: 3, max: 5},
}]);
}
});
it("compiler-error-reporting-reporter-2-7c", function() {
const schemas = [compile(`
@msg(${mkmsg('A')})
export type A =
[string?];
`), compile(`
export type A =
@msg(${mkmsg('A')})
[string?];
`)];
for (const schema of schemas) {
const ctx: Partial<ValidationContext> = {
checkAll: true,
schema,
};
expect(validate([1], getType(schema, 'A'), ctx)).toEqual(null);
expect(ctx.errors).toEqual([{
code: 'SequenceUnmatched',
message: 'A:sequenceUnmatched: ? A',
dataPath: 'A',
constraints: {},
}]);
}
});
it("compiler-error-reporting-reporter-2-7d", function() {
const schemas = [compile(`
@msg(${mkmsg('A')})
export type A =
[string?];
`), compile(`
export type A =
@msg(${mkmsg('A')})
[string?];
`)];
for (const schema of schemas) {
const ctx: Partial<ValidationContext> = {
checkAll: true,
schema,
};
expect(validate(['1', '2'], getType(schema, 'A'), ctx)).toEqual(null);
expect(ctx.errors).toEqual([{
code: 'RepeatQtyUnmatched',
message: '"sequence item of ?" of "A" should repeat 0..1 times.', // TODO: custom error message is ignored
dataPath: 'A.(2:sequence)',
constraints: {},
}]);
}
});
it("compiler-error-reporting-reporter-3", function() {
const schemas = [compile(`
export type A = string;
`)];
for (const schema of schemas) {
const ctx: Partial<ValidationContext> = {
checkAll: true,
schema,
errorMessages: mkmsgobj('G'),
};
expect(validate(1, getType(schema, 'A'), ctx)).toEqual(null);
expect(ctx.errors).toEqual([{
code: 'TypeUnmatched',
message: 'G:typeUnmatched: ? A string',
dataPath: 'A',
constraints: {},
value: 1,
}]);
}
});
}); | the_stack |
module es {
/**
* 类,它可以计算出一个网格,表示从给定的一组遮挡物的原点可以看到哪些区域。使用方法如下。
*
* - 调用 begin
* - 添加任何遮挡物
* - 调用end来获取可见度多边形。当调用end时,所有的内部存储都会被清空。
*/
export class VisibilityComputer {
/**
* 在近似圆的时候要用到的线的总数。只需要一个180度的半球,所以这将是近似该半球的线段数
*/
public lineCountForCircleApproximation: number = 10;
public _radius: number = 0;
public _origin: Vector2 = Vector2.zero;
public _isSpotLight: boolean = false;
public _spotStartAngle: number = 0;
public _spotEndAngle: number = 0;
public _endPoints: EndPoint[] = [];
public _segments: Segment[] = [];
public _radialComparer: EndPointComparer;
public static _cornerCache: Vector2[] = [];
public static _openSegments: LinkedList<Segment> = new LinkedList<Segment>();
constructor(origin?: Vector2, radius?: number){
this._origin = origin;
this._radius = radius;
this._radialComparer = new EndPointComparer();
}
/**
* 增加了一个对撞机作为PolyLight的遮蔽器
* @param collider
*/
public addColliderOccluder(collider: Collider) {
// 特殊情况下,BoxColliders没有旋转
if (collider instanceof BoxCollider && collider.rotation == 0) {
this.addSquareOccluder(collider.bounds);
return;
}
if (collider instanceof PolygonCollider) {
let poly = collider.shape as Polygon;
for (let i = 0; i < poly.points.length; i ++) {
let firstIndex = i - 1;
if (i == 0)
firstIndex += poly.points.length;
this.addLineOccluder(Vector2.add(poly.points[firstIndex], poly.position),
Vector2.add(poly.points[i], poly.position));
}
} else if(collider instanceof CircleCollider) {
this.addCircleOccluder(collider.absolutePosition, collider.radius);
}
}
/**
* 增加了一个圆形的遮挡器
* @param position
* @param radius
*/
public addCircleOccluder(position: Vector2, radius: number){
let dirToCircle = position.sub(this._origin);
let angle = Math.atan2(dirToCircle.y, dirToCircle.x);
let stepSize = Math.PI / this.lineCountForCircleApproximation;
let startAngle = angle + MathHelper.PiOver2;
let lastPt = MathHelper.angleToVector(startAngle, radius).addEqual(position);
for (let i = 1; i < this.lineCountForCircleApproximation; i ++) {
let nextPt = MathHelper.angleToVector(startAngle + i * stepSize, radius).addEqual(position);
this.addLineOccluder(lastPt, nextPt);
lastPt = nextPt;
}
}
/**
* 增加一个线型遮挡器
* @param p1
* @param p2
*/
public addLineOccluder(p1: Vector2, p2: Vector2) {
this.addSegment(p1, p2);
}
/**
* 增加一个方形的遮挡器
* @param bounds
*/
public addSquareOccluder(bounds: Rectangle) {
let tr = new Vector2(bounds.right, bounds.top);
let bl = new Vector2(bounds.left, bounds.bottom);
let br = new Vector2(bounds.right, bounds.bottom);
this.addSegment(bounds.location, tr);
this.addSegment(tr, br);
this.addSegment(br, bl);
this.addSegment(bl, bounds.location);
}
/**
* 添加一个段,第一个点在可视化中显示,但第二个点不显示。
* 每个端点都是两个段的一部分,但我们希望只显示一次
* @param p1
* @param p2
*/
public addSegment(p1: Vector2, p2: Vector2) {
let segment = new Segment();
let endPoint1 = new EndPoint();
let endPoint2 = new EndPoint();
endPoint1.position = p1;
endPoint1.segment = segment;
endPoint2.position = p2;
endPoint2.segment = segment;
segment.p1 = endPoint1;
segment.p2 = endPoint2;
this._segments.push(segment);
this._endPoints.push(endPoint1);
this._endPoints.push(endPoint2);
}
/**
* 移除所有的遮挡物
*/
public clearOccluders(){
this._segments.length = 0;
this._endPoints.length = 0;
}
/**
* 为计算机计算当前的聚光做好准备
* @param origin
* @param radius
*/
public begin(origin: Vector2, radius: number){
this._origin = origin;
this._radius = radius;
this._isSpotLight = false;
}
/**
* 计算可见性多边形,并返回三角形扇形的顶点(减去中心顶点)。返回的数组来自ListPool
*/
public end(): Vector2[] {
let output = ListPool.obtain<Vector2>(Vector2);
this.updateSegments();
this._endPoints.sort(this._radialComparer.compare);
let currentAngle = 0;
// 在扫描开始时,我们想知道哪些段是活动的。
// 最简单的方法是先进行一次段的收集,然后再进行一次段的收集和处理。
// 然而,更有效的方法是通过所有的段,找出哪些段与最初的扫描线相交,然后对它们进行分类
for (let pass = 0; pass < 2; pass ++) {
for (let p of this._endPoints) {
let currentOld = VisibilityComputer._openSegments.size() == 0 ? null : VisibilityComputer._openSegments.getHead().element;
if (p.begin) {
// 在列表中的正确位置插入
let node = VisibilityComputer._openSegments.getHead();
while (node != null && this.isSegmentInFrontOf(p.segment, node.element, this._origin))
node = node.next;
if (node == null)
VisibilityComputer._openSegments.push(p.segment);
else
VisibilityComputer._openSegments.insert(p.segment, VisibilityComputer._openSegments.indexOf(node.element));
} else {
VisibilityComputer._openSegments.remove(p.segment);
}
let currentNew = null;
if (VisibilityComputer._openSegments.size() != 0)
currentNew = VisibilityComputer._openSegments.getHead().element;
if (currentOld != currentNew) {
if (pass == 1) {
if (!this._isSpotLight || (VisibilityComputer.between(currentAngle, this._spotStartAngle, this._spotEndAngle) &&
VisibilityComputer.between(p.angle, this._spotStartAngle, this._spotEndAngle)))
this.addTriangle(output, currentAngle, p.angle, currentOld);
}
currentAngle = p.angle;
}
}
}
VisibilityComputer._openSegments.clear();
this.clearOccluders();
return output;
}
public addTriangle(triangles: Vector2[], angle1: number, angle2: number, segment: Segment) {
let p1 = this._origin.clone();
let p2 = new Vector2(this._origin.x + Math.cos(angle1), this._origin.y + Math.sin(angle1));
let p3 = Vector2.zero;
let p4 = Vector2.zero;
if (segment != null){
// 将三角形停在相交线段上
p3.x = segment.p1.position.x;
p3.y = segment.p1.position.y;
p4.x = segment.p2.position.x;
p4.y = segment.p2.position.y;
} else {
p3.x = this._origin.x + Math.cos(angle1) * this._radius * 2;
p3.y = this._origin.y + Math.sin(angle1) * this._radius * 2;
p4.x = this._origin.x + Math.cos(angle2) * this._radius * 2;
p4.y = this._origin.y + Math.sin(angle2) * this._radius * 2;
}
let pBegin = VisibilityComputer.lineLineIntersection(p3, p4, p1, p2);
p2.x = this._origin.x + Math.cos(angle2);
p2.y = this._origin.y + Math.sin(angle2);
let pEnd = VisibilityComputer.lineLineIntersection(p3, p4, p1, p2);
triangles.push(pBegin);
triangles.push(pEnd);
}
/**
* 计算直线p1-p2与p3-p4的交点
* @param p1
* @param p2
* @param p3
* @param p4
*/
public static lineLineIntersection(p1: Vector2, p2: Vector2, p3: Vector2, p4: Vector2){
let s = ((p4.x - p3.x) * (p1.y - p3.y) - (p4.y - p3.y) * (p1.x - p3.x))
/ ((p4.y - p3.y) * (p2.x - p1.x) - (p4.x - p3.x) * (p2.y - p1.y));
return new Vector2(p1.x + s * (p2.x - p1.x), p1.y + s * (p2.y - p1.y));
}
public static between(value: number, min: number, max: number) {
value = (360 + (value % 360)) % 360;
min = (3600000 + min) % 360;
max = (3600000 + max) % 360;
if (min < max)
return min <= value && value <= max;
return min <= value || value <= max;
}
/**
* 辅助函数,用于沿外周线构建分段,以限制光的半径。
*/
public loadRectangleBoundaries(){
this.addSegment(new Vector2(this._origin.x - this._radius, this._origin.y - this._radius),
new Vector2(this._origin.x + this._radius, this._origin.y - this._radius));
this.addSegment(new Vector2(this._origin.x - this._radius, this._origin.y + this._radius),
new Vector2(this._origin.x + this._radius, this._origin.y + this._radius));
this.addSegment(new Vector2(this._origin.x - this._radius, this._origin.y - this._radius),
new Vector2(this._origin.x - this._radius, this._origin.y + this._radius));
this.addSegment(new Vector2(this._origin.x + this._radius, this._origin.y - this._radius),
new Vector2(this._origin.x + this._radius, this._origin.y + this._radius));
}
/**
* 助手:我们知道a段在b的前面吗?实现不反对称(也就是说,isSegmentInFrontOf(a, b) != (!isSegmentInFrontOf(b, a)))。
* 另外要注意的是,在可见性算法中,它只需要在有限的一组情况下工作,我不认为它能处理所有的情况。
* 见http://www.redblobgames.com/articles/visibility/segment-sorting.html
* @param a
* @param b
* @param relativeTo
*/
public isSegmentInFrontOf(a: Segment, b: Segment, relativeTo: Vector2) {
// 注意:我们稍微缩短了段,所以在这个算法中,端点的交点(共同)不计入交点。
let a1 = VisibilityComputer.isLeftOf(a.p2.position, a.p1.position, VisibilityComputer.interpolate(b.p1.position, b.p2.position, 0.01));
let a2 = VisibilityComputer.isLeftOf(a.p2.position, a.p1.position, VisibilityComputer.interpolate(b.p2.position, b.p1.position, 0.01));
let a3 = VisibilityComputer.isLeftOf(a.p2.position, a.p1.position, relativeTo);
let b1 = VisibilityComputer.isLeftOf(b.p2.position, b.p1.position, VisibilityComputer.interpolate(a.p1.position, a.p2.position, 0.01));
let b2 = VisibilityComputer.isLeftOf(b.p2.position, b.p1.position, VisibilityComputer.interpolate(a.p2.position, a.p1.position, 0.01));
let b3 = VisibilityComputer.isLeftOf(b.p2.position, b.p1.position, relativeTo);
// 注:考虑A1-A2这条线。如果B1和B2都在一条边上,而relativeTo在另一条边上,那么A就在观看者和B之间。
if (b1 == b2 && b2 != b3)
return true;
if (a1 == a2 && a2 == a3)
return true;
if (a1 == a2 && a2 != a3)
return false;
if (b1 == b2 && b2 == b3)
return false;
// 如果A1 !=A2,B1 !=B2,那么我们就有一个交点。
// 一个更稳健的实现是在交叉点上分割段,使一部分段在前面,一部分段在后面,但无论如何我们不应该有重叠的碰撞器,所以这不是太重要
return false;
// 注意:以前的实现方式是a.d < b.d.,这比较简单,但当段的大小不一样时,就麻烦了。
// 如果你是在一个网格上,而且段的大小相似,那么使用距离将是一个更简单和更快的实现。
}
/**
* 返回略微缩短的向量:p * (1 - f) + q * f
* @param p
* @param q
* @param f
*/
public static interpolate(p: Vector2, q: Vector2, f: number){
return new Vector2(p.x * (1 - f) + q.x * f, p.y * (1 - f) + q.y * f);
}
/**
* 返回点是否在直线p1-p2的 "左边"。
* @param p1
* @param p2
* @param point
*/
public static isLeftOf(p1: Vector2, p2: Vector2, point: Vector2) {
let cross = (p2.x - p1.x) * (point.y - p1.y)
- (p2.y - p1.y) * (point.x - p1.x);
return cross < 0;
}
/**
* 处理片段,以便我们稍后对它们进行分类
*/
public updateSegments(){
for (let segment of this._segments) {
// 注:未来的优化:我们可以记录象限和y/x或x/y比率,并按(象限、比率)排序,而不是调用atan2。
// 参见<https://github.com/mikolalysenko/compare-slope>,有一个库可以做到这一点
segment.p1.angle = Math.atan2(segment.p1.position.y - this._origin.y, segment.p1.position.x - this._origin.x);
segment.p2.angle = Math.atan2(segment.p2.position.y - this._origin.y, segment.p2.position.x - this._origin.x);
// Pi和Pi之间的映射角度
let dAngle = segment.p2.angle - segment.p1.angle;
if (dAngle <= -Math.PI)
dAngle += Math.PI * 2;
if (dAngle > Math.PI)
dAngle -= Math.PI * 2;
segment.p1.begin = (dAngle > 0);
segment.p2.begin = !segment.p1.begin;
}
// 如果我们有一个聚光灯,我们需要存储前两个段的角度。
// 这些是光斑的边界,我们将用它们来过滤它们之外的任何顶点。
if (this._isSpotLight) {
this._spotStartAngle = this._segments[0].p2.angle;
this._spotEndAngle = this._segments[1].p2.angle;
}
}
}
} | the_stack |
import * as vscode from 'vscode';
import * as path from "path";
import * as child_process from "child_process";
function needShowFormatErr(): boolean {
let formatErrConfig = vscode.workspace.getConfiguration("luahelper.base", null).get("formatErrShow");
var formatErrshow = true;
if (formatErrConfig !== undefined) {
formatErrshow = <boolean><any>formatErrConfig;
}
return formatErrshow;
}
// 获取整型配置参数的字符串值
// itemStr 为配置项的名称
function getFormatIntStr(itemStr: string): string {
let value: number | undefined = vscode.workspace.getConfiguration("luahelper.format", null).get(itemStr);
if (value === undefined) {
return "";
}
itemStr = itemStr.replace(/_/g, "-");
let strResult: string = "--" + itemStr + "=" + String(value);
return strResult;
}
// 获取字符串配置参数的字符串值
// itemStr 为配置项的名称
function getFormatStrStr(itemStr: string): string {
let value: string | undefined = vscode.workspace.getConfiguration("luahelper.format", null).get(itemStr);
if (value === undefined) {
return "";
}
itemStr = itemStr.replace(/_/g, "-");
let strResult: string = "--" + itemStr + "=" + String(value);
return strResult;
}
// 获取bool配置参数的字符串值
// itemStr 为配置项的名称
function getFormatBoolStr(itemStr: string): string {
let value: boolean | undefined = vscode.workspace.getConfiguration("luahelper.format", null).get(itemStr);
if (value === undefined) {
return "";
}
itemStr = itemStr.replace(/_/g, "-");
let strResult: string = "";
if (value) {
strResult = "--" + itemStr;
} else {
strResult = "--no-" + itemStr;
}
return strResult;
}
// 获取格式化配置的参数
function getFormatConfigStrTable(): string[] {
let strAllResult: string[] = [];
let oneStr: string = "";
oneStr = getFormatIntStr("column_limit");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatIntStr("indent_width");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatBoolStr("use_tab");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatIntStr("tab_width");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatIntStr("continuation_indent_width");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatBoolStr("keep_simple_control_block_one_line");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatBoolStr("keep_simple_function_one_line");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatIntStr("spaces_before_call");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatBoolStr("keep_simple_block_one_line");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatBoolStr("align_args");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatBoolStr("break_after_functioncall_lp");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatBoolStr("break_before_functioncall_rp");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatBoolStr("align_parameter");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatBoolStr("chop_down_parameter");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatBoolStr("break_after_functiondef_lp");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatBoolStr("break_before_functiondef_rp");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatBoolStr("align_table_field");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatBoolStr("break_after_table_lb");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatBoolStr("break_before_table_rb");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatBoolStr("chop_down_table");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatBoolStr("chop_down_kv_table");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatStrStr("table_sep");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatBoolStr("extra_sep_at_table_end");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatBoolStr("break_after_operator");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatBoolStr("double_quote_to_single_quote");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatBoolStr("single_quote_to_double_quote");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatBoolStr("spaces_inside_functiondef_parens");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatBoolStr("spaces_inside_functioncall_parens");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatBoolStr("spaces_inside_table_braces");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatBoolStr("spaces_around_equals_in_field");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
oneStr = getFormatIntStr("line_breaks_after_function_body");
if (oneStr !== "") {
strAllResult.push(oneStr);
}
return strAllResult;
}
// 获取luafmt二进制的文件的路径
function GetLuaFmtPath(context: vscode.ExtensionContext): string {
var vscodeRunStr: string = path.resolve(context.extensionPath, "server");
let binaryPath = "";
if (process.platform === "win32") {
binaryPath = path.resolve(vscodeRunStr, "win32", "lua-format");
} else if (process.platform === "darwin") {
binaryPath = path.resolve(vscodeRunStr, "darwin", "lua-format");
} else if (process.platform === "linux") {
binaryPath = path.resolve(vscodeRunStr, "linux", "lua-format");
}
return binaryPath;
}
export class LuaFormatRangeProvider implements vscode.DocumentRangeFormattingEditProvider {
private context: vscode.ExtensionContext;
constructor(context: vscode.ExtensionContext) {
this.context = context;
}
public provideDocumentRangeFormattingEdits(document: vscode.TextDocument, range: vscode.Range, options: vscode.FormattingOptions, token: vscode.CancellationToken): Thenable<vscode.TextEdit[]> {
let data = document.getText();
data = data.substring(document.offsetAt(range.start), document.offsetAt(range.end));
let formatErrshow = needShowFormatErr();
let formatConfigStrTable: string[] = getFormatConfigStrTable();
return new Promise((resolve, reject) => {
let binaryPath = GetLuaFmtPath(this.context);
if (binaryPath === "") {
return;
}
try {
const args = ["-i"];
for (let str of formatConfigStrTable) {
args.push(str);
}
const cmd = child_process.spawn(binaryPath, args, {});
const result: Buffer[] = [], errorMsg: Buffer[] = [];
cmd.on('error', err => {
if (formatErrshow) {
vscode.window.showErrorMessage(`Run lua-format error : '${err.message}'`);
}
reject(err);
});
cmd.stdout.on('data', data => {
result.push(Buffer.from(data));
});
cmd.stderr.on('data', data => {
errorMsg.push(Buffer.from(data));
});
cmd.on('exit', code => {
const resultStr = Buffer.concat(result).toString();
if (code) {
if (formatErrshow) {
vscode.window.showErrorMessage(`Run lua-format failed with exit code: ${code}`);
}
reject(new Error(`Run lua-format failed with exit code: ${code}`));
return;
}
if (resultStr.length > 0) {
resolve([new vscode.TextEdit(range, resultStr)]);
}
});
cmd.stdin.write(data);
cmd.stdin.end();
} catch (e) {
console.log("exception");
}
});
}
}
export class LuaFormatProvider implements vscode.DocumentFormattingEditProvider {
private context: vscode.ExtensionContext;
constructor(context: vscode.ExtensionContext) {
this.context = context;
}
public provideDocumentFormattingEdits(document: vscode.TextDocument, options: vscode.FormattingOptions, token: vscode.CancellationToken): Thenable<vscode.TextEdit[]> {
var data = document.getText();
let formatErrshow = needShowFormatErr();
let formatConfigStrTable: string[] = getFormatConfigStrTable();
return new Promise((resolve, reject) => {
let binaryPath = GetLuaFmtPath(this.context);
if (binaryPath === "") {
return;
}
try {
const args = ["-i"];
for (let str of formatConfigStrTable) {
args.push(str);
}
const cmd = child_process.spawn(binaryPath, args, {});
const result: Buffer[] = [], errorMsg: Buffer[] = [];
cmd.on('error', err => {
if (formatErrshow) {
vscode.window.showErrorMessage(`Run lua-format error : '${err.message}'`);
}
reject(err);
});
cmd.stdout.on('data', data => {
result.push(Buffer.from(data));
});
cmd.stderr.on('data', data => {
errorMsg.push(Buffer.from(data));
});
cmd.on('exit', code => {
const resultStr = Buffer.concat(result).toString();
if (code) {
if (formatErrshow) {
vscode.window.showErrorMessage(`Run lua-format failed with exit code: ${code}`);
}
reject(new Error(`Run lua-format failed with exit code: ${code}`));
return;
}
if (resultStr.length > 0) {
const range = document.validateRange(new vscode.Range(0, 0, Infinity, Infinity));
resolve([new vscode.TextEdit(range, resultStr)]);
}
});
cmd.stdin.write(data);
cmd.stdin.end();
} catch (e) {
console.log("exception");
}
});
}
} | the_stack |
import assert from 'assert';
import GrowableBuffer from './growable_buffer';
import { WILDCARD } from './trie';
export { WILDCARD };
const FILE_HEADER_LENGTH = 6;
enum NodeType {
DATA = 1,
LEAF = 2,
COMPACT = 3,
INTERMEDIATE = 4,
NODE_TYPE_MAX = 4
}
enum NodeFlags {
NONE = 0,
WILDCARD = 8,
}
function writeNodeHeader(buffer : GrowableBuffer, offset : number, nodeType : NodeType, flags = NodeFlags.NONE) {
assert(nodeType >= 0 && nodeType <= NodeType.NODE_TYPE_MAX);
assert((flags & 0b111) === 0);
buffer.writeUInt8(nodeType | flags, offset);
offset++;
return offset;
}
function readNodeHeader(buffer : Buffer, offset : number) {
const header = buffer.readUInt8(offset);
assert((header & 0b111) <= NodeType.NODE_TYPE_MAX);
const nodeType = header & 0b111;
const flags = header & ~0b111;
return { nodeType, flags };
}
class TrieBuilderLeafNode {
value : string|undefined;
private _size : number;
private _dataPtrOffset : number|null;
constructor() {
this.value = undefined;
this._size = 0;
this._dataPtrOffset = null;
}
addValue(value : string, valueCombine : (one : string|undefined, two : string) => string) {
this.value = valueCombine(this.value, value);
assert(typeof this.value === 'string');
this._size ++;
}
get size() {
return this._size;
}
writeKey(buffer : GrowableBuffer, offset : number) {
offset = writeNodeHeader(buffer, offset, NodeType.LEAF);
this._dataPtrOffset = offset;
buffer.writeUInt32LE(0, offset);
offset += 4;
return offset;
}
writeData(buffer : GrowableBuffer, offset : number, valueMap : Map<string, number>) {
assert(this.value !== undefined);
if (valueMap.has(this.value)) {
const existing = valueMap.get(this.value)!;
buffer.writeUInt32LE(existing, this._dataPtrOffset!);
return offset;
}
valueMap.set(this.value, offset);
buffer.writeUInt32LE(offset, this._dataPtrOffset!);
offset = writeNodeHeader(buffer, offset, NodeType.DATA);
const dataBuffer = Buffer.from(this.value, 'utf8');
assert(dataBuffer.length <= 65536);
buffer.writeUInt16LE(dataBuffer.length, offset);
offset += 2;
buffer.writeBuffer(dataBuffer, offset);
offset += dataBuffer.length;
return offset;
}
}
class TrieBuilderIntermediateNode {
key : string | typeof WILDCARD;
children : Map<string | typeof WILDCARD, TrieBuilderIntermediateNode>;
protected _childrenBeginPtrOffset : number;
protected _leaf : TrieBuilderLeafNode|null;
protected _isCompact : boolean;
protected _size : number|undefined;
protected _sortedChildren : TrieBuilderIntermediateNode[]|undefined;
constructor(key : string | typeof WILDCARD) {
this.key = key;
this._leaf = null;
this.children = new Map;
this._childrenBeginPtrOffset = 0;
this._isCompact = true;
this._size = undefined;
this._sortedChildren = undefined;
}
get size() {
if (this._size !== undefined)
return this._size;
this._size = 0;
if (this._leaf)
this._size += this._leaf.size;
for (const child of this.children.values())
this._size += child.size;
return this._size;
}
setValue(value : string, valueCombine : (one : string|undefined, two : string) => string) {
if (this._leaf === null)
this._leaf = new TrieBuilderLeafNode();
this._leaf.addValue(value, valueCombine);
if (this.children.size > 0)
this._isCompact = false;
}
addChild(key : string | typeof WILDCARD) {
const child = new TrieBuilderIntermediateNode(key);
this.children.set(key, child);
if (this._leaf !== null)
this._isCompact = false;
if (this.children.size > 1)
this._isCompact = false;
return child;
}
getChild(key : string | typeof WILDCARD) {
return this.children.get(key);
}
protected _sortChildren() {
const keys = Array.from(this.children.keys());
keys.sort((a, b) => {
if (a === WILDCARD)
return -1;
if (b === WILDCARD)
return 1;
const asize = this.children.get(a)!.size;
const bsize = this.children.get(b)!.size;
if (asize > bsize)
return -1;
if (asize < bsize)
return 1;
if (a < b)
return -1;
if (b < a)
return 1;
return 0;
});
this._sortedChildren = keys.map((key) => this.children.get(key)!);
}
private _writeOwnKey(buffer : GrowableBuffer, offset : number, nodeType : NodeType) {
if (this.key === WILDCARD) {
offset = writeNodeHeader(buffer, offset, nodeType, NodeFlags.WILDCARD);
buffer.writeUInt8(0, offset++);
} else {
assert(typeof this.key === 'string');
offset = writeNodeHeader(buffer, offset, nodeType, NodeFlags.NONE);
const keyBuffer = Buffer.from(this.key, 'utf8');
assert(keyBuffer.length <= 255);
buffer.writeUInt8(keyBuffer.length, offset++);
buffer.writeBuffer(keyBuffer, offset);
offset += keyBuffer.length;
}
return offset;
}
writeKey(buffer : GrowableBuffer, offset : number) {
this._sortChildren();
assert(this._leaf || this.children.size > 0);
if (this._isCompact) {
offset = this._writeOwnKey(buffer, offset, NodeType.COMPACT);
if (this._leaf)
offset = this._leaf.writeKey(buffer, offset);
for (const child of this._sortedChildren!)
offset = child.writeKey(buffer, offset);
return offset;
} else {
offset = this._writeOwnKey(buffer, offset, NodeType.INTERMEDIATE);
this._childrenBeginPtrOffset = offset;
buffer.writeUInt32LE(0, offset);
offset += 4;
buffer.writeUInt16LE(0, offset);
offset += 2;
return offset;
}
}
writeData(buffer : GrowableBuffer, offset : number, valueMap : Map<string, number>) {
assert(typeof offset === 'number');
if (this._leaf)
offset = this._leaf.writeData(buffer, offset, valueMap);
for (const child of this._sortedChildren!)
offset = child.writeData(buffer, offset, valueMap);
return offset;
}
writeChildren(buffer : GrowableBuffer, offset : number) {
if (!this._isCompact) {
const beginOffset = offset;
if (this._leaf)
offset = this._leaf.writeKey(buffer, offset);
for (const child of this._sortedChildren!)
offset = child.writeKey(buffer, offset);
const endOffset = offset;
assert(endOffset - beginOffset <= 65536);
buffer.writeUInt32LE(beginOffset, this._childrenBeginPtrOffset);
buffer.writeUInt16LE(endOffset - beginOffset, this._childrenBeginPtrOffset+4);
}
for (const child of this._sortedChildren!)
offset = child.writeChildren(buffer, offset);
return offset;
}
}
class TrieBuilderRootNode extends TrieBuilderIntermediateNode {
constructor() {
super('');
this._isCompact = false;
this._childrenBeginPtrOffset = 0;
}
writeKey(buffer : GrowableBuffer, offset : number) {
this._sortChildren();
this._childrenBeginPtrOffset = offset;
buffer.writeUInt16LE(0, offset);
offset += 2;
return offset;
}
writeChildren(buffer : GrowableBuffer, offset : number) {
const beginOffset = offset;
if (this._leaf)
offset = this._leaf.writeKey(buffer, offset);
for (const child of this._sortedChildren!)
offset = child.writeKey(buffer, offset);
const endOffset = offset;
buffer.writeUInt16LE(endOffset - beginOffset, this._childrenBeginPtrOffset);
for (const child of this._sortedChildren!)
offset = child.writeChildren(buffer, offset);
return offset;
}
}
export class BTrieBuilder {
private _valueCombine : (one : string|undefined, two : string) => string;
root : TrieBuilderRootNode;
constructor(valueCombine : (one : string|undefined, two : string) => string) {
this._valueCombine = valueCombine;
this.root = new TrieBuilderRootNode();
}
insert(sequence : Array<string | typeof WILDCARD>, value : string) {
let node : TrieBuilderIntermediateNode = this.root;
for (const key of sequence) {
let child = node.getChild(key);
if (!child)
child = node.addChild(key);
node = child;
}
node.setValue(value, this._valueCombine);
}
build() : Buffer {
const buffer = new GrowableBuffer();
// write the header
// magic number (Almond Trie)
buffer.writeBuffer(Buffer.from('ALTR', 'utf8'), 0);
// version number: 0x01 0x00 (minor, major)
buffer.writeUInt16LE(1, 4);
let offset = this.root.writeKey(buffer, FILE_HEADER_LENGTH);
offset = this.root.writeChildren(buffer, offset);
const valueMap = new Map;
offset = this.root.writeData(buffer, offset, valueMap);
assert(offset === buffer.length);
return buffer.toBuffer();
}
}
interface MMappedNode {
offset : number;
size : number;
}
/**
* A B-Tree-based (immutable) Trie.
*
* This is a disk-based data structure for efficient storing of key-value pairs,
* where the keys are sequences. It is designed to be memory-mappable, which is
* memory efficient.
*
* The file is organized in _nodes_, which roughly represent the trie nodes.
* Each node is identified by a 1 byte head, followed by a variable size.
*
* Four types of nodes exist:
* - _data_ nodes contain the values mapped to by the Trie; they are formed by a 4 byte length
* followed by the data
* - _leaf_ nodes indicate a complete key (end of string marker); they are 4 bytes
* that point to the corresponding data node
* - _intermediate_ nodes indicate a portion of the key (a single word); they are composed
* of 1 byte key length, followed by the key, followed by 4 bytes of pointer and 2 bytes
* of length into a _key block_; the key block is the sequential list of children of this
* node
* - _compact_ nodes are an optimization of intermediate nodes with only one child; compact
* nodes have 1 byte key length, followed by the key; the child is then emitted immediately
* after the compact node, without pointers
*/
export class BTrie {
private _buffer : Buffer;
private _root : MMappedNode;
constructor(buffer : Buffer) {
this._buffer = buffer;
// read the header
if (buffer.toString('utf8', 0, 4) !== 'ALTR')
throw new Error('Invalid magic');
if (buffer.readUInt16LE(4) !== 1)
throw new Error('Invalid version');
this._root = {
offset: FILE_HEADER_LENGTH + 2,
size: buffer.readUInt16LE(FILE_HEADER_LENGTH)
};
this._check(this._root.size + this._root.offset <= this._buffer.length);
}
_check(condition : boolean, ...data : unknown[]) {
if (!condition) {
console.log(...data);
throw new Error(`BTrie file is corrupt`);
}
}
// skip a single node in the file
private _skipNode(offset : number) {
const header = readNodeHeader(this._buffer, offset);
offset ++;
switch (header.nodeType) {
case NodeType.DATA: {
const dataLength = this._buffer.readUInt32LE(offset);
this._check(offset + 2 + dataLength <= this._buffer.length);
offset += 2;
offset += dataLength;
break;
}
case NodeType.LEAF: {
// skip the data pointer
this._check(offset + 4 <= this._buffer.length);
offset += 4;
break;
}
case NodeType.COMPACT: {
const keyLength = this._buffer.readUInt8(offset);
this._check(offset + 1 + keyLength <= this._buffer.length);
offset += 1;
offset += keyLength;
break;
}
case NodeType.INTERMEDIATE: {
const keyLength = this._buffer.readUInt8(offset);
this._check(offset + 1 + keyLength <= this._buffer.length);
offset += 1;
offset += keyLength;
// skip the pointer to the key block and length
this._check(offset + 6 <= this._buffer.length);
offset += 6;
break;
}
}
return offset;
}
// Skip a whole entry (sequence of compact nodes followed by a non-compact one)
private _skipEntry(offset : number) {
let header = readNodeHeader(this._buffer, offset);
while (header.nodeType === NodeType.COMPACT) {
offset = this._skipNode(offset);
header = readNodeHeader(this._buffer, offset);
}
// skip one more node
// NOTE: in well-formed files, all compact nodes are guaranteed to be followed
// by a non-compact node, either a leaf or an intermediate node
return this._skipNode(offset);
}
private _findKey(key : Buffer|typeof WILDCARD, node : MMappedNode) {
let startOffset = node.offset;
while (startOffset < node.offset + node.size) {
const candidateHeader = readNodeHeader(this._buffer, startOffset);
this._check(candidateHeader.nodeType !== NodeType.DATA, startOffset, candidateHeader);
if (candidateHeader.nodeType === NodeType.LEAF) {
startOffset = this._skipNode(startOffset);
continue;
}
const keyLength = this._buffer.readUInt8(startOffset + 1);
this._check(startOffset + 2 + keyLength <= this._buffer.length);
if (key === WILDCARD) {
if ((candidateHeader.flags & NodeFlags.WILDCARD) !== NodeFlags.WILDCARD) {
startOffset = this._skipEntry(startOffset);
continue;
}
this._check(keyLength === 0);
} else {
assert(key instanceof Buffer);
if ((candidateHeader.flags & NodeFlags.WILDCARD) !== 0) {
startOffset = this._skipEntry(startOffset);
continue;
}
if (keyLength !== key.length ||
this._buffer.compare(key, 0, key.length,
startOffset + 2, startOffset + 2 + keyLength) !== 0) {
startOffset = this._skipEntry(startOffset);
continue;
}
}
if (candidateHeader.nodeType === NodeType.COMPACT) {
return {
offset: startOffset + 2 + keyLength,
size: 1
};
} else {
this._check(startOffset + 2 + keyLength + 6 <= this._buffer.length);
const child = {
offset: this._buffer.readUInt32LE(startOffset + 2 + keyLength),
size: this._buffer.readUInt16LE(startOffset + 2 + keyLength + 4)
};
this._check(child.offset + child.size <= this._buffer.length);
return child;
}
}
return null;
}
search(sequence : string[]) : string|undefined {
let node = this._root;
for (const key of sequence) {
assert(typeof key === 'string');
const keyBuffer = Buffer.from(key, 'utf8');
let child = this._findKey(keyBuffer, node);
if (child === null)
child = this._findKey(WILDCARD, node);
if (child === null)
return undefined;
node = child;
}
// this can only occur with the root node, for an empty trie
if (node.size === 0)
return undefined;
const nodeHeader = readNodeHeader(this._buffer, node.offset);
this._check(nodeHeader.nodeType !== NodeType.DATA);
if (nodeHeader.nodeType === NodeType.LEAF) {
const dataNodeOffset = this._buffer.readUInt32LE(node.offset + 1);
const dataHeader = readNodeHeader(this._buffer, dataNodeOffset);
this._check(dataHeader.nodeType === NodeType.DATA && dataHeader.flags === 0);
const dataSize = this._buffer.readUInt16LE(dataNodeOffset + 1);
const dataOffset = dataNodeOffset + 1 + 2;
return this._buffer.toString('utf8', dataOffset, dataOffset+dataSize);
} else {
return undefined;
}
}
} | the_stack |
import { action, computed, observable, runInAction } from "mobx";
import CesiumCartesian3 from "terriajs-cesium/Source/Core/Cartesian3";
import Cartographic from "terriajs-cesium/Source/Core/Cartographic";
import EllipsoidTerrainProvider from "terriajs-cesium/Source/Core/EllipsoidTerrainProvider";
import CesiumMath from "terriajs-cesium/Source/Core/Math";
import CesiumMatrix3 from "terriajs-cesium/Source/Core/Matrix3";
import Camera from "terriajs-cesium/Source/Scene/Camera";
import Scene from "terriajs-cesium/Source/Scene/Scene";
import Terria from "./Terria";
const sampleTerrainMostDetailed = require("terriajs-cesium/Source/Core/sampleTerrainMostDetailed")
.default;
interface EventLoopState {
intervalId?: any;
}
interface TerriaOrientation {
orientation: {
roll: number;
pitch: number;
heading: number;
};
destination?: CesiumCartesian3;
}
export default class AugmentedVirtuality {
/**
* Gets the the maximum number of times that the camera orientation will be
* updated per second by default. This is the number of camera orientation
* updates per seconds is capped to by default (explicitly the number of times
* the orientation is updated per second might be less but it won't be more
* then this number). We want the number of times that the orientation is
* updated capped so that we don't consume to much battery life updating to
* frequently, but responsiveness is still acceptable.
*/
static readonly DEFAULT_MAXIMUM_UPDATES_PER_SECOND = 10.0;
/**
* The minimum height that the viewer is allowed to hover at.
*/
static readonly MINIMUM_HOVER_HEIGHT = 20.0;
/* These are the heights that we can toggle through (in meters - above the surface height).
*/
static readonly PRESET_HEIGHTS = [1000, 250, 20];
@observable manualAlignment = false;
@observable private eventLoopState: EventLoopState = {};
@observable private orientationUpdated = false;
@observable private alpha = 0;
@observable private beta = 0;
@observable private gamma = 0;
@observable private realignAlpha = 0;
@observable private realignHeading = 0;
@observable private lastScreenOrientation?: number;
@observable private maximumUpdatesPerSecond =
AugmentedVirtuality.DEFAULT_MAXIMUM_UPDATES_PER_SECOND;
// Set the default height to be the last height so that when we first toggle
// (and increment) we cycle and go to the first height.
@observable hoverLevel = AugmentedVirtuality.PRESET_HEIGHTS.length - 1;
constructor(readonly terria: Terria) {}
toggleEnabled() {
if (this.active) {
this.deactivate();
} else {
this.activate();
}
}
@computed
get scene(): Scene | undefined {
return this.terria.cesium && this.terria.cesium.scene;
}
@computed
get camera(): Camera | undefined {
return this.terria.cesium && this.terria.cesium.scene.camera;
}
@computed
get active() {
return this.isEventLoopRunning || this.manualAlignment;
}
@action
activate() {
this.manualAlignment = false;
this.startEventLoop(true);
}
@action
deactivate() {
this.resetAlignment();
this.manualAlignment = false;
this.startEventLoop(false);
}
/**
* Toggles whether manual alignement is enabled or disabled.
*/
@action
toggleManualAlignment() {
this.setManualAlignment(!this.manualAlignment);
}
@computed
get manualAlignmentSet() {
return this.realignAlpha !== 0.0 || this.realignHeading !== 0.0;
}
@computed
private get isEventLoopRunning() {
return this.eventLoopState.intervalId !== undefined;
}
/**
* Toggles the viewer between a range of predefined heights, setting the
* cameras orientation so that it matches the * correct orientation.
*/
@action
toggleHoverHeight() {
this.hoverLevel =
(this.hoverLevel + 1) % AugmentedVirtuality.PRESET_HEIGHTS.length;
this.hover(AugmentedVirtuality.PRESET_HEIGHTS[this.hoverLevel]);
}
/** Moves the viewer to a specified height, setting the orientation so that
* it matches the correct Augmented Virtuality * orientation.
*
* @param height The height in Meters above the globe surface. Note: If height is below
* {@link AugmentedVirtuality.MINIMUM_HOVER_HEIGHT} the height will be set to
* {@link AugmentedVirtuality.MINIMUM_HOVER_HEIGHT} to avoid visual artifacts when the viewer
* becomes to close to the surface.
*
* @param [position] The location to hover over. If not specified the current camera location will be used.
* @param [flyTo=true] Whether to fly to the location (true) or whether to jump to the location (false).
*/
private hover(height: number, position?: Cartographic, flyTo?: boolean) {
// Get access to the camera...if it is not avaliable we can't set the new height so just return now.
if (!this.camera) return;
const camera = this.camera;
const hoverPosition = position
? position
: camera.positionCartographic.clone();
flyTo = flyTo === undefined ? true : flyTo;
// Clamp the minimum hover height (heights below this value could lead to poor visual artifacts).
if (height < AugmentedVirtuality.MINIMUM_HOVER_HEIGHT) {
height = AugmentedVirtuality.MINIMUM_HOVER_HEIGHT;
}
// Reset the viewer height.
const flyToHeight = (surfaceHeight: number) => {
height += surfaceHeight;
const newPosition = CesiumCartesian3.fromRadians(
hoverPosition.longitude,
hoverPosition.latitude,
height
);
const pose = {
destination: newPosition,
...this.getCurrentOrientation()
};
if (flyTo) {
camera.flyTo(pose);
} else {
camera.setView(pose);
}
// Needed on mobile to make sure that the render is marked as dirty so
// that once AV mode has been disabled for a while and then is reenabled
// the .setView() function still has effect (otherwise dispite the call
// the .setView() the view orientation does not visually update until the
// user manualy moves the camera position).
this.terria.currentViewer.notifyRepaintRequired();
};
// Get the ground surface height at this location and offset the height by it.
if (
!this.scene ||
!this.scene.terrainProvider ||
this.scene.terrainProvider instanceof EllipsoidTerrainProvider
) {
// If we can't get access to the terrain provider or we can get access to
// the terrain provider and the provider is just the Ellipsoid then use
// the height of 0.
flyToHeight(0);
} else {
const terrainProvider = this.scene.terrainProvider;
sampleTerrainMostDetailed(terrainProvider, [hoverPosition]).then(function(
updatedPosition: Cartographic[]
) {
flyToHeight(updatedPosition[0].height);
});
}
}
/**
* Moves the viewer to a specified location while maintaining the current
* height and the correct Augmented Virtuality * orientation.
*
* @param position The location to hover move to.
* @param [maximumHeight] The maximum height (in meters) to cap the current
* camera height to (if this value is specified and the viewer is above this
* height the camera will be restricted to this height).
* @param [flyTo] Whether to fly to the location (true) or whether to jump to
* the location (false).
*
* When the manual alignment is enabled this function has no effect.
*/
moveTo(position: Cartographic, maximumHeight: number, flyTo: boolean) {
// If we are in manual alignment mode we don't allow the viewer to move
// (since this would create a jaring UX for most use cases).
if (this.manualAlignment) return;
// Get access to the camera...if it is not avaliable we can't get the
// current height (or set the new location) so just return now.
if (this.camera === undefined) return;
const camera = this.camera;
const cameraPosition = camera.positionCartographic.clone();
const viewerHeight = cameraPosition.height;
// Reset the viewer height.
const moveToLocation = (surfaceHeight: number) => {
let hoverHeight = viewerHeight - surfaceHeight;
if (hoverHeight > maximumHeight) hoverHeight = maximumHeight;
this.hover(hoverHeight, position, flyTo);
};
const scene = this.scene;
// Get the ground surface height at this location and offset the height by it.
if (
scene === undefined ||
scene.terrainProvider === undefined ||
scene.terrainProvider instanceof EllipsoidTerrainProvider
) {
// If we can't get access to the terrain provider or we can get access to
// the terrain provider and the provider is just the Ellipsoid then use
// the height of 0.
moveToLocation(0);
} else {
const terrainProvider = scene.terrainProvider;
sampleTerrainMostDetailed(terrainProvider, [cameraPosition]).then(
function(updatedPosition: Array<Cartographic>) {
moveToLocation(updatedPosition[0].height);
}
);
}
}
/**
* Whether the user is currently setting a manual alignment.
*
* @return Whether the user is currently setting a manual alignment (true) or not (false).
*/
private getManualAlignment(): boolean {
return this.active && this.manualAlignment;
}
/**
* Starts / stops manual alignment.
*
* When manual realignment is enabled it allows the user to specify a new
* origin for the alignment between the devices physical and virtual
* alignment. When manual alignment is enabled the orientation is locked, to
* allow the user to realign a visual landmark with a physical landmark.
*
* Note: Manual alignment is only done for the heading axis, this is because in
* practice we have found that the heading axis is often out as mobile devices
* seem to have difficulty obtaining the compass direction, but seem to perform
* relatively well in the other axes.
*
* Note: Realignment is only possible when AugmentedVirtuality is enabled. If
* AugmentedVirtuality is disabled while manual alignment is in progress
* it will be cancelled.
*
*
* @param startEnd Whether the user is starting (true) or ending (false) the realignment.
*/
private setManualAlignment(startEnd: boolean) {
// Only allow manual alignment changes when the module is enabled.
if (this.active === false) return;
if (startEnd === false && this.camera !== undefined) {
this.realignAlpha = this.alpha;
this.realignHeading = CesiumMath.toDegrees(this.camera.heading);
}
if (this.manualAlignment !== startEnd) {
this.manualAlignment = startEnd;
this.startEventLoop(!this.manualAlignment);
}
}
/**
* Resets the alignment so that the alignement matches the devices absolute alignment.
*/
resetAlignment() {
this.orientationUpdated = true;
this.realignAlpha = 0;
this.realignHeading = 0;
}
/**
* Start or stop the Augmented Virutuality mode event loop. When enabled the
* orientation will effect the cameras view and when disabled the device
* orientation will not effect the cameras view.
*
* @param enable Whether to start the event loop (true) or stop the event loop (false).
*/
private startEventLoop(enable: boolean) {
if (this.isEventLoopRunning === enable) return;
if (enable === true) {
this.orientationUpdated = true;
const intervalMs = 1000 / this.maximumUpdatesPerSecond;
const id: any = setInterval(
() => runInAction(() => this.updateOrientation()),
intervalMs
);
if ("ondeviceorientation" in window) {
window.addEventListener(
"deviceorientation",
this.boundStoreOrientation
);
}
this.eventLoopState = { intervalId: id };
} else {
clearInterval(this.eventLoopState.intervalId);
window.removeEventListener(
"deviceorientation",
this.boundStoreOrientation
);
this.eventLoopState = {};
}
}
/**
* Device orientation update event callback function. Stores the updated
* orientation into the object state.
*
* @param event Contains the updated device orientation (in .alpha, .beta, .gamma).
*/
storeOrientation(event: DeviceOrientationEvent) {
const { alpha, beta, gamma } = event;
if (alpha !== null && beta !== null && gamma !== null) {
this.alpha = alpha;
this.beta = beta;
this.gamma = gamma;
this.orientationUpdated = true;
}
}
/**
* A bound version of `storeOrientation` that makes it easy to pass to
* add/removeEventListener calls.
*/
private boundStoreOrientation = this.storeOrientation.bind(this);
/**
* This function updates the cameras orientation using the last orientation
* recorded and the current screen orientation.
*
*/
private updateOrientation() {
// Check if the screen orientation has changed and mark the orientation updated if it has.
const screenOrientation = getCurrentScreenOrientation();
if (screenOrientation !== this.lastScreenOrientation)
this.orientationUpdated = true;
this.lastScreenOrientation = screenOrientation;
// Optimize by only updating the camera view if some part of the
// orientation calculation has changed.
if (!this.orientationUpdated) {
// The orientation has not been updated so don't waste time changing the
// orientation.
return;
}
this.orientationUpdated = false;
// Get access to the camera...if it is not avaliable we can't set the orientation so just return now.
if (this.camera) {
this.camera.setView(this.getCurrentOrientation(screenOrientation));
// Needed on mobile to make sure that the render is marked as dirty so that
// once AV mode has been disabled for a while and then is reenabled the
// .setView() function still has effect (otherwise dispite the call the
// .setView() the view orientation does not visually update until the user
// manualy moves the camera position).
this.terria.currentViewer.notifyRepaintRequired();
}
}
/**
* Gets the current orientation stored in the object state and returns the
* roll, pitch and heading which can be used to set the cameras orientation.
*
* @param screenOrientation The screen orientation in degrees. Note: This
* field is optional, if supplied this value will be used for the screen
* orientation, otherwise the screen orientation will be obtained during the
* execution of this function.
*
* @return A object with the roll, pitch and heading stored into the orientation.
*/
private getCurrentOrientation(screenOrientation?: number) {
const alpha = this.alpha;
const beta = this.beta;
const gamma = this.gamma;
const realignAlpha = this.realignAlpha;
const realignHeading = this.realignHeading;
if (screenOrientation === undefined)
screenOrientation = getCurrentScreenOrientation();
return computeTerriaOrientation(
alpha,
beta,
gamma,
screenOrientation,
realignAlpha,
realignHeading
);
}
}
function getCurrentScreenOrientation(): number {
if (screen.orientation && screen.orientation.angle !== undefined)
return screen.orientation.angle;
if (window.orientation) {
return Number(window.orientation);
}
return 0;
}
/**
* Turns the orientation in the device frame of reference into an orientation
* suitable for specifying the Terria camera orientation.
*
* @param alpha The alpha value of the device orientation in degrees (this is
* the alpha value in the device's frame of reference).
*
* @param beta The beta value of the device orientation in degrees (this is the
* beta value in the device's frame of reference).
*
* @param gamma The gamma value of the device orientation in degrees (this is
* the gamma value in the device's frame of reference).
*
* @param screenOrientation The screen orientation in degrees.
*
* @param realignAlpha The value of the alpha value the last time realignment
* was completed (supply zero if realignment is not supported).
*
* @param realignHeading The value of the heading value the last time
* realignment was completed (supply zero if realignment is not supported).
*
* @return An object with the roll, pitch and heading stored into the orientation.
*/
function computeTerriaOrientation(
alpha: number,
beta: number,
gamma: number,
screenOrientation: number,
realignAlpha: number,
realignHeading: number
): TerriaOrientation {
// Note: The algorithmic formulation in this function is for simplicity of
// mathematical expression, readability, maintainability and
// modification (i.e. it is easy to understand how to update or insert
// new offsets or features). This is not the simplest form which
// clearly flows from the current formuleation and clearly simplify the
// logic and operations but would increase the cost of future
// modifications and reduce the readability of the expression. It is
// not anticipated that the current verbose implementation would have a
// significant impact on performance or accuracy, but obviously there
// will be some impact on both and it can be simplified in future if
// needed.
const rotation = CesiumMatrix3.clone(CesiumMatrix3.IDENTITY);
let rotationIncrement;
// Roll - Counteract the change in the (orientation) frame of reference when
// the screen is rotated and the rotation lock is not on (the browser
// reorients the frame of reference to align with the new screen
// orientation - where as we want it of the device relative to the
// world).
rotationIncrement = CesiumMatrix3.fromRotationZ(
CesiumMath.toRadians(screenOrientation)
);
CesiumMatrix3.multiply(rotation, rotationIncrement, rotation);
// Pitch - Align the device orientation frame with the ceasium orientation frame.
rotationIncrement = CesiumMatrix3.fromRotationX(CesiumMath.toRadians(90));
CesiumMatrix3.multiply(rotation, rotationIncrement, rotation);
// Roll - Apply the deivce roll.
rotationIncrement = CesiumMatrix3.fromRotationZ(CesiumMath.toRadians(gamma));
CesiumMatrix3.multiply(rotation, rotationIncrement, rotation);
// Pitch - Apply the deivce pitch.
rotationIncrement = CesiumMatrix3.fromRotationX(CesiumMath.toRadians(-beta));
CesiumMatrix3.multiply(rotation, rotationIncrement, rotation);
// Heading - Apply the incremental deivce heading (from when start was last triggered).
rotationIncrement = CesiumMatrix3.fromRotationY(
CesiumMath.toRadians(-(alpha - realignAlpha))
);
CesiumMatrix3.multiply(rotation, rotationIncrement, rotation);
// Heading - Use the offset when the orientation was last started. Note:
// This is logically different from the alpha value and can only be
// applied here in the same way since Cesium camera is RPH (Heading
// last - most local). See Cesium camera rotation decomposition for
// more information on the Cesium camera formuleation.
rotationIncrement = CesiumMatrix3.fromRotationY(
CesiumMath.toRadians(realignHeading)
);
CesiumMatrix3.multiply(rotation, rotationIncrement, rotation);
// Decompose rotation matrix into roll, pitch and heading to supply to Cesium camera.
//
// Use notation:
// R = Roll, P = Pitch, H = Heading
// SH = Sin(Heading), CH = Cos(Heading)
//
// Ceasium camera rotation = RPH:
// [ CR, -SR, 0][ 1, 0, 0][ CH, 0, SH] [CRCH-SRSPSH, -SRCP, CRSH-SRSPCH]
// [ SR, CR, 0][ 0, CP, SP][ 0, 1, 0] = [SRCH-CRSPSH, CRCP, SRSH+CRSPCH]
// [ 0, 0, 1][ 0, -SP, CP][-SH, 0, CH] [ -CPSH , -SP, CPCH ]
// Note: The sign difference of the Sin terms in pitch is different to the standard right handed rotation since
// Cesium rotates pitch in the left handed direction. Both heading and roll are right handed rotations.
//
// Use the following notation to refer to elements in the Cesium camera rotation matrix:
// [R00, R10, R20]
// [R01, R11, R21]
// [R02, R12, R22]
//
// Also note: Tan(X) = Sin(X) / Cos(X)
//
// Decompose matrix:
// H = ATan(Tan(H)) = ATan(Sin(H)/Cos(H)) = ATan (SH / CH) = ATan(CPSH/CPCH) = ATan (-R02 / R22)
// R = ATan(Tan(R)) = ATan(Sin(R)/Cos(R)) = ATan (SR / CR) = ATan(SRCP/CRCP) = ATan (-R10 / R11)
// P = ATan(Tan(P)) = ATan(Sin(P)/Cos(P)) = ATan (SP / CP)
// SP = -R12
// Need to find CP:
// CP = Sqrt(CP^2)
// = Sqrt(CP^2*(CH^2+SH^2)) Since: (Cos@^2 + Sin@^2) = 1
// = Sqrt((CP^2)*(CH^2) + (CP^2)*(SH^2)) Expand
// = Sqrt((CPCH)^2 + (CPSH)^2) Since: N^2*M^2 = (NM)^2
// = Sqrt(R22^2 + (-R02)^2) Substitute
// = Sqrt(R22^2 + R02^2) Since: (-N)^2 = N^2
// So P = ATan (-R12 / Sqrt(R22^2 + R02^2))
const getColumn = (mat: CesiumMatrix3, col: number): number => {
return (<any>mat)[col];
};
// Simplify notation for readability:
const r10: number = getColumn(rotation, CesiumMatrix3.COLUMN1ROW0);
const r11: number = getColumn(rotation, CesiumMatrix3.COLUMN1ROW1);
const r02: number = getColumn(rotation, CesiumMatrix3.COLUMN0ROW2);
const r12: number = getColumn(rotation, CesiumMatrix3.COLUMN1ROW2);
const r22: number = getColumn(rotation, CesiumMatrix3.COLUMN2ROW2);
const heading = CesiumMath.toDegrees(Math.atan2(-r02, r22));
const roll = CesiumMath.toDegrees(Math.atan2(-r10, r11));
const pitch = CesiumMath.toDegrees(
Math.atan2(-r12, Math.sqrt(r02 * r02 + r22 * r22))
);
// Create an object with the roll, pitch and heading we just computed.
return {
orientation: {
roll: CesiumMath.toRadians(roll),
pitch: CesiumMath.toRadians(pitch),
heading: CesiumMath.toRadians(heading)
}
};
} | the_stack |
import 'jest';
import { EditorModel } from '../src/newmodel';
import { DSVEditor } from '../src/widget';
import { toArray, range } from '@lumino/algorithm';
import { Litestore } from '../src/litestore';
import { DATA } from './data';
const delimiter = ',';
let model: EditorModel;
let dataMatrix: string[][];
let bigModel: EditorModel;
function updateLitestore(
model: EditorModel,
update?: DSVEditor.ModelChangedArgs
): void {
// const selection = this._grid.selectionModel.currentSelection();
model.litestore.updateRecord(
{
schema: DSVEditor.DATAMODEL_SCHEMA,
record: DSVEditor.RECORD_ID
},
{
rowMap: update.rowUpdate || DSVEditor.NULL_NUM_SPLICE,
columnMap: update.columnUpdate || DSVEditor.NULL_NUM_SPLICE,
valueMap: update.valueUpdate || null,
selection: update.selection || null,
gridState: update.gridStateUpdate || null
}
);
}
function initModel(): void {
const data = [
'column 0,column 1,column 2',
'r0c0,r0c1:randomvalue,r1c2',
'r1c0,r1c1,r1c2:another-random-val',
'r2c0,r2c1,r2c2'
].join('\n');
model = new EditorModel({ data, delimiter });
// Define the initial update object for the litestore.
const update: DSVEditor.ModelChangedArgs = {};
// Define the initial state of the row and column map.
const rowUpdate = {
index: 0,
remove: 0,
values: toArray(range(0, model.totalRows))
};
const columnUpdate = {
index: 0,
remove: 0,
values: toArray(range(0, model.totalColumns))
};
// Add the map updates to the update object.
update.rowUpdate = rowUpdate;
update.columnUpdate = columnUpdate;
// Define the litestore
model.litestore = new Litestore({
id: 0,
schemas: [DSVEditor.DATAMODEL_SCHEMA]
});
// set inital status of litestore
model.litestore.beginTransaction();
updateLitestore(model, update);
model.litestore.endTransaction();
}
function initBigModel(): void {
// Parse the data matrix once.
dataMatrix = DATA.split('\n').map(row => row.split(','));
bigModel = new EditorModel({ data: DATA, delimiter });
// Define the initial update object for the litestore.
const update: DSVEditor.ModelChangedArgs = {};
// Define the initial state of the row and column map.
const rowUpdate = {
index: 0,
remove: 0,
values: toArray(range(0, bigModel.totalRows))
};
const columnUpdate = {
index: 0,
remove: 0,
values: toArray(range(0, bigModel.totalColumns))
};
// Add the map updates to the update object.
update.rowUpdate = rowUpdate;
update.columnUpdate = columnUpdate;
// Define the litestore
bigModel.litestore = new Litestore({
id: 0,
schemas: [DSVEditor.DATAMODEL_SCHEMA]
});
// set inital status of litestore
bigModel.litestore.beginTransaction();
updateLitestore(bigModel, update);
bigModel.litestore.endTransaction();
}
describe('Row & Column Map Manipulation', () => {
beforeEach(() => {
initModel();
});
it('should add a row to the row map', () => {
const update = model.addRows('body', 0, 1);
model.litestore.beginTransaction();
updateLitestore(model, update);
model.litestore.endTransaction();
const { rowMap } = model.litestore.getRecord({
schema: DSVEditor.DATAMODEL_SCHEMA,
record: DSVEditor.RECORD_ID
});
const compareArray = [];
for (let i = 0; i < rowMap.length; i++) {
compareArray.push(rowMap[i]);
}
const data = [0, -4, 1, 2, 3];
expect(compareArray).toStrictEqual(data);
});
it('should handle a row removal followed by an addition.', () => {
const update = model.removeRows('body', 0, 1);
model.litestore.beginTransaction();
updateLitestore(model, update);
model.litestore.endTransaction();
const nextUpdate = model.addRows('body', 0, 1);
model.litestore.beginTransaction();
updateLitestore(model, nextUpdate);
model.litestore.endTransaction();
const { rowMap } = model.litestore.getRecord({
schema: DSVEditor.DATAMODEL_SCHEMA,
record: DSVEditor.RECORD_ID
});
const compareArray = [];
for (let i = 0; i < rowMap.length; i++) {
compareArray.push(rowMap[i]);
}
const data = [0, -4, 2, 3];
expect(compareArray).toStrictEqual(data);
});
it('should handle a column removal followed by a column addition.', () => {
const update = model.removeColumns('body', 0, 1);
model.litestore.beginTransaction();
updateLitestore(model, update);
model.litestore.endTransaction();
const nextUpdate = model.addColumns('body', 0, 1);
model.litestore.beginTransaction();
updateLitestore(model, nextUpdate);
model.litestore.endTransaction();
const { columnMap } = model.litestore.getRecord({
schema: DSVEditor.DATAMODEL_SCHEMA,
record: DSVEditor.RECORD_ID
});
expect(columnMap.slice()).toStrictEqual([-3, 1, 2]);
});
it('should handle clear a row', () => {
const update = model.clearRows('row-header', 1, 1);
model.litestore.beginTransaction();
updateLitestore(model, update);
model.litestore.endTransaction();
const { rowMap } = model.litestore.getRecord({
schema: DSVEditor.DATAMODEL_SCHEMA,
record: DSVEditor.RECORD_ID
});
expect(rowMap.slice()).toStrictEqual([0, 1, -4, 3]);
});
it('should handle clear a column', () => {
const update = model.clearColumns('column-header', 2, 1);
model.litestore.beginTransaction();
updateLitestore(model, update);
model.litestore.endTransaction();
const { columnMap } = model.litestore.getRecord({
schema: DSVEditor.DATAMODEL_SCHEMA,
record: DSVEditor.RECORD_ID
});
expect(columnMap.slice()).toStrictEqual([0, 1, -3]);
});
});
describe('Serialization', () => {
beforeEach(() => {
initModel();
});
it('Should serialize a series of cell entries', () => {
// Add hello to upper-left corner.
const update: DSVEditor.ModelChangedArgs = {};
model.setData('body', 0, 0, 'hello', 1, 1, update);
model.litestore.beginTransaction();
updateLitestore(model, update);
model.litestore.endTransaction();
// Add world to lower-right corner.
const nextUpdate: DSVEditor.ModelChangedArgs = {};
model.setData('body', 2, 2, 'world', 1, 1, nextUpdate);
model.litestore.beginTransaction();
updateLitestore(model, nextUpdate);
model.litestore.endTransaction();
// Unpack updated litestore values.
const { valueMap } = model.litestore.getRecord({
schema: DSVEditor.DATAMODEL_SCHEMA,
record: DSVEditor.RECORD_ID
});
// Check that the valueMap was properly updated.
expect(valueMap['1,0']).toBe('hello');
expect(valueMap['3,2']).toBe('world');
// Check that these get properly serialized.
const newString = model.updateString();
expect(newString).toBe(
[
'column 0,column 1,column 2',
'hello,r0c1:randomvalue,r1c2',
'r1c0,r1c1,r1c2:another-random-val',
'r2c0,r2c1,world'
].join('\n')
);
});
it('should serialize a combo of each kind of macro update', () => {
let refMatrix = [
['column 0', 'column 1', 'column 2'],
['r0c0', 'r0c1:randomvalue', 'r1c2'],
['r1c0', 'r1c1', 'r1c2:another-random-val'],
['r2c0', 'r2c1', 'r2c2']
];
// Addition macro update
let addUpdate: DSVEditor.ModelChangedArgs = {};
addUpdate = model.addRows('body', 3, 1);
model.litestore.beginTransaction();
updateLitestore(model, addUpdate);
model.litestore.endTransaction();
refMatrix.push(['', '', '']);
// Removal macro update.
let removeUpdate: DSVEditor.ModelChangedArgs = {};
removeUpdate = model.removeColumns('body', 2, 1);
model.litestore.beginTransaction();
updateLitestore(model, removeUpdate);
model.litestore.endTransaction();
refMatrix = refMatrix.map(row => {
row.pop();
return row;
});
// Clear macro update.
let clearUpdate: DSVEditor.ModelChangedArgs = {};
clearUpdate = model.clearRows('row-header', 1, 1);
model.litestore.beginTransaction();
updateLitestore(model, clearUpdate);
model.litestore.endTransaction();
refMatrix[2] = ['', ''];
// Ensure the row and column maps check out
const { rowMap, columnMap } = model.litestore.getRecord({
schema: DSVEditor.DATAMODEL_SCHEMA,
record: DSVEditor.RECORD_ID
});
expect(rowMap.slice()).toStrictEqual([0, 1, -5, 3, -4]);
expect(columnMap.slice()).toStrictEqual([0, 1]);
// Make the comparison.
const newString = model.updateString();
const data = refMatrix.map(row => row.join(',')).join('\n');
expect(newString).toStrictEqual(data);
});
it('Should serialize a combo of micro and macro updates', () => {
const refMatrix = [
['column 0', 'column 1', 'column 2'],
['r0c0', 'r0c1:randomvalue', 'r1c2'],
['r1c0', 'r1c1', 'r1c2:another-random-val'],
['r2c0', 'r2c1', 'r2c2']
];
// Apply a micro update.
const clearUpdate = model.clearCells('body', {
r1: 1,
r2: 1,
c1: 0,
c2: 1
});
model.litestore.beginTransaction();
updateLitestore(model, clearUpdate);
model.litestore.endTransaction();
// Update reference matrix.
refMatrix[2][0] = '';
refMatrix[2][1] = '';
const addUpdate = model.addRows('body', 2, 1);
model.litestore.beginTransaction();
updateLitestore(model, addUpdate);
model.litestore.endTransaction();
refMatrix.splice(3, 0, ['', '', '']);
const expectedData = refMatrix.map(row => row.join(',')).join('\n');
const newString = model.updateString();
expect(newString).toBe(expectedData);
});
});
/**
* A test suite for testing data processing on a large data set.
* All functions are run with a fresh copy of the data
* NOTE: All of these tests should be wrapped in a promise resolution
* for the model to be done parsing.
*/
describe('Large string tests (isolated)', () => {
beforeEach(() => {
initBigModel();
});
it('Should serialize a cell entry', () => {
bigModel.model.ready.then(() => {
// Initialize the update object
const update: DSVEditor.ModelChangedArgs = {};
// Apply the change to the update object
bigModel.setData(
'body',
dataMatrix.length - 1,
dataMatrix.length[0] - 1,
'hello',
1,
1,
update
);
// Update the litestore.
bigModel.litestore.beginTransaction();
updateLitestore(bigModel, update);
bigModel.litestore.endTransaction();
// Update the data matrix.
dataMatrix[dataMatrix.length - 1][dataMatrix.length[0] - 1] = 'hello';
// Serialize
const string = bigModel.updateString();
// Compare
const same = string === dataMatrix.map(row => row.join(',')).join('\n');
expect(same).toBe(true);
});
});
describe('Add', () => {
it('Should add a row to the beginning', () => {
bigModel.model.ready.then(() => {
const update = bigModel.addRows('body', 0, 1);
// Update the litestore.
bigModel.litestore.beginTransaction();
updateLitestore(bigModel, update);
bigModel.litestore.endTransaction();
// Update the data matrix.
dataMatrix.unshift(new Array(dataMatrix[0].length).fill(''));
// Serialize
const string = bigModel.updateString();
// Compare
const same = string === dataMatrix.map(row => row.join(',')).join('\n');
expect(same).toBe(true);
});
});
it('Should add a row to the end', () => {
bigModel.model.ready.then(() => {
const update = bigModel.addRows('body', 1000, 1);
// Update the litestore.
bigModel.litestore.beginTransaction();
updateLitestore(bigModel, update);
bigModel.litestore.endTransaction();
// Update the data matrix.
dataMatrix.push(new Array(dataMatrix[0].length).fill(''));
// Serialize
const string = bigModel.updateString();
// Compare
const same = string === dataMatrix.map(row => row.join(',')).join('\n');
expect(same).toBe(true);
});
});
it('Should add a column to the end', () => {
bigModel.model.ready.then(() => {
const maxColumn = bigModel.totalColumns - 1;
const update = bigModel.addColumns('body', maxColumn, 1);
// Update the litestore.
bigModel.litestore.beginTransaction();
updateLitestore(bigModel, update);
bigModel.litestore.endTransaction();
// Update the data matrix.
dataMatrix.forEach((row, index) => {
dataMatrix[index].push('');
});
// Serialize
const string = bigModel.updateString();
// Compare
const same = string === dataMatrix.map(row => row.join(',')).join('\n');
expect(same).toBe(true);
});
});
it('Should add multiple rows to the beginning', () => {
bigModel.model.ready.then(() => {
const span = 3;
const update = bigModel.addRows('body', 1000, span);
// Update the litestore.
bigModel.litestore.beginTransaction();
updateLitestore(bigModel, update);
bigModel.litestore.endTransaction();
// Update the data matrix.
for (let i = 0; i < span; i++) {
dataMatrix.unshift(new Array(dataMatrix[0].length).fill(''));
}
// Serialize.
const string = bigModel.updateString();
// Compare.
const same = string === dataMatrix.map(row => row.join(',')).join('\n');
expect(same).toBe(true);
});
});
it('Should add multiple rows to the end', () => {
bigModel.model.ready.then(() => {
const span = 3;
const update = bigModel.addRows('body', 1000, span);
// Update the litestore.
bigModel.litestore.beginTransaction();
updateLitestore(bigModel, update);
bigModel.litestore.endTransaction();
// Update the data matrix.
for (let i = 0; i < span; i++) {
dataMatrix.push(new Array(dataMatrix[0].length).fill(''));
}
// Serialize.
const string = bigModel.updateString();
// Compare.
const same = string === dataMatrix.map(row => row.join(',')).join('\n');
expect(same).toBe(true);
});
});
it('Should add multiple columns to the end', () => {
bigModel.model.ready.then(() => {
const span = 2;
const maxColumn = bigModel.totalColumns - 1;
const update = bigModel.addColumns('body', maxColumn, span);
// Update the litestore.
bigModel.litestore.beginTransaction();
updateLitestore(bigModel, update);
bigModel.litestore.endTransaction();
// Update the data matrix.
for (let i = 0; i < span; i++) {
dataMatrix.forEach((row, index) => {
dataMatrix[index].push('');
});
}
// Serialize.
const string = bigModel.updateString();
// Compare.
const same = string === dataMatrix.map(row => row.join(',')).join('\n');
expect(same).toBe(true);
});
});
});
it('Should clear a row', () => {
bigModel.model.ready.then(() => {
const update = bigModel.clearRows('body', 800);
// Update the litestore.
bigModel.litestore.beginTransaction();
updateLitestore(bigModel, update);
bigModel.litestore.endTransaction();
// Update the data matrix.
dataMatrix[800] = new Array(dataMatrix.length[0]).fill('');
// Serialize.
const string = bigModel.updateString();
// Compare.
const same = string === dataMatrix.map(row => row.join(',')).join('\n');
expect(same).toBe(true);
});
});
it('Should clear a column', () => {
bigModel.model.ready.then(() => {
const update = bigModel.clearColumns('body', 700);
// Update the litestore.
bigModel.litestore.beginTransaction();
updateLitestore(bigModel, update);
bigModel.litestore.endTransaction();
// Update the data matrix.
dataMatrix.forEach((elem, index) => {
dataMatrix[index][700] = '';
});
// Serialize.
const string = bigModel.updateString();
// Compare.
const same = string === dataMatrix.map(row => row.join(',')).join('\n');
expect(same).toBe(true);
});
});
it('Should move a row', () => {
bigModel.model.ready.then(() => {
const update = bigModel.moveRows('body', 900, 950, 1);
// Update the litestore.
bigModel.litestore.beginTransaction();
updateLitestore(bigModel, update);
bigModel.litestore.endTransaction();
// Update the data matrix.
[dataMatrix[900], dataMatrix[950]] = [dataMatrix[950], dataMatrix[900]];
// Serialize.
const string = bigModel.updateString();
// Compare.
const same = string === dataMatrix.map(row => row.join(',')).join('\n');
expect(same).toBe(true);
});
});
it('Should move a column', () => {
bigModel.model.ready.then(() => {
const update = bigModel.moveColumns('body', 5, 2, 1);
// Update the litestore.
bigModel.litestore.beginTransaction();
updateLitestore(bigModel, update);
bigModel.litestore.endTransaction();
// Update the data matrix.
dataMatrix.forEach(row => {
[row[5], row[2]] = [row[2], row[5]];
});
// Serialize.
const string = bigModel.updateString();
// Compare.
const same = string === dataMatrix.map(row => row.join(',')).join('\n');
expect(same).toBe(true);
});
});
// it('Should remove a row', () => {
// bigModel.model.ready.then(() => {
// });
// });
// it('Should remove a column', () => {
// bigModel.model.ready.then(() => {
// })
// })
// })
// })
// it('Should clear a cell selection', () => {
// bigModel.model.ready.then(() => {
// })
// });
// it('Should cut a region', () => {
// bigModel.model.ready.then(() => {
// })
// });
// it('Should it should paste a region', () => {
// bigModel.model.ready.then(() => {
// })
// });
// it('Should undo', () => {
// bigModel.model.ready.then(() => {
// })
// });
// it('Should redo', () => {
// bigModel.model.ready.then(() => {
});
/**
* A test suite for testing data processing on a large data set.
* NOTE: All of these tests should be wrapped in a promise resolution
* for the model to be done parsing.
*/
describe('Large string tests (integrated)', () => {
beforeAll(() => {
initBigModel();
});
it('Should serialize a cell entry', () => {
bigModel.model.ready.then(() => {
// Initialize the update object
const update: DSVEditor.ModelChangedArgs = {};
// Apply the change to the update object
bigModel.setData('body', 900, 0, 'hello', 1, 1, update);
// Update the litestore.
bigModel.litestore.beginTransaction();
updateLitestore(bigModel, update);
bigModel.litestore.endTransaction();
// Fetch the map to get the right indices.
const { rowMap, columnMap } = bigModel.litestore.getRecord({
schema: DSVEditor.DATAMODEL_SCHEMA,
record: DSVEditor.RECORD_ID
});
const row = rowMap[900];
const column = columnMap[0];
// Update the data matrix.
dataMatrix[row][column] = 'hello';
// Serialize
const string = bigModel.updateString();
// Compare
const same = string === dataMatrix.map(row => row.join(',')).join('\n');
expect(same).toBe(true);
});
});
it('Should add a row to the end', () => {
bigModel.model.ready.then(() => {
const update = bigModel.addRows('body', 1000, 1);
// Update the litestore.
bigModel.litestore.beginTransaction();
updateLitestore(bigModel, update);
bigModel.litestore.endTransaction();
// Fetch the map to get the right indices.
const { rowMap } = bigModel.litestore.getRecord({
schema: DSVEditor.DATAMODEL_SCHEMA,
record: DSVEditor.RECORD_ID
});
const row = rowMap[1000];
// Create a blank row.
const newRow = new Array(dataMatrix[0].length).fill('');
// Update the data matrix.
dataMatrix.splice(row, 0, newRow);
// Serialize.
const string = bigModel.updateString();
// Compare.
const same = string === dataMatrix.map(row => row.join(',')).join('\n');
expect(same).toBe(true);
});
});
it('Should add a column to the end', () => {
bigModel.model.ready.then(() => {
const maxColumn = bigModel.totalColumns - 1;
const update = bigModel.addColumns('body', maxColumn, 1);
// Update the litestore.
bigModel.litestore.beginTransaction();
updateLitestore(bigModel, update);
bigModel.litestore.endTransaction();
// Fetch the map to get the right indices.
const { columnMap } = bigModel.litestore.getRecord({
schema: DSVEditor.DATAMODEL_SCHEMA,
record: DSVEditor.RECORD_ID
});
const column = columnMap[1000];
// Update the data matrix.
dataMatrix.forEach((row, index) => {
dataMatrix[index].splice(column, 0, '');
});
// Serialize.
const string = bigModel.updateString();
// Compare.
const same = string === dataMatrix.map(row => row.join(',')).join('\n');
expect(same).toBe(true);
});
});
it('Should clear a row', () => {
bigModel.model.ready.then(() => {
const update = bigModel.clearRows('body', 800);
// Update the litestore.
bigModel.litestore.beginTransaction();
updateLitestore(bigModel, update);
bigModel.litestore.endTransaction();
// Fetch the map to get the right indices.
const { rowMap } = bigModel.litestore.getRecord({
schema: DSVEditor.DATAMODEL_SCHEMA,
record: DSVEditor.RECORD_ID
});
const row = rowMap[800];
// Update the data matrix.
dataMatrix[row] = new Array(dataMatrix.length[0]).fill('');
// Serialize.
const string = bigModel.updateString();
// Compare.
const same = string === dataMatrix.map(row => row.join(',')).join('\n');
expect(same).toBe(true);
});
});
it('Should clear a column', () => {
bigModel.model.ready.then(() => {
const update = bigModel.clearColumns('body', 700);
// Update the litestore.
bigModel.litestore.beginTransaction();
updateLitestore(bigModel, update);
bigModel.litestore.endTransaction();
// Fetch the map to get the right indices.
const { columnMap } = bigModel.litestore.getRecord({
schema: DSVEditor.DATAMODEL_SCHEMA,
record: DSVEditor.RECORD_ID
});
const column = columnMap[700];
// Update the data matrix.
dataMatrix.forEach((elem, index) => {
dataMatrix[index][column] = '';
});
// Serialize.
const string = bigModel.updateString();
// Compare.
const same = string === dataMatrix.map(row => row.join(',')).join('\n');
expect(same).toBe(true);
});
});
it('Should move a row', () => {
bigModel.model.ready.then(() => {
const update = bigModel.moveRows('body', 900, 950, 1);
// Update the litestore.
bigModel.litestore.beginTransaction();
updateLitestore(bigModel, update);
bigModel.litestore.endTransaction();
// Fetch the map to get the right indices.
const { rowMap } = bigModel.litestore.getRecord({
schema: DSVEditor.DATAMODEL_SCHEMA,
record: DSVEditor.RECORD_ID
});
const start = rowMap[900];
const end = rowMap[950];
// Update the data matrix.
[dataMatrix[start], dataMatrix[end]] = [
dataMatrix[end],
dataMatrix[start]
];
// Serialize
const string = bigModel.updateString();
// Compare
const same = string === dataMatrix.map(row => row.join(',')).join('\n');
expect(same).toBe(true);
});
});
it('Should move a column', () => {
bigModel.model.ready.then(() => {
const update = bigModel.moveColumns('body', 5, 2, 1);
// Update the litestore
bigModel.litestore.beginTransaction();
updateLitestore(bigModel, update);
bigModel.litestore.endTransaction();
// Fetch the map to get the right indices.
const { columnMap } = bigModel.litestore.getRecord({
schema: DSVEditor.DATAMODEL_SCHEMA,
record: DSVEditor.RECORD_ID
});
const start = columnMap[5];
const end = columnMap[2];
// Update the data matrix.
dataMatrix.forEach(row => {
[row[end], row[start]] = [row[start], row[end]];
});
// Serialize
const string = bigModel.updateString();
// Compare
const same = string === dataMatrix.map(row => row.join(',')).join('\n');
expect(same).toBe(true);
});
});
// TODO: Add these tests
// it('Should remove a row', () => {
// bigModel.model.ready.then(() => {
// })
// })
it('Should remove a column', () => {
bigModel.model.ready.then(() => {
const update = bigModel.removeColumns('body', dataMatrix[0].length - 1);
// Update the litestore
bigModel.litestore.beginTransaction();
updateLitestore(bigModel, update);
bigModel.litestore.endTransaction();
// Fetch the map to get the right indices.
const { columnMap } = bigModel.litestore.getRecord({
schema: DSVEditor.DATAMODEL_SCHEMA,
record: DSVEditor.RECORD_ID
});
const column = columnMap[dataMatrix[0].length - 1];
// Update the data matrix.
dataMatrix.forEach(row => {
row.splice(column, 1);
});
// Serialize.
const string = bigModel.updateString();
// Compare.
const same = string === dataMatrix.map(row => row.join(',')).join('\n');
expect(same).toBe(true);
});
});
// })
// })
// })
// it('Should clear a cell selection', () => {
// bigModel.model.ready.then(() => {
// })
// });
it('Should add multiple rows to the end', () => {
bigModel.model.ready.then(() => {
const update = bigModel.addRows('body', dataMatrix.length - 1, 2);
// Update the litestore.
bigModel.litestore.beginTransaction();
updateLitestore(bigModel, update);
bigModel.litestore.endTransaction();
// Fetch the map to get the right indices.
const { rowMap } = bigModel.litestore.getRecord({
schema: DSVEditor.DATAMODEL_SCHEMA,
record: DSVEditor.RECORD_ID
});
const row = rowMap[dataMatrix.length - 1];
// Update the data matrix.
dataMatrix.splice(row, 0, new Array(dataMatrix[0].length).fill(''));
dataMatrix.splice(row, 0, new Array(dataMatrix[0].length).fill(''));
// Serialize
const string = bigModel.updateString();
// Compare
const same = string === dataMatrix.map(row => row.join(',')).join('\n');
expect(same).toBe(true);
});
});
it('Should add multiple columns to the end', () => {
bigModel.model.ready.then(() => {
const update = bigModel.addColumns('body', dataMatrix.length - 1, 2);
// Update the litestore.
bigModel.litestore.beginTransaction();
updateLitestore(bigModel, update);
bigModel.litestore.endTransaction();
// Fetch the map to get the right indices.
const { columnMap } = bigModel.litestore.getRecord({
schema: DSVEditor.DATAMODEL_SCHEMA,
record: DSVEditor.RECORD_ID
});
const column = columnMap[dataMatrix.length - 1];
// Update the data matrix.
dataMatrix.forEach(elem => {
elem.splice(column, 0, '', '');
});
// Serialize.
const string = bigModel.updateString();
// Compare.
const same = string === dataMatrix.map(row => row.join(',')).join('\n');
expect(same).toBe(true);
});
});
it('Should cut a region and paste to another region', () => {
bigModel.model.ready.then(() => {
let update = bigModel.cut('body', 500, 3, 550, 5);
// Update the litestore.
bigModel.litestore.beginTransaction();
updateLitestore(bigModel, update);
bigModel.litestore.endTransaction();
// Fetch the map to get the right indices.
const { columnMap, rowMap } = bigModel.litestore.getRecord({
schema: DSVEditor.DATAMODEL_SCHEMA,
record: DSVEditor.RECORD_ID
});
// Initialize an array to hold copied data.
const copyData = [];
// Update the data matrix.
for (let row = 500; row <= 550; row++) {
row = rowMap[row];
// Initialize the row data.
const rowData = [];
for (let column = 3; column <= 5; column++) {
column = columnMap[column];
rowData.push(dataMatrix[row][column]);
dataMatrix[row][column] = '';
}
copyData.push(rowData);
}
// Serialize.
let string = bigModel.updateString();
// Compare.
let same = string === dataMatrix.map(row => row.join(',')).join('\n');
expect(same).toBe(true);
update = bigModel.paste('body', 600, 600);
// Update the litestore.
bigModel.litestore.beginTransaction();
updateLitestore(bigModel, update);
bigModel.litestore.endTransaction();
// Initialize variables to iterate on the copy data.
let i = 0;
let j = 0;
// Update the data matrix.
for (let row = 500; row <= 550; row++) {
row = rowMap[row];
for (let column = 3; column <= 5; column++) {
column = columnMap[column];
dataMatrix[row][column] = copyData[i][j];
j++;
}
i++;
j = 0;
}
// Serialize.
string = bigModel.updateString();
// Compare.
same = string === dataMatrix.map(row => row.join(',')).join('\n');
expect(same).toBe(true);
});
});
it('Should compute the correct data types', () => {
bigModel.model.ready.then(() => {
const correctTypes = [
'string',
'string',
'string',
'string',
'string',
'date',
'integer',
'date',
'integer',
'number',
'number',
'number',
'number',
'number'
];
// Turn data formatting on.
bigModel.isDataFormatted = true;
// Generate an array with just the types.
const types = bigModel.dataTypes.map(elem => elem.type);
// Compare.
expect(types).toBe(correctTypes);
});
});
it('Should undo to the original state', () => {
bigModel.model.ready.then(() => {
// Recreate the original matrix.
const originalMatrix = DATA.split('\n').map(row => row.split(','));
// Fetch the undo stack.
const undoStack = bigModel.litestore.transactionStore.undoStack;
// Undo to the original state.
while (undoStack.length > 0) {
bigModel.litestore.undo();
}
// Serialize.
const string = bigModel.updateString();
// Compare.
const same =
string === originalMatrix.map(row => row.join(',')).join('\n');
expect(same).toBe(true);
});
});
it('Should redo to the last state', () => {
bigModel.model.ready.then(() => {
// Fetch the redo stack.
const redoStack = bigModel.litestore.transactionStore.undoStack;
// Redo to the last state.
while (redoStack.length > 0) {
bigModel.litestore.redo();
}
// Serialize.
const string = bigModel.updateString();
// Compare.
const same = string === dataMatrix.map(row => row.join(',')).join('\n');
expect(same).toBe(true);
});
});
}); | the_stack |
import { AbilitableManageProxyAbilities } from '@0xcert/ethereum-proxy-contracts/src/core/types';
import { XcertAbilities } from '@0xcert/ethereum-xcert-contracts/src/core/types';
import { Spec } from '@specron/spec';
import { ActionsGatewayAbilities } from '../../../core/types';
import * as common from '../../helpers/common';
import { getSignature } from '../../helpers/signature';
/**
* Test definition.
* ERC-721: Cat
*/
interface Data {
actionsGateway?: any;
abilitableManageProxy?: any;
cat?: any;
owner?: string;
jane?: string;
sara?: string;
zeroAddress?: string;
}
const spec = new Spec<Data>();
spec.before(async (ctx) => {
const accounts = await ctx.web3.eth.getAccounts();
ctx.set('owner', accounts[0]);
ctx.set('jane', accounts[1]);
ctx.set('sara', accounts[2]);
ctx.set('zeroAddress', '0x0000000000000000000000000000000000000000');
});
/**
* Cat
*/
spec.beforeEach(async (ctx) => {
const cat = await ctx.deploy({
src: '@0xcert/ethereum-xcert-contracts/build/xcert-mock.json',
contract: 'XcertMock',
args: ['cat', 'CAT', 'https://0xcert.org/', '.json', '0xa65de9e6', []],
});
ctx.set('cat', cat);
});
spec.beforeEach(async (ctx) => {
const abilitableManageProxy = await ctx.deploy({
src: '@0xcert/ethereum-proxy-contracts/build/abilitable-manage-proxy.json',
contract: 'AbilitableManageProxy',
});
ctx.set('abilitableManageProxy', abilitableManageProxy);
});
spec.beforeEach(async (ctx) => {
const abilitableManageProxy = ctx.get('abilitableManageProxy');
const owner = ctx.get('owner');
const actionsGateway = await ctx.deploy({
src: './build/actions-gateway.json',
contract: 'ActionsGateway',
});
await actionsGateway.instance.methods.grantAbilities(owner, ActionsGatewayAbilities.SET_PROXIES).send();
await actionsGateway.instance.methods.addProxy(abilitableManageProxy.receipt._address, 3).send({ from: owner });
ctx.set('actionsGateway', actionsGateway);
});
spec.beforeEach(async (ctx) => {
const actionsGateway = ctx.get('actionsGateway');
const owner = ctx.get('owner');
const abilitableManageProxy = ctx.get('abilitableManageProxy');
await abilitableManageProxy.instance.methods.grantAbilities(actionsGateway.receipt._address, AbilitableManageProxyAbilities.EXECUTE).send({ from: owner });
});
spec.test('Successfully sets ability no signature', async (ctx) => {
const actionsGateway = ctx.get('actionsGateway');
const abilitableManageProxy = ctx.get('abilitableManageProxy');
const jane = ctx.get('jane');
const owner = ctx.get('owner');
const cat = ctx.get('cat');
const createAbility = '0x0000000000000000000000000000000000000000000000000000000000000010'; // create asset in hex uint256
const actions = [
{
proxyId: 0,
contractAddress: cat.receipt._address,
params: `${createAbility}${jane.substring(2)}00`,
},
];
const orderData = {
signers: [owner],
actions,
seed: common.getCurrentTime(),
expirationTimestamp: common.getCurrentTime() + 3600,
};
const createTuple = ctx.tuple(orderData);
const signatureDataTuple = ctx.tuple([]);
let janeCreateAsset = await cat.instance.methods.isAble(jane, XcertAbilities.CREATE_ASSET).call();
ctx.false(janeCreateAsset);
await cat.instance.methods.grantAbilities(abilitableManageProxy.receipt._address, XcertAbilities.MANAGE_ABILITIES).send({ from: owner });
const logs = await actionsGateway.instance.methods.perform(createTuple, signatureDataTuple).send({ from: owner });
ctx.not(logs.events.Perform, undefined);
janeCreateAsset = await cat.instance.methods.isAble(jane, XcertAbilities.CREATE_ASSET).call();
ctx.true(janeCreateAsset);
});
spec.test('Successfully sets ability with signature', async (ctx) => {
const actionsGateway = ctx.get('actionsGateway');
const abilitableManageProxy = ctx.get('abilitableManageProxy');
const jane = ctx.get('jane');
const owner = ctx.get('owner');
const cat = ctx.get('cat');
const createAbility = '0x0000000000000000000000000000000000000000000000000000000000000010'; // create asset in hex uint256
const actions = [
{
proxyId: 0,
contractAddress: cat.receipt._address,
params: `${createAbility}${jane.substring(2)}00`,
},
];
const orderData = {
signers: [owner],
actions,
seed: common.getCurrentTime(),
expirationTimestamp: common.getCurrentTime() + 3600,
};
const createTuple = ctx.tuple(orderData);
const claim = await actionsGateway.instance.methods.getOrderDataClaim(createTuple).call();
const signature = await getSignature(ctx.web3, claim, owner);
const signatureDataTuple = ctx.tuple([signature]);
let janeCreateAsset = await cat.instance.methods.isAble(jane, XcertAbilities.CREATE_ASSET).call();
ctx.false(janeCreateAsset);
await cat.instance.methods.grantAbilities(abilitableManageProxy.receipt._address, XcertAbilities.MANAGE_ABILITIES).send({ from: owner });
const logs = await actionsGateway.instance.methods.perform(createTuple, signatureDataTuple).send({ from: jane });
ctx.not(logs.events.Perform, undefined);
janeCreateAsset = await cat.instance.methods.isAble(jane, XcertAbilities.CREATE_ASSET).call();
ctx.true(janeCreateAsset);
});
spec.test('Successfully sets ability with any taker', async (ctx) => {
const actionsGateway = ctx.get('actionsGateway');
const abilitableManageProxy = ctx.get('abilitableManageProxy');
const jane = ctx.get('jane');
const owner = ctx.get('owner');
const cat = ctx.get('cat');
const createAbility = '0x0000000000000000000000000000000000000000000000000000000000000010'; // create asset in hex uint256
const zeroAddress = ctx.get('zeroAddress');
const actions = [
{
proxyId: 0,
contractAddress: cat.receipt._address,
params: `${createAbility}${zeroAddress.substring(2)}00`,
},
];
const orderData = {
signers: [owner, zeroAddress],
actions,
seed: common.getCurrentTime(),
expirationTimestamp: common.getCurrentTime() + 3600,
};
const createTuple = ctx.tuple(orderData);
const claim = await actionsGateway.instance.methods.getOrderDataClaim(createTuple).call();
const signature = await getSignature(ctx.web3, claim, owner);
const signatureDataTuple = ctx.tuple([signature]);
let janeCreateAsset = await cat.instance.methods.isAble(jane, XcertAbilities.CREATE_ASSET).call();
ctx.false(janeCreateAsset);
await cat.instance.methods.grantAbilities(abilitableManageProxy.receipt._address, XcertAbilities.MANAGE_ABILITIES).send({ from: owner });
const logs = await actionsGateway.instance.methods.perform(createTuple, signatureDataTuple).send({ from: jane });
ctx.not(logs.events.Perform, undefined);
janeCreateAsset = await cat.instance.methods.isAble(jane, XcertAbilities.CREATE_ASSET).call();
ctx.true(janeCreateAsset);
});
spec.test('Successfully sets ability with any signer', async (ctx) => {
const actionsGateway = ctx.get('actionsGateway');
const abilitableManageProxy = ctx.get('abilitableManageProxy');
const jane = ctx.get('jane');
const sara = ctx.get('sara');
const owner = ctx.get('owner');
const cat = ctx.get('cat');
const createAbility = '0x0000000000000000000000000000000000000000000000000000000000000010'; // create asset in hex uint256
const zeroAddress = ctx.get('zeroAddress');
const actions = [
{
proxyId: 0,
contractAddress: cat.receipt._address,
params: `${createAbility}${zeroAddress.substring(2)}00`,
},
];
const orderData = {
signers: [owner, zeroAddress],
actions,
seed: common.getCurrentTime(),
expirationTimestamp: common.getCurrentTime() + 3600,
};
const createTuple = ctx.tuple(orderData);
const claim = await actionsGateway.instance.methods.getOrderDataClaim(createTuple).call();
const signature = await getSignature(ctx.web3, claim, owner);
const signature2 = await getSignature(ctx.web3, claim, jane);
const signatureDataTuple = ctx.tuple([signature, signature2]);
let janeCreateAsset = await cat.instance.methods.isAble(jane, XcertAbilities.CREATE_ASSET).call();
ctx.false(janeCreateAsset);
await cat.instance.methods.grantAbilities(abilitableManageProxy.receipt._address, XcertAbilities.MANAGE_ABILITIES).send({ from: owner });
const logs = await actionsGateway.instance.methods.perform(createTuple, signatureDataTuple).send({ from: sara });
ctx.not(logs.events.Perform, undefined);
janeCreateAsset = await cat.instance.methods.isAble(jane, XcertAbilities.CREATE_ASSET).call();
ctx.true(janeCreateAsset);
});
spec.test('Successfully removes own manage ability', async (ctx) => {
const actionsGateway = ctx.get('actionsGateway');
const abilitableManageProxy = ctx.get('abilitableManageProxy');
const jane = ctx.get('jane');
const owner = ctx.get('owner');
const cat = ctx.get('cat');
const noAbilities = '0x0000000000000000000000000000000000000000000000000000000000000000'; // no abilities in hex uint256
const actions = [
{
proxyId: 0,
contractAddress: cat.receipt._address,
params: `${noAbilities}${owner.substring(2)}00`,
},
];
const orderData = {
signers: [owner],
actions,
seed: common.getCurrentTime(),
expirationTimestamp: common.getCurrentTime() + 3600,
};
const createTuple = ctx.tuple(orderData);
const claim = await actionsGateway.instance.methods.getOrderDataClaim(createTuple).call();
const signature = await getSignature(ctx.web3, claim, owner);
const signatureDataTuple = ctx.tuple([signature]);
let ownerManageAbilitites = await cat.instance.methods.isAble(owner, XcertAbilities.MANAGE_ABILITIES).call();
ctx.true(ownerManageAbilitites);
await cat.instance.methods.grantAbilities(abilitableManageProxy.receipt._address, XcertAbilities.MANAGE_ABILITIES).send({ from: owner });
const logs = await actionsGateway.instance.methods.perform(createTuple, signatureDataTuple).send({ from: jane });
ctx.not(logs.events.Perform, undefined);
ownerManageAbilitites = await cat.instance.methods.isAble(owner, XcertAbilities.MANAGE_ABILITIES).call();
ctx.false(ownerManageAbilitites);
});
spec.test('Successfully sets multiple abilities', async (ctx) => {
const actionsGateway = ctx.get('actionsGateway');
const abilitableManageProxy = ctx.get('abilitableManageProxy');
const jane = ctx.get('jane');
const owner = ctx.get('owner');
const cat = ctx.get('cat');
const createAndRevokeAssetAbilities = '0x0000000000000000000000000000000000000000000000000000000000000030'; // create and revoke in hex uint256
const manageAbilities = '0x0000000000000000000000000000000000000000000000000000000000000001'; // manage abilities in hex uint256
const actions = [
{
proxyId: 0,
contractAddress: cat.receipt._address,
params: `${createAndRevokeAssetAbilities}${jane.substring(2)}00`,
},
{
proxyId: 0,
contractAddress: cat.receipt._address,
params: `${manageAbilities}${owner.substring(2)}00`,
},
];
const orderData = {
signers: [owner],
actions,
seed: common.getCurrentTime(),
expirationTimestamp: common.getCurrentTime() + 3600,
};
const createTuple = ctx.tuple(orderData);
const claim = await actionsGateway.instance.methods.getOrderDataClaim(createTuple).call();
const signature = await getSignature(ctx.web3, claim, owner);
const signatureDataTuple = ctx.tuple([signature]);
let janeCatCreateAsset = await cat.instance.methods.isAble(jane, XcertAbilities.CREATE_ASSET).call();
let janeCatRevokeAsset = await cat.instance.methods.isAble(jane, XcertAbilities.REVOKE_ASSET).call();
let ownerCatAllowManageAbilitites = await cat.instance.methods.isAble(owner, XcertAbilities.ALLOW_MANAGE_ABILITIES).call();
ctx.false(janeCatCreateAsset);
ctx.false(janeCatRevokeAsset);
ctx.true(ownerCatAllowManageAbilitites);
await cat.instance.methods.grantAbilities(abilitableManageProxy.receipt._address, XcertAbilities.MANAGE_ABILITIES).send({ from: owner });
const logs = await actionsGateway.instance.methods.perform(createTuple, signatureDataTuple).send({ from: jane });
ctx.not(logs.events.Perform, undefined);
janeCatCreateAsset = await cat.instance.methods.isAble(jane, XcertAbilities.CREATE_ASSET).call();
janeCatRevokeAsset = await cat.instance.methods.isAble(jane, XcertAbilities.REVOKE_ASSET).call();
ownerCatAllowManageAbilitites = await cat.instance.methods.isAble(owner, XcertAbilities.ALLOW_MANAGE_ABILITIES).call();
ctx.true(janeCatCreateAsset);
ctx.true(janeCatRevokeAsset);
ctx.false(ownerCatAllowManageAbilitites);
});
export default spec; | the_stack |
export namespace Messages {
// Default Application
export interface Application {}
// Class
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* A scriptable object.
*/
export interface Item {
/**
* The class of the object.
*/
class(): any;
/**
* All of the object's properties.
*/
properties(): any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* The application's top-level scripting object.
*/
export interface Application {
/**
* The name of the application.
*/
name(): string;
/**
* Is this the frontmost (active) application?
*/
frontmost(): boolean;
/**
* The version of the application.
*/
version(): string;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* A color.
*/
export interface Color {}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* An Messages document.
*/
export interface Document {
/**
* The document's name.
*/
name(): string;
/**
* Has the document been modified since the last save?
*/
modified(): boolean;
/**
* The document's location on disk.
*/
file(): any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* A window.
*/
export interface Window {
/**
* The full title of the window.
*/
name(): string;
/**
* The unique identifier of the window.
*/
id(): number;
/**
* The index of the window, ordered front to back.
*/
index(): number;
/**
* The bounding rectangle of the window.
*/
bounds(): any;
/**
* Whether the window has a close box.
*/
closeable(): boolean;
/**
* Whether the window can be minimized.
*/
minimizable(): boolean;
/**
* Whether the window is currently minimized.
*/
minimized(): boolean;
/**
* Whether the window can be resized.
*/
resizable(): boolean;
/**
* Whether the window is currently visible.
*/
visible(): boolean;
/**
* Whether the window can be zoomed.
*/
zoomable(): boolean;
/**
* Whether the window is currently zoomed.
*/
zoomed(): boolean;
/**
* The document whose contents are being displayed in the window.
*/
document(): any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* Rich (styled) text
*/
export interface RichText {
/**
* The color of the first character.
*/
color(): any;
/**
* The name of the font of the first character.
*/
font(): string;
/**
* The size in points of the first character.
*/
size(): any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* This subdivides the text into characters.
*/
export interface Character {
/**
* The color of the first character.
*/
color(): any;
/**
* The name of the font of the first character.
*/
font(): string;
/**
* The size in points of the first character.
*/
size(): number;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* This subdivides the text into paragraphs.
*/
export interface Paragraph {
/**
* The color of the first character.
*/
color(): any;
/**
* The name of the font of the first character.
*/
font(): string;
/**
* The size in points of the first character.
*/
size(): number;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* This subdivides the text into words.
*/
export interface Word {
/**
* The color of the first character.
*/
color(): any;
/**
* The name of the font of the first character.
*/
font(): string;
/**
* The size in points of the first character.
*/
size(): number;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* This subdivides the text into chunks that all have the same attributes.
*/
export interface AttributeRun {
/**
* The color of the first character.
*/
color(): any;
/**
* The name of the font of the first character.
*/
font(): string;
/**
* The size in points of the first character.
*/
size(): number;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* Represents an inline text attachment. This class is used mainly for make commands.
*/
export interface Attachment {
/**
* The path to the file for the attachment
*/
file(): any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* Messages application.
*/
export interface Application {
/**
* Time in seconds that I have been idle.
*/
idleTime(): number;
/**
* My image as it appears in all services.
*/
image(): any;
/**
* My status on all services.
*/
status(): any;
/**
* My status message, visible to other people while I am online.
*/
statusMessage(): string;
/**
* The currently active audio or video chat.
*/
activeAvChat(): any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* A buddy on a service.
*/
export interface Buddy {
/**
* The buddy's service and handle. For example: AIM:JohnDoe007
*/
id(): string;
/**
* The service on which this buddy exists.
*/
service(): any;
/**
* The buddy's name as it appears in the buddy list.
*/
name(): string;
/**
* The buddy's online account name.
*/
handle(): string;
/**
* The buddy's current status.
*/
status(): any;
/**
* The buddy's current status message.
*/
statusMessage(): string;
/**
* The time in seconds the buddy has been idle.
*/
idleTime(): number;
/**
* The buddy's messaging capabilities.
*/
capabilities(): any;
/**
* The buddy's custom image.
*/
image(): any;
scriptAccountLegacyName(): string;
/**
* The first name from this buddy's Contacts card, if available
*/
firstName(): string;
/**
* The last name from this buddy's Contacts card, if available
*/
lastName(): string;
/**
* The full name from this buddy's Contacts card, if available
*/
fullName(): string;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* A service that can be logged in from this system
*/
export interface Service {
/**
* A guid identifier for this service.
*/
id(): string;
/**
* The name of this service as defined in Account preferences description field
*/
name(): string;
/**
* My image as it appears in all services.
*/
image(): any;
/**
* Is the service enabled?
*/
enabled(): boolean;
/**
* The connection status for this account.
*/
connectionStatus(): any;
/**
* My status on this service.
*/
status(): any;
/**
* My status message, visible to other people on this service while I am online.
*/
statusMessage(): string;
/**
* The type of protocol for this service
*/
serviceType(): any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* An audio, video, or text chat.
*/
export interface Chat {
/**
* A guid identifier for this chat.
*/
id(): string;
/**
* The service which is participating in this chat.
*/
service(): any;
/**
* Other participants of this chat. This property may be specified at time of creation.
*/
participants(): any;
/**
* Is this chat secure?
*/
secure(): boolean;
/**
* Is this an invitation to a chat?
*/
invitation(): boolean;
/**
* Is this chat currently active?
*/
active(): boolean;
/**
* The date on which this chat started.
*/
started(): any;
/**
* The date when this chat was last updated.
*/
updated(): any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* A text chat.
*/
export interface TextChat {
/**
* The subject of this chat, if available.
*/
subject(): string;
/**
* An invitation message. This may only be specified at the time of creation. This message will be sent to chat participants when the chat is created.
*/
invitationMessage(): string;
/**
* How you are joined to this chat
*/
joinState(): any;
/**
* The address or room name of this chat. This property may be specified at time of creation.
*/
name(): string;
/**
* The type of this chat.
*/
chatType(): any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* An audio or video chat.
*/
export interface AudioChat {
/**
* Is the chat muted?
*/
muted(): boolean;
/**
* The connection state for this av chat.
*/
avConnectionStatus(): any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface VideoChat {
/**
* Is the chat paused?
*/
paused(): boolean;
/**
* Is the chat being displayed in full screen mode?
*/
showingFullScreen(): boolean;
/**
* Is the local video preview being displayed?
*/
showingLocalVideo(): boolean;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* A request to be added to someone else's buddy list
*/
export interface AuthorizationRequest {
/**
* The guid for this authorization request
*/
id(): string;
/**
* The service on which authorization was requested.
*/
service(): any;
/**
* The buddy requesting authorization
*/
buddy(): any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* A file being sent or received
*/
export interface FileTransfer {
/**
* The guid for this file transfer
*/
id(): string;
/**
* The name of this file
*/
name(): string;
/**
* The local path to this file transfer
*/
file(): any;
/**
* The direction in which this file is being sent
*/
direction(): any;
/**
* The service on which this file transfer is taking place
*/
service(): any;
/**
* The account participating in this file transfer
*/
buddy(): any;
/**
* Is this file transfer secure?
*/
secure(): boolean;
/**
* The total size in bytes of the completed file transfer
*/
fileSize(): number;
/**
* The number of bytes that have been transferred
*/
fileProgress(): number;
/**
* The current status of this file transfer
*/
transferStatus(): any;
/**
* The date that this file transfer started
*/
started(): any;
}
// CLass Extension
// Records
// Function options
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface CloseOptionalParameter {
/**
* Whether or not changes should be saved before closing.
*/
saving?: any;
/**
* The file in which to save the document.
*/
savingIn?: any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface SaveOptionalParameter {
/**
* The file in which to save the document.
*/
in?: any;
/**
* The type of file to save.
*/
as?: string;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface SetOptionalParameter {
/**
* The new value.
*/
to: any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface QuitOptionalParameter {
/**
* Whether or not changed documents should be saved before closing.
*/
saving?: any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface CountOptionalParameter {
/**
* The class of objects to be counted.
*/
each?: any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface DuplicateOptionalParameter {
/**
* The location for the new object(s).
*/
to?: any;
/**
* Properties to be set in the new duplicated object(s).
*/
withProperties?: any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface MakeOptionalParameter {
/**
* The class of the new object.
*/
new: any;
/**
* The location at which to insert the object.
*/
at?: any;
/**
* The initial contents of the object.
*/
withContents?: any;
/**
* The initial values for properties of the object.
*/
withProperties?: any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface MoveOptionalParameter {
/**
* The new location for the object(s).
*/
to: any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface InviteOptionalParameter {
to: any;
/**
* For text chats, an invitation message to send to this participant. This parameter is required for text chat invitations and ignored for other types of chats.
*/
withMessage?: string;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface SendOptionalParameter {
to: any;
}
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface ShowChatChooserOptionalParameter {
for: any;
}
}
export interface Messages extends Messages.Application {
// Functions
/**
* Open a document.
* @param directParameter The file(s) to be opened.
*
*/
open(directParameter: {}, ): void;
/**
* Close a document.
* @param directParameter the document(s) or window(s) to close.
* @param option
*
*/
close(directParameter: any, option?: Messages.CloseOptionalParameter): void;
/**
* Save a document.
* @param directParameter The document(s) or window(s) to save.
* @param option
*
*/
save(directParameter: any, option?: Messages.SaveOptionalParameter): void;
/**
* Set an object's data.
* @param directParameter undefined
* @param option
*
*/
set(directParameter: any, option?: Messages.SetOptionalParameter): void;
/**
* Print an object.
* @param directParameter The file(s) or document(s) to be printed.
*
*/
print(directParameter: any, ): void;
/**
* Quit the application.
* @param option
*
*/
quit(option?: Messages.QuitOptionalParameter): void;
/**
* Return the number of elements of a particular class within an object.
* @param directParameter the object whose elements are to be counted
* @param option
* @return the number of elements
*/
count(directParameter: any, option?: Messages.CountOptionalParameter): number;
/**
* Delete an object.
* @param directParameter the object to delete
*
*/
delete(directParameter: any, ): void;
/**
* Copy object(s) and put the copies at a new location.
* @param directParameter the object(s) to duplicate
* @param option
* @return to the duplicated object(s)
*/
duplicate(directParameter: any, option?: Messages.DuplicateOptionalParameter): any;
/**
* Verify if an object exists.
* @param directParameter the object in question
* @return true if it exists, false if not
*/
exists(directParameter: any, ): boolean;
/**
* Get the data for an object.
* @param directParameter undefined
* @return undefined
*/
get(directParameter: any, ): any;
/**
* Make a new object.
* @param option
* @return to the new object
*/
make(option?: Messages.MakeOptionalParameter): any;
/**
* Move object(s) to a new location.
* @param directParameter the object(s) to move
* @param option
* @return to the moved object(s)
*/
move(directParameter: any, option?: Messages.MoveOptionalParameter): any;
/**
* Invites a buddy to join an existing chat.
* @param directParameter undefined
* @param option
*
*/
invite(directParameter: {}, option?: Messages.InviteOptionalParameter): void;
/**
* Log in to the specified service, or all services if none is specified. If the account password is not in the keychain the user will be prompted to enter one.
* @param directParameter undefined
*
*/
logIn(directParameter?: {}, ): void;
/**
* Logs out of a service, or all services if none is specified.
* @param directParameter undefined
*
*/
logOut(directParameter?: {}, ): void;
/**
* Sends a message or file to a buddy or to a chat.
* @param directParameter undefined
* @param option
*
*/
send(directParameter: {}, option?: Messages.SendOptionalParameter): void;
/**
* Stores the currently set buddy picture into your recent pictures.
*
*/
storeRecentPicture(): void;
/**
* displays a dialog in Messages to start a new chat with the specified buddy
* @param option
*
*/
showChatChooser(option?: Messages.ShowChatChooserOptionalParameter): void;
/**
* Takes a snapshot of a video chat and saves it to a desktop.
* @param directParameter undefined
*
*/
takeSnapshot(directParameter: {}, ): void;
/**
* Accepts an incoming text, audio, or video chat invitation, or file transfer
* @param directParameter undefined
*
*/
accept(directParameter: {}, ): void;
/**
* Declines an incoming text, audio, or video chat invitation, or file transfer
* @param directParameter undefined
*
*/
decline(directParameter: {}, ): void;
/**
* Sends a recording request to all participants of an audio or video chat. Recording will not start until all participants have agreed to allow recording.
* @param directParameter undefined
*
*/
requestRecording(directParameter: {}, ): void;
/**
* Ends recording of an audio or video chat.
* @param directParameter undefined
*
*/
stopRecording(directParameter: {}, ): void;
} | the_stack |
import { Component, OnInit, OnChanges, Input, Output, ViewChild, EventEmitter } from '@angular/core';
import { AttrValueVO, AttributeVO, Pair } from './../model/index';
import { ImpexService, I18nEventBus, Util } from './../services/index';
import { UiUtil } from './../ui/index';
import { ModalComponent, ModalResult, ModalAction } from './../modal/index';
import { FormValidationEvent, Futures, Future } from './../event/index';
import { Config } from './../../../environments/environment';
import { LogUtil } from './../log/index';
@Component({
selector: 'cw-attribute-values',
templateUrl: 'attribute-values.component.html',
})
export class AttributeValuesComponent implements OnInit, OnChanges {
@Input() masterObject:any;
@Input() avPrototype:AttrValueVO;
@Input() masterObjectType:string;
@Input() showHelp:boolean = false;
@Output() dataSelected: EventEmitter<AttrValueVO> = new EventEmitter<AttrValueVO>();
@Output() dataChanged: EventEmitter<FormValidationEvent<Array<Pair<AttrValueVO, boolean>>>> = new EventEmitter<FormValidationEvent<Array<Pair<AttrValueVO, boolean>>>>();
@Output() pageSelected: EventEmitter<number> = new EventEmitter<number>();
@Output() sortSelected: EventEmitter<Pair<string, boolean>> = new EventEmitter<Pair<string, boolean>>();
//sorting
public sortColumn:string = 'name';
public sortDesc:boolean = false;
//paging
public maxSize:number = Config.UI_TABLE_PAGE_NUMS;
public itemsPerPage:number = Config.UI_TABLE_PAGE_SIZE;
public totalItems:number = 0;
public currentPage:number = 1;
// Must use separate variables (not currentPage) for table since that causes
// cyclic even update and then exception https://github.com/angular/angular/issues/6005
public pageStart:number = 0;
public pageEnd:number = this.itemsPerPage;
private _objectAttributes:Array<AttrValueVO>;
private objectAttributesRemove:Array<number>;
private objectAttributesEdit:Array<number>;
private _imageOnlyMode:boolean;
private _attributeFilter:string;
public filteredObjectAttributes:Array<AttrValueVO>;
private delayedFiltering:Future;
private delayedFilteringMs:number = Config.UI_INPUT_DELAY;
public changed:boolean = false;
public validForSave:boolean = false;
@ViewChild('deleteConfirmationModalDialog')
private deleteConfirmationModalDialog:ModalComponent;
@ViewChild('editModalDialog')
private editModalDialog:ModalComponent;
@ViewChild('addModalDialog')
private addModalDialog:ModalComponent;
public selectedRow:AttrValueVO;
private selectedAttribute:AttributeVO;
public attributeToEdit:AttrValueVO;
public attributeToEditImagePreviewAvailable:boolean = true;
public attributeToEditImagePreview:string = '';
public booleanEditor:boolean = false;
public miniTextEditor:boolean = false;
public textEditor:boolean = false;
public textAreaEditor:boolean = false;
public selectEditor:boolean = false;
public selectEditorValues:Pair<string, string>[] = null;
public localisableEditor:boolean = false;
public imageEditor:boolean = false;
public fileEditor:boolean = false;
public lockedEditor:boolean = false;
public loading:boolean = false;
public loadingFilter:boolean = false;
/**
* Construct attribute panel
*/
constructor(private _impexService:ImpexService) {
LogUtil.debug('AttributeValuesComponent constructed');
this.attributeToEdit = null;
let that = this;
this.delayedFiltering = Futures.perpetual(function() {
that.filterAttributes();
}, this.delayedFilteringMs);
}
@Input()
set objectAttributes(objectAttributes:Array<AttrValueVO>) {
this._objectAttributes = objectAttributes;
this.loadData();
}
get objectAttributes():Array<AttrValueVO> {
return this._objectAttributes;
}
@Input()
set attributeFilter(attributeFilter:string) {
this._attributeFilter = attributeFilter;
this.delayedFiltering.delay();
}
@Input()
set sortorder(sort:Pair<string, boolean>) {
if (sort != null && (sort.first !== this.sortColumn || sort.second !== this.sortDesc)) {
this.sortColumn = sort.first;
this.sortDesc = sort.second;
this.delayedFiltering.delay();
}
}
@Input()
set imageOnlyMode(value: boolean) {
this._imageOnlyMode = value;
this.delayedFiltering.delay();
}
get imageOnlyMode(): boolean {
return this._imageOnlyMode;
}
set attributeToEditBoolean(val:boolean) {
this.attributeToEdit.val = '' + val;
}
get attributeToEditBoolean():boolean {
// Must use get/set because there is string to boolean conversion happens somewhere in binding,
// so: ngTrueValue="'true'" ngFalseValue="'false'" does not work
return this.attributeToEdit && ('' + this.attributeToEdit.val === 'true');
}
ngOnInit() {
LogUtil.debug('AttributeValuesComponent ngOnInit', this.masterObject);
}
ngOnChanges(changes:any) {
LogUtil.debug('AttributeValuesComponent ngOnChanges', changes);
this.delayedFiltering.delay();
}
onRowAdd() {
if (this.avPrototype != null) {
this.addModalDialog.show();
}
}
onRowDeleteSelected() {
if (this.selectedRow != null) {
this.onRowDelete(this.selectedRow);
}
}
onRowEditSelected() {
if (this.selectedRow != null) {
this.onRowEdit(this.selectedRow);
}
}
onRowDelete(row:AttrValueVO) {
LogUtil.debug('AttributeValuesComponent onRowDelete handler', row);
this.deleteConfirmationModalDialog.show();
}
onRowEdit(row:AttrValueVO) {
LogUtil.debug('AttributeValuesComponent onRowEdit handler', row);
this.validForSave = false;
this.attributeToEdit = Util.clone(row);
this.detectAttributeEditor(this.attributeToEdit);
this.processImageView(this.attributeToEdit);
this.editModalDialog.show();
}
onAttributeSelected(row:AttributeVO) {
this.selectedAttribute = row;
}
onAttributeAddModalResult(modalresult: ModalResult) {
LogUtil.debug('AttributeValuesComponent onAttributeAddModalResult modal result is ', modalresult);
if (ModalAction.POSITIVE === modalresult.action) {
let idx = this._objectAttributes.findIndex(attrVo => {return attrVo.attribute.code === this.selectedAttribute.code;} );
if (idx != -1) {
this.onRowEdit(this._objectAttributes[idx]);
} else {
let av = Util.clone(this.avPrototype);
av.attribute = this.selectedAttribute;
this.onRowEdit(av);
}
} else {
this.selectedAttribute = null;
}
}
onSelectRow(row:AttrValueVO) {
LogUtil.debug('AttributeValuesComponent onSelectRow handler', row);
if (row == this.selectedRow) {
this.selectedRow = null;
} else {
this.selectedRow = row;
}
this.dataSelected.emit(this.selectedRow);
}
onDataChange(event:any) {
let val = this.attributeToEdit.val;
let typ = this.attributeToEdit.attribute.etype;
let customRegEx = this.attributeToEdit.attribute.regexp;
if (customRegEx) {
let regex = new RegExp(customRegEx);
this.validForSave = regex.test(val);
} else {
switch (typ) {
case 'Integer':
case 'Timestamp':
this.validForSave = /^[\-]?[0-9]+$/.test(val);
break;
case 'Float':
this.validForSave = /^(([\-][0-9]+)|([0-9]*))[\.]?[0-9]+$/.test(val);
break;
case 'Phone':
this.validForSave = /^[\+]?[\(\)0-9\- ]+$/.test(val);
break;
case 'Email':
this.validForSave = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/.test(val);
break;
case 'DateTime':
this.validForSave = /^[0-9]{4}\-([0][1-9]|[1][0-2])\-([0][1-9]|[1-2][0-9]|[3][0-1])( ([0][0-9]|[1][0-9]|[2][0-3]):[0-5][0-9]:[0-5][0-9])?$/.test(val);
break;
case 'Date':
this.validForSave = /^[0-9]{4}\-([0][1-9]|[1][0-2])\-([0][1-9]|[1-2][0-9]|[3][0-1])?$/.test(val);
break;
case 'Any':
this.validForSave = true;
break;
default:
this.validForSave = val != null && /\S+(.*\S)*/.test(val);
break;
}
}
LogUtil.debug('AttributeValuesComponent data changed and ' + (this.validForSave ? 'is valid' : 'is NOT valid'), event);
}
onDeleteConfirmationResult(modalresult: ModalResult) {
LogUtil.debug('AttributeValuesComponent onDeleteConfirmationResult modal result is ', modalresult);
if (ModalAction.POSITIVE === modalresult.action) {
let attrToDelete = this.selectedRow.attrvalueId;
if (attrToDelete === 0) {
let idx = this._objectAttributes.findIndex(attrVo => {
return attrVo.attribute.code === this.selectedRow.attribute.code;
});
this._objectAttributes[idx].val = null;
LogUtil.debug('AttributeValuesComponent onDeleteConfirmationResult index in array of new attribute ' + idx);
} else {
LogUtil.debug('AttributeValuesComponent onDeleteConfirmationResult attribute ' + attrToDelete);
this.objectAttributesRemove.push(attrToDelete);
this.objectAttributesEdit.push(attrToDelete);
}
this.filterAttributes();
this.onSelectRow(null);
this.changed = true;
this.processDataChangesEvent();
} else {
this.attributeToEdit = null;
}
}
onEditModalResult(modalresult: ModalResult) {
LogUtil.debug('AttributeValuesComponent onEditModalResult modal result is ', modalresult);
this.detectAttributeEditor(null);
if (ModalAction.POSITIVE === modalresult.action) {
if (this.attributeToEdit.attrvalueId === 0) { // add new
LogUtil.debug('AttributeValuesComponent onEditModalResult add new attribute', this._objectAttributes);
let idx = this._objectAttributes.findIndex(attrVo => {return attrVo.attribute.code === this.attributeToEdit.attribute.code;} );
if (idx != -1) {
this._objectAttributes[idx] = this.attributeToEdit;
} else {
this._objectAttributes.push(this.attributeToEdit);
}
} else { // edit existing
LogUtil.debug('AttributeValuesComponent onEditModalResult update existing', this._objectAttributes);
let idx = this._objectAttributes.findIndex(attrVo => {return attrVo.attrvalueId === this.attributeToEdit.attrvalueId;} );
this._objectAttributes[idx] = this.attributeToEdit;
this.objectAttributesEdit.push(this.attributeToEdit.attrvalueId);
}
this.selectedRow = this.attributeToEdit;
this.changed = true;
this.filterAttributes();
this.processDataChangesEvent();
} else {
this.attributeToEdit = null;
}
}
isRemovedAttribute(row:AttrValueVO):boolean {
return this.objectAttributesRemove.indexOf(row.attrvalueId) !== -1;
}
isEditedAttribute(row:AttrValueVO):boolean {
return this.objectAttributesEdit.indexOf(row.attrvalueId) !== -1;
}
isNewAttribute(row:AttrValueVO):boolean {
return row.attrvalueId == 0 && row.val != null && row.val != '' && row.val.indexOf('* ') !== 0;
}
isInheritedAttribute(row:AttrValueVO):boolean {
return row.attrvalueId == 0 && row.val != null && row.val != '' && row.val.indexOf('* ') === 0;
}
getAttributeColor(row:AttrValueVO, removed:string, edited:string, added:string, inherited:string, prestine:string) {
if (this.isRemovedAttribute(row)) {
return removed;
}
if (this.isEditedAttribute(row)) {
return edited;
}
if (this.isNewAttribute(row)) {
return added;
}
if (this.isInheritedAttribute(row)) {
return inherited;
}
return prestine;
}
resetLastPageEnd() {
let _pageEnd = this.pageStart + this.itemsPerPage;
if (_pageEnd > this.totalItems) {
this.pageEnd = this.totalItems;
} else {
this.pageEnd = _pageEnd;
}
}
onPageChanged(event:any) {
if (this.currentPage != event.page) {
this.pageSelected.emit(event.page - 1);
}
this.pageStart = (event.page - 1) * this.itemsPerPage;
let _pageEnd = this.pageStart + this.itemsPerPage;
if (_pageEnd > this.totalItems) {
this.pageEnd = this.totalItems;
} else {
this.pageEnd = _pageEnd;
}
}
onSortClick(event:any) {
if (event == this.sortColumn) {
if (this.sortDesc) { // same column already desc, remove sort
this.sortColumn = 'name';
this.sortDesc = false;
} else { // same column asc, change to desc
this.sortColumn = event;
this.sortDesc = true;
}
} else { // different column, start asc sort
this.sortColumn = event;
this.sortDesc = false;
}
this.filterAttributes();
this.sortSelected.emit({ first: this.sortColumn, second: this.sortDesc });
}
getSearchFlags(row:AttributeVO) {
if (this.masterObjectType === 'product') {
let flags = '';
if (row.store) {
flags += '<i class="fa fa-save"></i> ';
}
if (row.search) {
if (row.primary) {
flags += '<i class="fa fa-search-plus"></i> ';
} else {
flags += '<i class="fa fa-search"></i> ';
}
}
if (row.navigation) {
flags += '<i class="fa fa-list-alt"></i> ';
}
return flags;
}
return ' ';
}
getDisplayValue(row:AttrValueVO):string {
if (row.val != null) {
if (row.attribute.etype === 'SecureString') {
return '*****';
}
if (row.attribute.etype === 'Boolean') {
if (('' + row.val) === 'true') {
return '<i class="fa fa-check-circle"></i>';
} else {
return '<i class="fa fa-times-circle"></i>';
}
} else if (row.attribute.etype === 'HTML' || row.attribute.etype === 'Properties') {
return '<pre>' + row.val + '</pre>';
} else if (row.attribute.etype === 'Image' && row.valBase64Data) {
return '<img class="av-image-thumb" src="' + row.valBase64Data + '" alt="' + row.val + '"/>';
}
return row.val;
}
return ' ';
}
detectAttributeEditor(av:AttrValueVO) {
this.booleanEditor = false;
this.miniTextEditor = false;
this.textEditor = false;
this.textAreaEditor = false;
this.selectEditor = false;
this.selectEditorValues = null;
this.localisableEditor = false;
this.imageEditor = false;
this.fileEditor = false;
this.lockedEditor = false;
if (av != null) {
switch (av.attribute.etype) {
case 'String':
case 'SecureString':
this.localisableEditor = true;
break;
case 'Boolean':
this.booleanEditor = true;
break;
case 'Image':
this.imageEditor = true;
break;
case 'File':
case 'SystemFile':
this.fileEditor = true;
break;
case 'CommaSeparatedList':
let lang = I18nEventBus.getI18nEventBus().current();
let _choice = UiUtil.toChoicePairs(av.attribute.choiceData, lang);
if (_choice != null) {
this.selectEditor = true;
this.selectEditorValues = _choice;
} else {
this.textAreaEditor = true;
}
break;
case 'HTML':
case 'Any':
case 'Properties':
this.textAreaEditor = true;
break;
case 'Float':
case 'Integer':
case 'Date':
case 'DateTime':
case 'Timestamp':
this.miniTextEditor = true;
break;
case 'Locked':
this.lockedEditor = true;
break;
default:
this.textEditor = true;
break;
}
}
}
processImageView(av:AttrValueVO) {
if (av.attribute.etype === 'Image') {
if (av.val != null) {
this.attributeToEditImagePreviewAvailable = av.valBase64Data != null;
if (this.attributeToEditImagePreviewAvailable) {
this.attributeToEditImagePreview = '<img src="' + av.valBase64Data + '"/>';
} else {
this.attributeToEditImagePreview = ' ';
}
} else {
this.attributeToEditImagePreviewAvailable = true;
this.attributeToEditImagePreview = ' ';
}
}
}
isImageUploadDisabled():boolean {
let input:any = document.getElementById('avmodaluploadimage');
return input == null || input.disabled;
}
onImageClickRelay() {
LogUtil.debug('AttributeValuesComponent image upload relay button click');
document.getElementById('avmodaluploadimage').click();
}
onImageFileSelected(event:any) {
let srcElement:any = event.target || event.srcElement;
let image:any = srcElement.files[0];
if (image != null) {
let imageName:string = image.name;
LogUtil.debug('AttributeValuesComponent image file selected', imageName);
let reader:FileReader = new FileReader();
this.loading = true;
let that = this;
reader.onloadend = function(e:any) {
LogUtil.debug('AttributeValuesComponent image file loaded', e.target.result);
that.attributeToEdit.val = imageName;
that.attributeToEdit.valBase64Data = e.target.result;
that.processImageView(that.attributeToEdit);
that.changed = true;
that.validForSave = true;
that.loading = false;
srcElement.value = '';
};
reader.readAsDataURL(image);
}
}
isFileUploadDisabled():boolean {
let input:any = document.getElementById('avmodaluploadfile');
return input == null || input.disabled;
}
onFileClickRelay() {
LogUtil.debug('AttributeValuesComponent file upload relay button click');
document.getElementById('avmodaluploadfile').click();
}
onMediaFileSelected(event:any) {
let srcElement:any = event.target || event.srcElement;
let file:any = srcElement.files[0];
if (file != null) {
LogUtil.debug('AttributeValuesComponent media file selected', file.name);
let reader:FileReader = new FileReader();
this.loading = true;
let that = this;
reader.onloadend = function(e:any) {
LogUtil.debug('AttributeValuesComponent media file loaded', e.target.result);
that.attributeToEdit.val = file.name;
that.attributeToEdit.valBase64Data = e.target.result;
that.changed = true;
that.validForSave = true;
that.loading = false;
srcElement.value = '';
};
reader.readAsDataURL(file);
}
}
getAttributeName(attrVal:AttrValueVO):string {
if (attrVal == null || attrVal.attribute == null) {
return '';
}
let attr = attrVal.attribute;
let lang = I18nEventBus.getI18nEventBus().current();
let i18n = attr.displayNames;
let def = attr.name != null ? attr.name : attr.code;
return UiUtil.toI18nString(i18n, def, lang);
}
downloadFile(fileVault:string, masterObjectType:string, fileName:string):void {
let path = 'filevault/' + fileVault + '/' + masterObjectType + '?fileName=' + fileName + '&nocache=' + Math.random();
this._impexService.downloadFile(path, fileName).subscribe(res => {
LogUtil.debug('AttributeValuesComponent download', path, res);
})
}
private loadData() {
if (this.masterObject && this._objectAttributes) {
LogUtil.debug('AttributeValuesComponent attributes', this._objectAttributes);
this.objectAttributesRemove = [];
this.objectAttributesEdit = [];
this.filterAttributes();
} else {
this.objectAttributesRemove = null;
this.objectAttributesEdit = null;
this.filteredObjectAttributes = [];
}
this.changed = false;
this.onSelectRow(null);
}
private filterAttributes() {
this.loadingFilter = true;
let _filter = this._attributeFilter ? this._attributeFilter.toLowerCase() : null;
let _filteredObjectAttributes:Array<AttrValueVO> = [];
if (this._objectAttributes) {
if (_filter) {
if (_filter === '###') { // all existing values (check for blank is suppressed because sometimes we have empty values from imports)
_filteredObjectAttributes = this._objectAttributes.filter(val =>
/* val.val != null && val.val != '' && */ val.attrvalueId > 0
);
} else if (_filter === '##0') { // non-empty values
_filteredObjectAttributes = this._objectAttributes.filter(val =>
val.val != null && val.val != ''
);
} else if (_filter === '#00') { // non-empty new values
_filteredObjectAttributes = this._objectAttributes.filter(val =>
val.val != null && val.val != '' && val.attrvalueId == 0
);
} else if (_filter === '#0#') { // non-empty inherited
_filteredObjectAttributes = this._objectAttributes.filter(val =>
this.isEditedAttribute(val) || (val.attrvalueId == 0 && val.val != null && val.val != '' && val.val.indexOf('* ') !== 0)
);
} else {
_filteredObjectAttributes = this._objectAttributes.filter(val =>
val.attribute.code.toLowerCase().indexOf(_filter) !== -1 ||
val.attribute.name.toLowerCase().indexOf(_filter) !== -1 ||
val.attribute.description && val.attribute.description.toLowerCase().indexOf(_filter) !== -1 ||
val.val && val.val.toLowerCase().indexOf(_filter) !== -1 ||
this.getAttributeName(val).toLowerCase().indexOf(_filter) !== -1
);
}
LogUtil.debug('AttributeValuesComponent filterAttributes ' + _filter, _filteredObjectAttributes);
} else {
_filteredObjectAttributes = this._objectAttributes.slice(0, this._objectAttributes.length);
LogUtil.debug('AttributeValuesComponent filterAttributes no filter', _filteredObjectAttributes);
}
}
if (_filteredObjectAttributes === null) {
_filteredObjectAttributes = [];
}
let _sortProp = this.sortColumn;
let _sortOrder = this.sortDesc ? -1 : 1;
if (_sortProp === 'name') {
_filteredObjectAttributes.sort((a, b) => {
let _a1 = this.getAttributeName(a).toLowerCase();
let _b1 = this.getAttributeName(b).toLowerCase();
return (_a1 > _b1 ? 1 : -1) * _sortOrder;
});
} else {
_filteredObjectAttributes.sort((a, b) => {
let _a1:any = a.attribute;
let _b1:any = b.attribute;
return (_a1[_sortProp] > _b1[_sortProp] ? 1 : -1) * _sortOrder;
});
}
if (this._imageOnlyMode) {
this.filteredObjectAttributes = _filteredObjectAttributes.filter(val =>
val.attribute.etype == 'Image'
);
} else {
this.filteredObjectAttributes = _filteredObjectAttributes;
}
let _total = this.filteredObjectAttributes.length;
this.totalItems = _total;
if (_total > 0) {
this.resetLastPageEnd();
}
this.loadingFilter = false;
}
private processDataChangesEvent() {
LogUtil.debug('AttributeValuesComponent data changes', this.masterObject);
if (this.masterObject && this._objectAttributes) {
let _update = <Array<Pair<AttrValueVO, boolean>>>[];
this._objectAttributes.forEach(attr => {
if ((attr.attrvalueId !== 0 && this.isEditedAttribute(attr)) || (attr.attrvalueId === 0 && attr.val !== null && /\S+(.*\S)*/.test(attr.val) && !(/\* .+/.test(attr.val)))) {
_update.push(new Pair(attr, this.isRemovedAttribute(attr)));
}
});
LogUtil.debug('AttributeValuesComponent data changes update', _update);
this.dataChanged.emit({ source: _update, valid: this.validForSave });
}
}
} | the_stack |
// clang-format off
import {assert} from 'chrome://resources/js/assert.m.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {PromiseResolver} from 'chrome://resources/js/promise_resolver.m.js';
import {createEmptySearchBubble, findAndRemoveHighlights, highlight, removeHighlights, stripDiacritics} from 'chrome://resources/js/search_highlight_utils.js';
import {findAncestor} from 'chrome://resources/js/util.m.js';
import {DomIf, microTask} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {SettingsSectionElement} from './settings_page/settings_section.js';
import {SettingsSubpageElement} from './settings_page/settings_subpage.js';
// clang-format on
declare global {
interface Window {
// https://github.com/microsoft/TypeScript/issues/40807
requestIdleCallback(callback: () => void): number;
}
}
/**
* A data structure used by callers to combine the results of multiple search
* requests.
*/
export type SearchResult = {
canceled: boolean,
didFindMatches: boolean,
wasClearSearch: boolean,
};
/**
* A CSS attribute indicating that a node should be ignored during searching.
*/
const SKIP_SEARCH_CSS_ATTRIBUTE: string = 'no-search';
/**
* List of elements types that should not be searched at all.
* The only DOM-MODULE node is in <body> which is not searched, therefore
* DOM-MODULE is not needed in this set.
*/
const IGNORED_ELEMENTS: Set<string> = new Set([
'CONTENT',
'CR-ACTION-MENU',
'CR-DIALOG',
'CR-ICON-BUTTON',
'CR-SLIDER',
'DIALOG',
'IMG',
'IRON-ICON',
'IRON-LIST',
'PAPER-RIPPLE',
'PAPER-SPINNER-LITE',
'SLOT',
'STYLE',
'TEMPLATE',
]);
/**
* Traverses the entire DOM (including Shadow DOM), finds text nodes that
* match the given regular expression and applies the highlight UI. It also
* ensures that <settings-section> instances become visible if any matches
* occurred under their subtree.
*
* @param root The root of the sub-tree to be searched
* @return Whether or not matches were found.
*/
function findAndHighlightMatches_(request: SearchRequest, root: Node): boolean {
let foundMatches = false;
const highlights: Array<HTMLElement> = [];
function doSearch(node: Node) {
// NOTE: For subpage wrappers <template route-path="..."> when |no-search|
// participates in a data binding:
//
// - Always use noSearch Polymer property, for example
// no-search="[[foo]]"
// - *Don't* use a no-search CSS attribute like no-search$="[[foo]]"
//
// The latter throws an error during the automatic Polymer 2 conversion to
// <dom-if><template...></dom-if> syntax.
if (node.nodeName === 'DOM-IF' &&
(node as DomIf).hasAttribute('route-path') && !(node as DomIf).if &&
!(node as any)['noSearch'] &&
!(node as DomIf).hasAttribute(SKIP_SEARCH_CSS_ATTRIBUTE)) {
request.queue.addRenderTask(new RenderTask(request, node));
return;
}
if (IGNORED_ELEMENTS.has(node.nodeName)) {
return;
}
if (node instanceof HTMLElement) {
const element = node as HTMLElement;
if (element.hasAttribute(SKIP_SEARCH_CSS_ATTRIBUTE) ||
element.hasAttribute('hidden') || element.style.display === 'none') {
return;
}
}
if (node.nodeType === Node.TEXT_NODE) {
const textContent = node.nodeValue;
if (textContent!.trim().length === 0) {
return;
}
const strippedText = stripDiacritics(textContent!);
const ranges = [];
for (let match; match = request.regExp!.exec(strippedText);) {
ranges.push({start: match.index, length: match[0].length});
}
if (ranges.length > 0) {
foundMatches = true;
revealParentSection_(
node, /*numResults=*/ ranges.length, request.bubbles);
if (node.parentNode!.nodeName === 'OPTION') {
const select = node.parentNode!.parentNode!;
assert(select.nodeName === 'SELECT');
// TODO(crbug.com/355446): support showing bubbles inside subpages.
// Currently, they're incorrectly positioned and there's no great
// signal at which to know when to reposition them (because every
// page asynchronously loads/renders things differently).
const isSubpage = (n: Node) => n.nodeName === 'SETTINGS-SUBPAGE';
if (findAncestor(select, isSubpage, true)) {
return;
}
showBubble_(
select, /*numResults=*/ ranges.length, request.bubbles,
/*horizontallyCenter=*/ true);
} else {
request.addTextObserver(node);
highlights.push(highlight(node, ranges));
}
}
// Returning early since TEXT_NODE nodes never have children.
return;
}
let child = node.firstChild;
while (child !== null) {
// Getting a reference to the |nextSibling| before calling doSearch()
// because |child| could be removed from the DOM within doSearch().
const nextSibling = child.nextSibling;
doSearch(child);
child = nextSibling;
}
const shadowRoot = (node as HTMLElement).shadowRoot;
if (shadowRoot) {
doSearch(shadowRoot);
}
}
doSearch(root);
request.addHighlights(highlights);
return foundMatches;
}
/**
* Finds and makes visible the <settings-section> parent of |node|.
* @param bubbles A map of bubbles created so far.
*/
function revealParentSection_(
node: Node, numResults: number, bubbles: Map<Node, number>) {
let associatedControl = null;
// Find corresponding SETTINGS-SECTION parent and make it visible.
let parent = node;
while (parent.nodeName !== 'SETTINGS-SECTION') {
parent = parent.nodeType === Node.DOCUMENT_FRAGMENT_NODE ?
(parent as ShadowRoot).host :
parent.parentNode as Node;
if (!parent) {
// |node| wasn't inside a SETTINGS-SECTION.
return;
}
if (parent.nodeName === 'SETTINGS-SUBPAGE') {
const subpage = parent as SettingsSubpageElement;
associatedControl = assert(
subpage.associatedControl,
'An associated control was expected for SETTINGS-SUBPAGE ' +
subpage.pageTitle + ', but was not found.');
}
}
(parent as SettingsSectionElement).hiddenBySearch = false;
// Need to add the search bubble after the parent SETTINGS-SECTION has
// become visible, otherwise |offsetWidth| returns zero.
if (associatedControl) {
showBubble_(
associatedControl, numResults, bubbles,
/* horizontallyCenter= */ false);
}
}
function showBubble_(
control: Node, numResults: number, bubbles: Map<Node, number>,
horizontallyCenter: boolean) {
const bubble = createEmptySearchBubble(control, horizontallyCenter);
const numHits = numResults + (bubbles.get(bubble) || 0);
bubbles.set(bubble, numHits);
const msgName =
numHits === 1 ? 'searchResultBubbleText' : 'searchResultsBubbleText';
bubble.firstChild!.textContent = loadTimeData.getStringF(msgName, numHits);
}
abstract class Task {
protected request: SearchRequest;
protected node: Node;
constructor(request: SearchRequest, node: Node) {
this.request = request;
this.node = node;
}
abstract exec(): Promise<void>;
}
/**
* A task that takes a <template is="dom-if">...</template> node
* corresponding to a setting subpage and renders it. A
* SearchAndHighlightTask is posted for the newly rendered subtree, once
* rendering is done.
*/
class RenderTask extends Task {
protected node: DomIf;
exec() {
const routePath = this.node.getAttribute('route-path')!;
const content = DomIf._contentForTemplate(
this.node.firstElementChild as HTMLTemplateElement);
const subpageTemplate = content!.querySelector('settings-subpage')!;
subpageTemplate.setAttribute('route-path', routePath);
assert(!this.node.if);
this.node.if = true;
return new Promise<void>(resolve => {
const parent = this.node.parentNode!;
microTask.run(() => {
const renderedNode =
parent.querySelector('[route-path="' + routePath + '"]');
// Register a SearchAndHighlightTask for the part of the DOM that was
// just rendered.
this.request.queue.addSearchAndHighlightTask(
new SearchAndHighlightTask(this.request, assert(renderedNode!)));
resolve();
});
});
}
}
class SearchAndHighlightTask extends Task {
exec() {
const foundMatches = findAndHighlightMatches_(this.request, this.node);
this.request.updateMatches(foundMatches);
return Promise.resolve();
}
}
class TopLevelSearchTask extends Task {
protected node: HTMLElement;
exec() {
const shouldSearch = this.request.regExp !== null;
this.setSectionsVisibility_(!shouldSearch);
if (shouldSearch) {
const foundMatches = findAndHighlightMatches_(this.request, this.node);
this.request.updateMatches(foundMatches);
}
return Promise.resolve();
}
private setSectionsVisibility_(visible: boolean) {
const sections = this.node.querySelectorAll('settings-section');
for (let i = 0; i < sections.length; i++) {
sections[i].hiddenBySearch = !visible;
}
}
}
type Queues = {
high: Array<Task>; middle: Array<Task>; low: Array<Task>;
};
class TaskQueue {
private request_: SearchRequest;
private queues_: Queues;
private running_: boolean;
private onEmptyCallback_: (() => void)|null = null;
constructor(request: SearchRequest) {
this.request_ = request;
this.reset();
/**
* Whether a task is currently running.
*/
this.running_ = false;
}
/** Drops all tasks. */
reset() {
this.queues_ = {high: [], middle: [], low: []};
}
addTopLevelSearchTask(task: TopLevelSearchTask) {
this.queues_.high.push(task);
this.consumePending_();
}
addSearchAndHighlightTask(task: SearchAndHighlightTask) {
this.queues_.middle.push(task);
this.consumePending_();
}
addRenderTask(task: RenderTask) {
this.queues_.low.push(task);
this.consumePending_();
}
/**
* Registers a callback to be called every time the queue becomes empty.
*/
onEmpty(onEmptyCallback: () => void) {
this.onEmptyCallback_ = onEmptyCallback;
}
private popNextTask_(): Task|undefined {
return this.queues_.high.shift() || this.queues_.middle.shift() ||
this.queues_.low.shift();
}
private consumePending_() {
if (this.running_) {
return;
}
const task = this.popNextTask_();
if (!task) {
this.running_ = false;
if (this.onEmptyCallback_) {
this.onEmptyCallback_();
}
return;
}
this.running_ = true;
window.requestIdleCallback(() => {
if (!this.request_.canceled) {
task.exec().then(() => {
this.running_ = false;
this.consumePending_();
});
}
// Nothing to do otherwise. Since the request corresponding to this
// queue was canceled, the queue is disposed along with the request.
});
}
}
export class SearchRequest {
private rawQuery_: string;
private root_: Element;
regExp: RegExp|null;
canceled: boolean;
private foundMatches_: boolean;
resolver: PromiseResolver<SearchRequest>;
queue: TaskQueue;
private textObservers_: Set<MutationObserver>;
private highlights_: Array<HTMLElement>;
bubbles: Map<HTMLElement, number>;
constructor(rawQuery: string, root: Element) {
this.rawQuery_ = rawQuery;
this.root_ = root;
this.regExp = this.generateRegExp_();
/**
* Whether this request was canceled before completing.
*/
this.canceled = false;
this.foundMatches_ = false;
this.resolver = new PromiseResolver();
this.queue = new TaskQueue(this);
this.queue.onEmpty(() => {
this.resolver.resolve(this);
});
this.textObservers_ = new Set();
this.highlights_ = [];
this.bubbles = new Map();
}
/** @param highlights The highlight wrappers to add */
addHighlights(highlights: Array<HTMLElement>) {
this.highlights_.push(...highlights);
}
removeAllTextObservers() {
this.textObservers_.forEach(observer => {
observer.disconnect();
});
this.textObservers_.clear();
}
removeAllHighlightsAndBubbles() {
removeHighlights(this.highlights_);
this.bubbles.forEach((_count, bubble) => bubble.remove());
this.highlights_ = [];
this.bubbles.clear();
}
addTextObserver(textNode: Node) {
const originalParentNode = textNode.parentNode as Node;
const observer = new MutationObserver(mutations => {
const oldValue = mutations[0].oldValue!.trim();
const newValue = textNode.nodeValue!.trim();
if (oldValue !== newValue) {
observer.disconnect();
this.textObservers_.delete(observer);
findAndRemoveHighlights(originalParentNode);
}
});
observer.observe(
textNode, {characterData: true, characterDataOldValue: true});
this.textObservers_.add(observer);
}
/**
* Fires this search request.
*/
start() {
this.queue.addTopLevelSearchTask(new TopLevelSearchTask(this, this.root_));
}
private generateRegExp_(): RegExp|null {
let regExp = null;
// Generate search text by escaping any characters that would be
// problematic for regular expressions.
const strippedQuery = stripDiacritics(this.rawQuery_.trim());
const sanitizedQuery = strippedQuery.replace(SANITIZE_REGEX, '\\$&');
if (sanitizedQuery.length > 0) {
regExp = new RegExp(`(${sanitizedQuery})`, 'ig');
}
return regExp;
}
/**
* @return Whether this SearchRequest refers to an identical query.
*/
isSame(rawQuery: string): boolean {
return this.rawQuery_ === rawQuery;
}
/**
* Updates the result for this search request.
*/
updateMatches(found: boolean) {
this.foundMatches_ = this.foundMatches_ || found;
}
/** @return Whether any matches were found. */
didFindMatches(): boolean {
return this.foundMatches_;
}
}
const SANITIZE_REGEX: RegExp = /[-[\]{}()*+?.,\\^$|#\s]/g;
export interface SearchManager {
/**
* @param text The text to search for.
* @param page
* @return A signal indicating that searching finished.
*/
search(text: string, page: Element): Promise<SearchRequest>;
}
class SearchManagerImpl implements SearchManager {
private activeRequests_: Set<SearchRequest> = new Set();
private completedRequests_: Set<SearchRequest> = new Set();
private lastSearchedText_: string|null = null;
search(text: string, page: Element) {
// Cancel any pending requests if a request with different text is
// submitted.
if (text !== this.lastSearchedText_) {
this.activeRequests_.forEach(function(request) {
request.removeAllTextObservers();
request.removeAllHighlightsAndBubbles();
request.canceled = true;
request.resolver.resolve(request);
});
this.activeRequests_.clear();
this.completedRequests_.forEach(request => {
request.removeAllTextObservers();
request.removeAllHighlightsAndBubbles();
});
this.completedRequests_.clear();
}
this.lastSearchedText_ = text;
const request = new SearchRequest(text, page);
this.activeRequests_.add(request);
request.start();
return request.resolver.promise.then(() => {
this.activeRequests_.delete(request);
this.completedRequests_.add(request);
return request;
});
}
}
let instance: SearchManager|null = null;
export function getSearchManager(): SearchManager {
if (instance === null) {
instance = new SearchManagerImpl();
}
return instance;
}
/**
* Sets the SearchManager singleton instance, useful for testing.
*/
export function setSearchManagerForTesting(searchManager: SearchManager) {
instance = searchManager;
} | the_stack |
import {
AxisString,
BoundsSpec,
BoundsSpecX,
BoundsSpecY,
BoundsSpecZ,
BytecodeNode,
BytecodeNodeMemoryObject,
ClientRect,
ComputedLayoutSpec,
IHaikuComponent,
IHaikuElement,
LayoutSpec,
StringableThreeDimensionalLayoutProperty,
ThreeDimensionalLayoutProperty,
TwoPointFiveDimensionalLayoutProperty,
} from './api';
import HaikuBase from './HaikuBase';
import {cssMatchOne} from './HaikuNode';
import Layout3D, {AUTO_SIZING_TOKEN, SIZE_ABSOLUTE, SIZE_PROPORTIONAL} from './Layout3D';
export const HAIKU_ID_ATTRIBUTE = 'haiku-id';
export const HAIKU_TITLE_ATTRIBUTE = 'haiku-title';
export const HAIKU_VAR_ATTRIBUTE = 'haiku-var';
export const HAIKU_SOURCE_ATTRIBUTE = 'haiku-source';
export const HAIKU_LOCKED_ATTRIBUTE = 'haiku-locked';
const SVG_PRIMITIVE_NAMES = {
rect: true,
line: true,
circle: true,
ellipse: true,
path: true,
polygon: true,
polyline: true,
};
const DEFAULT_DEPTH = 0;
const DEFAULT_TAG_NAME = 'div';
const COMPONENT_PSEUDO_TAG_NAME = DEFAULT_TAG_NAME;
const SIZING_AXES = ['x', 'y', 'z'];
const TEXT_PSEUDO_TAG_NAME = '__text__';
const CSS_QUERY_MAPPING = {
name: 'elementName',
attributes: 'attributes',
children: 'children',
};
const LAYOUT_DEFAULTS = Layout3D.createLayoutSpec();
export default class HaikuElement extends HaikuBase implements IHaikuElement {
node: BytecodeNode;
isHovered: boolean;
constructor () {
super();
this.isHovered = false;
}
get childNodes (): (string|BytecodeNode)[] {
return (
this.node &&
((this.memory && this.memory.children) || this.node.children)
) || [];
}
get children (): HaikuElement[] {
return this.childNodes.map((childNode) => {
return HaikuElement.findOrCreateByNode(childNode);
});
}
get attributes (): any {
return (this.node && this.node.attributes) || {};
}
get type (): any {
return (this.node && this.node.elementName) || DEFAULT_TAG_NAME;
}
get title (): string {
return this.attributes[HAIKU_TITLE_ATTRIBUTE];
}
get source (): string {
return this.attributes[HAIKU_SOURCE_ATTRIBUTE];
}
get id (): string {
return this.attributes.id;
}
get className (): string {
return this.attributes.class;
}
get tagName (): string {
if (this.isTextNode()) {
return TEXT_PSEUDO_TAG_NAME;
}
if (this.isComponent()) {
return COMPONENT_PSEUDO_TAG_NAME;
}
return this.type || DEFAULT_TAG_NAME;
}
get nodeType (): any {
if (this.isTextNode()) {
return 3;
}
return 1;
}
/**
* @method subcomponent
* @description Returns the HaikuComponent instance that manages nodes below this one.
* This node is considered the 'wrapper' node and its child is considered the 'root'.
*/
get subcomponent (): IHaikuComponent {
return this.memory && this.memory.subcomponent;
}
/**
* @method instance
* @description Returns the HaikuComponent instance that manages this node and those beneath.
* This node is considered the 'root' node of the instance.
*/
get instance (): IHaikuComponent {
return this.memory && this.memory.instance;
}
/**
* @method containee
* @description Returns the HaikuComponent instance into which this node was passed as a container.
*/
get containee (): IHaikuComponent {
return this.memory && this.memory.containee;
}
get owner (): IHaikuComponent {
if (this.instance) {
return this.instance;
}
return this.parent && this.parent.owner;
}
get top (): IHaikuComponent {
return this.instanceContext && this.instanceContext.component;
}
get instanceContext (): any {
return this.memory && this.memory.context;
}
get parentNode (): BytecodeNode {
return this.memory && this.memory.parent;
}
get memory (): BytecodeNodeMemoryObject {
return this.node && this.node.__memory;
}
get parent (): any {
return this.parentNode && HaikuElement.findOrCreateByNode(this.parentNode);
}
get layout (): ComputedLayoutSpec {
return this.node && this.node.layout && this.node.layout.computed;
}
get layoutMatrix (): number[] {
return (this.layout && this.layout.matrix) || Layout3D.createMatrix();
}
get layoutAncestry (): any[] {
const ancestry = [];
if (this.layout) {
ancestry.unshift(this.layout);
}
// tslint:disable-next-line:no-this-assignment
let ancestor = this;
while (ancestor.parent) {
ancestor = ancestor.parent;
const layout = ancestor.layout;
if (layout) {
ancestry.unshift(layout);
}
}
return ancestry;
}
get layoutAncestryMatrices (): number[][] {
return this.layoutAncestry.filter((layout) => !!layout.matrix).map((layout) => layout.matrix);
}
get rootSVG (): HaikuElement {
let parent = this.parent;
while (parent) {
if (parent.type === 'svg') {
return parent;
}
parent = parent.parent;
}
return undefined;
}
get isChildOfDefs (): boolean {
let parent = this.parent;
while (parent) {
if (parent.type === 'defs') {
return true;
}
parent = parent.parent;
}
return false;
}
getTranscludedElement (): HaikuElement|undefined {
if (this.type !== 'use') {
return this;
}
const href = this.attributes['xlink:href'] || this.attributes.href;
if (!href) {
return;
}
const rootSVG = this.rootSVG;
if (!rootSVG) {
return;
}
const address = href.substr(1);
let out: HaikuElement;
this.rootSVG.visit((desc: HaikuElement) => {
if (desc.id === address) {
out = desc;
return false;
}
});
return out;
}
get rawLayout (): LayoutSpec {
return this.node && this.node.layout;
}
get shown (): boolean {
return this.layout && this.layout.shown;
}
get opacity (): number {
return this.layout && this.layout.opacity;
}
get shear () {
return this.layout && this.layout.shear;
}
get matrix (): number[] {
return this.layout && this.layout.matrix;
}
get translation (): ThreeDimensionalLayoutProperty {
return (this.layout && this.layout.translation) || {...LAYOUT_DEFAULTS.translation};
}
get rotation (): ThreeDimensionalLayoutProperty {
return (this.layout && this.layout.rotation) || {...LAYOUT_DEFAULTS.rotation};
}
get scale (): ThreeDimensionalLayoutProperty {
return (this.layout && this.layout.scale) || {...LAYOUT_DEFAULTS.scale};
}
get origin (): ThreeDimensionalLayoutProperty {
return (this.layout && this.layout.origin) || {...LAYOUT_DEFAULTS.origin};
}
get offset (): ThreeDimensionalLayoutProperty {
return (this.layout && this.layout.offset) || {...LAYOUT_DEFAULTS.offset};
}
get targets (): Element[] {
return (this.memory && this.memory.targets) || [];
}
get target (): Element {
// Assume the most recently added target is the canonical target due to an implementation
// detail in the Haiku editing environment; FIXME. On 3 Jun 2018 was changed from the first
// added to the last added one to fix a bug related to ungrouping
return this.targets[this.targets.length - 1];
}
get rotationX (): number {
return this.rotation && this.rotation.x;
}
get rotationY (): number {
return this.rotation && this.rotation.y;
}
get rotationZ (): number {
return this.rotation && this.rotation.z;
}
get scaleX (): number {
return this.scale && this.scale.x;
}
get scaleY (): number {
return this.scale && this.scale.y;
}
get scaleZ (): number {
return this.scale && this.scale.z;
}
get positionX (): number {
return this.translation && this.translation.x;
}
get positionY (): number {
return this.translation && this.translation.y;
}
get positionZ (): number {
return this.translation && this.translation.z;
}
get translationX (): number {
return this.translation && this.translation.x;
}
get translationY (): number {
return this.translation && this.translation.y;
}
get translationZ (): number {
return this.translation && this.translation.z;
}
get originX (): number {
return this.origin && this.origin.x;
}
get originY (): number {
return this.origin && this.origin.y;
}
get originZ (): number {
return this.origin && this.origin.z;
}
get offsetX (): number {
return this.offset && this.offset.x;
}
get offsetY (): number {
return this.offset && this.offset.y;
}
get offsetZ (): number {
return this.offset && this.offset.z;
}
/**
* @description Returns the size as computed when the layout was last rendered.
*/
get sizePrecomputed (): ThreeDimensionalLayoutProperty {
return this.layout && this.layout.size;
}
get sizePrecomputedX (): number {
return this.sizePrecomputed && this.sizePrecomputed.x;
}
get sizePrecomputedY (): number {
return this.sizePrecomputed && this.sizePrecomputed.y;
}
get sizePrecomputedZ (): number {
return this.sizePrecomputed && this.sizePrecomputed.z;
}
get size (): ThreeDimensionalLayoutProperty {
return {
x: this.sizeX,
y: this.sizeY,
z: this.sizeZ,
};
}
get sizeX (): number {
return this.computeSizeX();
}
get sizeY (): number {
return this.computeSizeY();
}
get sizeZ (): number {
return this.computeSizeZ();
}
get width (): number {
return this.sizeX;
}
get height (): number {
return this.sizeY;
}
get depth (): number {
return this.sizeZ;
}
get attributeWidth (): number {
if (this.attributes && this.attributes.width) {
return Number(this.attributes.width);
}
return;
}
get attributeHeight (): number {
if (this.attributes && this.attributes.height) {
return Number(this.attributes.height);
}
return;
}
get sizeAbsolute (): StringableThreeDimensionalLayoutProperty {
return (this.rawLayout && this.rawLayout.sizeAbsolute) || {...LAYOUT_DEFAULTS.sizeAbsolute};
}
get sizeAbsoluteX (): number|string {
return this.sizeAbsolute && this.sizeAbsolute.x;
}
get sizeAbsoluteY (): number|string {
return this.sizeAbsolute && this.sizeAbsolute.y;
}
get sizeAbsoluteZ (): number|string {
return this.sizeAbsolute && this.sizeAbsolute.z;
}
get sizeMode (): ThreeDimensionalLayoutProperty {
return this.rawLayout && this.rawLayout.sizeMode;
}
get sizeModeX (): number {
return this.sizeMode && this.sizeMode.x;
}
get sizeModeY (): number {
return this.sizeMode && this.sizeMode.y;
}
get sizeModeZ (): number {
return this.sizeMode && this.sizeMode.z;
}
get sizeProportional (): ThreeDimensionalLayoutProperty {
return (this.rawLayout && this.rawLayout.sizeProportional) || {...LAYOUT_DEFAULTS.sizeProportional};
}
get sizeProportionalX (): number {
return this.sizeProportional && this.sizeProportional.x;
}
get sizeProportionalY (): number {
return this.sizeProportional && this.sizeProportional.y;
}
get sizeProportionalZ (): number {
return this.sizeProportional && this.sizeProportional.z;
}
get sizeDifferential (): ThreeDimensionalLayoutProperty {
return (this.rawLayout && this.rawLayout.sizeDifferential) || {...LAYOUT_DEFAULTS.sizeDifferential};
}
get sizeDifferentialX (): number {
return this.sizeDifferential && this.sizeDifferential.x;
}
get sizeDifferentialY (): number {
return this.sizeDifferential && this.sizeDifferential.y;
}
get sizeDifferentialZ (): number {
return this.sizeDifferential && this.sizeDifferential.z;
}
get properties () {
return {
shown: this.shown,
opacity: this.opacity,
offset: this.offset,
origin: this.origin,
translation: this.translation,
rotation: this.rotation,
scale: this.scale,
shear: this.shear,
sizeMode: this.sizeMode,
sizeProportional: this.sizeProportional,
sizeDifferential: this.sizeDifferential,
sizeAbsolute: this.sizeAbsolute,
size: this.size,
matrix: this.matrix,
};
}
get componentId (): string {
return this.getComponentId();
}
computeSize (): ThreeDimensionalLayoutProperty {
return {
x: this.computeSizeX(),
y: this.computeSizeY(),
z: this.computeSizeZ(),
};
}
computeBoundsForAxis (axis: AxisString): BoundsSpecX|BoundsSpecY|BoundsSpecZ {
if (axis === 'x') {
return this.computeContentBoundsX();
}
if (axis === 'y') {
return this.computeContentBoundsY();
}
if (axis === 'z') {
return this.computeContentBoundsZ();
}
}
computeContentBounds (): BoundsSpec {
return {
...this.computeContentBoundsX(),
...this.computeContentBoundsY(),
...this.computeContentBoundsZ(),
};
}
computeContentBoundsX (): BoundsSpecX {
if (typeof this.sizeAbsolute.x === 'number') {
return {
left: null,
right: null,
};
}
const lefts = [];
const rights = [];
const children = this.children;
if (children.length < 1) {
return {
left: null,
right: null,
};
}
for (let i = 0; i < children.length; i++) {
const child = children[i];
// These fields should account for the child's translation, rotation, scale, etc.
const {
left,
right,
} = child.getLocallyTransformedBoundingClientRect();
lefts.push(left);
rights.push(right);
}
return {
left: Math.min.apply(Math, lefts),
right: Math.max.apply(Math, rights),
};
}
computeContentBoundsY (): BoundsSpecY {
if (typeof this.sizeAbsolute.y === 'number') {
return {
top: null,
bottom: null,
};
}
const tops = [];
const bottoms = [];
const children = this.children;
if (children.length < 1) {
return {
top: null,
bottom: null,
};
}
for (let i = 0; i < children.length; i++) {
const child = children[i];
// These fields should account for the child's translation, rotation, scale, etc.
const {
top,
bottom,
} = child.getLocallyTransformedBoundingClientRect();
tops.push(top);
bottoms.push(bottom);
}
return {
top: Math.min.apply(Math, tops),
bottom: Math.max.apply(Math, bottoms),
};
}
computeContentBoundsZ (): BoundsSpecZ {
return {
front: null,
back: null,
};
}
computeSizeForAxis (axis: AxisString): number {
if (axis === 'x') {
return this.computeSizeX();
}
if (axis === 'y') {
return this.computeSizeY();
}
if (axis === 'z') {
return this.computeSizeZ();
}
}
/**
* @description For elements that only have a single child, we can save some computation
* by looking up their defined absolute size instead of computing their bounding box.
* In particular this is useful in the case of the component wrapper div and its one child.
*/
getOnlyChildSize (axis: AxisString): number {
const children = this.children;
if (children.length !== 1) {
return;
}
const child = children[0];
if (!child || typeof child !== 'object') {
return;
}
if (typeof child.sizeAbsolute[axis] === 'number') {
return child.sizeAbsolute[axis] as number;
}
return child.getOnlyChildSize(axis);
}
computeSizeX (): number {
// SVG primitives use native SVG layout instead of our system
if (this.isSvgPrimitive() && typeof this.attributeWidth === 'number') {
return this.attributeWidth;
}
if (typeof this.sizeAbsolute.x === 'number') {
return this.sizeAbsolute.x;
}
const onlyChildSize = this.getOnlyChildSize('x');
if (typeof onlyChildSize === 'number') {
return onlyChildSize;
}
const {left, right} = this.computeContentBoundsX();
return right - left;
}
computeSizeY (): number {
// SVG primitives use native SVG layout instead of our system
if (this.isSvgPrimitive() && typeof this.attributeHeight === 'number') {
return this.attributeHeight;
}
if (typeof this.sizeAbsolute.y === 'number') {
return this.sizeAbsolute.y;
}
const onlyChildSize = this.getOnlyChildSize('y');
if (typeof onlyChildSize === 'number') {
return onlyChildSize;
}
const {top, bottom} = this.computeContentBoundsY();
return bottom - top;
}
computeSizeZ (): number {
if (typeof this.sizeAbsolute.z === 'number') {
return this.sizeAbsolute.z;
}
const onlyChildSize = this.getOnlyChildSize('z');
if (typeof onlyChildSize === 'number') {
return onlyChildSize;
}
const {front, back} = this.computeContentBoundsZ();
return back - front;
}
getComponentId (): string {
return this.attributes[HAIKU_ID_ATTRIBUTE];
}
isSimpleNode (): boolean {
return !this.isComponent();
}
isTextNode (): boolean {
return typeof this.node !== 'object';
}
isComponent (): boolean {
return !!this.instance;
}
isWrapper (): boolean {
return !!this.subcomponent;
}
isSvgPrimitive (): boolean {
return !!SVG_PRIMITIVE_NAMES[this.tagName];
}
componentMatches (selector: string): boolean {
if (!this.isComponent()) {
return false;
}
const trimmed = selector.trim();
const source = this.source;
const title = this.title;
const id = this.id;
return (
trimmed === COMPONENT_PSEUDO_TAG_NAME ||
trimmed === source ||
trimmed === title ||
trimmed === id
);
}
matches (selector: string): boolean {
return (
this.componentMatches(selector) ||
cssMatchOne(this.node, selector, CSS_QUERY_MAPPING)
);
}
visit (iteratee: Function, filter?: (value: HaikuElement, index: number, array: HaikuElement[]) => boolean) {
const result = iteratee(this);
if (result !== false) {
return this.visitDescendants(iteratee, filter);
}
return result;
}
visitDescendants (
iteratee: Function,
filter?: (value: HaikuElement, index: number, array: HaikuElement[]) => boolean,
) {
if (this.parent && this.parent.isWrapper()) {
// Avoids traversing down into a subcomponent.
return true;
}
const children = filter ? this.children.filter(filter) : this.children;
for (let i = 0; i < children.length; i++) {
const result = children[i].visit(iteratee, filter);
if (result === false) {
return result;
}
}
return true;
}
querySelector (selector: string): any {
return this.cacheFetch(`querySelector:${selector}`, () => {
let out;
this.visitDescendants((element) => {
if (element.matches(selector)) {
out = element;
// Returning `false` short-circuits the visitor
return false;
}
});
return out;
});
}
querySelectorAll (selector: string): any {
return this.cacheFetch(`querySelectorAll:${selector}`, () => {
const out = [];
this.visitDescendants((element) => {
if (element.matches(selector)) {
out.push(element);
}
});
return out;
});
}
getRawBoundingBoxPoints (): ThreeDimensionalLayoutProperty[] {
const {
x,
y,
} = this.computeSize();
return [
{x: 0, y: 0, z: 0}, {x: x / 2, y: 0, z: 0}, {x, y: 0, z: 0},
{x: 0, y: y / 2, z: 0}, {x: x / 2, y: y / 2, z: 0}, {x, y: y / 2, z: 0},
{y, x: 0, z: 0}, {y, x: x / 2, z: 0}, {y, x, z: 0},
];
}
getLocallyTransformedBoundingBoxPoints (): ThreeDimensionalLayoutProperty[] {
return HaikuElement.transformPointsInPlace(
this.getRawBoundingBoxPoints(),
HaikuElement.computeLayout(
this.node as BytecodeNode,
null, // parentNode; none available here
).matrix,
);
}
getLocallyTransformedBoundingClientRect (): ClientRect {
const points = this.getLocallyTransformedBoundingBoxPoints();
return HaikuElement.getRectFromPoints(points);
}
getNearestDefinedNonZeroAncestorSizeX (): number {
const x = this.sizeAbsolute.x;
if (typeof x === 'number' && x > 0) {
return x;
}
if (this.parent) {
return this.parent.getNearestDefinedNonZeroAncestorSizeX();
}
return 1;
}
getNearestDefinedNonZeroAncestorSizeY (): number {
const y = this.sizeAbsolute.y;
if (typeof y === 'number' && y > 0) {
return y;
}
if (this.parent) {
return this.parent.getNearestDefinedNonZeroAncestorSizeY();
}
return 1;
}
getNearestDefinedNonZeroAncestorSizeZ (): number {
const z = this.sizeAbsolute.z;
if (typeof z === 'number' && z > 0) {
return z;
}
if (this.parent) {
return this.parent.getNearestDefinedNonZeroAncestorSizeZ();
}
return 1;
}
triggerHover (event) {
let manager = this.top;
// In case of the root container of a render tree
if (!manager) {
manager = this.containee;
}
// Not sure how we'd get here, but if we do, skip this process
if (!manager || manager.isDeactivated) {
return;
}
// tslint:disable-next-line:no-this-assignment
let hoverable = this;
// If no last hovered element, there's nothing to unhover.
let mustUnhover = manager.lastHoveredElement !== undefined;
const hovers = [];
while (hoverable) {
// If the last hovered element is an ancestor,
// we _don't_ want to unhover it—that's the
// annoying browser behavior we're trying to
// "fix" in the first place.
if (mustUnhover && manager.lastHoveredElement === hoverable) {
mustUnhover = false;
}
// If we are hovered here, by virtue of this algorithm we are hovered above.
if (hoverable.isHovered) {
break;
}
hovers.push(hoverable);
hoverable.isHovered = true;
hoverable = hoverable.parent;
}
hovers.forEach((hov) => {
const delegator = HaikuElement.getElementEventDelegator(hov);
if (delegator && !delegator.isDeactivated) {
(delegator as IHaikuComponent).routeEventToHandlerAndEmitWithoutBubblingAndWithoutGlobalHandlers(
hov.selector,
'hover',
[hov, hov.target, event],
);
}
});
const unhovers = [];
// We must be in a different branch of the tree.
if (mustUnhover) {
let unhoverable = manager.lastHoveredElement;
// Stop until we hit the common hovered ancestor (wherever we break'ed above).
while (unhoverable && unhoverable !== hoverable) {
unhovers.push(unhoverable);
unhoverable.isHovered = false;
unhoverable = unhoverable.parent;
}
}
unhovers.forEach((unhov) => {
const delegator = HaikuElement.getElementEventDelegator(unhov);
if (delegator && !delegator.isDeactivated) {
(delegator as IHaikuComponent).routeEventToHandlerAndEmitWithoutBubblingAndWithoutGlobalHandlers(
unhov.selector,
'unhover',
[unhov, unhov.target, event],
);
}
});
manager.lastHoveredElement = this;
}
get selector (): string {
return `haiku:${this.getComponentId()}`;
}
dump (): string {
return `${this.$id}:<${this.tagName}>(${this.getComponentId() || '[container]'})`;
}
static getElementEventDelegator = (el): IHaikuComponent => {
if (!el) {
return;
}
if (el.isComponent()) {
return el;
}
return el.owner;
};
static transformVectorByMatrix = (out, v, m): number[] => {
out[0] = m[0] * v[0] + m[4] * v[1] + m[8] * v[2] + m[12];
out[1] = m[1] * v[0] + m[5] * v[1] + m[9] * v[2] + m[13];
out[2] = m[2] * v[0] + m[6] * v[1] + m[10] * v[2] + m[14];
return out;
};
static getRectFromPoints = (
points: ThreeDimensionalLayoutProperty[]|TwoPointFiveDimensionalLayoutProperty[],
): ClientRect => {
const top = Math.min(points[0].y, points[2].y, points[6].y, points[8].y);
const bottom = Math.max(points[0].y, points[2].y, points[6].y, points[8].y);
const left = Math.min(points[0].x, points[2].x, points[6].x, points[8].x);
const right = Math.max(points[0].x, points[2].x, points[6].x, points[8].x);
const width = Math.abs(bottom - top);
const height = Math.abs(right - left);
return {
top,
right,
bottom,
left,
width,
height,
};
};
static getBoundingBoxPoints = (points) => {
let x1 = points[0].x;
let y1 = points[0].y;
let x2 = points[0].x;
let y2 = points[0].y;
points.forEach((point) => {
if (point.x < x1) {
x1 = point.x;
} else if (point.x > x2) {
x2 = point.x;
}
if (point.y < y1) {
y1 = point.y;
} else if (point.y > y2) {
y2 = point.y;
}
});
const w = x2 - x1;
const h = y2 - y1;
return [
{x: x1, y: y1, z: 0}, {x: x1 + w / 2, y: y1, z: 0}, {x: x2, y: y1, z: 0},
{x: x1, y: y1 + h / 2, z: 0}, {x: x1 + w / 2, y: y1 + h / 2, z: 0}, {x: x2, y: y1 + h / 2, z: 0},
{x: x1, y: y2, z: 0}, {x: x1 + w / 2, y: y2, z: 0}, {x: x2, y: y2, z: 0},
];
};
static transformPointsInPlace = (points, matrix) => {
for (let i = 0; i < points.length; i++) {
HaikuElement.transformPointInPlace(points[i], matrix);
}
return points;
};
static transformPointInPlace = (point, matrix) => {
const offset = HaikuElement.transformVectorByMatrix([], [point.x, point.y, point.z], matrix);
point.x = offset[0];
point.y = offset[1];
point.z = offset[2];
return point;
};
static getAncestry = (ancestors: HaikuElement[], element: HaikuElement): HaikuElement[] => {
ancestors.unshift(element);
if (element.parent) {
HaikuElement.getAncestry(ancestors, element.parent);
}
return ancestors;
};
// tslint:disable-next-line:variable-name
static __name__ = 'HaikuElement';
static findByNode = (node): HaikuElement => {
const registry = HaikuBase.getRegistryForClass(HaikuElement);
for (let i = 0; i < registry.length; i++) {
if (registry[i].node === node) {
return registry[i];
}
}
return;
};
static connectNodeWithElement = (node, element) => {
// In case the element wasn't initialized yet
if (element) {
element.node = node;
}
// In case we got a string or null node
if (node && typeof node === 'object') {
// The purpose of the __memory object is to allow a mutable reference to be
// passed around even when the node's base attributes are cloned. Also
// to consolidate a host of __* properties which were becoming unweildy.
//
// Important: Platform-specific renderers may attach properties to this object;
// for example the HaikuDOMRenderer attaches list of .targets (DOM nodes).
if (!node.__memory) {
node.__memory = {};
}
node.__memory.element = element;
}
};
static createByNode = (node): HaikuElement => {
const element = new HaikuElement();
HaikuElement.connectNodeWithElement(node, element);
return element;
};
static findOrCreateByNode = (node): HaikuElement => {
let found;
if (node && typeof node === 'object') {
found = node.__memory && node.__memory.element;
}
if (!found) {
found = HaikuElement.findByNode(node);
}
if (found) {
HaikuElement.connectNodeWithElement(node, found);
return found;
}
return HaikuElement.createByNode(node);
};
static useAutoSizing = (givenValue): boolean => {
return (
givenValue === AUTO_SIZING_TOKEN ||
// Legacy. Because HaikuComponent#render gets called before Migration.runMigrations,
// the legacy value won't be correctly migrated to 'auto' by the time this gets called
// for the very first time, so we keep it around for backwards compat. Jun 22, 2018.
givenValue === true
);
};
static computeLayout = (
targetNode: BytecodeNode,
parentNode: BytecodeNode,
): ComputedLayoutSpec => {
const layoutSpec = targetNode.layout;
const targetSize = {
x: null,
y: null,
z: null,
};
const parentBounds = (
parentNode &&
parentNode.layout &&
parentNode.layout.computed &&
parentNode.layout.computed.bounds
);
const targetBounds = {
left: null,
top: null,
right: null,
bottom: null,
front: null,
back: null,
};
let leftOffset = 0;
let topOffset = 0;
if (parentBounds) {
if (typeof parentBounds.left === 'number') {
leftOffset += parentBounds.left;
}
if (typeof parentBounds.top === 'number') {
topOffset += parentBounds.top;
}
}
const targetElement = HaikuElement.findOrCreateByNode(targetNode);
// We'll define this later if any axes are requesting SIZE_PROPORTIONAL. It isn't needed for SIZE_ABSOLUTE.
let parentsizeAbsolute;
for (let i = 0; i < SIZING_AXES.length; i++) {
const sizeAxis = SIZING_AXES[i] as AxisString;
switch (layoutSpec.sizeMode[sizeAxis]) {
case SIZE_PROPORTIONAL:
if (!parentsizeAbsolute) {
parentsizeAbsolute = (
parentNode &&
parentNode.layout &&
parentNode.layout.computed &&
parentNode.layout.computed.size
) || {x: 0, y: 0, z: 0};
if (parentsizeAbsolute.z === undefined || parentsizeAbsolute.z === null) {
parentsizeAbsolute.z = DEFAULT_DEPTH;
}
if (parentsizeAbsolute.x === 0 && parentsizeAbsolute.y === 0 && parentsizeAbsolute.z === 0) {
// Size must be inherited from an ancestor above parent. Traverse upward until we find it.
let traversalParentNode = targetNode;
while (traversalParentNode) {
traversalParentNode = traversalParentNode.__memory && traversalParentNode.__memory.parent;
if (traversalParentNode && traversalParentNode.layout && traversalParentNode.layout.computed) {
Object.assign(parentsizeAbsolute, traversalParentNode.layout.computed.size);
break;
}
}
}
}
// Size is calculated as: parentSizeValue * sizeProportional + sizeProportional.
targetSize[sizeAxis] = parentsizeAbsolute[sizeAxis] * layoutSpec.sizeProportional[sizeAxis] +
layoutSpec.sizeDifferential[sizeAxis];
break;
case SIZE_ABSOLUTE:
const givenValue = layoutSpec.sizeAbsolute[sizeAxis];
// Implements "auto"-sizing: Use content size if available, otherwise fallback to parent
if (HaikuElement.useAutoSizing(givenValue)) {
targetSize[sizeAxis] = targetElement.computeSizeForAxis(sizeAxis);
Object.assign(targetBounds, targetElement.computeBoundsForAxis(sizeAxis));
} else {
targetSize[sizeAxis] = givenValue; // Assume the given value is numeric
}
break;
}
}
const virtualSpec = {
...layoutSpec,
offset: {
x: layoutSpec.offset.x - leftOffset,
y: layoutSpec.offset.y - topOffset,
z: layoutSpec.offset.z,
},
};
const targetMatrix = Layout3D.computeMatrix(virtualSpec, targetSize);
return {
shown: layoutSpec.shown,
opacity: layoutSpec.opacity,
offset: layoutSpec.offset,
origin: layoutSpec.origin,
translation: layoutSpec.translation,
rotation: layoutSpec.rotation,
scale: layoutSpec.scale,
shear: layoutSpec.shear,
sizeMode: layoutSpec.sizeMode,
sizeProportional: layoutSpec.sizeProportional,
sizeDifferential: layoutSpec.sizeDifferential,
sizeAbsolute: layoutSpec.sizeAbsolute,
size: targetSize,
matrix: targetMatrix,
bounds: targetBounds,
};
};
} | the_stack |
import { config } from "dotenv";
import { connect, ConnectRequest, Emitter, EmitterMessage } from 'emitter-io';
import LatLon from "geodesy/latlon-spherical.js";
interface ControlEvent {
type: "pause" | "resume" | "cancel" | "set_altitude";
filter: {
name?: string[];
warehouse?: string[];
hangar?: string[];
};
data: {
message: string;
altitude?: number;
};
}
interface DroneEvent {
type: "drone_deployed" | "drone_grounded" | "low_battery" | "package_loaded" | "package_delivered" | "system_warning" | "system_error" | "control_event_rx";
data: {
message: string;
name: string;
batteryPercent?: number;
batteryConsumed?: number;
event?: string;
hangar?: string;
location?: Location;
payload?: number;
warehouse?: string;
}
}
interface DronePosition {
altitude: number;
batteryPercent: number;
bearing: number;
destination: {
lat: number;
lon: number;
};
location: {
lat: number;
lon: number;
};
name: string;
payloadPercent: number;
speed: number;
status: string;
tempCelsius: number;
}
interface Position {
location: LatLon;
dest: LatLon;
speed: number;
bearing: number;
altitude: number;
}
interface Options {
host: string;
port: number;
channels: {[channel: string]: string }; // value is the channel key
secure?: boolean;
}
const CHAN_CONTROL_EVENT: string = "control-event";
const CHAN_DRONE_EVENT = "drone-event";
const CHAN_DRONE_POSITION = "drone-position"
export class TrafficController {
private run: boolean;
private client: Emitter;
private drones: {[name: string]: Position};
private channels: {[channel: string]: string};
constructor(options: Options) {
this.run = true;
this.drones = {};
this.channels = options.channels;
this.client = connect({
host: options.host,
port: options.port,
secure: !! options.secure}, () => {
console.log("connected to data feed");
this.client.on('error', (error: any) => console.log(error.stack))
this.client.on('offline', () => { this.run = false })
this.client.on("message", (msg: EmitterMessage) => {
if (msg.channel === "drone-position/") {
const message: DronePosition = msg.asObject();
// save or update the position info
if (!this.drones[message.name]) {
this.drones[message.name] = {
altitude: message.altitude,
bearing: message.bearing,
dest: new LatLon(message.destination.lat, message.destination.lon),
location: new LatLon(message.location.lat, message.location.lon),
speed: message.speed,
};
} else {
this.drones[message.name].bearing = message.bearing;
this.drones[message.name].dest.lat = message.destination.lat;
this.drones[message.name].dest.lon = message.destination.lon;
this.drones[message.name].location.lat = message.location.lat;
this.drones[message.name].location.lon = message.location.lon;
this.drones[message.name].speed = message.speed;
// altitude updates are internally calculated and managed
}
this.detectCollision(message.name, this.drones[message.name]);
} else if (msg.channel === "drone-event/") {
// manage behavior based on events
const message: DroneEvent = msg.asObject();
// drones return to warehouse at 200 meters
if (message.type === "package_delivered") {
console.log("%s delivered package - adjusting altitude", message.data.name);
this.setAltitude(message.data.name, 200, "ATC adjusting target altitude to 200 for return to warehouse");
}
// drones deliver at 100 meters
if (message.type === "package_loaded") {
console.log("%s loaded package - adjusting altitude", message.data.name);
this.setAltitude(message.data.name, 150, "ATC adjusting target altitude to 150 for package delivery");
}
// drones return to hangar at 300 meters
if (message.type === "low_battery") {
console.log("%s returning to hangar - adjusting altitude", message.data.name);
this.setAltitude(message.data.name, 300, "ATC adjusting target altitude to 300 for return to hangar");
}
// reduce altitude to avoid weather
if (message.type === "system_warning") {
console.log("%s sent warning - adjusting for conditions", message.data.name);
this.setAltitude(message.data.name, 50, "ATC reducing altitude to avoid windy conditions");
}
// return to hangar
if (message.type === "system_error") {
console.log("%s sent error - cancelling", message.data.name);
this.setAltitude(message.data.name, 300, "Adjusting target altitude to 300 for return to hangar");
this.cancelDrone(message.data.name, "ATC detected system error - returning drone to hangar");
}
}
});
});
}
public async setAltitude( drone: string, alt: number, reason: string) {
// tslint:disable-next-line: no-unused-expression
this.drones[drone].altitude = alt;
this.sendControlEvent({
data: {
altitude: alt,
message: reason,
},
filter: {name: [drone]},
type: "set_altitude",
});
}
public async pauseDrone( drone: string, reason: string ) {
// tslint:disable-next-line: no-unused-expression
this.sendControlEvent({
data: {
message: reason,
},
filter: {name: [drone]},
type: "pause",
});
}
public async resumeDrone( drone: string, reason: string ) {
// tslint:disable-next-line: no-unused-expression
this.sendControlEvent({
data: {
message: reason,
},
filter: {name: [drone]},
type: "resume",
});
}
public async cancelDrone( drone: string, reason: string ) {
// tslint:disable-next-line: no-unused-expression
this.sendControlEvent({
data: {
message: reason,
},
filter: {name: [drone]},
type: "cancel",
});
}
public async monitor() {
this.client.subscribe({
channel: CHAN_DRONE_POSITION,
key: this.channels[CHAN_DRONE_POSITION],
});
this.client.subscribe({
channel: CHAN_DRONE_EVENT,
key: this.channels[CHAN_DRONE_EVENT],
});
while (this.run) {
await new Promise((resolve) => setTimeout(resolve, 5000));
}
}
private async sendControlEvent( msg: ControlEvent) {
// tslint:disable-next-line: no-unused-expression
this.client && this.client.publish({
channel: CHAN_CONTROL_EVENT,
key: this.channels[CHAN_CONTROL_EVENT],
message: JSON.stringify(msg),
});
}
private async detectCollision( name: string, position: Position ) {
// check trajectory for airspace conflicts
const conflicts = [];
const conflictNames = [];
for ( const [otherName, other] of Object.entries(this.drones)) {
if (otherName === name) {
// can't collide with yourself
continue;
}
if (position.dest.equals(other.dest)) {
// ignore drones going to same location (hangar or warehouse)
continue;
}
if (position.location.equals(other.location)) {
// ignore drones in the same location (hangar or warehouse)
continue;
}
if (position.location.equals(position.dest) || other.location.equals(other.dest)) {
// ignore stationary drones
continue;
}
if (Math.abs(position.altitude - other.altitude) >= 20) {
// ignore drones running at significantly different altitudes
continue;
}
if (position.location.distanceTo(other.location) > 600) {
// drones far enough apart that collisions can't happen
continue;
}
// find where the drone paths intersect
const bear1To = position.location.initialBearingTo(position.dest);
const bear1From = position.dest.initialBearingTo(position.location);
const bear2To = other.location.initialBearingTo(other.dest);
const bear2From = other.dest.initialBearingTo(other.location);
const intersectionTo = LatLon.intersection(position.location, bear1To,
other.location, bear2To);
const intersectionFrom = LatLon.intersection(position.dest, bear1From,
other.dest, bear2From);
if (intersectionTo && intersectionFrom
&& intersectionTo.distanceTo(intersectionFrom) < 100) {
// drones may intersect - alter course
console.log("Potential path conflict between %s and %s", name, otherName);
console.log(position);
console.log(other);
console.log(intersectionTo);
console.log(intersectionFrom);
conflicts.push(other);
conflictNames.push(otherName);
}
}
if (0 === conflicts.length) {
return;
}
// find clear space, we want 20m between drones - locate gaps between drones > 40m
const options = [];
// start looking from ground up first
conflicts.sort((a, b) => (a.altitude > b.altitude) ? 1 : -1);
let floor = 50;
for (const conflict of conflicts) {
if (conflict.altitude - floor >= 40) {
options.push(conflict.altitude - 20);
}
floor = conflict.altitude;
}
// now look from sky down
conflicts.sort((a, b) => (b.altitude > a.altitude) ? 1 : -1);
let ceil = 1000;
for (const conflict of conflicts) {
if (ceil - conflict.altitude > 40) {
options.push(conflict.altitude + 20);
}
ceil = conflict.altitude;
}
// sort options to find closest gap
options.sort((a: number, b: number) => {
return Math.abs(position.altitude - a) > Math.abs(position.altitude - b) ? 1 : -1;
});
console.log(options);
console.log("adjusting %s from %d to %d to avoid airspace violatioon",
name, position.altitude, options[0]);
// adjust the drone
this.setAltitude(name, options[0], "ATC adjusting altitude to "
+ options[0] + " to avoid collision(s) with " + conflictNames.toString());
}
} | the_stack |
import { getCoordinates } from "./util/text-caret-pos";
import { html, render } from "lit-html";
import {
AnnotationItem,
createTextCheckerStore,
TextCheckerElementRectItem,
TextCheckerState
} from "./text-checker-store";
// @ts-ignore
import toPX from "to-px";
export type TextCheckerElementAttributes = {
onEnter?: () => void;
onLeave?: () => void;
targetElement: HTMLTextAreaElement;
hoverPadding: number;
};
const Marker = (rect: TextCheckerElementRectItem, isHighLight: boolean = false) => {
if (isHighLight) {
return html`<span
style="pointer-events: none; border: 2px dotted red; position: absolute; left: ${rect.left}px; top: ${rect.top}px; width: ${rect.width}px; height: ${rect.height}px;"
></span>`;
} else {
return html`<span
style="pointer-events: none; border-bottom: 2px dotted red; position: absolute; left: ${rect.left}px; top: ${rect.top}px; width: ${rect.width}px; height: ${rect.height}px;"
></span>`;
}
};
export class TextCheckerElement extends HTMLElement {
private annotationBox!: HTMLDivElement;
private targetElement!: HTMLTextAreaElement;
private store: ReturnType<typeof createTextCheckerStore>;
private hoverPadding: number = 8;
private target!: string;
public isFocus: boolean = false;
public isHovering: boolean = false;
private onEnter: (() => void) | undefined;
private onLeave: (() => void) | undefined;
constructor(args: TextCheckerElementAttributes) {
super();
this.store = createTextCheckerStore();
this.targetElement = args?.targetElement;
this.onEnter = args?.onEnter;
this.onLeave = args?.onLeave;
this.hoverPadding = args?.hoverPadding ?? 8;
}
static get observedAttributes() {
return ["target", "hoverPadding"] as const;
}
attributeChangedCallback = (
name: typeof TextCheckerElement.observedAttributes[number],
_oldValue: any,
newValue: any
) => {
if (this[name]) {
// @ts-ignore
this[name] = newValue;
if (name === "target") {
this.targetElement = document.querySelector(newValue);
}
}
};
connectedCallback(): void {
const target = this.targetElement;
if (!target) {
throw new Error("target element is not found");
}
const shadow = this.attachShadow({ mode: "closed" });
const overlay = document.createElement("div");
overlay.className = "overlay";
overlay.setAttribute(
"style",
"color: transparent; border: position: absolute; top: 0px; left: 0px; pointer-events: none;"
);
const annotationBox = document.createElement("div");
annotationBox.className = "annotationBox";
overlay.append(annotationBox);
shadow.append(overlay);
this.annotationBox = annotationBox;
// we need to capture over textarea
this.targetElement.dataset.attachedTextCheckerElement = "true";
this.targetElement.addEventListener("mousemove", this.onMouseUpdate);
this.targetElement.addEventListener("focus", this.onFocus);
this.targetElement.addEventListener("blur", this.onBlur);
this.targetElement.addEventListener("mouseenter", this.onMouseEnter);
this.targetElement.addEventListener("mouseleave", this.onMouseLeave);
this.store.onChange(() => {
this.renderAnnotationMarkers(this.store.get());
});
}
disconnectedCallback() {
this.targetElement.removeEventListener("mousemove", this.onMouseUpdate);
this.targetElement.removeEventListener("focus", this.onFocus);
this.targetElement.removeEventListener("blur", this.onBlur);
this.targetElement.removeEventListener("mouseenter", this.onMouseEnter);
this.targetElement.removeEventListener("mouseleave", this.onMouseLeave);
}
private onMouseEnter = () => {
this.isHovering = true;
this.onEnter?.();
};
private onMouseLeave = () => {
this.isHovering = false;
this.onLeave?.();
this.resetHoverState();
};
resetAnnotations() {
this.store.clear();
}
resetHoverState() {
this.store.clearHoverState();
}
updateAnnotations(annotationItems: AnnotationItem[]) {
const target = this.targetElement;
const targetStyle = window.getComputedStyle(target);
const copyAttributes = ["box-sizing"] as const;
const copyStyle = copyAttributes
.map((attr) => {
return `${attr}: ${targetStyle.getPropertyValue(attr)};`;
})
.join("");
this.annotationBox.setAttribute(
"style",
`color: transparent; overflow:hidden; position: absolute; pointer-events: none; ${copyStyle}`
);
// Ref: https://github.com/yuku/textoverlay
// Outer position
// update annotation box that align with target textarea
// top-left (0,0)
// read styles form target element
const offsetTop = target.offsetTop;
const offsetLeft = target.offsetLeft;
const offsetHeight = target.offsetHeight;
const offsetWidth =
target.clientWidth +
parseInt(targetStyle.borderLeftWidth || "0", 10) +
parseInt(targetStyle.borderRightWidth || "0", 10);
// const textareaScrollTop = target.scrollTop;
const textareaZIndex = targetStyle.zIndex !== null && targetStyle.zIndex !== "auto" ? +targetStyle.zIndex : 0;
// updates style
this.annotationBox.style.zIndex = `${textareaZIndex + 1}`;
this.annotationBox.style.left = `${offsetLeft}px`;
this.annotationBox.style.top = `${offsetTop}px`;
this.annotationBox.style.height = `${offsetHeight}px`;
this.annotationBox.style.width = `${offsetWidth}px`;
// box
const fontSize: number = toPX(targetStyle.getPropertyValue("font-size")) ?? 16.123;
const boxMarginTop: number = toPX(targetStyle.getPropertyValue("margin-top")) ?? 0;
const boxMarginBottom: number = toPX(targetStyle.getPropertyValue("margin-bottom")) ?? 0;
const boxBorderWidth: number = toPX(targetStyle.getPropertyValue("border-width")) ?? 0;
const boxPaddingTop: number = toPX(targetStyle.getPropertyValue("padding-top")) ?? 0;
const boxPaddingBottom: number = toPX(targetStyle.getPropertyValue("padding-bottom")) ?? 0;
const boundingClientRect = target.getBoundingClientRect();
const boxAbsoluteX: number = boundingClientRect.x;
const boxAbsoluteY: number = boundingClientRect.y;
const boxWidth: number = boundingClientRect.width;
const boxHeight: number = boundingClientRect.height;
// Inner position
// textarea is scrollable element
const visibleArea = {
top: target.scrollTop,
left: target.scrollLeft,
width: boxWidth,
height: boxHeight
};
this.annotationBox.scrollTop = target.scrollTop;
this.annotationBox.scrollLeft = target.scrollLeft;
// FIXME: more correct way
// AnnotationItems should be sorted by range.
// Because, drop non-visible rect items for performance.
// Example)
// ZYXWVUTSRQPONMLKJIHGFEDCBA
// ^^^^^^^--------------------
// visible ^^^^^
// non-visible = drop from `rectItems`
const annotationItemsByDescendingOrder = annotationItems.slice().reverse();
let stopSearchAboveIsNotVisible = false;
const rectItems = annotationItemsByDescendingOrder.flatMap((annotation) => {
// already the annotation is not visible, skip it
if (stopSearchAboveIsNotVisible) {
return [];
}
const start = annotation.start;
const end = annotation.end;
// 0 start
const startCoordinate = getCoordinates(this.targetElement, start, {
reuse: true,
returnHeight: true,
returnDiv: false,
debug: false
});
// Stop to search if out of visible
if (startCoordinate.top + fontSize < visibleArea.top) {
stopSearchAboveIsNotVisible = true;
return [];
}
const endCoordinate = getCoordinates(this.targetElement, end, {
reuse: true,
returnHeight: true,
returnDiv: true,
debug: false
});
const rectItems: TextCheckerElementRectItem[] =
startCoordinate.top === endCoordinate.top
? [
{
id: annotation.id,
// left and top is visible position
// annotationBox(textarea) also scroll with same position of actual textarea
left: startCoordinate.left - visibleArea.left,
top: startCoordinate.top - visibleArea.top,
height: fontSize, //startCoordinate.height,
width: endCoordinate.left - startCoordinate.left,
boxMarginTop,
boxMarginBottom,
boxBorderWidth,
boxAbsoluteX,
boxAbsoluteY,
boxWidth,
boxHeight,
boxPaddingTop,
boxPaddingBottom
}
]
: // two line
[
{
id: annotation.id,
left: startCoordinate.left - visibleArea.left,
top: startCoordinate.top - visibleArea.top,
height: fontSize, //startCoordinate.height,
width:
(startCoordinate?._div?.getBoundingClientRect()?.width ?? 0) - startCoordinate.left,
boxMarginTop,
boxMarginBottom,
boxBorderWidth,
boxAbsoluteX,
boxAbsoluteY,
boxWidth,
boxHeight,
boxPaddingTop,
boxPaddingBottom
},
{
id: annotation.id,
left: -visibleArea.left,
top: endCoordinate.top - visibleArea.top,
height: fontSize,
width: (startCoordinate?._div?.getBoundingClientRect()?.left ?? 0) + endCoordinate.left,
boxMarginTop,
boxMarginBottom,
boxBorderWidth,
boxAbsoluteX,
boxAbsoluteY,
boxWidth,
boxHeight,
boxPaddingTop,
boxPaddingBottom
}
];
return rectItems;
});
this.store.update({
annotationItems,
rectItems
});
}
renderAnnotationMarkers = (state: TextCheckerState) => {
const items = state.rectItems.map((rect) => Marker(rect, state.highlightRectIdSet.has(rect.id)));
render(items, this.annotationBox);
};
onFocus = () => {
this.isFocus = true;
};
onBlur = () => {
this.isFocus = false;
};
isHoverRectItem = (rectItem: TextCheckerElementRectItem): boolean => {
const state = this.store.get();
return Boolean(state.mouseHoverRectIdMap.get(rectItem.id));
};
onMouseUpdate = (event: MouseEvent) => {
const state = this.store.get();
const hoverPadding = this.hoverPadding;
const isIncludedIndexes = state.rectItems
.filter((rect) => {
const point = {
x: event.clientX - rect.boxAbsoluteX,
y: event.clientY - rect.boxAbsoluteY
};
return (
rect.left - hoverPadding <= point.x &&
rect.left + rect.width + hoverPadding >= point.x &&
rect.top - hoverPadding <= point.y &&
rect.top + rect.height + hoverPadding >= point.y
);
})
.map((item) => item.id);
// call mouseover
// naive implementation
// TODO: https://github.com/mourner/flatbush is useful for search
state.rectItems.forEach((rectItem) => {
const isHoverRect = state.mouseHoverRectIdMap.get(rectItem.id);
const isIncludedMouse = isIncludedIndexes.includes(rectItem.id);
if (!isHoverRect && isIncludedMouse) {
state.annotationItems
.find((item) => item.id === rectItem.id)
?.onMouseEnter({
rectItem: rectItem
});
} else if (isHoverRect && !isIncludedMouse) {
state.annotationItems
.find((item) => item.id === rectItem.id)
?.onMouseLeave({
rectItem: rectItem
});
}
state.mouseHoverRectIdMap.set(rectItem.id, isIncludedMouse);
});
// update highlight
this.store.highlightRectIndexes(isIncludedIndexes);
};
}
if (!window.customElements.get("text-checker-element")) {
window.customElements.define("text-checker-element", TextCheckerElement);
} | the_stack |
import {Component, ElementRef, EventEmitter, Injector, OnDestroy, OnInit, Output, ViewChild} from '@angular/core';
import {PublicType, Workspace} from '@domain/workspace/workspace';
import {CommonUtil} from 'app/common/util/common.util';
import {Alert} from '@common/util/alert.util';
import {WorkspaceService} from '../../service/workspace.service';
import {PermissionService} from '../../../user/service/permission.service';
import {RoleSet, RoleSetScope} from '@domain/user/role/roleSet';
import {PermissionSchemaComponent} from '../permission/permission-schema.component';
import {AbstractComponent} from '@common/component/abstract.component';
import * as _ from 'lodash';
import {PermissionSchemaSetComponent} from '../permission/permission-schema-set.component';
@Component({
selector: 'app-create-workspace',
templateUrl: './create-workspace.component.html',
})
// 공용 워크스페이스 생성
export class CreateWorkspaceComponent extends AbstractComponent implements OnInit, OnDestroy {
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
private _docOverflow: string; // 화면 불러오기 시 이전에 설정된 overflow 값
// 퍼미션 스키마 컴포넌트
@ViewChild(PermissionSchemaComponent)
private _permSchemaComp: PermissionSchemaComponent;
// 퍼미션 스키마 설정 컴포넌트
@ViewChild(PermissionSchemaSetComponent)
private _permissionSchemaSetComp: PermissionSchemaSetComponent;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
@Output()
public createComplete = new EventEmitter();
public isShow: boolean = false;
public shareWorkspace: Workspace;
public sharedWorkspaceList: Workspace[];
// 유효성 관련 - 이름
public isInvalidName: boolean = false;
public errMsgName: string = '';
// 유효성 관련 - 설명
public isInvalidDesc: boolean = false;
public errMsgDesc: string = '';
public isShowPredefinedRoleSetList: boolean = false;
public isShowCustomRoleSetList: boolean = false;
public isUseCustomRoleSet: boolean = false;
// Role & RoleSet
public roleSetList: RoleSet[] = []; // RoleSet 목록
public selectedRoleSetInfo: RoleSet; // RoleSet 선택 정보
public selectedRoleSetDetail: RoleSet; // 선택된 RoleSet 상세 정보
public params = {
size: this.page.size,
page: this.page.page,
sort: {name: this.translateService.instant('msg.comm.ui.list.name.asc'), value: 'name,asc', selected: true}
};
get disableCreateWorkspace() {
return this.isInvalidName || this.isInvalidDesc
|| !this.shareWorkspace.name || '' === this.shareWorkspace.name
|| !this.selectedRoleSetDetail;
} // get - disableCreateWorkspace
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Constructor
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// 생성자
constructor(private workbookService: WorkspaceService,
private workspaceService: WorkspaceService,
protected permissionService: PermissionService,
protected elementRef: ElementRef,
protected injector: Injector) {
super(elementRef, injector);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Override Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// Init
public ngOnInit() {
super.ngOnInit();
}
// Destroy
public ngOnDestroy() {
super.ngOnDestroy();
$(document.body).css('overflow', this._docOverflow);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method - 공통 및 워크스페이스 관련
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// 시작점
public init() {
// 초기 hidden 처리
this._docOverflow = $(document.body).css('overflow');
$(document.body).css('overflow', 'hidden');
// 데이터 초기화
this.roleSetList = []; // RoleSet 목록
this.selectedRoleSetInfo = null; // RoleSet 선택 정보
this.selectedRoleSetDetail = null; // 선택된 RoleSet 상세 정보
this.isShowPredefinedRoleSetList = false;
this.isShowCustomRoleSetList = false;
this.isUseCustomRoleSet = false;
this._loadRoleSets().then(() => {
this.shareWorkspace = new Workspace();
this.isShow = true;
});
} // function - init
// 닫기
public close() {
this.sharedWorkspaceList = undefined;
this.isInvalidName = undefined;
$(document.body).css('overflow', this._docOverflow);
this.isShow = false;
}
/**
* Check if name is in use
* @param {string} newWorkspaceName
*/
public async nameChange(newWorkspaceName) {
this.shareWorkspace.name = newWorkspaceName;
this.params.size = 100;
this.loadingShow();
if (_.isNil(this.sharedWorkspaceList)) {
// get workspaces which contains keyword(newWorkspaceName)
this.workspaceService.getSharedWorkspaces('forListView', this.params).then(workspaces => {
if (workspaces['_embedded']) {
this.sharedWorkspaceList = workspaces['_embedded']['workspaces'];
this._checkDuplicateName(newWorkspaceName);
} else {
this.sharedWorkspaceList = [];
}
}).catch((_error) => {
Alert.error(this.translateService.instant('msg.space.alert.retrieve'));
this.loadingHide();
});
} else if (this.sharedWorkspaceList.length > 0) {
this._checkDuplicateName(newWorkspaceName);
}
this.loadingHide();
}
/**
* 컴포넌트 자체 클릭 이벤트
* @param {MouseEvent} event
*/
public clickComponent(event: MouseEvent) {
event.stopPropagation();
const $eventTarget: any = $(event.target);
if (!$eventTarget.hasClass('ddp-type-selectbox') && 0 === $eventTarget.closest('.ddp-type-selectbox').length) {
this.isShowCustomRoleSetList = false;
this.isShowPredefinedRoleSetList = false;
}
} // function - clickComponent
/**
* RoleSet 선택
* @param {RoleSet} item
* @param {boolean} isCustom
*/
public selectRoleSet(item: RoleSet, isCustom: boolean = false) {
this.selectedRoleSetInfo = item;
this.permissionService.getRolesetDetail(item.id).then((result: RoleSet) => {
if (isCustom) {
// Custom에서 신규 모드로 무조건 생성하기 위해. 아이디 정보를 지운다.
delete result.id;
delete result.name;
result.scope = RoleSetScope.PRIVATE;
}
this.selectedRoleSetDetail = result;
}).catch(err => this.commonExceptionHandler(err));
} // function - selectRolSet
/**
* 공유 워크스페이스 생성
*/
public createShareWorkspace() {
if (this.disableCreateWorkspace) {
this.shareWorkspace.name = this.shareWorkspace.name ? this.shareWorkspace.name.trim() : '';
// check if name is empty
if (this.shareWorkspace.name == null || this.shareWorkspace.name.length === 0) {
this.isInvalidName = true;
this.errMsgName = this.translateService.instant('msg.alert.create.name.empty');
}
// check name length
if (CommonUtil.getByte(this.shareWorkspace.name) > 150) {
this.isInvalidName = true;
this.errMsgName = this.translateService.instant('msg.alert.edit.name.len');
}
// check description length
if (this.shareWorkspace.description != null
&& CommonUtil.getByte(this.shareWorkspace.description.trim()) > 450) {
this.isInvalidDesc = true;
this.errMsgDesc = this.translateService.instant('msg.alert.edit.description.len');
}
Alert.fail(this.translateService.instant('msg.comm.alert.error'));
return;
}
this.loadingShow();
this.shareWorkspace.publicType = PublicType.SHARED;
// RoleSet 정보 저장
this._permSchemaComp.setRoleSets(this.shareWorkspace.id, this.shareWorkspace.name).then((roleSet: RoleSet) => {
const createParam: any = _.cloneDeep(this.shareWorkspace);
createParam['roleSets'] = ['/api/rolesets/' + roleSet.id];
// 워크스페이스 생성
this.workbookService.createWorkspace(createParam).then((workspace: Workspace) => {
this.loadingHide();
Alert.success(`'${this.shareWorkspace.name}' ` + this.translateService.instant('msg.space.alert.create.workspace.success'));
this.close();
this.createComplete.emit(workspace.id);
}).catch(() => {
Alert.error(this.translateService.instant('msg.space.alert.create.workspace.fail'));
this.loadingHide();
});
});
} // function - createShareWorkspace
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method - Role & RoleSet 관련 함수
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* RoleSet Type 변경
* @param {boolean} isCustom
*/
public changeRoleSetType(isCustom: boolean) {
this.isUseCustomRoleSet = isCustom;
this.selectedRoleSetInfo = null;
if (isCustom) {
this.selectedRoleSetDetail = new RoleSet();
} else {
this.selectedRoleSetDetail = null;
this.selectRoleSet(this.roleSetList[0], false);
}
} // function - changeRoleSetType
/**
* 사전정의 RoleSet 옵션 펼침
*/
public openPredefinedRoleSetOpts() {
this.isUseCustomRoleSet = false;
this.isShowCustomRoleSetList = false;
this.isShowPredefinedRoleSetList = !this.isShowPredefinedRoleSetList;
} // function - openPredefinedRoleSetOpts
/**
* 커스텀 RoleSet 옵션 펼침
*/
public openCustomRoleSetOpts() {
this.isUseCustomRoleSet = true;
this.isShowPredefinedRoleSetList = false;
this.isShowCustomRoleSetList = !this.isShowCustomRoleSetList;
} // function - openCustomRoleSetOpts
/**
* 퍼미션 설정 팝업 오픈
*/
public onClickOpenPermissionSchemaSet() {
const cloneRoleSet: RoleSet = _.cloneDeep(this.selectedRoleSetDetail);
this._permissionSchemaSetComp.init(cloneRoleSet, true, false);
} // function - onClickOpenPermissionSchemaSet
public afterUpdatePermissionRoles(roleset: RoleSet) {
this.selectedRoleSetDetail = roleset;
} // function - afterUpdatePermissionRoles
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* RoleSet 목록 조회
* @return {Promise<any>}
* @private
*/
private _loadRoleSets(): Promise<any> {
return new Promise((resolve, reject) => {
this.loadingShow();
const params = {
page: this.page.page,
size: 1000,
sort: this.page.sort,
scope: RoleSetScope.PUBLIC
};
this.permissionService.getRolesets(params).then(result => {
if (result && result['_embedded']) {
this.roleSetList = result['_embedded']['roleSets'];
this.selectRoleSet(this.roleSetList[0], false);
}
resolve(null);
this.loadingHide();
}).catch(err => {
this.commonExceptionHandler(err);
reject();
});
});
} // function - _loadRoleSets
private _checkDuplicateName(newWorkspaceName: string) {
// check if name is in use and set isInvalidName flag according to the condition
this.isInvalidName = this.sharedWorkspaceList.some((workspace) => {
if (workspace.name === newWorkspaceName) {
this.errMsgName = this.translateService.instant('msg.comm.ui.workspace.name.duplicated');
return true;
}
});
}
} | the_stack |
import _ObnizBLE from './libs/embeds/bleHci/ble';
import _BleAdvertisement from './libs/embeds/bleHci/bleAdvertisement';
import _BleAdvertisementBuilder from './libs/embeds/bleHci/bleAdvertisementBuilder';
import _BleCharacteristic from './libs/embeds/bleHci/bleCharacteristic';
import _BlePeripheral from './libs/embeds/bleHci/blePeripheral';
import { BleConnectionUpdateParam as _BleConnectionUpdateParam } from './libs/embeds/bleHci/blePeripheral';
import { BleConnectionState as _BleConnectionState } from './libs/embeds/bleHci/blePeripheral';
import _BleRemoteCharacteristic from './libs/embeds/bleHci/bleRemoteCharacteristic';
import _BleRemoteDescriptor from './libs/embeds/bleHci/bleRemoteDescriptor';
import _BleRemotePeripheral from './libs/embeds/bleHci/bleRemotePeripheral';
import { BleConnectSetting as _BleConnectSetting } from './libs/embeds/bleHci/bleRemotePeripheral';
import { BlePairingOptions as _BlePairingOptions } from './libs/embeds/bleHci/bleRemotePeripheral';
import { IBeacon as _IBeacon } from './libs/embeds/bleHci/bleRemotePeripheral';
import _BleRemoteService from './libs/embeds/bleHci/bleRemoteService';
import _BleScan from './libs/embeds/bleHci/bleScan';
import { BleScanAdvertisementFilterParam as _BleScanAdvertisementFilterParam } from './libs/embeds/bleHci/bleScan';
import { BleScanSetting as _BleScanSetting } from './libs/embeds/bleHci/bleScan';
import { BleScanTarget as _BleScanTarget } from './libs/embeds/bleHci/bleScan';
import { BleBinary as _BleBinary } from './libs/embeds/bleHci/bleScan';
import { BleScanMode as _BleScanMode } from './libs/embeds/bleHci/bleScan';
import _BleService from './libs/embeds/bleHci/bleService';
import { BleAdvertisementData as _BleAdvertisementData } from './libs/embeds/bleHci/bleTypes';
import { BleCharacteristicDefine as _BleCharacteristicDefine } from './libs/embeds/bleHci/bleTypes';
import { BleDescriptorDefine as _BleDescriptorDefine } from './libs/embeds/bleHci/bleTypes';
import { BlePeripheralDefine as _BlePeripheralDefine } from './libs/embeds/bleHci/bleTypes';
import { BleScanResponseData as _BleScanResponseData } from './libs/embeds/bleHci/bleTypes';
import { BleServiceDefine as _BleServiceDefine } from './libs/embeds/bleHci/bleTypes';
import { BleAdvertisementFlag as _BleAdvertisementFlag } from './libs/embeds/bleHci/bleTypes';
import { BleAttributePropery as _BleAttributePropery } from './libs/embeds/bleHci/bleTypes';
import { BleDeviceAddress as _BleDeviceAddress } from './libs/embeds/bleHci/bleTypes';
import { BleDeviceAddressType as _BleDeviceAddressType } from './libs/embeds/bleHci/bleTypes';
import { BleDeviceType as _BleDeviceType } from './libs/embeds/bleHci/bleTypes';
import { BleEventType as _BleEventType } from './libs/embeds/bleHci/bleTypes';
import { Handle as _Handle } from './libs/embeds/bleHci/bleTypes';
import { UUID as _UUID } from './libs/embeds/bleHci/bleTypes';
import _ObnizBLEHci from './libs/embeds/bleHci/hci';
import _Display from './libs/embeds/display';
import _ObnizSwitch from './libs/embeds/switch';
import { M5StackBasic as _M5StackBasic } from './libs/hw/m5stack_basic';
import { M5StickC as _M5StickC } from './libs/hw/m5stickc';
import _ObnizBoard from './libs/hw/obnizBoard';
import _PeripheralAD from './libs/io_peripherals/ad';
import { AnimationStatus as _AnimationStatus } from './libs/io_peripherals/common';
import { BitType as _BitType } from './libs/io_peripherals/common';
import { DriveType as _DriveType } from './libs/io_peripherals/common';
import { FlowControlType as _FlowControlType } from './libs/io_peripherals/common';
import { ParityType as _ParityType } from './libs/io_peripherals/common';
import { PullType as _PullType } from './libs/io_peripherals/common';
import { StopBitType as _StopBitType } from './libs/io_peripherals/common';
import _Directive from './libs/io_peripherals/directive';
import { DirectiveAnimationFrame as _DirectiveAnimationFrame } from './libs/io_peripherals/directive';
import _PeripheralGrove from './libs/io_peripherals/grove';
import { PeripheralGroveParams as _PeripheralGroveParams } from './libs/io_peripherals/grove';
import { GrovePinOption as _GrovePinOption } from './libs/io_peripherals/grove';
import { PeripheralGroveType as _PeripheralGroveType } from './libs/io_peripherals/grove';
import _PeripheralI2C from './libs/io_peripherals/i2c';
import _PeripheralIO from './libs/io_peripherals/io';
import _PeripheralPWM from './libs/io_peripherals/pwm';
import { PWMInterface as _PWMInterface } from './libs/io_peripherals/pwm';
import { PWMModulateType as _PWMModulateType } from './libs/io_peripherals/pwm';
import _PeripheralSPI from './libs/io_peripherals/spi';
import _PeripheralUART from './libs/io_peripherals/uart';
import { PeripheralUARTOptions as _PeripheralUARTOptions } from './libs/io_peripherals/uart';
import _LogicAnalyzer from './libs/measurements/logicanalyzer';
import { LogicAnalyzerOptions as _LogicAnalyzerOptions } from './libs/measurements/logicanalyzer';
import { LogicAnalyzerOptionsExt as _LogicAnalyzerOptionsExt } from './libs/measurements/logicanalyzer';
import _ObnizMeasure from './libs/measurements/measure';
import { ObnizMeasureOptions as _ObnizMeasureOptions } from './libs/measurements/measure';
import { ObnizMeasureResult as _ObnizMeasureResult } from './libs/measurements/measure';
import _WiFi from './libs/network/wifi';
import _Plugin from './libs/plugin/plugin';
import _Tcp from './libs/protocol/tcp';
import _ObnizUtil from './libs/utils/util';
import _ObnizApi from './ObnizApi';
import _ObnizApp from './ObnizApp';
import ObnizDevice from './ObnizDevice';
import { ObnizBleAttError as _ObnizBleAttError } from './ObnizError';
import { ObnizBleHciStateError as _ObnizBleHciStateError } from './ObnizError';
import { ObnizBleOpError as _ObnizBleOpError } from './ObnizError';
import { ObnizBlePairingRejectByRemoteError as _ObnizBlePairingRejectByRemoteError } from './ObnizError';
import { ObnizBleScanStartError as _ObnizBleScanStartError } from './ObnizError';
import { ObnizBleUnknownCharacteristicError as _ObnizBleUnknownCharacteristicError } from './ObnizError';
import { ObnizBleUnknownDescriptorError as _ObnizBleUnknownDescriptorError } from './ObnizError';
import { ObnizBleUnknownPeripheralError as _ObnizBleUnknownPeripheralError } from './ObnizError';
import { ObnizBleUnknownServiceError as _ObnizBleUnknownServiceError } from './ObnizError';
import { ObnizBleUnsupportedHciError as _ObnizBleUnsupportedHciError } from './ObnizError';
import { ObnizBleUnSupportedOSVersionError as _ObnizBleUnSupportedOSVersionError } from './ObnizError';
import { ObnizDeprecatedFunctionError as _ObnizDeprecatedFunctionError } from './ObnizError';
import { ObnizError as _ObnizError } from './ObnizError';
import { ObnizI2cError as _ObnizI2cError } from './ObnizError';
import { ObnizI2cWarning as _ObnizI2cWarning } from './ObnizError';
import { ObnizOfflineError as _ObnizOfflineError } from './ObnizError';
import { ObnizParameterError as _ObnizParameterError } from './ObnizError';
import { ObnizTimeoutError as _ObnizTimeoutError } from './ObnizError';
import _ObnizPartsInterface from './ObnizPartsInterface';
import { ObnizPartsInfo as _ObnizPartsInfo } from './ObnizPartsInterface';
import { PartsList } from './ObnizPartsList';
/**
* obniz class is the abstract version of obniz Board hardware within JavaScript.
*
* By providing obniz id and instantiating it, you can control obniz Board and the connected parts
* without the details of websocket api.
*
*
* ### obnizOS version and obniz.js version
*
* obniz cloud compare your obniz.js version and target device obnizOS version.
* If your js sdk major number is below from OS version (eg obniz.js is 2.0.0 and obnizOS is 3.0.0) then obniz cloud will alert when connection established.
* It will work somehow but some functions looses compatibility.
*
* ### one device from two program
*
* obniz cloud accept multiple websocket connection from multiple obniz.js at same time.
* every commands from obniz.js will passed to a device and every command from a device will be dispatched to every obniz.js connected to the cloud.
*
* But If one of obniz.js established a connection to a device, then target device will send datas only via local connect. So other connected obniz.js only can send datas and never receive datas from a device.
*
* If you'd like to receive, you need to specify `local_connect: false` at all of obniz.js to disable local connect.
*
*/
export declare class Obniz extends ObnizDevice {
/**
* M5StickC device
*/
static M5StickC: typeof _M5StickC;
static M5StackBasic: typeof _M5StackBasic;
/**
* obniz REST api class
*
* @returns {ObnizApi}
*/
static get api(): typeof _ObnizApi;
/**
* App Support class
*
* @returns {ObnizApp}
*/
static get App(): typeof _ObnizApp;
}
/**
* types
*/
export declare namespace Obniz {
type ObnizApp = _ObnizApp;
type ObnizApi = _ObnizApi;
type ObnizPartsInfo = _ObnizPartsInfo;
type ObnizPartsInterface = _ObnizPartsInterface;
type BleAdvertisement = _BleAdvertisement;
type BleAdvertisementBuilder = _BleAdvertisementBuilder;
type BleAdvertisementData = _BleAdvertisementData;
type BleCharacteristic = _BleCharacteristic;
type BleCharacteristicDefine = _BleCharacteristicDefine;
type BleConnectionUpdateParam = _BleConnectionUpdateParam;
type BleConnectSetting = _BleConnectSetting;
type BleDescriptorDefine = _BleDescriptorDefine;
type BlePairingOptions = _BlePairingOptions;
type BlePeripheral = _BlePeripheral;
type BlePeripheralDefine = _BlePeripheralDefine;
type BleRemoteCharacteristic = _BleRemoteCharacteristic;
type BleRemoteDescriptor = _BleRemoteDescriptor;
type BleRemotePeripheral = _BleRemotePeripheral;
type BleRemoteService = _BleRemoteService;
type BleScan = _BleScan;
type BleScanAdvertisementFilterParam = _BleScanAdvertisementFilterParam;
type BleScanResponseData = _BleScanResponseData;
type BleScanSetting = _BleScanSetting;
type BleScanTarget = _BleScanTarget;
type BleService = _BleService;
type BleServiceDefine = _BleServiceDefine;
type Directive = _Directive;
type DirectiveAnimationFrame = _DirectiveAnimationFrame;
type Display = _Display;
type IBeacon = _IBeacon;
type LogicAnalyzer = _LogicAnalyzer;
type LogicAnalyzerOptions = _LogicAnalyzerOptions;
type LogicAnalyzerOptionsExt = _LogicAnalyzerOptionsExt;
type M5StackBasic = _M5StackBasic;
type M5StickC = _M5StickC;
type ObnizBLE = _ObnizBLE;
type ObnizBleAttError = _ObnizBleAttError;
type ObnizBLEHci = _ObnizBLEHci;
type ObnizBleHciStateError = _ObnizBleHciStateError;
type ObnizBleOpError = _ObnizBleOpError;
type ObnizBlePairingRejectByRemoteError = _ObnizBlePairingRejectByRemoteError;
type ObnizBleScanStartError = _ObnizBleScanStartError;
type ObnizBleUnknownCharacteristicError = _ObnizBleUnknownCharacteristicError;
type ObnizBleUnknownDescriptorError = _ObnizBleUnknownDescriptorError;
type ObnizBleUnknownPeripheralError = _ObnizBleUnknownPeripheralError;
type ObnizBleUnknownServiceError = _ObnizBleUnknownServiceError;
type ObnizBleUnsupportedHciError = _ObnizBleUnsupportedHciError;
type ObnizBleUnSupportedOSVersionError = _ObnizBleUnSupportedOSVersionError;
type ObnizBoard = _ObnizBoard;
type ObnizDeprecatedFunctionError = _ObnizDeprecatedFunctionError;
type ObnizError = _ObnizError;
type ObnizI2cError = _ObnizI2cError;
type ObnizI2cWarning = _ObnizI2cWarning;
type ObnizMeasure = _ObnizMeasure;
type ObnizMeasureOptions = _ObnizMeasureOptions;
type ObnizMeasureResult = _ObnizMeasureResult;
type ObnizOfflineError = _ObnizOfflineError;
type ObnizParameterError = _ObnizParameterError;
type ObnizSwitch = _ObnizSwitch;
type ObnizTimeoutError = _ObnizTimeoutError;
type ObnizUtil = _ObnizUtil;
type PeripheralAD = _PeripheralAD;
type PeripheralGrove = _PeripheralGrove;
type PeripheralGroveParams = _PeripheralGroveParams;
type PeripheralI2C = _PeripheralI2C;
type PeripheralIO = _PeripheralIO;
type PeripheralPWM = _PeripheralPWM;
type PeripheralSPI = _PeripheralSPI;
type PeripheralUART = _PeripheralUART;
type PeripheralUARTOptions = _PeripheralUARTOptions;
type Plugin = _Plugin;
type PWMInterface = _PWMInterface;
type Tcp = _Tcp;
type WiFi = _WiFi;
type AnimationStatus = _AnimationStatus;
type BitType = _BitType;
type BleAdvertisementFlag = _BleAdvertisementFlag;
type BleAttributePropery = _BleAttributePropery;
type BleBinary = _BleBinary;
type BleConnectionState = _BleConnectionState;
type BleDeviceAddress = _BleDeviceAddress;
type BleDeviceAddressType = _BleDeviceAddressType;
type BleDeviceType = _BleDeviceType;
type BleEventType = _BleEventType;
type BleScanMode = _BleScanMode;
type DriveType = _DriveType;
type FlowControlType = _FlowControlType;
type GrovePinOption = _GrovePinOption;
type Handle = _Handle;
type ParityType = _ParityType;
type PeripheralGroveType = _PeripheralGroveType;
type PullType = _PullType;
type PWMModulateType = _PWMModulateType;
type StopBitType = _StopBitType;
type UUID = _UUID;
type Parts<K extends keyof PartsList> = PartsList[K]['class'];
type PartsOptions<K extends keyof PartsList> = PartsList[K]['options'];
} | the_stack |
import { RoughCanvas } from 'roughjs/bin/canvas'
import { Drawable, Options } from 'roughjs/bin/core'
import { RoughSVG } from 'roughjs/bin/svg'
import { Point } from './geom/point'
import { RenderMode } from './RenderMode'
const tinycolor = require('tinycolor2')
const units = require('units-css')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type Color = any // type alias for tinycolor
/**
* Regexp that detects curved commands in path data.
*/
export const PATH_CURVES_REGEX = /[acsqt]/i
/**
* A simple regexp which is used to test whether a given string value
* contains unit identifiers, e.g. "1px", "1em", "1%", ...
*/
export const CONTAINS_UNIT_REGEXP = /[a-z%]/
/**
* Calculates the average color of the colors in the given array.
* @returns The average color
*/
export function averageColor(colorArray: Color[]): Color {
const count = colorArray.length
let r = 0
let g = 0
let b = 0
let a = 0
colorArray.forEach(tinycolor => {
const color = tinycolor.toRgb()
r += color.r * color.r
g += color.g * color.g
b += color.b * color.b
a += color.a
})
return tinycolor({
r: Math.sqrt(r / count),
g: Math.sqrt(g / count),
b: Math.sqrt(b / count),
a: a / count
})
}
/**
* Returns the Node's children, since Node.prototype.children is not available on all browsers.
* https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/children
*/
export function getNodeChildren(element: Element): Element[] {
if (typeof element.children !== 'undefined') {
return element.children as unknown as Element[]
}
let i = 0
let node
const nodes = element.childNodes
const children = []
while ((node = nodes[i++])) {
if (node.nodeType === 1) {
children.push(node)
}
}
return children as Element[]
}
/**
* @return length in pixels
*/
export function getLengthInPx(svgLengthList: SVGAnimatedLengthList): number {
if (svgLengthList && svgLengthList.baseVal.numberOfItems > 0) {
return svgLengthList.baseVal.getItem(0).value
}
return 0
}
/**
* Whether the given SVGTransform resembles an identity transform.
* @returns Whether the transform is an identity transform.
* Returns true if transform is undefined.
*/
export function isIdentityTransform(svgTransform: SVGTransform | null): boolean {
if (!svgTransform) {
return true
}
const matrix = svgTransform.matrix
return (
!matrix ||
(matrix.a === 1 &&
matrix.b === 0 &&
matrix.c === 0 &&
matrix.d === 1 &&
matrix.e === 0 &&
matrix.f === 0)
)
}
/**
* Whether the given SVGTransform does not scale nor skew.
* @returns Whether the given SVGTransform does not scale nor skew.
* Returns true if transform is undefined.
*/
export function isTranslationTransform(svgTransform: SVGTransform | null): boolean {
if (!svgTransform) {
return true
}
const matrix = svgTransform.matrix
return !matrix || (matrix.a === 1 && matrix.b === 0 && matrix.c === 0 && matrix.d === 1)
}
/**
* Applies a given `SVGTransform` to the point.
*
* [a c e] [x] = (a*x + c*y + e)
* [b d f] [y] = (b*x + d*y + f)
* [0 0 1] [1] = (0 + 0 + 1)
*/
export function applyMatrix(point: Point, svgTransform: SVGTransform | null): Point {
if (!svgTransform) {
return point
}
const matrix = svgTransform.matrix
const x = matrix.a * point.x + matrix.c * point.y + matrix.e
const y = matrix.b * point.x + matrix.d * point.y + matrix.f
return new Point(x, y)
}
/**
* Returns a random number in the given range.
*/
export function getRandomNumber(min: number, max: number): number {
return Math.random() * (max - min) + min
}
/**
* Returns the `offset` of an `SVGStopElement`.
* @return stop percentage
*/
export function getStopOffset(stop: SVGStopElement): number {
const offset = stop.getAttribute('offset')
if (!offset) {
return 0
}
if (offset.indexOf('%')) {
return parseFloat(offset.substring(0, offset.length - 1))
} else {
return parseFloat(offset) * 100
}
}
/**
* Returns the `stop-color` of an `SVGStopElement`.
*/
export function getStopColor(stop: SVGStopElement): Color {
let stopColorStr = stop.getAttribute('stop-color')
if (!stopColorStr) {
const style = stop.getAttribute('style') ?? ''
const match = /stop-color:\s?(.*);?/.exec(style)
if (match && match.length > 1) {
stopColorStr = match[1]
}
}
return stopColorStr ? tinycolor(stopColorStr) : tinycolor('white')
}
/**
* Converts an SVG gradient to a color by mixing all stop colors
* with `tinycolor.mix`.
*/
export function gradientToColor(
gradient: SVGLinearGradientElement | SVGRadialGradientElement,
opacity: number
): string {
const stops = Array.prototype.slice.apply(gradient.querySelectorAll('stop'))
if (stops.length === 0) {
return 'transparent'
} else if (stops.length === 1) {
const color = getStopColor(stops[0])
color.setAlpha(opacity)
return color.toString()
} else {
// Because roughjs can only deal with solid colors, we try to calculate
// the average color of the gradient here.
// The idea is to create an array of discrete (average) colors that represents the
// gradient under consideration of the stop's offset. Thus, larger offsets
// result in more entries of the same mixed color (of the two adjacent color stops).
// At the end, this array is averaged again, to create a single solid color.
const resolution = 10
const discreteColors = []
let lastColor = null
for (let i = 0; i < stops.length; i++) {
const currentColor = getStopColor(stops[i])
const currentOffset = getStopOffset(stops[i])
// combine the adjacent colors
const combinedColor = lastColor ? averageColor([lastColor, currentColor]) : currentColor
// fill the discrete color array depending on the offset size
let entries = Math.max(1, (currentOffset / resolution) | 0)
while (entries > 0) {
discreteColors.push(combinedColor)
entries--
}
lastColor = currentColor
}
// average the discrete colors again for the final result
const mixedColor = averageColor(discreteColors)
mixedColor.setAlpha(opacity)
return mixedColor.toString()
}
}
/**
* Returns the id from the url string
*/
export function getIdFromUrl(url: string | null): string | null {
if (url === null) {
return null
}
const result =
/url\('#?(.*?)'\)/.exec(url) || /url\("#?(.*?)"\)/.exec(url) || /url\(#?(.*?)\)/.exec(url)
if (result && result.length > 1) {
return result[1]
}
return null
}
/**
* Converts SVG opacity attributes to a [0, 1] range.
*/
export function getOpacity(element: SVGElement, attribute: string): number {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const attr = (getComputedStyle(element) as any)[attribute] || element.getAttribute(attribute)
if (attr) {
if (attr.indexOf('%') !== -1) {
return Math.min(1, Math.max(0, parseFloat(attr.substring(0, attr.length - 1)) / 100))
}
return Math.min(1, Math.max(0, parseFloat(attr)))
}
return 1
}
/**
* Returns the consolidated transform of the given element.
*/
export function getSvgTransform(element: SVGGraphicsElement): SVGTransform | null {
if (element.transform && element.transform.baseVal.numberOfItems > 0) {
return element.transform.baseVal.consolidate()
}
return null
}
export function getDefsElement(svgElement: SVGSVGElement): SVGDefsElement {
let outputDefs = svgElement.querySelector('defs')
if (!outputDefs) {
outputDefs = document.createElementNS('http://www.w3.org/2000/svg', 'defs')
if (svgElement.childElementCount > 0) {
svgElement.insertBefore(outputDefs, svgElement.firstElementChild)
} else {
svgElement.appendChild(outputDefs)
}
}
return outputDefs
}
export function isHidden(element: SVGElement): boolean {
const style = element.style
if (!style) {
return false
}
return style.display === 'none' || style.visibility === 'hidden'
}
/**
* The angle in degree of the line defined by the given points.
*/
export function getAngle(p0: Point, p1: Point): number {
return Math.atan2(p1.y - p0.y, p1.x - p0.x) * (180 / Math.PI)
}
export function getPointsArray(element: SVGPolygonElement | SVGPolylineElement): Array<Point> {
const pointsAttr = element.getAttribute('points')
if (!pointsAttr) {
return []
}
let coordinateRegexp
if (pointsAttr.indexOf(' ') > 0) {
// just assume that the coordinates (or pairs) are separated with space
coordinateRegexp = /\s+/g
} else {
// there are no spaces, so assume comma separators
coordinateRegexp = /,/g
}
const pointList = pointsAttr.split(coordinateRegexp)
const points = []
for (let i = 0; i < pointList.length; i++) {
const currentEntry = pointList[i]
const coordinates = currentEntry.split(',')
if (coordinates.length === 2) {
points.push(new Point(parseFloat(coordinates[0]), parseFloat(coordinates[1])))
} else {
// space as separators, take next entry as y coordinate
const next = i + 1
if (next < pointList.length) {
points.push(new Point(parseFloat(currentEntry), parseFloat(pointList[next])))
// skip the next entry
i = next
}
}
}
return points
}
/**
* Traverses the given elements hierarchy bottom-up to determine its effective
* opacity attribute.
* @param currentUseCtx Consider different DOM hierarchy for use elements
*/
export function getEffectiveElementOpacity(
context: RenderContext,
element: SVGElement,
currentOpacity: number,
currentUseCtx?: UseContext | null
): number {
let attr
if (!currentUseCtx) {
attr = getComputedStyle(element)['opacity'] || element.getAttribute('opacity')
} else {
// use elements traverse a different parent-hierarchy, thus we cannot use getComputedStyle here
attr = element.getAttribute('opacity')
}
if (attr) {
let elementOpacity = 1
if (attr.indexOf('%') !== -1) {
elementOpacity = Math.min(
1,
Math.max(0, parseFloat(attr.substring(0, attr.length - 1)) / 100)
)
} else {
elementOpacity = Math.min(1, Math.max(0, parseFloat(attr)))
}
// combine opacities
currentOpacity *= elementOpacity
}
// traverse upwards to combine parent opacities as well
let parent: Element | null = element.parentElement
const useCtx = currentUseCtx
let nextUseCtx = useCtx
if (useCtx && useCtx.referenced === element) {
// switch context and traverse the use-element parent now
parent = useCtx.root
nextUseCtx = useCtx.parentContext
}
if (!parent || parent === context.sourceSvg) {
return currentOpacity
}
return getEffectiveElementOpacity(context, parent as SVGElement, currentOpacity, nextUseCtx)
}
/**
* Returns the attribute value of an element under consideration
* of inherited attributes from the `parentElement`.
* @param attributeName Name of the attribute to look up
* @param currentUseCtx Consider different DOM hierarchy for use elements
* @return attribute value if it exists
*/
export function getEffectiveAttribute(
context: RenderContext,
element: SVGElement,
attributeName: string,
currentUseCtx?: UseContext | null
): string | null {
// getComputedStyle doesn't work for, e.g. <svg fill='rgba(...)'>
let attr
if (!currentUseCtx) {
attr =
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(getComputedStyle(element) as any)[attributeName] || element.getAttribute(attributeName)
} else {
// use elements traverse a different parent-hierarchy, thus we cannot use getComputedStyle here
attr = element.getAttribute(attributeName)
}
if (!attr) {
let parent: Element | null = element.parentElement
const useCtx = currentUseCtx
let nextCtx = useCtx
if (useCtx && useCtx.referenced === element) {
// switch context and traverse the use-element parent now
parent = useCtx.root
nextCtx = useCtx.parentContext
}
if (!parent || parent === context.sourceSvg) {
return null
}
return getEffectiveAttribute(context, parent as SVGElement, attributeName, nextCtx)
}
return attr
}
/**
* Parses a `fill` url by looking in the SVG `defs` element.
* When a gradient is found, it is converted to a color and stored
* in the internal defs store for this url.
* @returns The parsed color
*/
export function parseFillUrl(
context: RenderContext,
url: string,
opacity: number
): string | undefined {
const id = getIdFromUrl(url)
if (!id) {
return 'transparent'
}
const fill = context.idElements[id]
if (fill) {
if (typeof fill === 'string') {
// maybe it was already parsed and replaced with a color
return fill
} else {
if (fill instanceof SVGLinearGradientElement || fill instanceof SVGRadialGradientElement) {
const color = gradientToColor(fill, opacity)
context.idElements[id] = color
return color
}
}
}
}
/**
* Converts the given string to px unit. May be either a <length>
* (https://developer.mozilla.org/de/docs/Web/SVG/Content_type#Length)
* or a <percentage>
* (https://developer.mozilla.org/de/docs/Web/SVG/Content_type#Percentage).
* @returns The value in px unit
*/
export function convertToPixelUnit(context: RenderContext, value: string): number {
// css-units fails for converting from unit-less to 'px' in IE11,
// thus we only apply it to non-px values
if (value.match(CONTAINS_UNIT_REGEXP) !== null) {
return units.convert('px', value, context.sourceSvg)
}
return parseFloat(value)
}
/**
* Converts the effective style attributes of the given `SVGElement`
* to a Rough.js config object that is used to draw the element with
* Rough.js.
* @return config for Rough.js drawing
*/
export function parseStyleConfig(
context: RenderContext,
element: SVGElement,
svgTransform: SVGTransform | null
): Options {
const config = Object.assign({}, context.roughConfig)
// Scalefactor for certain style attributes. For lack of a better option here, use the determinant
let scaleFactor = 1
if (!isIdentityTransform(svgTransform)) {
const m = svgTransform!.matrix
const det = m.a * m.d - m.c * m.b
scaleFactor = Math.sqrt(det)
}
// incorporate the elements base opacity
const elementOpacity = getEffectiveElementOpacity(context, element, 1, context.useElementContext)
const fill = getEffectiveAttribute(context, element, 'fill', context.useElementContext) || 'black'
const fillOpacity = elementOpacity * getOpacity(element, 'fill-opacity')
if (fill) {
if (fill.indexOf('url') !== -1) {
config.fill = parseFillUrl(context, fill, fillOpacity)
} else if (fill === 'none') {
delete config.fill
} else {
const color = tinycolor(fill)
color.setAlpha(fillOpacity)
config.fill = color.toString()
}
}
const stroke = getEffectiveAttribute(context, element, 'stroke', context.useElementContext)
const strokeOpacity = elementOpacity * getOpacity(element, 'stroke-opacity')
if (stroke) {
if (stroke.indexOf('url') !== -1) {
config.stroke = parseFillUrl(context, fill, strokeOpacity)
} else if (stroke === 'none') {
config.stroke = 'none'
} else {
const color = tinycolor(stroke)
color.setAlpha(strokeOpacity)
config.stroke = color.toString()
}
} else {
config.stroke = 'none'
}
const strokeWidth = getEffectiveAttribute(
context,
element,
'stroke-width',
context.useElementContext
)
if (strokeWidth) {
// Convert to user space units (px)
config.strokeWidth = convertToPixelUnit(context, strokeWidth) * scaleFactor
} else {
config.strokeWidth = 0
}
const strokeDashArray = getEffectiveAttribute(
context,
element,
'stroke-dasharray',
context.useElementContext
)
if (strokeDashArray && strokeDashArray !== 'none') {
config.strokeLineDash = strokeDashArray
.split(/[\s,]+/)
.filter(entry => entry.length > 0)
// make sure that dashes/dots are at least somewhat visible
.map(dash => Math.max(0.5, convertToPixelUnit(context, dash) * scaleFactor))
}
const strokeDashOffset = getEffectiveAttribute(
context,
element,
'stroke-dashoffset',
context.useElementContext
)
if (strokeDashOffset) {
config.strokeLineDashOffset = convertToPixelUnit(context, strokeDashOffset) * scaleFactor
}
// unstroked but filled shapes look weird, so always apply a stroke if we fill something
if (config.fill && config.stroke === 'none') {
config.stroke = config.fill
config.strokeWidth = 1
}
// nested paths should be filled twice, see
// https://github.com/rough-stuff/rough/issues/158
// however, fill-rule is still problematic, see
// https://github.com/rough-stuff/rough/issues/131
if (typeof config.combineNestedSvgPaths === 'undefined') {
config.combineNestedSvgPaths = true
}
if (context.randomize) {
// Rough.js default is 0.5 * strokeWidth
config.fillWeight = getRandomNumber(0.5, 3)
// Rough.js default is -41deg
config.hachureAngle = getRandomNumber(-30, -50)
// Rough.js default is 4 * strokeWidth
config.hachureGap = getRandomNumber(3, 5)
// randomize double stroke effect if not explicitly set through user config
if (typeof config.disableMultiStroke === 'undefined') {
config.disableMultiStroke = Math.random() > 0.3
}
}
return config
}
/**
* A context that represents the current state of the rendering,
* which is used in the rendering functions.
*/
export type RenderContext = {
rc: RoughCanvas | RoughSVG
roughConfig: Options
renderMode: RenderMode
fontFamily: string | null
pencilFilter: boolean
randomize: boolean
idElements: Record<string, SVGElement | string>
sourceSvg: SVGSVGElement
targetCanvas?: HTMLCanvasElement
targetCanvasContext?: CanvasRenderingContext2D
targetSvg?: SVGSVGElement
useElementContext?: UseContext | null
processElement: (
context: RenderContext,
root: SVGSVGElement | SVGGElement | SVGSymbolElement | SVGMarkerElement | SVGElement,
svgTransform: SVGTransform | null,
width?: number,
height?: number
) => void
}
/**
* The context for rendering use elements.
*/
export type UseContext = {
referenced: SVGElement
root: Element | null
parentContext: UseContext | null
}
/**
* Helper method to append the returned `SVGGElement` from
* Rough.js when drawing in SVG mode.
*/
export function postProcessElement(
context: RenderContext,
element: SVGElement,
sketchElement?: Drawable | SVGElement
): void {
if (context.renderMode === RenderMode.SVG && context.targetSvg && sketchElement) {
let sketch = sketchElement as SVGElement
// original element may have a clip-path
const sketchClipPathId = element.getAttribute('data-sketchy-clip-path')
const applyPencilFilter = context.pencilFilter && element.tagName !== 'text'
// wrap it in another container to safely apply post-processing attributes,
// though avoid no-op <g> containers
const isPlainContainer = sketch.tagName === 'g' && sketch.attributes.length === 0
if (!isPlainContainer && (sketchClipPathId || applyPencilFilter)) {
const g = document.createElementNS('http://www.w3.org/2000/svg', 'g')
g.appendChild(sketch)
sketch = g
}
if (sketchClipPathId) {
sketch.setAttribute('clip-path', `url(#${sketchClipPathId})`)
}
if (applyPencilFilter) {
sketch.setAttribute('filter', 'url(#pencilTextureFilter)')
}
context.targetSvg.appendChild(sketch)
}
}
/**
* Helper method to sketch a path.
* Paths with curves should utilize the preserverVertices option to avoid line disjoints.
* For non-curved paths it looks nicer to actually allow these diskoints.
* @returns Returns the SVGElement for the SVG render mode, or undefined otherwise
*/
export function sketchPath(
context: RenderContext,
path: string,
options?: Options
): Drawable | SVGElement {
if (PATH_CURVES_REGEX.test(path)) {
options = options ? { ...options, preserveVertices: true } : { preserveVertices: true }
}
return context.rc.path(path, options)
}
/**
* Combines the given transform with the element's transform.
* If no transform is given, it returns the SVGTransform of the element.
*/
export function getCombinedTransform(
context: RenderContext,
element: SVGGraphicsElement,
transform: SVGTransform | null
): SVGTransform | null {
if (!transform) {
return getSvgTransform(element)
}
const elementTransform = getSvgTransform(element)
if (elementTransform) {
const elementTransformMatrix = elementTransform.matrix
const combinedMatrix = transform.matrix.multiply(elementTransformMatrix)
return context.sourceSvg.createSVGTransformFromMatrix(combinedMatrix)
}
return transform
}
/**
* Applies the given svgTransform to the canvas context or the given element when in SVG mode.
* @param element The element to which the transform should be applied
* when in SVG mode.
*/
export function applyGlobalTransform(
context: RenderContext,
svgTransform: SVGTransform | null,
element?: SVGGraphicsElement | null
): void {
if (svgTransform && svgTransform.matrix) {
const matrix = svgTransform.matrix
if (context.renderMode === RenderMode.CANVAS && context.targetCanvasContext) {
// IE11 doesn't support SVGMatrix as parameter for setTransform
context.targetCanvasContext.setTransform(
matrix.a,
matrix.b,
matrix.c,
matrix.d,
matrix.e,
matrix.f
)
} else if (context.renderMode === RenderMode.SVG && element) {
if (element.transform.baseVal.numberOfItems > 0) {
element.transform.baseVal.getItem(0).setMatrix(matrix)
} else {
element.transform.baseVal.appendItem(svgTransform)
}
}
}
} | the_stack |
import {Observable, Subscription} from 'rxjs';
import {tap} from 'rxjs/operators';
import {
DispatchFailReason,
EventReplay,
EventUnitClear,
EventUnitClearCache,
EventUnitClearValue,
EventUnitDispatch,
EventUnitDispatchFail,
EventUnitFreeze,
EventUnitJump,
EventUnitReset,
EventUnitResetValue,
EventUnitUnfreeze,
EventUnitUnmute,
UnitConfig,
UnitEvents,
UnitStreamObservableProducer,
} from '../models';
import {Stream} from '../lib/stream';
import {NonPrimitiveUnitBase} from '../lib/abstract-non-primitive-unit-base';
import {Configuration} from '../lib/configuration';
import {Selection} from '../lib/selection';
import {UnitBase} from '../lib/abstract-unit-base';
import {Base} from '../lib/abstract-base';
import {
findRandomPath,
multipleOf,
numberOrRandomValue,
randomBoolean,
randomNumber,
randomNumOrStr,
randomString,
randomUnit,
randomUnitCtor,
randomValidValue,
randomValue,
randomValues,
selectRandom,
somewhatValidConfig,
times,
unitsDefaultValue,
} from './utils';
import {isNumber} from '../utils/funcs';
import createSpy = jasmine.createSpy;
const configOptions: Array<keyof UnitConfig<any>> = [
// 'id', // tests with id are done separately to keep other tests simple
// 'immutable', // immutability tests are done separately to keep other tests simple
// 'persistent', // persistence tests are done separately to keep other tests simple
'replay',
'initialValue',
'cacheSize',
'distinctDispatchCheck',
'customDispatchCheck',
'dispatchDebounce',
'dispatchDebounceMode',
];
describe(
'Units Common',
times(30, () => {
beforeAll(() => {
Configuration.reset();
});
let unitConfig: UnitConfig<any>;
let unit: UnitBase<any> & NonPrimitiveUnitBase<any>;
describe('configuration', () => {
beforeAll(() => {
Configuration.reset();
});
it('should extend UnitBase', () => {
expect(randomUnit()).toBeInstanceOf(UnitBase);
});
it('should extend Base', () => {
expect(randomUnit()).toBeInstanceOf(Base);
});
describe('Inheriting from Global Configuration', () => {
beforeEach(() => {
Configuration.reset();
});
it('should inherit', () => {
Configuration.set({UNITS: {cacheSize: 3}});
unit = randomUnit();
expect(unit.cacheSize).toBe(3);
});
it('should not inherit after instantiation', () => {
unit = randomUnit();
Configuration.set({UNITS: {cacheSize: 3}});
expect(unit.cacheSize).toBe(2);
});
it('should prioritize specific Unit type config over common Units config', () => {
const unitCtor = randomUnitCtor();
const unitClassKey = unitCtor.name.replace(/(?<!^)([A-Z])/g, '_$1').toUpperCase();
Configuration.set({
UNITS: {cacheSize: 3},
[unitClassKey]: {cacheSize: 4},
});
unit = new unitCtor();
expect(unit.cacheSize).toBe(4);
});
});
describe('Different Configurations', () => {
beforeAll(() => {
Configuration.reset();
});
beforeEach(() => {
const unitCtor = randomUnitCtor();
unitConfig = {
...somewhatValidConfig(configOptions, unitCtor),
initialValue: randomValidValue(unitCtor),
};
unit = new unitCtor(unitConfig);
});
it('should have events', () => {
expect(unit.events$).toBeInstanceOf(Observable);
});
it('should have valid replay config', () => {
if (typeof unitConfig.replay === 'boolean') {
expect(unitConfig.replay).toBe(unit.config.replay);
} else {
expect(typeof unitConfig.replay).not.toBe('boolean');
}
});
it('should respect initialValue', () => {
expect(unit.initialValue()).toEqual(unitConfig.initialValue);
expect(unit.value()).toEqual(unitConfig.initialValue);
});
it('should respect cacheSize', () => {
const {cacheSize} = unitConfig;
expect(unit.cacheSize).toBe(isNumber(cacheSize) ? Math.max(1, cacheSize) : 2);
});
it('should respect replay-nes', () => {
unit = randomUnit(unitConfig);
const callBackSpy = createSpy();
unit.subscribe(callBackSpy);
if (unit.config.replay === false) {
expect(callBackSpy).not.toHaveBeenCalled();
} else {
expect(callBackSpy).toHaveBeenCalledWith(unit.value());
}
});
it('should respect dispatch checks', () => {
const wouldCustomCheckAllow =
typeof unitConfig.customDispatchCheck !== 'function' ||
unitConfig.customDispatchCheck(1, 2);
const wouldDistinctCheckAllow =
unitConfig.distinctDispatchCheck !== true || unit.value() !== unit.value();
let event;
unit.events$.subscribe(e => (event = e));
const {emitCount} = unit;
const dispatchOptions = {bypassDebounce: true};
const didDispatch = unit.dispatch(unit.value(), dispatchOptions);
if (wouldCustomCheckAllow && wouldDistinctCheckAllow) {
expect(didDispatch).toBe(true);
expect(unit.emitCount).toBe(emitCount + 1);
expect(event).toBeInstanceOf(EventUnitDispatch);
return;
}
expect(didDispatch).toBe(false);
expect(unit.emitCount).toBe(emitCount);
expect(event).toBeInstanceOf(EventUnitDispatchFail);
expect(event).toEqual(
new EventUnitDispatchFail(
unit.value(),
wouldDistinctCheckAllow
? DispatchFailReason.CUSTOM_DISPATCH_CHECK
: DispatchFailReason.DISTINCT_CHECK,
dispatchOptions
)
);
});
it('should respect dispatchDebounce and dispatchDebounceMode', () => {
const {dispatchDebounce, dispatchDebounceMode} = unitConfig;
const debounceMode = ['START', 'BOTH'].includes(dispatchDebounceMode)
? dispatchDebounceMode
: 'END';
const didDispatch = unit.dispatch(randomValidValue(unit));
if (dispatchDebounce === true || isNumber(dispatchDebounce)) {
expect(didDispatch === undefined).toBe(debounceMode === 'END');
} else {
expect(typeof didDispatch === 'boolean').toBe(true);
}
});
});
});
describe('basic Tests', () => {
beforeAll(() => {
Configuration.reset();
});
beforeEach(() => {
const unitCtor = randomUnitCtor();
unitConfig = somewhatValidConfig(configOptions, unitCtor);
unit = new unitCtor(unitConfig);
});
it('should be observable', () => {
expect(unit).toBeInstanceOf(Observable);
expect(unit.asObservable()).toBeInstanceOf(Observable);
expect((unit.asObservable() as any).source).toBe((unit as any).source);
});
it('should disallow invalid values', () => {
const unitCtor = randomUnitCtor();
unit = new unitCtor({
...somewhatValidConfig(configOptions, unitCtor),
initialValue: randomValidValue(unit),
distinctDispatchCheck: false,
customDispatchCheck: null,
dispatchDebounce: null,
});
randomValues().forEach(value => {
const wouldDispatch = unit.wouldDispatch(value);
let event: UnitEvents<any>;
unit.events$.subscribe(e => (event = e));
expect(unit.dispatch(value)).toBe(wouldDispatch);
expect(event).toBeInstanceOf(wouldDispatch ? EventUnitDispatch : EventUnitDispatchFail);
if (event instanceof EventUnitDispatchFail) {
expect(event.reason).toBe(DispatchFailReason.INVALID_VALUE);
}
});
});
it('should not goBack, goForward, jump, jumpToStart, jumpToEnd', () => {
const emitCount = unit.emitCount;
const cachedValues = unit.cachedValues();
expect(unit.goBack()).toBe(false);
expect(unit.goForward()).toBe(false);
expect(unit.jump(0)).toBe(false);
expect(unit.jump(-2)).toBe(false);
expect(unit.jump(3)).toBe(false);
expect(unit.jumpToStart()).toBe(false);
expect(unit.jumpToEnd()).toBe(false);
expect(unit.cachedValues()).toEqual(cachedValues);
expect(unit.emitCount).toBe(emitCount);
});
it('should not unmute even without events', () => {
const emitCount = unit.emitCount;
unit.mute();
unit.unmute();
unit.unmute();
expect(unit.emitCount).toBe(emitCount);
});
});
describe('medium to advanced tests', () => {
let emitCount: number;
let value: any;
let cachedValues: any[];
let event: UnitEvents<any>;
let eventsSubscription: Subscription;
beforeAll(() => {
Configuration.reset();
});
beforeEach(() => {
const unitCtor = randomUnitCtor();
unitConfig = {
...somewhatValidConfig(configOptions, unitCtor),
cacheSize: randomNumber(4, 20),
dispatchDebounce: null,
customDispatchCheck: null,
};
unit = new unitCtor(unitConfig);
// dispatch 10 times
Array(randomNumber(1, 10))
.fill(null)
.forEach(() => {
// without `force` BoolUnit might not have enough cached values
unit.dispatch(randomValidValue(unit), {force: true});
});
value = unit.value();
emitCount = unit.emitCount;
cachedValues = unit.cachedValues();
event = undefined;
if (eventsSubscription) {
eventsSubscription.unsubscribe();
}
eventsSubscription = unit.events$.subscribe(e => (event = e));
});
it('should give rawValue', () => {
if (unit.config.immutable === true) {
expect(unit.rawValue()).not.toBe(value);
expect(unit.rawValue()).toEqual(value);
} else {
expect(unit.rawValue()).toBe(value);
}
});
it('should be empty, or not', () => {
if (unit.isEmpty) {
expect(unit.value()).toEqual(unitsDefaultValue(unit));
} else {
expect(unit.value()).not.toEqual(unitsDefaultValue(unit));
}
});
it('should toJsonString', () => {
expect(unit.toJsonString()).toBe(JSON.stringify(unit.value()));
});
it('should implement toString', () => {
if (unit.value() == null) {
expect(unit.toString).toThrow();
} else {
expect(unit.toString()).toBe(unit.value().toString());
}
});
it('should implement toLocaleString', () => {
if (value == null) {
expect(() => unit.toLocaleString()).toThrowError(TypeError);
} else {
expect(unit.toLocaleString()).toBe(value.toLocaleString());
}
});
it('should implement valueOf', () => {
expect(unit.valueOf()).toBe(unit.rawValue());
});
it('should implement toJSON', () => {
expect(unit.toJSON()).toEqual(unit.rawValue());
});
it('should implement propertyIsEnumerable', () => {
const randString = selectRandom(
Object.getOwnPropertyNames(value ?? 0).concat(multipleOf(randomString, 3))
);
if (value == null) {
expect(() => unit.propertyIsEnumerable(randString)).toThrowError(TypeError);
} else {
expect(unit.propertyIsEnumerable(randString)).toEqual(
value.propertyIsEnumerable(randString)
);
}
});
it('should implement hasOwnProperty', () => {
const randString = selectRandom(
Object.getOwnPropertyNames(value ?? 0).concat(multipleOf(randomString, 3))
);
if (value == null) {
expect(() => unit.hasOwnProperty(randString)).toThrowError(TypeError);
} else {
expect(unit.hasOwnProperty(randString)).toEqual(value.hasOwnProperty(randString));
}
});
it('should dispatch', () => {
const validValue = randomValidValue(unit);
const valOrProducer = randomBoolean() ? validValue : () => validValue;
if (unit.wouldDispatch(validValue)) {
expect(unit.dispatch(valOrProducer)).toBe(true);
expect(unit.value()).toEqual(validValue);
} else {
expect(unit.dispatch(valOrProducer, {force: true})).toBe(true);
expect(unit.value()).toEqual(validValue);
}
});
it('should replace cache', () => {
expect(unit.jump(-randomNumber(1, unit.cachedValuesCount - 1))).toBe(true);
const validValue = randomValidValue(unit);
const {cacheIndex} = unit;
if (unit.wouldDispatch(validValue)) {
expect(unit.dispatch(validValue, {cacheReplace: true})).toBe(true);
expect(unit.value()).toEqual(validValue);
expect(unit.cacheIndex).toEqual(cacheIndex);
} else {
expect().nothing();
}
});
it('should behave like browser history', () => {
expect(unit.jump(-randomNumber(1, unit.cachedValuesCount - 1))).toBe(true);
const validValue = randomValidValue(unit);
if (unit.wouldDispatch(validValue)) {
expect(unit.dispatch(validValue)).toBe(true);
expect(unit.value()).toEqual(validValue);
expect(unit.cacheIndex).toEqual(unit.cachedValuesCount - 1);
expect(unit.goForward()).toEqual(false);
} else {
expect().nothing();
}
});
it('should replay', () => {
expect(unit.replay()).toBe(true);
expect(unit.value()).toEqual(value);
expect(unit.emitCount).toBe(emitCount + 1);
expect(unit.cachedValues()).toEqual(cachedValues);
expect(event).toBeInstanceOf(EventReplay);
expect(event).toEqual(new EventReplay(unit.value()));
});
it('should goBack', () => {
expect(unit.jump(-randomNumber(1, unit.cachedValuesCount - 2))).toBe(true);
if (unit.cacheIndex === 0) {
expect(unit.goBack()).toBe(false);
return;
}
const {cacheIndex} = unit;
expect(unit.goBack()).toBe(true);
expect(unit.value()).toEqual(cachedValues[cacheIndex - 1]);
expect(unit.cacheIndex).toBe(cacheIndex - 1);
expect(unit.emitCount).toBe(emitCount + 2);
expect(unit.cachedValues()).toEqual(cachedValues);
expect(event).toBeInstanceOf(EventUnitJump);
expect(event).toEqual(new EventUnitJump(-1, cacheIndex - 1));
});
it('should goForward', () => {
expect(unit.goBack()).toBe(true);
const cacheIndex = unit.cacheIndex;
expect(unit.goForward()).toBe(true);
expect(unit.value()).toEqual(cachedValues[cacheIndex + 1]);
expect(unit.emitCount).toBe(emitCount + 2);
expect(unit.cachedValues()).toEqual(cachedValues);
expect(event).toBeInstanceOf(EventUnitJump);
expect(event).toEqual(new EventUnitJump(1, cacheIndex + 1));
});
it('should jumpToStart', () => {
const {cacheIndex} = unit;
unit.jumpToStart();
expect(unit.value()).toEqual(cachedValues[0]);
expect(unit.cacheIndex).toBe(0);
expect(unit.emitCount).toBe(emitCount + 1);
expect(event).toBeInstanceOf(EventUnitJump);
expect(event).toEqual(new EventUnitJump(-cacheIndex, 0));
});
it('should jumpToEnd', () => {
const {cachedValuesCount} = unit;
expect(unit.jump(-randomNumber(1, cachedValuesCount - 1))).toBe(true);
const {cacheIndex} = unit;
expect(unit.jumpToEnd()).toBe(true);
expect(unit.value()).toEqual(unit.getCachedValue(unit.cachedValuesCount - 1));
expect(unit.emitCount).toBe(emitCount + 2);
expect(unit.cachedValues()).toEqual(cachedValues);
expect(event).toBeInstanceOf(EventUnitJump);
expect(event).toEqual(
new EventUnitJump(cachedValuesCount - cacheIndex - 1, cachedValuesCount - 1)
);
});
it('should jump back', () => {
let {cacheIndex} = unit;
let jumpSteps = -randomNumber(1, cacheIndex);
expect(unit.jump(jumpSteps)).toBe(true);
cacheIndex += jumpSteps;
emitCount++;
if (cacheIndex > 1) {
jumpSteps = -randomNumber(1, cacheIndex);
expect(unit.jump(jumpSteps)).toBe(true);
cacheIndex += jumpSteps;
emitCount++;
}
expect(unit.value()).toEqual(unit.getCachedValue(cacheIndex));
expect(unit.emitCount).toBe(emitCount);
expect(unit.cachedValues()).toEqual(cachedValues);
expect(event).toBeInstanceOf(EventUnitJump);
expect(event).toEqual(new EventUnitJump(jumpSteps, cacheIndex));
});
it('should jump forward', () => {
const {cachedValuesCount} = unit;
expect(unit.jump(-randomNumber(1, cachedValuesCount - 1))).toBe(true);
const {cacheIndex} = unit;
const jumpSteps = randomNumber(1, cachedValuesCount - cacheIndex - 1);
expect(unit.jump(jumpSteps)).toBe(true);
expect(unit.value()).toEqual(unit.getCachedValue(cacheIndex + jumpSteps));
expect(unit.emitCount).toBe(emitCount + 2);
expect(unit.cachedValues()).toEqual(cachedValues);
expect(event).toBeInstanceOf(EventUnitJump);
expect(event).toEqual(new EventUnitJump(jumpSteps, cacheIndex + jumpSteps));
});
it('should reset value', () => {
if (unit.value() === unit.initialValue()) {
expect(unit.resetValue()).toBe(false);
expect(unit.emitCount).toBe(emitCount);
expect(event).toBe(undefined);
} else {
expect(unit.resetValue()).toBe(true);
expect(unit.emitCount).toBe(emitCount + 1);
expect(event).toBeInstanceOf(EventUnitResetValue);
}
expect(unit.value()).toEqual(unit.initialValue());
});
it('should clear value', () => {
if (unit.emitCount === 0 || unit.isEmpty) {
expect(unit.clearValue()).toBe(false);
expect(unit.emitCount).toBe(emitCount);
expect(event).toBe(undefined);
} else {
expect(unit.clearValue()).toBe(true);
expect(unit.emitCount).toBe(emitCount + 1);
expect(event).toBeInstanceOf(EventUnitClearValue);
}
expect(unit.value()).toEqual(unitsDefaultValue(unit));
});
it('should clear cache', () => {
expect(unit.clearCache()).toBe(true);
expect(unit.emitCount).toBe(emitCount);
expect(unit.cachedValues()).toEqual([]);
expect(event).toBeInstanceOf(EventUnitClearCache);
});
it('should clear cache: leave first value', () => {
cachedValues = [cachedValues.shift()];
expect(unit.clearCache({leaveFirst: true})).toBe(true);
expect(unit.emitCount).toBe(emitCount);
expect(unit.cachedValues()).toEqual(cachedValues);
expect(event).toBeInstanceOf(EventUnitClearCache);
expect(event).toEqual(new EventUnitClearCache({leaveFirst: true}));
});
it('should clear cache: leave last value', () => {
cachedValues = [cachedValues.pop()];
expect(unit.clearCache({leaveLast: true})).toBe(true);
expect(unit.emitCount).toBe(emitCount);
expect(unit.cachedValues()).toEqual(cachedValues);
expect(event).toBeInstanceOf(EventUnitClearCache);
expect(event).toEqual(new EventUnitClearCache({leaveLast: true}));
});
it('should clear cache: leave first and last values', () => {
if (cachedValues.length < 3) {
expect(unit.clearCache({leaveFirst: true, leaveLast: true})).toBe(false);
return;
}
cachedValues = [cachedValues.shift(), cachedValues.pop()];
expect(unit.clearCache({leaveFirst: true, leaveLast: true})).toBe(true);
expect(unit.emitCount).toBe(emitCount);
expect(unit.cachedValues()).toEqual(cachedValues);
expect(event).toBeInstanceOf(EventUnitClearCache);
expect(event).toEqual(new EventUnitClearCache({leaveFirst: true, leaveLast: true}));
});
it('should getCachedValue', () => {
const randIndex = numberOrRandomValue();
expect(unit.getCachedValue(randIndex)).toEqual(cachedValues[randIndex]);
});
it('should reset', () => {
const wouldEmit = unit.value() !== unit.initialValue();
unit.freeze();
unit.reset();
const cachedValuesThatWillRemain = unit.cachedValues().splice(-1);
expect(unit.isFrozen).toBe(false);
expect(unit.value()).toEqual(unit.initialValue());
expect(unit.emitCount).toBe(emitCount + (wouldEmit ? 1 : 0));
expect(unit.cachedValues()).toEqual(cachedValuesThatWillRemain);
expect(event).toBeInstanceOf(EventUnitReset);
});
it('should clear', () => {
const wouldEmit = !unit.isEmpty;
unit.freeze();
unit.clear();
expect(unit.isFrozen).toBe(false);
expect(unit.value()).toEqual(unitsDefaultValue(unit));
expect(unit.emitCount).toBe(emitCount + (wouldEmit ? 1 : 0));
expect(unit.cachedValues()).toEqual([]);
expect(event).toBeInstanceOf(EventUnitClear);
});
it('should freeze', () => {
unit.freeze();
expect(event).toBeInstanceOf(EventUnitFreeze);
expect(event).toEqual(new EventUnitFreeze());
expect(unit.dispatch(randomValidValue(unit), {force: randomBoolean()})).not.toBe(true);
expect((event as EventUnitDispatchFail<any>).reason).toBe(DispatchFailReason.FROZEN_UNIT);
expect(unit.goBack()).toBe(false);
expect(unit.goForward()).toBe(false);
expect(unit.jump(0)).toBe(false);
expect(unit.jump(-2)).toBe(false);
expect(unit.jump(3)).toBe(false);
expect(unit.jumpToStart()).toBe(false);
expect(unit.jumpToEnd()).toBe(false);
expect(unit.resetValue()).toBe(false);
expect(unit.clearCache()).toBe(false);
expect(unit.clearValue()).toBe(false);
expect(unit.replay()).toBe(false);
expect(unit.isFrozen).toBe(true);
expect(unit.cachedValues()).toEqual(cachedValues);
expect(unit.emitCount).toBe(emitCount);
});
it('should unfreeze', () => {
unit.freeze();
unit.dispatch(randomValidValue(unit), {force: randomBoolean()});
unit.unfreeze();
expect(event).toBeInstanceOf(EventUnitUnfreeze);
expect(event).toEqual(new EventUnitUnfreeze());
expect(unit.emitCount).toBe(emitCount);
expect(unit.cachedValues()).toEqual(cachedValues);
expect(unit.replay()).toBe(true);
expect(unit.isFrozen).toBe(false);
});
it('should not freeze already frozen unit', () => {
unit.freeze();
expect(event).toBeInstanceOf(EventUnitFreeze);
event = undefined;
unit.freeze();
expect(event).toBe(undefined);
});
it('should not unfreeze already unfrozen unit', () => {
unit.freeze();
unit.unfreeze();
expect(event).toBeInstanceOf(EventUnitUnfreeze);
event = undefined;
unit.unfreeze();
expect(event).toBe(undefined);
});
it('should mute', () => {
unit.mute();
unit.goBack();
unit.goForward();
unit.jump(0);
unit.jump(-2);
unit.jump(3);
unit.jumpToStart();
unit.jumpToEnd();
unit.resetValue();
unit.clearCache();
unit.dispatch(randomValidValue(unit), {force: true});
unit.clearValue();
unit.dispatch(randomValidValue(unit), {force: true});
unit.replay();
unit.dispatch(randomValidValue(unit), {force: true});
unit.clear();
unit.dispatch(randomValidValue(unit), {force: true});
unit.reset();
unit.freeze();
unit.unfreeze();
expect(unit.isMuted).toBe(true);
expect(event).toBe(undefined);
expect(unit.emitCount).toBe(emitCount);
expect(event).toBe(undefined);
});
it('should unmute', () => {
unit.mute();
const validValue = randomValidValue(unit);
const didDispatch = unit.dispatch(validValue);
unit.unmute();
expect(event).toBeInstanceOf(EventUnitUnmute);
if (didDispatch) {
expect(unit.value()).toEqual(validValue);
expect(unit.emitCount).toBe(emitCount + 1);
} else {
expect(unit.emitCount).toBe(emitCount);
expect(unit.cachedValues()).toEqual(cachedValues);
}
expect(unit.replay()).toBe(true);
expect(unit.isMuted).toBe(false);
});
it('should not unmute already unmuted unit', () => {
unit.mute();
unit.dispatch(randomValidValue(unit));
unit.unmute();
event = null;
emitCount = unit.emitCount;
unit.unmute();
expect(unit.emitCount).toBe(emitCount);
expect(event).not.toBeInstanceOf(EventUnitUnmute);
});
it('should not emit on subsequent mute-unmute', () => {
unit.mute();
unit.dispatch(randomValidValue(unit));
unit.unmute();
emitCount = unit.emitCount;
unit.mute();
unit.unmute();
expect(unit.emitCount).toBe(emitCount);
});
it('should createStream', () => {
const operatorSpy = createSpy('operatorSpy');
const observableProducer = createSpy<UnitStreamObservableProducer>(
'observableProducer'
).and.callFake(sourceUnit => {
return sourceUnit.pipe(tap(v => operatorSpy(v)));
});
const stream = unit.createStream(observableProducer);
expect(stream).toBeInstanceOf(Stream);
expect(observableProducer).toHaveBeenCalledWith(unit);
if (unit.config.replay === false) {
expect(operatorSpy).not.toHaveBeenCalled();
} else {
expect(operatorSpy).toHaveBeenCalledWith(unit.value());
}
operatorSpy.calls.reset();
if (unit.dispatch(randomValue(1))) {
expect(operatorSpy).toHaveBeenCalledWith(unit.value());
} else {
expect(operatorSpy).not.toHaveBeenCalled();
}
});
it('should return Selection for NonPrimitive Units', () => {
if (unit instanceof NonPrimitiveUnitBase) {
let randPath = findRandomPath(unit.value());
if (!randPath.length) {
randPath = [randomNumOrStr()];
}
const selection = unit.select(...(randPath as [any]));
expect(selection).toBeInstanceOf(Selection);
} else {
expect((unit as any).select).toBe(undefined);
}
});
});
})
); | the_stack |
import * as ts from "typescript";
export interface DocEntry {
filename?: string;
exportMembers?: string[];
escapedName?: string;
name?: string;
type?: string;
locals?: DocEntry[];
exports?: DocEntry[];
members?: DocEntry[];
resolvedModules?: {
name?: string;
resolvedFileName: string;
isExternalLibraryImport?: boolean;
}[];
comment?: string;
constructors?: DocEntry[];
isRequired?: boolean;
documentation?: string;
parameters?: DocEntry[];
returnType?: string;
extends?: DocEntry[] | string[];
valueDeclarationText?: string;
initializerText?: string;
}
const customType: any = {
"8388608": "React",
"16777220": "prototype"
};
export class Parser {
constructor(options?: ts.CompilerOptions, host?: ts.CompilerHost) {
const defaultOptions: ts.CompilerOptions = {
target: ts.ScriptTarget.ES5,
maxNodeModuleJsDepth: 1,
module: ts.ModuleKind.CommonJS
};
this.options = options || defaultOptions;
this.host = host;
}
getAllLocalMembers = false;
private rootNames: string[];
private options: ts.CompilerOptions;
private host: ts.CompilerHost;
private program: ts.Program;
private checker: ts.TypeChecker;
private sourceFiles: ts.SourceFile[];
private currSourceFile: ts.SourceFile;
private output: DocEntry = {};
getResultCallback: (result: DocEntry) => void;
parse = (fileName: string | string[], callback = (result?: DocEntry) => { }) => {
const rootNames = Array.isArray(fileName) ? fileName : [fileName];
this.rootNames = rootNames;
this.program = ts.createProgram(rootNames, this.options, this.host);
this.checker = this.program.getTypeChecker();
this.sourceFiles = this.program.getSourceFiles() as ts.SourceFile[];
for (const fileName of this.rootNames) {
this.currSourceFile = this.program.getSourceFile(fileName);
this.visit(this.currSourceFile);
// ts.forEachChild(this.currSourceFile, this.visit);
}
if (this.output.members) {
this.output.members = this.output.members.filter(member => member);
}
callback(this.output);
return this.output;
}
visit = (node: ts.Node) => {
if (!node) return;
let symbol: ts.Symbol = null;
switch (node.kind) {
case ts.SyntaxKind.SourceFile: {
symbol = this.getSymbolByType(node as ts.SourceFile);
if (!symbol) {
symbol = this.currSourceFile as any;
}
this.output.filename = (node as ts.SourceFile).fileName;
break;
}
case ts.SyntaxKind.ClassDeclaration: {
// const t = node as ts.ClassDeclaration;
symbol = this.getSymbolByType(node as ts.ClassDeclaration);
break;
}
case ts.SyntaxKind.InterfaceDeclaration: {
symbol = this.getSymbolByType(node as ts.InterfaceDeclaration);
break;
}
case ts.SyntaxKind.FunctionDeclaration: {
symbol = this.getSymbolByType(node as ts.FunctionDeclaration);
break;
}
case ts.SyntaxKind.MethodDeclaration: {
symbol = this.getSymbolByType(node as ts.MethodDeclaration);
break;
}
case ts.SyntaxKind.PropertyDeclaration: {
symbol = this.getSymbolByType(node as ts.PropertyDeclaration);
break;
}
case ts.SyntaxKind.EnumDeclaration: {
symbol = this.getSymbolByType(node as ts.EnumDeclaration);
break;
}
case ts.SyntaxKind.ImportDeclaration: {
symbol = this.getSymbolByType(node as ts.ImportDeclaration);
break;
}
case ts.SyntaxKind.VariableDeclaration: {
symbol = this.getSymbolByType(node as ts.VariableDeclaration);
break;
}
case ts.SyntaxKind.VariableStatement: {
symbol = this.getSymbolByType(node as ts.VariableStatement);
break;
}
case ts.SyntaxKind.ExportAssignment: {
symbol = this.getSymbolByType(node as ts.ExportAssignment);
break;
}
case ts.SyntaxKind.EndOfFileToken: {
symbol = this.getSymbolByType(node as ts.EndOfFileToken);
break;
}
default: {
// console.log(`Missing parse kind: ${node.kind}`);
break;
}
}
if (node.kind === ts.SyntaxKind.SourceFile) {
const result = this.serializeSymbol(symbol);
Object.assign(this.output, result);
} else {
const result = this.serializeSymbol(symbol);
if (this.getResultCallback) {
this.getResultCallback(result);
this.getResultCallback = void 0;
}
if (result && !this.getAllLocalMembers) {
this.output.members = [...(this.output.members || []), result];
}
}
}
getSymbolByType = <T>(declaration: T | ts.SourceFile) => {
return this.checker.getSymbolAtLocation(declaration["name"]) || this.checker.getSymbolAtLocation(declaration as ts.SourceFile);
}
serializeSymbol = (symbol: ts.Symbol, getAllAst = true): DocEntry => {
if (!symbol || typeof symbol !== "object") {
return;
}
let name = symbol.getName ? symbol.getName() : symbol.name;
let docEntryFilename: string;
let escapedName: string;
let initializerText: string;
if (symbol.valueDeclaration) {
const initializer = symbol.valueDeclaration["initializer"];
if (initializer) {
initializerText = initializer.getFullText();
}
}
let valueDeclarationText: string;
if (symbol.valueDeclaration && symbol.valueDeclaration.getFullText) {
valueDeclarationText = symbol.valueDeclaration.getFullText();
}
let type: string;
try {
type = this.checker.typeToString(this.checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration));
} catch (e) {
// console.error(e);
type = "unknown";
}
if (!type || type === "any") {
type = ts.SymbolFlags[symbol.flags] || "any";
}
const isSourceFile = Boolean(
symbol.flags === ts.SymbolFlags.ValueModule || (
symbol["kind"] && symbol["kind"] === ts.SyntaxKind.SourceFile
)
);
const isNamseSpace = symbol.flags === ts.SymbolFlags.NamespaceModule;
let documentation: string;
try {
documentation = ts.displayPartsToString(symbol.getDocumentationComment(void 0));
} catch (e) {
// console.error(e);
}
let isRequired: boolean;
const parentSymbol: ts.Symbol = (symbol as any).parent;
if (parentSymbol && parentSymbol.flags === ts.SymbolFlags.Interface) {
const valueDeclaration: any = symbol.valueDeclaration;
isRequired = valueDeclaration ? !valueDeclaration.questionToken : false;
}
if (symbol.flags === ts.SymbolFlags.AliasExcludes ||
symbol.flags === 2097152 // ts.SymbolFlags.Alias
) {
const aliasSymbol = this.checker.getAliasedSymbol(symbol);
escapedName = aliasSymbol.escapedName.toString();
if (aliasSymbol["parent"]) {
docEntryFilename = aliasSymbol["parent"].valueDeclaration.fileName;
}
}
if (symbol.flags === ts.SymbolFlags.Property) {
const docEntry: DocEntry = {
name,
isRequired
};
docEntry.type = this.checker.typeToString(this.checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration));
docEntry.documentation = ts.displayPartsToString(symbol.getDocumentationComment(void 0));
docEntry.initializerText = initializerText;
docEntry.valueDeclarationText = valueDeclarationText;
docEntry.documentation = docEntry.documentation ? docEntry.documentation : void 0;
return docEntry;
}
let extendsDocEntry: DocEntry[] = [];
let exportsDocEntry: DocEntry[];
let membersDocEntry: DocEntry[];
if (symbol.flags === ts.SymbolFlags.Class || symbol.flags === ts.SymbolFlags.Interface) {
symbol.declarations.forEach((declaration, index) => {
if (declaration["heritageClauses"]) {
const firstHeritageClause = declaration["heritageClauses"]![0];
firstHeritageClause.types.forEach((type, index) => {
const firstHeritageClauseType = firstHeritageClause.types![index];
const extendsSymbol = this.checker.getSymbolAtLocation(firstHeritageClauseType.expression);
extendsDocEntry.push(this.serializeSymbol(extendsSymbol, false));
});
}
});
}
if ("exports" in symbol && symbol.exports.size) {
exportsDocEntry = [];
const values = symbol.exports.values();
for (let i = 0; i < symbol.exports.size; i++) {
const result: any = values.next();
exportsDocEntry.push(this.serializeSymbol(result.value, isNamseSpace));
}
}
if (isSourceFile || (
getAllAst && (symbol.flags === ts.SymbolFlags.Class || symbol.flags === ts.SymbolFlags.Interface)
)) {
if (isSourceFile && this.getAllLocalMembers) {
membersDocEntry = [];
} else if ("members" in symbol && symbol.members.size) {
membersDocEntry = [];
const values = symbol.members.values();
for (let i = 0; i < symbol.members.size; i++) {
const result = values.next();
const docEntry = this.serializeSymbol(result.value, isSourceFile ? false : (isNamseSpace ? false : true));
membersDocEntry.push(docEntry);
}
}
}
const docEntry: DocEntry = {
name,
escapedName,
exports: isNamseSpace ? membersDocEntry : exportsDocEntry,
members: isNamseSpace ? exportsDocEntry : membersDocEntry,
type,
isRequired,
documentation: documentation ? documentation : void 0,
extends: extendsDocEntry.length > 0 ? extendsDocEntry : void 0,
filename: isSourceFile ? (symbol["fileName"] || symbol.valueDeclaration["resolvedPath"]) : docEntryFilename,
initializerText,
valueDeclarationText
};
if (isSourceFile) {
if (symbol.valueDeclaration) {
const resolvedModules = symbol.valueDeclaration["resolvedModules"];
if (resolvedModules) {
docEntry.resolvedModules = [];
for (const moduleNode of resolvedModules) {
const data = moduleNode[1];
docEntry.resolvedModules.push({
name: moduleNode[0],
resolvedFileName: data ? data.resolvedFileName : void 0,
isExternalLibraryImport: data ? data.isExternalLibraryImport : void 0
});
}
}
}
docEntry.locals = [];
if (this.getAllLocalMembers) {
docEntry.members = [];
}
docEntry.exportMembers = [];
let locals = symbol["locals"];
if (!locals && symbol.valueDeclaration) {
locals = symbol.valueDeclaration["locals"];
}
for (const local of locals) {
const isExportMember = Boolean(local[1]["exportSymbol"]);
const symbol: ts.Symbol = isExportMember ? local[1]["exportSymbol"] : local[1];
if (isExportMember) {
let name = symbol.name;
if (!name && symbol.getName) {
name = symbol.getName();
}
if (name) {
docEntry.exportMembers.push(name);
}
}
docEntry.locals.push(this.serializeSymbol(symbol, false));
if (this.getAllLocalMembers) {
docEntry.members.push(this.serializeSymbol(symbol, this.getAllLocalMembers));
}
}
}
return docEntry;
}
}
export default Parser; | the_stack |
import { decodeHdPrivateKey, deriveHdPath } from '../key/hd-key';
import { TransactionContextCommon } from '../transaction/transaction-types';
import { CompilerDefaults } from './compiler-defaults';
import {
AnyCompilationEnvironment,
CompilationData,
CompilationEnvironment,
CompilerOperation,
CompilerOperationErrorFatal,
CompilerOperationResult,
CompilerOperationSkip,
} from './compiler-types';
import { resolveScriptIdentifier } from './language/resolve';
import { AuthenticationTemplateHdKey } from './template-types';
/**
* Attempt a series of compiler operations, skipping to the next operation if
* the current operation returns a `CompilerOperationSkip` (indicating it failed
* and can be skipped). The `finalOperation` may not be skipped, and must either
* return `CompilerOperationSuccess` or `CompilerOperationError`.
*
* @param operations - an array of skippable operations to try
* @param finalOperation - a final, un-skippable operation
*/
export const attemptCompilerOperations = <
TransactionContext = TransactionContextCommon
>(
operations: CompilerOperation<TransactionContext, true>[],
finalOperation: CompilerOperation<TransactionContext>
): CompilerOperation<TransactionContext> => (identifier, data, environment) => {
// eslint-disable-next-line functional/no-loop-statement
for (const operation of operations) {
const result = operation(identifier, data, environment);
if (result.status !== 'skip') return result;
}
return finalOperation(identifier, data, environment);
};
/**
* Modify a compiler operation to verify that certain properties exist in the
* `CompilationData` and `CompilationEnvironment` before executing the provided
* operation. If the properties don't exist, an error message is returned.
*
* This is useful for eliminating repetitive existence checks.
*
* @param canBeSkipped - if `true`, the accepted operation may return `false`,
* and any missing properties will cause the returned operation to return
* `false` (meaning the operation should be skipped)
* @param dataProperties - an array of the top-level properties required in the
* `CompilationData`
* @param environmentProperties - an array of the top-level properties required
* in the `CompilationEnvironment`
* @param operation - the operation to run if all required properties exist
*/
export const compilerOperationRequires = <
CanBeSkipped extends boolean,
RequiredDataProperties extends keyof CompilationData<unknown>,
RequiredEnvironmentProperties extends keyof CompilationEnvironment,
TransactionContext = TransactionContextCommon
>({
canBeSkipped,
dataProperties,
environmentProperties,
operation,
}: {
canBeSkipped: CanBeSkipped;
dataProperties: RequiredDataProperties[];
environmentProperties: RequiredEnvironmentProperties[];
operation: (
identifier: string,
data: Required<
Pick<CompilationData<TransactionContext>, RequiredDataProperties>
> &
CompilationData<TransactionContext>,
environment: Required<
Pick<
CompilationEnvironment<TransactionContext>,
RequiredEnvironmentProperties
>
> &
CompilationEnvironment<TransactionContext>
) => CompilerOperationResult<CanBeSkipped>;
// eslint-disable-next-line complexity
}): CompilerOperation<TransactionContext, CanBeSkipped> => (
identifier,
data,
environment
) => {
// eslint-disable-next-line functional/no-loop-statement
for (const property of environmentProperties) {
if (environment[property] === undefined)
return (canBeSkipped
? { status: 'skip' }
: {
error: `Cannot resolve "${identifier}" – the "${property}" property was not provided in the compilation environment.`,
status: 'error',
}) as CanBeSkipped extends true
? CompilerOperationSkip
: CompilerOperationErrorFatal;
}
// eslint-disable-next-line functional/no-loop-statement
for (const property of dataProperties) {
if (
(data[property] as typeof data[typeof property] | undefined) === undefined
)
return (canBeSkipped
? { status: 'skip' }
: {
error: `Cannot resolve "${identifier}" – the "${property}" property was not provided in the compilation data.`,
status: 'error',
}) as CanBeSkipped extends true
? CompilerOperationSkip
: CompilerOperationErrorFatal;
}
return operation(
identifier,
data as Required<
Pick<CompilationData<TransactionContext>, RequiredDataProperties>
>,
environment as Required<
Pick<
CompilationEnvironment<TransactionContext>,
RequiredEnvironmentProperties
>
> &
CompilationEnvironment<TransactionContext>
);
};
export const compilerOperationAttemptBytecodeResolution = compilerOperationRequires(
{
canBeSkipped: true,
dataProperties: ['bytecode'],
environmentProperties: [],
operation: (identifier, data) => {
const { bytecode } = data;
if ((bytecode[identifier] as Uint8Array | undefined) !== undefined) {
return { bytecode: bytecode[identifier], status: 'success' };
}
return { status: 'skip' };
},
}
);
// eslint-disable-next-line complexity
export const compilerOperationHelperDeriveHdPrivateNode = ({
addressIndex,
entityId,
entityHdPrivateKey,
environment,
hdKey,
identifier,
}: {
addressIndex: number;
entityId: string;
entityHdPrivateKey: string;
environment: {
ripemd160: NonNullable<CompilationEnvironment['ripemd160']>;
secp256k1: NonNullable<CompilationEnvironment['secp256k1']>;
sha256: NonNullable<CompilationEnvironment['sha256']>;
sha512: NonNullable<CompilationEnvironment['sha512']>;
};
hdKey: AuthenticationTemplateHdKey;
identifier: string;
}): CompilerOperationResult => {
const addressOffset =
hdKey.addressOffset ?? CompilerDefaults.hdKeyAddressOffset;
const privateDerivationPath =
hdKey.privateDerivationPath ?? CompilerDefaults.hdKeyPrivateDerivationPath;
const i = addressIndex + addressOffset;
const validPrivatePathWithIndex = /^m(?:\/(?:[0-9]+|i)'?)*$/u;
if (!validPrivatePathWithIndex.test(privateDerivationPath)) {
return {
error: `Could not generate ${identifier} – the path "${privateDerivationPath}" is not a valid "privateDerivationPath".`,
status: 'error',
};
}
const instancePath = privateDerivationPath.replace('i', i.toString());
const masterContents = decodeHdPrivateKey(environment, entityHdPrivateKey);
if (typeof masterContents === 'string') {
return {
error: `Could not generate ${identifier} – the HD private key provided for ${entityId} could not be decoded: ${masterContents}`,
status: 'error',
};
}
const instanceNode = deriveHdPath(
environment,
masterContents.node,
instancePath
);
if (typeof instanceNode === 'string') {
return {
error: `Could not generate ${identifier} – the path "${instancePath}" could not be derived for entity "${entityId}": ${instanceNode}`,
status: 'error',
};
}
return {
bytecode: instanceNode.privateKey,
status: 'success',
};
};
export const compilerOperationHelperUnknownEntity = (
identifier: string,
variableId: string
) => ({
error: `Identifier "${identifier}" refers to an HdKey, but the "entityOwnership" for "${variableId}" is not available in this compilation environment.`,
status: 'error' as const,
});
export const compilerOperationHelperAddressIndex = (identifier: string) => ({
error: `Identifier "${identifier}" refers to an HdKey, but "hdKeys.addressIndex" was not provided in the compilation data.`,
status: 'error' as const,
});
export const compilerOperationHelperDeriveHdKeyPrivate = ({
environment,
hdKeys,
identifier,
}: {
environment: {
entityOwnership: NonNullable<CompilationEnvironment['entityOwnership']>;
ripemd160: NonNullable<CompilationEnvironment['ripemd160']>;
secp256k1: NonNullable<CompilationEnvironment['secp256k1']>;
sha256: NonNullable<CompilationEnvironment['sha256']>;
sha512: NonNullable<CompilationEnvironment['sha512']>;
variables: NonNullable<CompilationEnvironment['variables']>;
};
hdKeys: NonNullable<CompilationData['hdKeys']>;
identifier: string;
}): CompilerOperationResult => {
const { addressIndex, hdPrivateKeys } = hdKeys;
const [variableId] = identifier.split('.');
const entityId = environment.entityOwnership[variableId] as
| string
| undefined;
if (entityId === undefined) {
return compilerOperationHelperUnknownEntity(identifier, variableId);
}
if (addressIndex === undefined) {
return compilerOperationHelperAddressIndex(identifier);
}
const entityHdPrivateKey =
hdPrivateKeys === undefined ? undefined : hdPrivateKeys[entityId];
if (entityHdPrivateKey === undefined) {
return {
error: `Identifier "${identifier}" refers to an HdKey owned by "${entityId}", but an HD private key for this entity (or an existing signature) was not provided in the compilation data.`,
recoverable: true,
status: 'error',
};
}
/**
* Guaranteed to be an `HdKey` if this method is reached in the compiler.
*/
const hdKey = environment.variables[
variableId
] as AuthenticationTemplateHdKey;
return compilerOperationHelperDeriveHdPrivateNode({
addressIndex,
entityHdPrivateKey,
entityId,
environment,
hdKey,
identifier,
});
};
/**
* Returns `false` if the target script ID doesn't exist in the compilation
* environment (allows for the caller to generate the error message).
*
* If the compilation produced errors, returns a `CompilerOperationErrorFatal`.
*
* If the compilation was successful, returns the compiled bytecode as a
* `Uint8Array`.
*/
export const compilerOperationHelperCompileScript = <TransactionContext>({
targetScriptId,
data,
environment,
}: {
targetScriptId: string;
data: CompilationData<TransactionContext>;
environment: AnyCompilationEnvironment<TransactionContext>;
}) => {
const signingTarget = environment.scripts[targetScriptId] as
| string
| undefined;
const compiledTarget = resolveScriptIdentifier({
data,
environment,
identifier: targetScriptId,
});
if (signingTarget === undefined || compiledTarget === false) {
return false;
}
if (typeof compiledTarget === 'string') {
return {
error: compiledTarget,
status: 'error',
} as CompilerOperationErrorFatal;
}
return compiledTarget.bytecode;
};
/**
* Returns either the properly generated `coveredBytecode` or a
* `CompilerOperationErrorFatal`.
*/
export const compilerOperationHelperGenerateCoveredBytecode = <
TransactionContext
>({
data,
environment,
identifier,
sourceScriptIds,
unlockingScripts,
}: {
data: CompilationData<TransactionContext>;
environment: AnyCompilationEnvironment<TransactionContext>;
identifier: string;
sourceScriptIds: string[];
unlockingScripts: {
[unlockingScriptId: string]: string;
};
}): CompilerOperationErrorFatal | Uint8Array => {
const currentScriptId = sourceScriptIds[sourceScriptIds.length - 1] as
| string
| undefined;
if (currentScriptId === undefined) {
return {
error: `Identifier "${identifier}" requires a signing serialization, but "coveredBytecode" cannot be determined because the compilation environment's "sourceScriptIds" is empty.`,
status: 'error',
};
}
const targetLockingScriptId = unlockingScripts[currentScriptId] as
| string
| undefined;
if (targetLockingScriptId === undefined) {
return {
error: `Identifier "${identifier}" requires a signing serialization, but "coveredBytecode" cannot be determined because "${currentScriptId}" is not present in the compilation environment "unlockingScripts".`,
status: 'error',
};
}
const result = compilerOperationHelperCompileScript({
data,
environment,
targetScriptId: targetLockingScriptId,
});
if (result === false) {
return {
error: `Identifier "${identifier}" requires a signing serialization which covers an unknown locking script, "${targetLockingScriptId}".`,
status: 'error',
};
}
return result;
}; | the_stack |
import * as _ from 'lodash';
import { CacheSnapshot } from '../../../../src/CacheSnapshot';
import { CacheContext } from '../../../../src/context/CacheContext';
import { migrate, read, MigrationMap, QueryResult } from '../../../../src/operations';
import { OptimisticUpdateQueue } from '../../../../src/OptimisticUpdateQueue';
import { createGraphSnapshot, strictConfig, query } from '../../../helpers';
function createNewCacheSnapshot(cacheContext: CacheContext) {
const snapshot = createGraphSnapshot(
{
foo: 123,
bar: 'asdf',
viewer: {
id: 'a',
first: 'Jonh',
last: 'Doe',
__typename: 'Viewer',
},
},
`{ foo bar viewer { id first last __typename } }`,
cacheContext
);
return new CacheSnapshot(snapshot, snapshot, new OptimisticUpdateQueue());
}
// same as cache snapshot created by `createNewCacheShapshot1` plus the
// `user(id: $id)` parameterized field
function createNewCacheSnapshot2(cacheContext: CacheContext) {
const snapshot = createGraphSnapshot(
{
foo: 123,
bar: 'asdf',
viewer: {
id: 'a',
first: 'Jonh',
last: 'Doe',
__typename: 'Viewer',
},
user: {
id: 'xxx',
first: 'YoYo',
last: 'Ma',
__typename: 'User',
},
},
`query dummy($id: ID) {
foo
bar
viewer { id first last __typename }
user(id: $id) { id first last __typename }
}`,
cacheContext,
{ id: 'xxx' }
);
return new CacheSnapshot(snapshot, snapshot, new OptimisticUpdateQueue());
}
// same as cache snapshot created by `createNewCacheShapshot` plus the
// `friends(circle: $circle)` parameterized field
function createNewCacheSnapshot3(cacheContext: CacheContext) {
const snapshot = createGraphSnapshot(
{
foo: 123,
bar: 'asdf',
viewer: {
id: 'a',
first: 'Jonh',
last: 'Doe',
__typename: 'Viewer',
friends: [{
id: 'friend-1',
first: 'Bob',
last: 'Breaker',
__typename: 'Friend',
}, {
id: 'friend-2',
first: 'Susan',
last: 'Fixer',
__typename: 'Friend',
}],
},
},
`query dummy($circle: String) {
foo
bar
viewer {
id
first
last
__typename
friends(circle: $circle) { id first last }
}
}`,
cacheContext,
{ circle: 'elementary' }
);
return new CacheSnapshot(snapshot, snapshot, new OptimisticUpdateQueue());
}
describe(`operations.migrate`, () => {
let cacheContext: CacheContext;
beforeAll(() => {
cacheContext = new CacheContext({ ...strictConfig, freeze: false });
});
it(`can add parameterized fields to root`, () => {
const migrationMap: MigrationMap = {
_parameterized: {
Query: [{
path: ['user'],
args: { id: 'xxx' },
defaultReturn: null,
}],
},
};
const migrated = migrate(createNewCacheSnapshot(cacheContext), migrationMap);
const { result, complete } = read(cacheContext, query(`
query dummy($id: ID) {
foo
bar
user(id: $id)
}
`, { id: 'xxx' }), migrated.baseline);
jestExpect(complete).toBeTruthy();
jestExpect(_.get(result, 'user')).toBeNull();
});
it(`doesn't wipe out compatable parameterized fields at root`, () => {
const migrationMap: MigrationMap = {
_parameterized: {
Query: [{
path: ['user'],
args: { id: 'xxx' },
defaultReturn: null,
}],
},
};
// start with a snapshot with user(id: $id) already in place at root
const snapshot = createNewCacheSnapshot2(cacheContext);
const migrated = migrate(snapshot, migrationMap);
// migration should yield no change to the user(id: $id) parameterized field
const { result, complete } = read(cacheContext, query(`
query dummy($id: ID) {
foo
bar
user(id: $id) {
id
first
last
}
}
`, { id: 'xxx' }), migrated.baseline);
jestExpect(complete).toBeTruthy();
jestExpect(_.get(result, 'user')).toEqual({
id: 'xxx',
first: 'YoYo',
last: 'Ma',
__typename: 'User',
});
});
it(`can modify the signature of existing parameterized fields at root`, () => {
const migrationMap: MigrationMap = {
_parameterized: {
['Query']: [{
path: ['user'],
args: { id: 'xxx', extraInfo: true },
defaultReturn: null,
}],
},
};
// start with a snapshot with user(id: $id) already in place at root
const snapshot = createNewCacheSnapshot2(cacheContext);
const migrated = migrate(snapshot, migrationMap);
// read for the old parameterized field should no longer succeed
const { result, complete } = read(cacheContext, query(`
query dummy($id: ID) {
foo
bar
user(id: $id, extraInfo: true)
}
`, { id: 'xxx' }), migrated.baseline);
jestExpect(complete).toBeTruthy();
jestExpect(_.get(result, 'user')).toBe(null);
});
it(`can add parameterized fields to entity`, () => {
const migrationMap: MigrationMap = {
_parameterized: {
['Viewer']: [{
path: ['friends'],
args: { circle: 'elementary' },
defaultReturn: [],
}],
},
};
const migrated = migrate(createNewCacheSnapshot(cacheContext), migrationMap);
const { result, complete } = read(cacheContext, query(`
query dummy($circle: String) {
foo
bar
viewer {
id
friends(circle: $circle) {
id
first
last
}
}
}
`, { circle: 'elementary' }), migrated.baseline);
jestExpect(complete).toBeTruthy();
jestExpect(_.get(result, ['viewer', 'friends'])).toEqual([]);
});
it(`doesn't wipe out compatable parameterized fields on entity`, () => {
const migrationMap: MigrationMap = {
_parameterized: {
Viewer: [{
path: ['friends'],
args: { circle: 'elementary' },
defaultReturn: [],
}],
},
};
// start with a snapshot with user(id: $id) already in place at root
const snapshot = createNewCacheSnapshot3(cacheContext);
const migrated = migrate(snapshot, migrationMap);
// migration should yield no change to the user(id: $id) parameterized field
const { result, complete } = read(cacheContext, query(`
query dummy($circle: String) {
foo
bar
viewer {
id
friends(circle: $circle) {
id
first
last
}
}
}
`, { circle: 'elementary' }), migrated.baseline);
jestExpect(complete).toBeTruthy();
jestExpect(_.get(result, ['viewer', 'friends'])).toEqual([{
id: 'friend-1',
first: 'Bob',
last: 'Breaker',
}, {
id: 'friend-2',
first: 'Susan',
last: 'Fixer',
}]);
});
it(`can modify parameterized fields of entity`, () => {
const migrationMap: MigrationMap = {
_parameterized: {
Viewer: [{
path: ['friends'],
args: { circle: 'elementary', stillFriends: true },
defaultReturn: [],
}],
},
};
const migrated = migrate(createNewCacheSnapshot3(cacheContext), migrationMap);
const { result, complete } = read(cacheContext, query(`
query dummy($circle: String, $stillFriends: Boolean) {
foo
bar
viewer {
id
friends(circle: $circle, stillFriends: $stillFriends) {
id
first
last
}
}
}
`, { circle: 'elementary', stillFriends: true }), migrated.baseline);
jestExpect(complete).toBeTruthy();
jestExpect(_.get(result, ['viewer', 'friends'])).toEqual([]);
});
it(`can copy from path`, () => {
const copyFrom = { path: ['friends'], args: { circle: 'elementary' } };
const { result, complete } = copyFromPath(cacheContext, copyFrom);
jestExpect(complete).toBeTruthy();
jestExpect(_.get(result, ['viewer', 'friends'])).toEqual([{
id: 'friend-1',
first: 'Bob',
last: 'Breaker',
}, {
id: 'friend-2',
first: 'Susan',
last: 'Fixer',
}]);
});
it(`defaults to defaultReturn if can't copy from path`, () => {
const copyFrom = { path: ['friends'], args: { circle: 'foo' } };
const { result, complete } = copyFromPath(cacheContext, copyFrom);
jestExpect(complete).toBeTruthy();
jestExpect(_.get(result, ['viewer', 'friends'])).toEqual([]);
});
it(`defaults to defaultReturn if copyFrom is undefined`, () => {
const copyFrom = undefined;
const { result, complete } = copyFromPath(cacheContext, copyFrom);
jestExpect(complete).toBeTruthy();
jestExpect(_.get(result, ['viewer', 'friends'])).toEqual([]);
});
it(`defaults to defaultReturn if copyFrom.args is undefined`, () => {
const copyFrom = { path: ['friends'] };
const { result, complete } = copyFromPath(cacheContext, copyFrom);
jestExpect(complete).toBeTruthy();
jestExpect(_.get(result, ['viewer', 'friends'])).toEqual([]);
});
it(`can complete when parameterized entity is undefined`, () => {
const migrationMap: MigrationMap = {
_parameterized: {
Viewer: [{
path: ['friends'],
args: { circle: 'elementary' },
defaultReturn: null,
copyFrom: { path: ['friends'], args: { circle: 'elementary', stillFriends: true } },
}],
},
};
const snapshot = createNewCacheSnapshot2(cacheContext);
const migrated = migrate(snapshot, migrationMap);
const { complete, result } = read(
cacheContext,
query(parameterizedQuery, { circle: 'elementary', stillFriends: true }),
migrated.baseline
);
jestExpect(complete).toBeTruthy();
jestExpect(_.get(result, ['viewer', 'friends'])).toEqual(null);
});
});
const parameterizedQuery = `
query dummy($circle: String, $stillFriends: Boolean) {
foo
bar
viewer {
id
friends(circle: $circle, stillFriends: $stillFriends) {
id
first
last
}
}
}
`;
function copyFromPath(cacheContext: CacheContext, copyFrom?: any): QueryResult {
const migrationMap: MigrationMap = {
_parameterized: {
Viewer: [{
path: ['friends'],
args: { circle: 'elementary', stillFriends: true },
defaultReturn: [],
copyFrom,
}],
},
};
const snapshot = createNewCacheSnapshot3(cacheContext);
const migrated = migrate(snapshot, migrationMap);
return read(
cacheContext,
query(parameterizedQuery, { circle: 'elementary', stillFriends: true }),
migrated.baseline,
);
} | the_stack |
import { Component, ViewChild, OnInit, OnDestroy } from '@angular/core';
import { LoggerService } from '../../../../shared/services/logger.service';
import { ErrorHandlingService } from '../../../../shared/services/error-handling.service';
import { AdminService } from '../../../services/all-admin.service';
import { environment } from './../../../../../environments/environment';
import { NgForm } from '@angular/forms';
import { Subscription } from 'rxjs/Subscription';
import { UtilsService } from '../../../../shared/services/utils.service';
import { WorkflowService } from '../../../../core/services/workflow.service';
import { RouterUtilityService } from '../../../../shared/services/router-utility.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-admin-create-edit-policy',
templateUrl: './create-edit-policy.component.html',
styleUrls: ['./create-edit-policy.component.css'],
providers: [
LoggerService,
ErrorHandlingService,
AdminService
]
})
export class CreateEditPolicyComponent implements OnInit, OnDestroy {
@ViewChild('policyForm') policyForm: NgForm;
policyId: any;
isPolicyIdValid: any = -1;
policyUrl: any;
policyVersion: String;
policyName: any;
policyDesc: any;
policyResolution: any;
policyDetails: any;
loadingStatus: any;
pageTitle: String = 'Policies';
issueListingdata: any;
selectedAssetGroup: String;
breadcrumbArray: any = ['Admin'];
breadcrumbLinks: any = ['asset-dashboard'];
breadcrumbPresent: any;
outerArr: any = [];
filters: any = [];
successTitle: String = '';
failedTitle: String = '';
successSubTitle: String = '';
isPolicyCreationFailed: boolean = false;
isPolicyCreationSuccess: boolean = false;
ruleContentLoader: boolean = true;
policyLoader: boolean = false;
invocationId: String = '';
paginatorSize: number = 25;
isLastPage: boolean;
isFirstPage: boolean;
totalPages: number;
pageNumber: number = 0;
showLoader: boolean = true;
errorMessage: any;
hideContent: boolean = false;
filterText: any = {};
errorValue: number = 0;
urlID: String = '';
isCreate: boolean = true;
FullQueryParams: any;
queryParamsWithoutFilter: any;
urlToRedirect: any = '';
mandatory: any;
public labels: any;
private previousUrl: any = '';
private pageLevel = 0;
public backButtonRequired;
private routeSubscription: Subscription;
private getKeywords: Subscription;
private previousUrlSubscription: Subscription;
private downloadSubscription: Subscription;
constructor(
private router: Router,
private utils: UtilsService,
private logger: LoggerService,
private errorHandling: ErrorHandlingService,
private workflowService: WorkflowService,
private routerUtilityService: RouterUtilityService,
private adminService: AdminService
) {
this.routerParam();
this.updateComponent();
}
ngOnInit() {
this.urlToRedirect = this.router.routerState.snapshot.url;
this.breadcrumbPresent = 'Create Policy';
this.backButtonRequired = this.workflowService.checkIfFlowExistsCurrently(
this.pageLevel
);
}
nextPage() {
try {
if (!this.isLastPage) {
this.pageNumber++;
this.showLoader = true;
}
} catch (error) {
this.errorMessage = this.errorHandling.handleJavascriptError(error);
this.logger.log('error', error);
}
}
prevPage() {
try {
if (!this.isFirstPage) {
this.pageNumber--;
this.showLoader = true;
}
} catch (error) {
this.errorMessage = this.errorHandling.handleJavascriptError(error);
this.logger.log('error', error);
}
}
allpolicyId: any = [];
isPolicyIdAvailable(policyIdValidKeyword) {
if (policyIdValidKeyword.trim().length == 0) {
this.isPolicyIdValid = -1;
} else {
policyIdValidKeyword = 'PacMan_'+policyIdValidKeyword+'_'+this.policyVersion;
let isKeywordExits = this.allpolicyId.findIndex(item => policyIdValidKeyword.trim().toLowerCase() === item.trim().toLowerCase());
if (isKeywordExits === -1) {
this.isPolicyIdValid = 1;
} else {
this.isPolicyIdValid = 0;
}
}
}
getAllPolicyIds() {
this.hideContent = true;
this.loadingStatus = 'Existing policies is been loading'
this.isPolicyCreationSuccess = false;
this.isPolicyCreationFailed = false;
this.policyLoader = true;
const url = environment.allPolicyIds.url;
const method = environment.allPolicyIds.method;
this.adminService.executeHttpAction(url, method, {}, {}).subscribe(reponse => {
this.policyLoader = false;
this.hideContent = false;
this.allpolicyId = reponse[0];
},
error => {
this.policyLoader = false;
this.failedTitle = 'Loading Failed !!';
this.isPolicyCreationFailed = true;
})
}
createOrUpdatePolicy(policyForm: NgForm) {
let policyDetails = policyForm.form.value;
let url: String = '';
let method: String = '';
let formData = Object();
if (this.isCreate) {
url = environment.createPolicy.url;
method = environment.createPolicy.method;
formData.policyId = 'PacMan_' + policyDetails.policyName + '_' + this.policyVersion;
this.policyId = formData.policyId;
formData.policyName = policyDetails.policyName;
formData.policyDesc = policyDetails.policyDesc;
formData.resolution = policyDetails.policyResolution;
formData.policyUrl = policyDetails.policyUrl;
formData.policyVersion = this.policyVersion;
formData.status = 'ENABLED';
this.loadingStatus = 'details is been creating'
} else {
url = environment.updatePolicy.url;
method = environment.updatePolicy.method;
formData.policyId = this.policyId
formData.policyDesc = policyDetails.policyDesc;
formData.resolution = policyDetails.policyResolution;
formData.policyUrl = policyDetails.policyUrl;
formData.policyVersion = this.policyVersion;
this.loadingStatus = 'details is been updating'
}
this.isPolicyCreationSuccess = false;
this.isPolicyCreationFailed = false;
this.policyLoader = true;
this.hideContent = true;
this.adminService.executeHttpAction(url, method, formData, {}).subscribe(reponse => {
if(this.isCreate) {
this.successTitle = 'Policy Created';
this.successSubTitle = 'created';
} else {
this.successTitle = 'Policy Updated';
this.successSubTitle = 'updated';
}
this.policyLoader = false;
this.isPolicyCreationSuccess = true;
},
error => {
this.policyLoader = false;
this.isPolicyCreationFailed = true;
if(this.isCreate) {
this.failedTitle = 'Creation Failed !!';
} else {
this.failedTitle = 'Updation Failed !!';
}
});
}
closeErrorMessage() {
this.policyLoader = false;
this.isPolicyCreationFailed = false;
this.hideContent = false;
}
getData() {
//this.getAllPolicyIds();
}
/*
* This function gets the urlparameter and queryObj
*based on that different apis are being hit with different queryparams
*/
routerParam() {
try {
// this.filterText saves the queryparam
let currentQueryParams = this.routerUtilityService.getQueryParametersFromSnapshot(this.router.routerState.snapshot.root);
if (currentQueryParams) {
this.FullQueryParams = currentQueryParams;
this.queryParamsWithoutFilter = JSON.parse(JSON.stringify(this.FullQueryParams));
this.policyId = this.queryParamsWithoutFilter.policyId;
delete this.queryParamsWithoutFilter['filter'];
if (this.policyId) {
this.pageTitle = 'Edit Policy';
this.breadcrumbPresent = 'Edit Policy';
this.isCreate = false;
this.hideContent = true;
this.isPolicyIdValid = 1;
this.getPolicyDetails(this.policyId);
} else {
this.pageTitle = 'Create New Policy';
this.breadcrumbPresent = 'Create Policy';
this.policyVersion = 'version-1';
this.isCreate = true;
this.getAllPolicyIds();
}
/**
* The below code is added to get URLparameter and queryparameter
* when the page loads ,only then this function runs and hits the api with the
* filterText obj processed through processFilterObj function
*/
this.filterText = this.utils.processFilterObj(
this.FullQueryParams
);
this.urlID = this.FullQueryParams.TypeAsset;
//check for mandatory filters.
if (this.FullQueryParams.mandatory) {
this.mandatory = this.FullQueryParams.mandatory;
}
}
} catch (error) {
this.errorMessage = this.errorHandling.handleJavascriptError(error);
this.logger.log('error', error);
}
}
getPolicyDetails(policyId) {
this.policyLoader = true;
let url = environment.getPolicyById.url;
let method = environment.getPolicyById.method;
this.loadingStatus = 'details is been loading'
this.adminService.executeHttpAction(url, method, {}, {policyId: policyId}).subscribe(reponse => {
this.policyLoader = false;
this.policyDetails = reponse[0];
this.policyId = this.policyDetails.policyId;
this.policyUrl = this.policyDetails.policyUrl;
this.policyVersion = this.policyDetails.policyVersion;
this.policyName = this.policyDetails.policyName;
this.policyDesc = this.policyDetails.policyDesc;
this.policyResolution = this.policyDetails.resolution;
this.hideContent = false;
},
error => {
this.policyLoader = false;
});
}
/**
* This function get calls the keyword service before initializing
* the filter array ,so that filter keynames are changed
*/
updateComponent() {
this.outerArr = [];
this.showLoader = true;
this.errorValue = 0;
this.getData();
}
navigateBack() {
try {
this.workflowService.goBackToLastOpenedPageAndUpdateLevel(this.router.routerState.snapshot.root);
} catch (error) {
this.logger.log('error', error);
}
}
ngOnDestroy() {
try {
if (this.routeSubscription) {
this.routeSubscription.unsubscribe();
}
if (this.previousUrlSubscription) {
this.previousUrlSubscription.unsubscribe();
}
} catch (error) {
this.logger.log('error', '--- Error while unsubscribing ---');
}
}
} | the_stack |
import {Checkbox, DropDown, Duration, NotificationType, Ticker} from 'argo-ui';
import * as moment from 'moment';
import * as PropTypes from 'prop-types';
import * as React from 'react';
import {ErrorNotification, Revision, Timestamp} from '../../../shared/components';
import {AppContext} from '../../../shared/context';
import * as models from '../../../shared/models';
import {services} from '../../../shared/services';
import * as utils from '../utils';
require('./application-operation-state.scss');
interface Props {
application: models.Application;
operationState: models.OperationState;
}
const Filter = (props: {filters: string[]; setFilters: (f: string[]) => void; options: string[]; title: string; style?: React.CSSProperties}) => {
const {filters, setFilters, options, title, style} = props;
return (
<DropDown
isMenu={true}
anchor={() => (
<div title='Filter' style={style}>
<button className='argo-button argo-button--base'>
{title} <i className='argo-icon-filter' aria-hidden='true' />
</button>
</div>
)}>
{options.map(f => (
<div key={f} style={{minWidth: '150px', lineHeight: '2em', padding: '5px'}}>
<Checkbox
checked={filters.includes(f)}
onChange={checked => {
const selectedValues = [...filters];
const idx = selectedValues.indexOf(f);
if (idx > -1 && !checked) {
selectedValues.splice(idx, 1);
} else {
selectedValues.push(f);
}
setFilters(selectedValues);
}}
/>
<label htmlFor={`filter__${f}`}>{f}</label>
</div>
))}
</DropDown>
);
};
export const ApplicationOperationState: React.StatelessComponent<Props> = ({application, operationState}, ctx: AppContext) => {
const operationAttributes = [
{title: 'OPERATION', value: utils.getOperationType(application)},
{title: 'PHASE', value: operationState.phase},
...(operationState.message ? [{title: 'MESSAGE', value: operationState.message}] : []),
{title: 'STARTED AT', value: <Timestamp date={operationState.startedAt} />},
{
title: 'DURATION',
value: (
<Ticker>
{time => <Duration durationMs={((operationState.finishedAt && moment(operationState.finishedAt)) || time).diff(moment(operationState.startedAt)) / 1000} />}
</Ticker>
)
}
];
if (operationState.finishedAt && operationState.phase !== 'Running') {
operationAttributes.push({title: 'FINISHED AT', value: <Timestamp date={operationState.finishedAt} />});
} else if (operationState.phase !== 'Terminating') {
operationAttributes.push({
title: '',
value: (
<button
className='argo-button argo-button--base'
onClick={async () => {
const confirmed = await ctx.apis.popup.confirm('Terminate operation', 'Are you sure you want to terminate operation?');
if (confirmed) {
try {
await services.applications.terminateOperation(application.metadata.name);
} catch (e) {
ctx.apis.notifications.show({
content: <ErrorNotification title='Unable to terminate operation' e={e} />,
type: NotificationType.Error
});
}
}
}}>
Terminate
</button>
)
});
}
if (operationState.syncResult) {
operationAttributes.push({title: 'REVISION', value: <Revision repoUrl={application.spec.source.repoURL} revision={operationState.syncResult.revision} />});
}
let initiator = '';
if (operationState.operation.initiatedBy) {
if (operationState.operation.initiatedBy.automated) {
initiator = 'automated sync policy';
} else {
initiator = operationState.operation.initiatedBy.username;
}
}
operationAttributes.push({title: 'INITIATED BY', value: initiator || 'Unknown'});
const resultAttributes: {title: string; value: string}[] = [];
const syncResult = operationState.syncResult;
if (operationState.finishedAt) {
if (syncResult) {
(syncResult.resources || []).forEach(res => {
resultAttributes.push({
title: `${res.namespace}/${res.kind}:${res.name}`,
value: res.message
});
});
}
}
const [filters, setFilters] = React.useState([]);
const Statuses = Object.keys(models.ResultCodes);
const OperationPhases = Object.keys(models.OperationPhases);
// const syncPhases = ['PreSync', 'Sync', 'PostSync', 'SyncFail'];
// const hookPhases = ['Running', 'Terminating', 'Failed', 'Error', 'Succeeded'];
let filtered: models.ResourceResult[] = [];
if (syncResult) {
if (syncResult.resources && syncResult.resources.length > 0) {
filtered = syncResult.resources.filter(r => filters.length === 0 || filters.includes(getStatus(r)));
}
}
return (
<div>
<div className='white-box'>
<div className='white-box__details'>
{operationAttributes.map(attr => (
<div className='row white-box__details-row' key={attr.title}>
<div className='columns small-3'>{attr.title}</div>
<div className='columns small-9'>{attr.value}</div>
</div>
))}
</div>
</div>
{syncResult && syncResult.resources && syncResult.resources.length > 0 && (
<React.Fragment>
<div style={{display: 'flex'}}>
<label style={{display: 'block', marginBottom: '1em'}}>RESULT</label>
<div style={{marginLeft: 'auto'}}>
<Filter options={Statuses} filters={filters} setFilters={setFilters} title='STATUS' style={{marginRight: '5px'}} />
<Filter options={OperationPhases} filters={filters} setFilters={setFilters} title='HOOK' />
</div>
</div>
<div className='argo-table-list'>
<div className='argo-table-list__head'>
<div className='row'>
<div className='columns large-1 show-for-large application-operation-state__icons_container_padding'>KIND</div>
<div className='columns large-2 show-for-large'>NAMESPACE</div>
<div className='columns large-2 small-2'>NAME</div>
<div className='columns large-1 small-2'>STATUS</div>
<div className='columns large-1 show-for-large'>HOOK</div>
<div className='columns large-4 small-8'>MESSAGE</div>
</div>
</div>
{filtered.length > 0 ? (
filtered.map((resource, i) => (
<div className='argo-table-list__row' key={i}>
<div className='row'>
<div className='columns large-1 show-for-large application-operation-state__icons_container_padding'>
<div className='application-operation-state__icons_container'>
{resource.hookType && <i title='Resource lifecycle hook' className='fa fa-anchor' />}
</div>
<span title={getKind(resource)}>{getKind(resource)}</span>
</div>
<div className='columns large-2 show-for-large' title={resource.namespace}>
{resource.namespace}
</div>
<div className='columns large-2 small-2' title={resource.name}>
{resource.name}
</div>
<div className='columns large-1 small-2' title={getStatus(resource)}>
<utils.ResourceResultIcon resource={resource} /> {getStatus(resource)}
</div>
<div className='columns large-1 show-for-large' title={resource.hookType}>
{resource.hookType}
</div>
<div className='columns large-4 small-8' title={resource.message}>
<div className='application-operation-state__message'>{resource.message}</div>
</div>
</div>
</div>
))
) : (
<div style={{textAlign: 'center', marginTop: '2em', fontSize: '20px'}}>No Sync Results match filter</div>
)}
</div>
</React.Fragment>
)}
</div>
);
};
const getKind = (resource: models.ResourceResult): string => {
return (resource.group ? `${resource.group}/${resource.version}` : resource.version) + `/${resource.kind}`;
};
const getStatus = (resource: models.ResourceResult): string => {
return resource.hookType ? resource.hookPhase : resource.status;
};
ApplicationOperationState.contextTypes = {
apis: PropTypes.object
}; | the_stack |
import { ILayoutRestorer, IRouter, JupyterFrontEnd } from "@jupyterlab/application";
import {
IWindowResolver,
Toolbar,
ToolbarButton,
WidgetTracker, /*Clipboard, Dialog, IWindowResolver, showDialog, showErrorMessage*/
} from "@jupyterlab/apputils";
// import { PathExt, URLExt } from "@jupyterlab/coreutils";
import { IDocumentManager /*isValidFileName, renameFile*/ } from "@jupyterlab/docmanager";
// import { DocumentRegistry } from "@jupyterlab/docregistry";
import { Contents, ContentsManager } from "@jupyterlab/services";
import {
closeIcon,
copyIcon,
cutIcon,
pasteIcon,
refreshIcon,
} from "@jupyterlab/ui-components";
// import JSZip from "jszip";
import { DisposableSet, IDisposable } from "@lumino/disposable";
import { PanelLayout, Widget } from "@lumino/widgets";
import { Format, IContentRow, Path, TreeFinderPanelElement } from "tree-finder";
import { JupyterClipboard } from "./clipboard";
import { IFSResource } from "./filesystem";
import { fileTreeIcon } from "./icons";
// import { Uploader } from "./upload";
export class JupyterContents {
constructor(cm: ContentsManager, drive?: string) {
this.cm = cm;
this.drive = drive;
}
async get(path: string) {
path = JupyterContents.toFullPath(path, this.drive);
return JupyterContents.toJupyterContentRow(await this.cm.get(path), this.cm, this.drive);
}
readonly cm: ContentsManager;
readonly drive: string;
}
export namespace JupyterContents {
export interface IJupyterContentRow extends Omit<Contents.IModel, "path" | "content" | "type">, IContentRow {}
export function toFullPath(path: string, drive?: string): string {
return (!drive || path.startsWith(`${drive}:`)) ? path : [drive, path].join(":");
}
export function toLocalPath(path: string): string {
const [first, ...rest] = path.split("/");
return [first.split(":").pop(), ...rest].join("/");
}
export function toJupyterContentRow(row: Contents.IModel, cm: ContentsManager, drive: string): IJupyterContentRow {
const { path, type, ...rest } = row;
const pathWithDrive = toFullPath(path, drive);
const kind = type === "directory" ? "dir" : type;
return {
path: Path.toarray(pathWithDrive),
kind,
...rest,
...(kind === "dir" ? {
getChildren: async () => (await cm.get(pathWithDrive, { content: true })).content.map((c: Contents.IModel) => toJupyterContentRow(c, cm, drive)),
}: {}),
};
}
}
export class TreeFinderTracker extends WidgetTracker<TreeFinderSidebar> {
async add(finder: TreeFinderSidebar) {
this._finders.set(finder.id, finder);
// eslint-disable-next-line @typescript-eslint/unbound-method
finder.disposed.connect(this._onWidgetDisposed, this);
return super.add(finder);
}
remove(finder: TreeFinderSidebar) {
this._finders.delete(finder.id);
// eslint-disable-next-line @typescript-eslint/unbound-method
finder.disposed.disconnect(this._onWidgetDisposed, this);
}
findByDrive(drive: string) {
return this._finders.get(drive);
}
hasByDrive(drive: string) {
return this._finders.has(drive);
}
private _onWidgetDisposed(finder: TreeFinderSidebar) {
this.remove(finder);
}
private _finders = new Map<string, TreeFinderSidebar>();
}
export class TreeFinderWidget extends Widget {
constructor({
app,
rootPath = "",
}: TreeFinderSidebar.IOptions) {
const { commands, serviceManager: { contents } } = app;
const node = document.createElement<JupyterContents.IJupyterContentRow>("tree-finder-panel");
super({ node });
this.addClass("jp-tree-finder");
this.cm = new JupyterContents(contents, rootPath);
rootPath = rootPath === "" ? rootPath : rootPath + ":";
void this.cm.get(rootPath).then(root => this.node.init({
root,
gridOptions: {
columnFormatters: {
last_modified: (x => Format.timeSince(x as any as Date)),
size: (x => Format.bytesToHumanReadable(x)),
},
doWindowResize: true,
showFilter: true,
},
modelOptions: {
columnNames: ["size", "mimetype", "last_modified"],
},
})).then(() => {
this.model.openSub.subscribe(rows => rows.forEach(row => {
if (!row.getChildren) {
void commands.execute("docmanager:open", { path: Path.fromarray(row.path) });
}
}));
});
}
draw() {
this.model.requestDraw();
}
refresh() {
this.model.refreshSub.next();
}
get model() {
return this.node.model;
}
get selection() {
return this.model.selection;
}
get selectionPathstrs() {
return this.model.selection.map(c => Path.fromarray(c.row.path));
}
cm: JupyterContents;
readonly node: TreeFinderPanelElement<JupyterContents.IJupyterContentRow>;
}
export class TreeFinderSidebar extends Widget {
constructor({
app,
rootPath = "",
caption = "TreeFinder",
id = "jupyterlab-tree-finder",
}: TreeFinderSidebar.IOptions) {
super();
this.id = id;
this.title.icon = fileTreeIcon;
this.title.caption = caption;
this.title.closable = true;
this.addClass("jp-tree-finder-sidebar");
// each separate widget gets its own unique commands, with each commandId prefixed with the widget's unique id
// TODO: check on edge cases where two widget's share id (ie when two widgets are both views onto the same ContentsManager on the backend)
this.commandIDs = Object.fromEntries(TreeFinderSidebar.commandNames.map(name => [name, `${this.id}:treefinder:${name}`])) as TreeFinderSidebar.ICommandIDs;
// this.dr = app.docRegistry;
this.toolbar = new Toolbar();
this.toolbar.addClass("jp-tree-finder-toolbar");
// this.toolbar.addClass(id);
this.treefinder = new TreeFinderWidget({ app, rootPath });
this.layout = new PanelLayout();
this.layout.addWidget(this.toolbar);
this.layout.addWidget(this.treefinder);
}
restore() { // restore expansion prior to rebuild
this.treefinder.refresh();
// const array: Array<Promise<any>> = [];
// Object.keys(this.controller).forEach(key => {
// if (this.controller[key].open && (key !== "")) {
// const promise = this.cm.get(this.basepath + key);
// promise.catch(res => {
// // eslint-disable-next-line no-console
// console.log(res);
// });
// array.push(promise);
// }
// });
// Promise.all(array).then(results => {
// for (const r in results) {
// const row_element = this.node.querySelector("[id='" + u_btoa(results[r].path.replace(this.basepath, "")) + "']");
// this.buildTableContents(results[r].content, 1 + results[r].path.split("/").length, row_element);
// }
// }).catch(reasons => {
// // eslint-disable-next-line no-console
// console.log(reasons);
// });
}
// async download(path: string, folder: boolean): Promise<any> {
// if (folder) {
// const zip = new JSZip();
// await this.wrapFolder(zip, path); // folder packing
// // generate and save zip, reset path
// path = PathExt.basename(path);
// writeZipFile(zip, path);
// } else {
// return this.cm.getDownloadUrl(this.basepath + path).then(url => {
// const element = document.createElement("a");
// document.body.appendChild(element);
// element.setAttribute("href", url);
// element.setAttribute("download", "");
// element.click();
// document.body.removeChild(element);
// return void 0;
// });
// }
// }
// async wrapFolder(zip: JSZip, path: string) {
// const base = this.cm.get(this.basepath + path);
// const next = base.then(async res => {
// if (res.type === "directory") {
// const new_folder = zip.folder(res.name);
// for (const c in res.content) {
// await this.wrapFolder(new_folder, res.content[c].path);
// }
// } else {
// zip.file(res.name, res.content);
// }
// });
// await next;
// }
protected onBeforeShow(msg: any): void {
this.treefinder.refresh();
this.treefinder.draw();
}
protected onResize(msg: any): void {
this.treefinder.draw();
}
cm: JupyterContents;
// dr: DocumentRegistry;
toolbar: Toolbar;
treefinder: TreeFinderWidget;
readonly commandIDs: TreeFinderSidebar.ICommandIDs;
readonly layout: PanelLayout;
}
// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace TreeFinderSidebar {
const namespace = "jupyter-fs:TreeFinder";
// define the command ids as a constant tuple
export const commandNames = [
"copy",
"cut",
"delete",
"open",
"paste",
"refresh",
"rename",
] as const;
// use typescript-fu to convert commandIds to an interface
export type ICommandIDs = {[k in typeof commandNames[number]]: string};
export const tracker = new TreeFinderTracker({ namespace });
export const clipboard = new JupyterClipboard(tracker);
export interface IOptions {
app: JupyterFrontEnd;
rootPath?: string;
caption?: string;
id?: string;
}
export interface ISidebarProps extends IOptions {
manager: IDocumentManager;
paths: JupyterFrontEnd.IPaths;
resolver: IWindowResolver;
restorer: ILayoutRestorer;
router: IRouter;
side?: string;
}
export function sidebarFromResource(resource: IFSResource, props: TreeFinderSidebar.ISidebarProps): IDisposable {
return sidebar({
...props,
rootPath: resource.drive,
caption: `${resource.name}\nFile Tree`,
id: [resource.name.split(" ").join(""), resource.drive].join("_"),
});
}
export function sidebar({
app,
manager,
paths,
resolver,
restorer,
router,
rootPath = "",
caption = "TreeFinder",
id = "jupyterlab-tree-finder",
side = "left",
}: TreeFinderSidebar.ISidebarProps): IDisposable {
const selector = `#${id}`;
const widget = new TreeFinderSidebar({ app, rootPath, caption, id });
void tracker.add(widget);
restorer.add(widget, widget.id);
app.shell.add(widget, side);
// const uploader_button = new Uploader({ manager, widget });
// const new_file_button = new ToolbarButton({
// icon: newFolderIcon,
// onClick: () => {
// app.commands.execute((CommandIDs.create_folder + ":" + widget.id), { path: "" });
// },
// tooltip: "New Folder",
// });
const refresh_button = new ToolbarButton({
icon: refreshIcon,
onClick: () => {
void app.commands.execute(widget.commandIDs.refresh);
},
tooltip: "Refresh",
});
// widget.toolbar.addItem("upload", uploader_button);
// widget.toolbar.addItem("new file", new_file_button);
widget.toolbar.addItem("refresh", refresh_button);
// // remove context highlight on context menu exit
// document.ondblclick = () => {
// app.commands.execute((CommandIDs.set_context + ":" + widget.id), { path: "" });
// };
// widget.node.onclick = event => {
// app.commands.execute((CommandIDs.select + ":" + widget.id), { path: "" });
// };
// setInterval(() => {
// app.commands.execute(CommandIDs.refresh);
// }, 10000);
// return a disposable containing all disposables associated
// with this widget, ending with the widget itself
return [
// globally accessible jupyter commands
app.commands.addCommand(widget.commandIDs.copy, {
execute: args => clipboard.model.copySelection(widget.treefinder.model),
icon: copyIcon,
label: "Copy",
}),
app.commands.addCommand(widget.commandIDs.cut, {
execute: args => clipboard.model.cutSelection(widget.treefinder.model),
icon: cutIcon,
label: "Cut",
}),
app.commands.addCommand(widget.commandIDs.delete, {
execute: args => clipboard.model.deleteSelection(widget.treefinder.model),
icon: closeIcon.bindprops({ stylesheet: "menuItem" }),
label: "Delete",
}),
app.commands.addCommand(widget.commandIDs.open, {
execute: args => widget.treefinder.model.openSub.next(widget.treefinder.selection.map(c => c.row)),
label: "Open",
}),
app.commands.addCommand(widget.commandIDs.paste, {
execute: args => clipboard.model.pasteSelection(widget.treefinder.model),
icon: pasteIcon,
label: "Paste",
}),
app.commands.addCommand(widget.commandIDs.refresh, {
execute: args => args["selection"] ? clipboard.refreshSelection(widget.treefinder.model) : clipboard.refresh(widget.treefinder.model),
icon: refreshIcon,
label: args => args["selection"] ? "Refresh Selection" : "Refresh",
}),
// context menu items
app.contextMenu.addItem({
command: widget.commandIDs.open,
selector,
rank: 1,
}),
app.contextMenu.addItem({
command: widget.commandIDs.copy,
selector,
rank: 2,
}),
app.contextMenu.addItem({
command: widget.commandIDs.cut,
selector,
rank: 3,
}),
app.contextMenu.addItem({
command: widget.commandIDs.paste,
selector,
rank: 4,
}),
app.contextMenu.addItem({
command: widget.commandIDs.delete,
selector,
rank: 5,
}),
app.contextMenu.addItem({
args: { selection: true },
command: widget.commandIDs.refresh,
selector,
rank: 10,
}),
// the widget itself is a disposable
widget,
].reduce((set: DisposableSet, d) => {
set.add(d); return set;
}, new DisposableSet());
}
} | the_stack |
import * as _ from 'lodash';
import { WhereFilterOp, FieldPath } from '@google-cloud/firestore';
import type { FirestoreFilter, StrapiAttribute, StrapiOrFilter, StrapiWhereFilter } from '../types';
import type { FirestoreConnectorModel } from '../model';
import { coerceAttrToModel, CoercionError } from '../coerce/coerce-to-model';
import { isEqualHandlingRef } from '../db/reference';
import { StatusError } from './status-error';
import { mapNotNull } from './map-not-null';
import { ManualFilter } from './manual-filter';
const FIRESTORE_MAX_ARRAY_ELEMENTS = 10;
export class EmptyQueryError extends Error {
constructor() {
super('Query parameters will result in an empty response');
}
}
/**
* Convert a Strapi or Firestore query operator to a Firestore operator
* or a manual function.
*/
export function convertWhere(model: FirestoreConnectorModel<any>, { field, operator, value }: StrapiWhereFilter | StrapiOrFilter | FirestoreFilter, mode: 'manualOnly'): ManualFilter | null
export function convertWhere(model: FirestoreConnectorModel<any>, { field, operator, value }: StrapiWhereFilter | StrapiOrFilter | FirestoreFilter, mode: 'nativeOnly'): FirestoreFilter | null
export function convertWhere(model: FirestoreConnectorModel<any>, { field, operator, value }: StrapiWhereFilter | StrapiOrFilter | FirestoreFilter, mode: 'manualOnly' | 'nativeOnly' | 'preferNative'): FirestoreFilter | ManualFilter | null
export function convertWhere(model: FirestoreConnectorModel<any>, { field, operator, value }: StrapiWhereFilter | StrapiOrFilter | FirestoreFilter, mode: 'manualOnly' | 'nativeOnly' | 'preferNative'): FirestoreFilter | ManualFilter | null {
if (operator === 'or') {
const filters: StrapiOrFilter['value'] = _.castArray(value || []);
if (!filters.length) {
throw new EmptyQueryError();
}
// Optimise OR filters where possible with native versions (e.g. 'in' and 'not-in')
const consolidated = consolidateOrFilters(filters);
if (consolidated) {
field = consolidated.field;
operator = consolidated.operator;
value = consolidated.value;
} else {
if (mode === 'nativeOnly') {
throw new StatusError(`OR filters are not supported natively by Firestore. Use the \`allowNonNativeQueries\` option to enable a manual version of this query.`, 400);
}
const orFilters: ManualFilter[] = mapNotNull(filters, andFilters => {
try {
// Combine the AND filters within this OR filter
const convertedAndFilters = andFilters.map(filter => convertWhere(model, filter, 'manualOnly'));
return snap => {
for (const f of convertedAndFilters) {
if (f && !f(snap))
return false;
}
return true;
}
} catch (err) {
// If any of the AND filters within this OR filter are empty
// Then ignore this OR filter (i.e. "or false" has no effect)
if (err instanceof EmptyQueryError) {
return null;
} else {
throw err;
}
}
});
if (!orFilters.length) {
throw new EmptyQueryError();
}
return snap => {
for (const f of orFilters) {
if (f(snap))
return true;
}
return false;
}
}
}
if (!field) {
throw new StatusError(`Query field must not be empty, received: ${JSON.stringify(field)}.`, 400);
}
const attr = model.getAttribute(field);
if (attr && attr.type === 'password') {
throw new StatusError('Not allowed to query password fields', 400);
}
// Determine if the target attribute is an array
// Meta attributes have "repeatable" set to true
const attrIsArray = attr && (attr.collection || attr.repeatable);
let op: WhereFilterOp | ((filterValue: any, fieldValue: any) => boolean);
switch (operator) {
case '==':
case 'eq':
if (Array.isArray(value)) {
// Equals any (OR)
// I.e. "in"
return convertWhere(model, { field, operator: 'in', value }, mode);
} else {
// Equals
op = '==';
break;
}
case '!=':
case 'ne':
if (Array.isArray(value)) {
// Not equals any (OR)
// I.e. "nin"
return convertWhere(model, { field, operator: 'not-in', value }, mode);
} else {
// Not equal
op = '!=';
break;
}
case 'in':
// Implicitly convert 'in' operator to 'array-contains-any' if the target is an array
const actualOp: WhereFilterOp = attrIsArray ? 'array-contains-any' : 'in';
// Included in an array of values
// `value` must be an array, don't coerce as it's likely to be an error if it's not an array
if (!Array.isArray(value) || value.some(v => v === undefined)) {
throw new StatusError(`value for 'in' filter must be an array without undefined values`, 400);
}
if ((value as any[]).length === 0) {
throw new EmptyQueryError();
}
op = ((value as any[]).length > FIRESTORE_MAX_ARRAY_ELEMENTS)
? fsOps[actualOp]
: actualOp;
break;
case 'not-in':
case 'nin':
// Not included in an array of values
// `value` must be an array, don't coerce as it's likely to be an error if it's not an array
if (!Array.isArray(value) || value.some(v => v === undefined)) {
throw new StatusError(`value for 'in' filter must be an array without undefined values`, 400);
}
if (value.length === 0) {
return null;
}
// If the target is an array, then we implicitly use an 'array-contains-none' operation, but this
// is only supported by manual query, not by native Firestore
// TODO: Don't do as above, because this will cause a built-in Strapi query to fail (find users without a role using role_nin)
// so just ignore for now (that query won't function, but at least Strapi doesn't crash)
op = ((value.length > FIRESTORE_MAX_ARRAY_ELEMENTS) /*|| attrIsArray*/)
? fsOps['not-in']
: 'not-in';
break;
case 'contains':
// NO NATIVE SUPPORT
// String includes value case insensitive
// Implicitly handle OR case by casting array
value = _.castArray(value);
op = contains;
break;
case 'ncontains':
// NO NATIVE SUPPORT
// String doesn't contain value case insensitive
// Implicitly handle OR case by casting array
value = _.castArray(value);
op = ncontains;
break;
case 'containss':
// NO NATIVE SUPPORT
// String includes value
// Implicitly handle OR case by casting array
value = _.castArray(value);
op = containss;
break;
case 'ncontainss':
// NO NATIVE SUPPORT
// String doesn't include value
// Implicitly handle OR case by casting array
value = _.castArray(value);
op = ncontainss;
break;
case '<':
case 'lt':
if (Array.isArray(value)) {
// Less than any (OR)
// Just take the maximum
value = _.max(value);
}
// Less than
op = '<';
break;
case '<=':
case 'lte':
if (Array.isArray(value)) {
// Less than any (OR)
// Just take the maximum
value = _.max(value);
}
// Less than or equal
op = '<=';
break;
case '>':
case 'gt':
if (Array.isArray(value)) {
// Greater than any (OR)
// Just take the minimum
value = _.min(value);
}
// Greater than
op = '>';
break;
case '>=':
case 'gte':
if (Array.isArray(value)) {
// Greater than any (OR)
// Just take the minimum
value = _.min(value);
}
// Greater than or equal
op = '>=';
break;
case 'null':
if ((value === true) || _.toLower(value) === 'true') {
// Equal to null
return convertWhere(model, { field, operator: '==', value: null }, mode);
} else {
// Not equal to null
return convertWhere(model, { field, operator: '!=', value: null }, mode);
}
case 'array-contains-any':
// Array includes any value in the given array
// `value` must be an array, don't coerce as it's likely to be an error if it's not an array
if (!Array.isArray(value) || value.some(v => v === undefined)) {
throw new StatusError(`value for 'array-contains-any' filter must be an array without undefined values`, 400);
}
if (value.length === 0) {
throw new EmptyQueryError();
}
op = (value.length > FIRESTORE_MAX_ARRAY_ELEMENTS)
? fsOps['array-contains-any']
: 'array-contains-any';
break;
default:
// If Strapi adds other operators in the future then they
// will be passed directly to Firestore which will most
// likely result in an error
op = operator;
}
if (mode === 'manualOnly') {
if (typeof op !== 'function') {
op = fsOps[op];
if (!op) {
throw new Error(`Unknown operator could not be converted to a function: "${operator}".`);
}
}
}
if ((mode === 'nativeOnly') && (typeof op === 'function')) {
throw new StatusError(`Operator "${operator}" is not supported natively by Firestore. Use the \`allowNonNativeQueries\` option to enable a manual version of this query.`, 400);
}
// Coerce the attribute into the correct type
try {
value = coerceAttribute(attr, value);
} catch (err) {
if (err instanceof CoercionError) {
// If the value cannot be coerced to the appropriate type
// then this filter will reject all entries
throw new EmptyQueryError();
} else {
throw err;
}
}
if (typeof op === 'function') {
const path = field;
const testFn = op;
return snap => {
const fieldValue = model.getAttributeValue(path, snap);
return testFn(fieldValue, value);
};
} else {
if (field === model.primaryKey) {
field = FieldPath.documentId();
}
return {
field,
operator: op,
value,
};
}
}
function coerceAttribute(attr: StrapiAttribute | undefined, value: unknown): unknown {
// Use editMode == 'update' so that strict coercion rules will be applies
// An error will be thrown rather than silently ignoring
if (Array.isArray(value)) {
value = value.map(v => coerceAttrToModel(attr, v, { editMode: 'update' }));
} else {
value = coerceAttrToModel(attr, value, { editMode: 'update' });
}
return value;
}
/**
* Returns the field, operator, and corresponding values if an only if
* the all fields and operators are the same, and the operator is one of `'eq'` or `'ne'`,
* otherwise returns `null`.
*/
function consolidateOrFilters(filters: StrapiOrFilter['value']): StrapiWhereFilter | null {
let opAndField: { field: string, operator: 'eq' | 'ne' } | undefined;
let values: any[] = [];
for (const andFilters of filters) {
if (andFilters.length !== 1) {
return null;
}
const [{ field, operator, value }] = andFilters;
if (opAndField) {
if ((operator === opAndField.operator) && (field == opAndField.field)) {
values = values.concat(value);
} else {
return null;
}
} else if ((operator === 'eq') || (operator === 'ne')) {
opAndField = { field, operator };
values = values.concat(value);
}
return null;
}
if (!opAndField) {
return null;
}
return {
field: opAndField.field,
operator: opAndField.operator === 'eq' ? 'in' : 'nin',
value: values,
};
}
interface TestFn<A = any, B = any> {
(fieldValue: A, filterValue: B): boolean
}
const inFn: TestFn<any, any[]> = (fieldValue, filterValue) => {
if (Array.isArray(fieldValue)) {
// Any element is equal to any value in the filter value array
for (const val of fieldValue) {
for (const v of filterValue) {
if (isEqualHandlingRef(val, v))
return true;
}
}
} else {
// Equal to any value in the filter value array
for (const v of filterValue) {
if (isEqualHandlingRef(fieldValue, v))
return true;
}
}
return false;
};
/**
* Defines a manual equivalent for every native Firestore operator.
*/
const fsOps: { [op in WhereFilterOp]: TestFn } = {
'==': isEqualHandlingRef,
'!=': _.negate(isEqualHandlingRef),
'<': (a, b) => a < b,
'<=': (a, b) => a <= b,
'>': (a, b) => a > b,
'>=': (a, b) => a >= b,
'in': inFn,
'not-in': _.negate(inFn),
'array-contains': (fieldValue, filterValue) => {
if (Array.isArray(fieldValue)) {
for (const v of fieldValue) {
if (isEqualHandlingRef(v, filterValue))
return true;
}
}
return false;
},
'array-contains-any': (fieldValue, filterValue: any[]) => {
if (Array.isArray(fieldValue)) {
for (const val of fieldValue) {
for (const v of filterValue) {
if (isEqualHandlingRef(v, val))
return true;
}
}
}
return false;
}
};
/**
* Any of filterValue's are contained in field value, case insensitive.
*/
const contains: TestFn<any, string[]> = (fieldValue, filterValue) => {
if (typeof fieldValue === 'string') {
const uprFieldValue = fieldValue.toUpperCase();
for (const v of filterValue) {
const uprV = (typeof v === 'string') ? v.toUpperCase() : v;
if (uprFieldValue.includes(uprV))
return true;
}
}
return false;
};
/**
* Any of filterValue's are not contained in field value, case insensitive.
* This is not the same as the negation of `contains` (that would mean:
* *all* of filterValue's are not contains in field value)
*/
const ncontains: TestFn<any, string[]> = (fieldValue, filterValue) => {
if (typeof fieldValue === 'string') {
const uprFieldValue = fieldValue.toUpperCase();
for (const v of filterValue) {
const uprV = (typeof v === 'string') ? v.toUpperCase() : v;
if (!uprFieldValue.includes(uprV))
return true;
}
}
return false;
};
/**
* Any of filterValue's are contained in field value.
*/
const containss: TestFn<any, string[]> = (fieldValue, filterValue) => {
if (typeof fieldValue === 'string') {
for (const v of filterValue) {
if (fieldValue.includes(v))
return true;
}
}
return false;
};
/**
* Any of filterValue's are not contained in field value.
* This is not the same as the negation of `contains` (that would mean:
* *all* of filterValue's are not contains in field value)
*/
const ncontainss: TestFn<any, string[]> = (fieldValue, filterValue) => {
if (typeof fieldValue === 'string') {
for (const v of filterValue) {
if (!fieldValue.includes(v))
return true;
}
}
return false;
}; | the_stack |
declare const enum Block {
//% blockIdentity="blocks.block" enumval=2 block="Grass Block"
//% jres
Grass = 2,
//% blockIdentity="blocks.block" enumval=0 block="Air"
//% jres
Air = 0
}
declare const enum Item {
//% blockIdentity="blocks.item" enumval=256 block="Iron Shovel"
//% jres
IronShovel = 256,
//% blockIdentity="blocks.item" enumval=257 block="Iron Pickaxe"
//% jres
IronPickaxe = 257,
}
declare const enum TravelMethod {
/**
* Walking normally (default if on ground)
*/
//% block=walk enumval=1
Walk = 1,
/**
* Swimming in water
*/
//% block="swim water" enumval=2
SwimWater = 2,
}
declare const enum TestForBlocksMask {
/**
* Every block in the source and destination regions must match exactly.
*/
//% block=all
All,
/**
* Air blocks in the source region will match any block in the destination region.
*/
//% block=masked
Masked
}
declare const enum CloneMask {
//% block=replace
Replace,
//% block=masked
Masked
}
declare const enum CloneMode {
//% block=normal
Normal,
//% block=move
Move
}
declare const enum TargetSelectorKind {
//% block="nearest player (@p)"
NearestPlayer,
//% block="yourself (@s)"
LocalPlayer
}
declare const enum Axis {
//% block="x (East/West)"
X,
//% block="y (Up/Down)"
Y,
//% block="z (South/North)"
Z
}
declare const enum SixDirection {
//% block=forward
Forward,
//% block=back
Back,
//% block=left
Left,
//% block=right
Right,
//% block=up
Up,
//% block=down
Down
}
declare const enum FourDirection {
//% block=forward
Forward,
//% block=back
Back,
//% block=left
Left,
//% block=right
Right
}
declare const enum TurnDirection {
//% block=left
Left,
//% block=right
Right
}
declare const enum CardinalDirection {
//% block="North (negative Z)"
North,
//% block="East (positive X)"
East,
//% block="South (positive Z)"
South,
//% block="up (positive Y)"
Up,
//% block="West (negative X)"
West,
//% block="down (negative Y)"
Down
}
declare const enum CompassDirection {
//% block="West (negative X)"
West = CardinalDirection.West,
//% block="East (positive X)"
East = CardinalDirection.East,
//% block="North (negative Z)"
North = CardinalDirection.North,
//% block="South (positive Z)"
South = CardinalDirection.South
}
declare const enum AnimalMob {
//% block="chicken" enumval=10
//% jres
Chicken,
//% block="cow" enumval=11
//% jres
Cow,
}
declare const enum MonsterMob {
//% block="zombie" enumval=32
//% jres
Zombie,
//% block="creeper" enumval=33
//% jres
Creeper,
}
declare const enum ProjectileMob {
//% block="primed tnt" enumval=65
PrimedTnt,
//% block="xp bottle" enumval=68
XpBottle,
}
declare const enum Effect {
//% block="Speed" enumval=1
//% jres
Speed = 1,
//% block="Slowness" enumval=2
//% jres
Slowness = 2,
}
declare const enum AgentCommand {
//% block=attack
Attack,
//% block=destroy
Destroy
}
declare const enum AgentDetection {
//% block="block"
Block,
//% block="redstone"
Redstone
}
declare const enum AgentInspection {
//% block="block"
Block,
//% block="data"
Data
}
declare const enum BlockColor {
//% block="white" enumval=14540253 blockIdentity=blocks.color
White,
//% block="orange" enumval=14384446 blockIdentity=blocks.color
Orange
}
declare const enum GameMode {
//% block=survival
Survival,
//% block=creative
Creative
}
declare const enum Weather {
//% block=clear
Clear,
//% block=rain
Rain
}
declare const enum DayTime {
//% block=day enumval=1000
Day,
//% block=dawn enumval=0
Dawn
}
declare const enum FillOperation {
//% block=replace
Replace,
//% block=hollow
Hollow,
}
declare const enum GameRule {
//% block=PvP
PvP,
//% block="drowning damage"
DrowningDamage,
}
declare const enum GameDifficulty {
//% block="peaceful"
Peaceful,
//% block="easy"
Easy,
}
declare const enum AgentAssist {
//% block="place on move"
PlaceOnMove,
//% block="place from any slot"
PlaceFromAnySlot,
}
declare const enum TimeQuery {
//% block=gametime
GameTime,
//% block=daytime
DayTime,
}
declare const enum LeverPosition {
//% block="on block bottom pointing West"
BlockBottomEastWhenOff,
//% block="on block East side"
BlockSideFacingEast,
}
declare const enum ComparatorMode {
//% block="compare"
Compare,
//% block="substract"
Substract
}
declare const enum ShapeOperation {
//% block=replace
Replace,
//% block=hollow
Hollow
}
declare const enum ChatArgument {
number,
number2,
string,
string2,
position,
position2,
selector,
selector2
}
declare const enum ColoredBlock {
//% blockIdentity="blocks.block" enumval=35 block="wool"
//% jres
Wool = 35,
//% blockIdentity="blocks.block" enumval=236 block="concrete"
Concrete = 236
}
// Auto-generated from simulator. Do not edit.
declare namespace agent {
/**
* Requests the agent to move in the specified direction
* @param direction the direction in which the agent will move, eg: SixDirection.Forward
* @param blocks how far the agent should move, in blocks, eg: 1
*/
//% help=agent/move
//% promise
//% weight=370
//% blockId=minecraftAgentMove block="agent move %direction|by %blocks"
//% topblock topblockWeight=63
//% shim=agent::moveAsync promise
function move(direction: SixDirection, blocks: number): void;
/**
* Turns the agent in the specified direction
* @param direction the turn direction, eg: TurnDirection.Left
*/
//% help=agent/turn
//% promise
//% weight=360
//% blockId=minecraftAgentTurn block="agent turn %direction"
//% topblock topblockWeight=60
//% shim=agent::turnAsync promise
function turn(direction: TurnDirection): void;
/**
* Returns the agent's position in world coordinates
*/
//% help=agent/get-position
//% promise
//% weight=350
//% blockId=minecraftAgentGetPosition block="agent position"
//% shim=agent::getPositionAsync promise
function getPosition(): Position;
/**
* Returns the agent's orientation, in degrees
*/
//% help=agent/get-orientation
//% promise
//% weight=340
//% blockId=minecraftAgentGetOrientation block="agent orientation"
//% shim=agent::getOrientationAsync promise
function getOrientation(): number;
/**
* Places an item or block in the world from the agent's currently selected inventory slot
* @param direction the direction in which to place the item, eg: SixDirection.Back
*/
//% help=agent/place
//% promise
//% group="Actions" weight=270
//% blockId=minecraftAgentPlace block="agent place %direction"
//% topblock topblockWeight=55
//% shim=agent::placeAsync promise
function place(direction: SixDirection): void;
/**
* Detects if there is a block next to the agent in the specified direction
* @param kind what the agent should attempt to detect
* @param direction the direction in which to perform the detection, eg: SixDirection.Forward
*/
//% help=agent/detect
//% promise
//% weight=320
//% blockId=minecraftAgentDetect block="agent detect %kind|%direction"
//% shim=agent::detectAsync promise
function detect(kind: AgentDetection, direction: SixDirection): boolean;
/**
* Commands the agent to destroy a block in the given direction
* @param direction the direction in which the agent will destroy a block, eg: SixDirection.Forward
*/
//% help=agent/destroy
//% promise
//% group="Actions" weight=260
//% blockId=minecraftAgentCommandDestroy block="agent destroy|%direction"
//% shim=agent::destroyAsync promise
function destroy(direction: SixDirection): void;
/**
* Commands the agent to till soil in the given direction
* @param direction the direction in which to till the soil, eg: SixDirection.Forward
*/
//% help=agent/till
//% promise
//% group="Actions" weight=250
//% blockId=minecraftAgentCommandTill block="agent till|%direction"
//% shim=agent::tillAsync promise
function till(direction: SixDirection): void;
/**
* Commands the agent to attack in the given direction
* @param direction the direction in which to attack, eg: SixDirection.Forward
*/
//% help=agent/attack
//% promise
//% group="Actions" weight=240
//% blockId=minecraftAgentCommandAttack block="agent attack|%direction"
//% shim=agent::attackAsync promise
function attack(direction: SixDirection): void;
/**
* Commands the agent to drop its entire inventory in the given direction
* @param direction the direction in which to drop items, eg: SixDirection.Forward
*/
//% help=agent/drop-all
//% promise
//% group="Inventory" weight=160
//% blockId=minecraftAgentCommandDropAll block="agent drop all|%direction"
//% shim=agent::dropAllAsync promise
function dropAll(direction: SixDirection): void;
/**
* Sets the agent's active inventory slot
* @param slot the slot index between 1 and 27, eg: 1
*/
//% help=agent/set-slot
//% group="Inventory" weight=170
//% blockId=minecraftAgentSetSlot block="agent set active slot %slot"
//% slot.min=1 slot.max=27
//% shim=agent::setSlot
function setSlot(slot: number): void;
/**
* Puts the specified block or item in the agent's inventory
* @param blockOrItem the block or item to give
* @param count the amount to give, eg: 1
* @param slot the slot index between 1 and 27, eg: 1
*/
//% help=agent/set-item
//% promise
//% group="Inventory" weight=165
//% blockId=minecraftAgentSetItem block="agent set block or item $blockOrItem|count $count|in slot $slot"
//% blockOrItem.shadow=minecraftBlockField
//% slot.min=1 slot.max=27
//% count.min=1 count.max=64
//% shim=agent::setItemAsync promise
function setItem(blockOrItem: number, count: number, slot: number): void;
/**
* Controls which assists are enabled for the agent
* @param assist the super power of the agent!
* @param on whether the assist is enabled or not
*/
//% help=agent/set-assist
//% weight=310 blockGap=30
//% blockId=minecraftAgentChangeAssist block="agent %assist|%on"
//% shim=agent::setAssist
function setAssist(assist: AgentAssist, on: boolean): void;
/**
* Commands the agent to Collect a block or item of the specified type
* @param block the type of the block or item to collect
*/
//% help=agent/collect
//% promise
//% group="Actions" weight=220
//% blockId=minecraftAgentCollect block="agent collect %block=minecraftItem"
//% block.shadow=minecraftItem
//% shim=agent::collectAsync promise
function collect(block: number): void;
/**
* Commands the agent to collect all nearby blocks and items
*/
//% help=agent/collect-all
//% promise
//% group="Actions" weight=230
//% blockId=minecraftAgentCollectAll block="agent collect all"
//% shim=agent::collectAllAsync promise
function collectAll(): void;
/**
* Inspects a block in the specified direction and returns the block ID or data
* @param kind the desired result type for the detection: block id or data
* @param direction the direction in which to inspect, eg: SixDirection.Forward
*/
//% help=agent/inspect
//% promise
//% group="Actions" weight=210 blockGap=30
//% blockId=minecraftAgentInspect block="agent inspect %kind|%direction"
//% shim=agent::inspectAsync promise
function inspect(kind: AgentInspection, direction: SixDirection): number;
/**
* Transfers items from an inventory slot to another slot
* @param quantity the quantity of items to transfer, eg: 1
* @param sourceSlot the source slot index, from 1 to 27, eg: 1
* @param destinationSlot the inventory slot in which to drop the items, from 1 to 27, eg:2
*/
//% help=agent/transfer
//% promise
//% group="Inventory" weight=140 blockGap=30
//% blockId=minecraftAgentTransfer block="agent transfer|amount %quantity|from slot %srcSlot|to slot %destinationSlot"
//% inlineInputMode="inline"
//% quantity.min=1 quantity.max=64 sourceSlot.min=1 sourceSlot.max=27 destinationSlot.min=1 destinationSlot.max=27
//% shim=agent::transferAsync promise
function transfer(quantity: number, sourceSlot: number, destinationSlot: number): void;
/**
* Drops an item from the inventory
* @param slot the slot from which the item will be dropped, from 1 to 27, eg: 1
* @param direction the direction in which to drop the item, eg: SixDirection.Back
* @param quantity the quantity of items to drop, eg: 1
*/
//% help=agent/drop
//% promise
//% group="Inventory" weight=150
//% blockId=minecraftAgentDrop block="agent drop %direction|from slot %slot|amount %amount"
//% inlineInputMode="inline"
//% quantity.min=1 quantity.max=64 slot.min=1 slot.max=27
//% shim=agent::dropAsync promise
function drop(direction: SixDirection, slot: number, quantity: number): void;
/**
* Gets the number of items in the specified slot
* @param slot the slot index for which to count items, from 1 to 27, eg: 1
*/
//% help=agent/get-item-count
//% promise
//% group="Inventory" weight=130
//% blockId=minecraftAgentGetItemCount block="agent get item count from slot %slot"
//% slot.min=1 slot.max=27
//% shim=agent::getItemCountAsync promise
function getItemCount(slot: number): number;
/**
* Gets the remaining space in the specified slot
* @param slot the slot index for which to count the remaining space, from 1 to 27, eg: 1
*/
//% help=agent/get-item-space
//% promise
//% group="Inventory" weight=110
//% blockId=minecraftAgentGetItemSpace block="agent get remaining space in slot %slot"
//% slot.min=1 slot.max=27
//% shim=agent::getItemSpaceAsync promise
function getItemSpace(slot: number): number;
/**
* Gets the ID of the item in the specified inventory slot of the agent
* @param slot the slot index for which to return the item info, from 1 to 27, eg: 1
*/
//% help=agent/get-item-detail
//% promise
//% group="Inventory" weight=120
//% blockId=minecraftAgentGetItemDetail block="agent get item id from slot %slot"
//% slot.min=1 slot.max=27
//% shim=agent::getItemDetailAsync promise
function getItemDetail(slot: number): number;
/**
* Teleports the agent to the player
*/
//% help=agent/teleport-to-player
//% promise
//% weight=380
//% blockId=minecraftAgentTeleport block="agent teleport to player"
//% topblock topblockWeight=65
//% shim=agent::teleportToPlayerAsync promise
function teleportToPlayer(): void;
/**
* Teleports the agent to the specified coordinates facing the specified orientation
* @param pos the position to teleport the agent to
* @param dir the compass direction the agent should face after teleporting
*/
//% help=agent/teleport
//% promise
//% weight=330
//% blockId=minecraftAgentTeleportPos block="agent teleport to $pos=minecraftCreatePosition|facing $dir"
//% shim=agent::teleportAsync promise
function teleport(pos: Position, dir: CompassDirection): void;
}
declare namespace blocks {
/**
* Places a block in the world
* @param block the block to place
* @param pos the position at which to place the block
*/
//% help=blocks/place
//% promise
//% weight=360
//% blockId=minecraftPlace block="place %block=minecraftBlock|at %pos=minecraftCreatePosition"
//% block.shadow=minecraftBlockField
//% topblock topblockWeight=85
//% shim=blocks::placeAsync promise
function place(block: number, pos: Position): void;
/**
* Fills a volume between two positions
* @param block the block to fill the volume with
* @param from the first corner of the cubic region
* @param to the opposite corner of the cubic region
* @param operator= handling for existing blocks in the specified region
*/
//% help=blocks/fill
//% promise
//% weight=250
//% blockId=minecraftFill block="fill with %block=minecraftBlock|from %from=minecraftCreatePosition|to %to=minecraftCreatePosition|%operator" blockExternalInputs=1
//% block.shadow=minecraftBlockField
//% shim=blocks::fillAsync promise
function fill(block: number, from: Position, to: Position, operator?: FillOperation): void;
/**
* Runs code when a certain type of block is placed
* @param block the type of block that should trigger this code when placed
*/
//% help=blocks/on-block-placed
//% promise
//% weight=350
//% blockId=minecraftOnBlockPlaced block="on %block=minecraftBlock|placed"
//% block.shadow=minecraftBlockField
//% shim=blocks::onBlockPlacedAsync promise
function onBlockPlaced(block: number, handler: () => void): void;
/**
* Runs code when a certain type of block is mined or broken
* @param block the type of block that should trigger this code when broken
*/
//% help=blocks/on-block-broken
//% promise
//% weight=340
//% blockId=minecraftOnBlockBroken block="on %block=minecraftBlock|broken"
//% block.shadow=minecraftBlockField
//% shim=blocks::onBlockBrokenAsync promise
function onBlockBroken(block: number, handler: () => void): void;
/**
* Replaces all the blocks of a certain type inside the specified region with a new block type
* @param newblock the new block type that will replace existing blocks
* @param oldblock the block type that will be replaced by the new block type
* @param from the first corner of the cubic region
* @param to the opposite corner of the cubic region
*/
//% help=blocks/replace
//% promise
//% weight=130
//% blockId=minecraftReplace block="replace with %newblock=minecraftBlock|when block is %oldblock=minecraftBlock|from %from=minecraftCreatePosition|to %to=minecraftCreatePosition" blockExternalInputs=1
//% newblock.shadow=minecraftBlockField
//% oldblock.shadow=minecraftBlockField
//% shim=blocks::replaceAsync promise
function replace(newblock: number, oldblock: number, from: Position, to: Position): void;
/**
* Clones a cubic region into a different location
* @param begin the first corner of the cubic region
* @param end the opposite corner of the cubic region
* @param destination the first corner of the destination region
* @param mask how to handle air blocks
* @param mode how to handle the cloned region
*/
//% help=blocks/clone
//% promise
//% weight=120
//% blockId=minecraftClone block="clone from %begin=minecraftCreatePosition|to %end=minecraftCreatePosition|into %destination=minecraftCreatePosition|mask %mask|mode %mode" blockExternalInputs=1
//% shim=blocks::cloneAsync promise
function clone(begin: Position, end: Position, destination: Position, mask: CloneMask, mode: CloneMode): void;
/**
* Clones a cubic region into a different location, if the blocks in the region match a certain block type
* @param begin the first corner of the cubic region
* @param end the opposite corner of the cubic region
* @param destination the first corner of the destination region
* @param block the block type to look for when cloning
* @param mode how to handle the cloned region
*/
//% help=blocks/clone-filtered
//% promise
//% weight=110
//% blockId=minecraftCloneFiltered block="clone from %begin=minecraftCreatePosition|to %end=minecraftCreatePosition|into %destination=minecraftCreatePosition|filtered by %block=minecraftBlock|mode %mode"
//% block.shadow=minecraftBlockField
//% blockExternalInputs=1
//% shim=blocks::cloneFilteredAsync promise
function cloneFiltered(begin: Position, end: Position, destination: Position, block: number, mode: CloneMode): void;
/**
* Tests whether the block at the specified coordinate is of a certain type
* @param block the type of the block to test for
* @param pos the coordinates where the block should be
*/
//% help=blocks/test-for-block
//% promise
//% weight=310 blockGap=60
//% blockId=minecraftTestForBlock block="test for %block=minecraftBlock|at %pos=minecraftCreatePosition"
//% block.shadow=minecraftBlockField
//% shim=blocks::testForBlockAsync promise
function testForBlock(block: number, pos: Position): boolean;
/**
* Tests whether the blocks in two regions match.
*/
//% promise
//% shim=blocks::testForBlocksAsync promise
function testForBlocks(begin: Position, end: Position, destination: Position, mask?: TestForBlocksMask): boolean;
/**
* Represents a block from the game
* @param block the block
*/
//% help=blocks/block
//% blockGap=8
//% weight=330
//% blockId=minecraftBlock block="%block"
//% block.fieldEditor="gridpicker"
//% block.fieldOptions.width=340 block.fieldOptions.columns=8 block.fieldOptions.tooltips=true
//% block.fieldOptions.tooltipsXOffset="20" block.fieldOptions.tooltipsYOffset="-20"
//% block.fieldOptions.maxRows="8"
//% block.fieldOptions.hasSearchBar=true
//% block.fieldOptions.hideRect=true
//% shim=blocks::block
function block(block: Block): number;
/**
* Represents an item from the game
* @param item the item
*/
//% help=blocks/item
//% weight=320
//% blockId=minecraftItem block="item %item"
//% item.fieldEditor="gridpicker"
//% item.fieldOptions.width=340 item.fieldOptions.columns=8 item.fieldOptions.tooltips=true
//% item.fieldOptions.tooltipsXOffset="20" item.fieldOptions.tooltipsYOffset="-20"
//% item.fieldOptions.maxRows="8"
//% item.fieldOptions.hasSearchBar=true
//% item.fieldOptions.hideRect=true
//% shim=blocks::item
function item(item: Item): number;
/**
* Represents a block or item from the game with a data value
* @param b the block or item
* @param data the data value for the block or item
*/
//% help=blocks/block-with-data
//% weight=230
//% blockId=minecraftBlockData block="%block=minecraftBlock|with data %data"
//% block.shadow=minecraftBlockField
//% shim=blocks::blockWithData
function blockWithData(b: number, data: number): number;
/**
* Represents a block or item from the game by its value ID
* @param id the ID of the block or item from the game
*/
//% help=blocks/block-by-id
//% weight=220
//% blockId=minecraftBlockID block="block by ID %id"
//% shim=blocks::blockById
function blockById(id: number): number;
/**
* Represents a block or item from the game by its code name
* @param name the name of the block, eg: "stone"
*/
//% help=blocks/block-by-name
//% weight=210 blockGap=60
//% blockId=minecraftBlockName block="block by name %name"
//% shim=blocks::blockByName
function blockByName(name: string): number;
/**
* Represents a colored block from the game
* @param type the type of block, either wool or concrete
* @param color the color of the block
*/
//% help=blocks/color-to-block
//% weight=1
//% blockId=minecraftBlocksColorToBlock block="%type|of color %color=minecraftBlocksColor"
//% deprecated=true
//% shim=blocks::colorToBlock
function colorToBlock(type: ColoredBlock, color: number): number;
/**
* Returns the color value of known block colors
* @param color the color
*/
//% help=blocks/color
//% weight=1
//% blockId=minecraftBlocksColor block="%color"
//% deprecated=true
//% shim=blocks::color
function color(color: BlockColor): number;
/**
* Creates a repeater in a particular state
* @param direction the direction which the repeater is facing
* @param delay the delay for the repeater, in game ticks
*/
//% help=blocks/repeater
//% weight=150
//% delay.min=1 delay.max=4
//% blockId=minecraftBlockRepeater block="repeater|facing %direction|delay %ticks"
//% shim=blocks::repeater
function repeater(direction: CompassDirection, delay: number): number;
/**
* Creates a lever in a particular state
* @param position the position state of the lever
*/
//% help=blocks/lever
//% weight=160
//% blockId=minecraftBlockLever block="lever %position"
//% shim=blocks::lever
function lever(position: LeverPosition): number;
/**
* Creates a comparator in a particular state
* @param direction the direction which the comparator is facing
* @param mode the comparison mode of the comparator
*/
//% help=blocks/comparator
//% weight=140
//% blockId=minecraftBlockComparator block="comparator facing %direction|mode %mode"
//% inlineInputMode="external"
//% shim=blocks::comparator
function comparator(direction: CompassDirection, mode: ComparatorMode): number;
}
declare namespace Math {
/**
* Exposes JavaScript's isNaN() function
* @param n
*/
//%
//% shim=Math::isNaN
function isNaN(n: number): boolean;
/**
* Constrains a number to be within a range
* @param value the number to constrain, all data types
* @param low the lower end of the range, all data types
* @param high the upper end of the range, all data types
*/
//%
//% shim=Math::constrain
function constrain(value: number, low: number, high: number): number;
/**
* Re-maps a number from one range to another. That is, a value of ``from low`` would get mapped to ``to low``, a value of ``from high`` to ``to high``, values in-between to values in-between, etc.
* @param value value to map in ranges
* @param fromLow the lower bound of the value's current range
* @param fromHigh the upper bound of the value's current range, eg: 1023
* @param toLow the lower bound of the value's target range
* @param toHigh the upper bound of the value's target range, eg: 4
*/
//%
//% shim=Math::map
function map(value: number, fromLow: number, fromHigh: number, toLow: number, toHigh: number): number;
}
declare namespace gameplay {
/**
* Change the game mode for the selected players
* @param mode the desired game mode, eg: GameMode.Survival
* @param player a selector to determine which players to change the game mode for
*/
//% help=gameplay/set-game-mode
//% promise
//% weight=210 blockGap=60
//% blockId=minecraftGamemode block="change game mode to %mode|for %player=minecraftTarget"
//% blockExternalInputs=1
//% shim=gameplay::setGameModeAsync promise
function setGameMode(mode: GameMode, player: TargetSelector): void;
/**
* Set the current time of day to a preset time or a custom hour, in game ticks
* @param time the desired time of day, eg: DayTime.Day
*/
//% help=gameplay/time-set
//% promise
//% weight=320
//% blockId=minecraftTimeSet block="time set %time=minecraftTime"
//% shim=gameplay::timeSetAsync promise
function timeSet(time: number): void;
/**
* Add ticks to the current time of day
* @param amount the number of ticks to add to the current time of day, eg: 100
*/
//% help=gameplay/time-add
//% promise
//% weight=310 blockGap=60
//% blockId=minecraftTimeAdd block="time add %amount"
//% shim=gameplay::timeAddAsync promise
function timeAdd(amount: number): void;
/**
* Get the current time of day, in game ticks
* @param query the type of time to query
*/
//% help=gameplay/time-query
//% promise
//% weight=130
//% blockId=minecraftTimeQuery block="time query %query"
//% shim=gameplay::timeQueryAsync promise
function timeQuery(query: TimeQuery): number;
/**
* Represents a preset time of the day
* @param time a preset time, eg: DateTime.Day
*/
//% blockId=minecraftTime block="%time" blockHidden=1
//% weight=2
//% shim=gameplay::time
function time(time: DayTime): number;
/**
* Change the current weather.
* @param weather the desired weather, eg: Weather.Clear
*/
//% help=gameplay/set-weather
//% promise
//% weight=340
//% blockId=minecraftWeather block="weather %weather"
//% shim=gameplay::setWeatherAsync promise
function setWeather(weather: Weather): void;
/**
* Starts raining if it isn't, or stops raining if it is.
*/
//% help=gameplay/toggle-downfall
//% promise
//% weight=330
//% blockId=minecraftToggleDownfall block="toggle downfall"
//% shim=gameplay::toggleDownfallAsync promise
function toggleDownfall(): void;
/**
* Give experience points to the selected players
* @param amount the number of experience points to give, eg: 10
* @param target a selector to determine which players to give experience points to
*/
//% help=gameplay/xp
//% promise
//% weight=120
//% blockId=minecraftXp block="xp give %amount|to %target=minecraftTarget"
//% shim=gameplay::xpAsync promise
function xp(amount: number, target: TargetSelector): void;
/**
* Enable or disable a game rule
* @param rule the game rule to change, eg: GameRule.PvP
* @param enabled whether the specified rule is enabled or not
*/
//% help=gameplay/set-game-rule
//% promise
//% weight=110
//% blockId=minecraftGameRule block="change game rule %rule|to %enabled"
//% shim=gameplay::setGameRuleAsync promise
function setGameRule(rule: GameRule, enabled: boolean): void;
/**
* Change whether the world can be altered or not
* @param enabled true if modifying the world is allowed, false if not
*/
//% help=gameplay/immutable-world
//% promise
//% blockId=minecraftImmutableWorld block="immutable world %enabled"
//% deprecated=true weight=1
//% shim=gameplay::immutableWorldAsync promise
function immutableWorld(enabled: boolean): void;
/**
* Changes the game difficulty
* @param difficulty the new difficulty
*/
//% help=gameplay/set-difficulty
//% promise
//% weight=220
//% blockId=setDifficulty block="set difficulty to %difficulty"
//% shim=gameplay::setDifficultyAsync promise
function setDifficulty(difficulty: GameDifficulty): void;
/**
* Shows a title and subtitle to the selected targets
* @param target the players and entities to select
* @param title the large title to display
* @param subTitle the subtitle to display
*/
//% help=gameplay/title
//% promise
//% weight=200
//% blockId=minecraftTitle block="show %target=minecraftTarget|title %title|subtitle %subTitle"
//% shim=gameplay::titleAsync promise
function title(target: TargetSelector, title: string, subTitle: string): void;
/**
* Closes the chat window if it is open (EE only)
*/
//% promise
//% shim=gameplay::dismissChatAsync promise
function dismissChat(): void;
}
declare namespace blocks {
/**
* Creates the specified text in the game world, made of the specified block, at the given location
* @param text the text to print in the world, eg: "HELLO"
* @param block the block type that will be used to create the text
* @param position the coordinates where the text will be printed in the world
* @param direction the axis along which the text will be printed
*/
//% help=blocks/print
//% weight=240
//% blockId=minecraftPrintAsync block="print %text|of %block=minecraftBlock|at %position=minecraftCreatePosition|along %direction"
//% block.shadow=minecraftBlockField
//% blockExternalInputs=1
//% text.shadowOptions.toString=true
//% shim=blocks::printAsync promise
function print(text: string, block: number, position: Position, direction: CompassDirection): void;
}
declare namespace loops {
/**
* Repeat the code forever in the background. On each iteration, allow other code to run.
* @param body code to repeat forever
*/
//% help=loops/forever weight=55 blockAllowMultiple=true
//% blockId=device_forever block="forever" icon="\uf01e" blockGap=24
//% shim=loops::forever
function forever(body: () => void): void;
/**
* Pause for the specified time in milliseconds
* @param ms how long to pause for, eg: 100, 200, 500, 1000, 2000
*/
//% help=loops/pause weight=54 blockGap=24
//% async block="pause (ms) %pause"
//% blockId=device_pause icon="\uf110"
//% shim=loops::pause
function pause(ms: number): void;
/**
* Run this code in parallel with the current code
*/
//% blockId=fork icon="\uf110" block="run in background"
//% help=loops/run-in-background weight=0
//% shim=loops::runInBackground
function runInBackground(handler: () => void): void;
}
declare namespace mobs {
/**
* Summons a creature at a given location
* @param mob the type of creature to summon
* @param destination the coordinates at which to summon the creature
*/
//% help=mobs/spawn
//% promise
//% weight=350
//% blockId=minecraftSummon block="spawn %entity=minecraftAnimal|at %destination=minecraftCreatePosition"
//% entity.shadow=minecraftAnimal
//% topblock topblockWeight=80
//% shim=mobs::spawnAsync promise
function spawn(mob: number, destination: Position): void;
/**
* Runs code when a creature of a certain type is killed
* @param mob the type of creature
*/
//% help=mobs/on-mob-killed
//% weight=340
//% blockId=minecraftMobKilled block="on %mob=minecraftAnimal|killed"
//% mob.shadow=minecraftAnimal
//% shim=mobs::onMobKilledAsync promise
function onMobKilled(mob: number, handler: () => void): void;
/**
* Applies a status effect to the specified target
* @param target a target selector that determines which entity will receive the effect
* @param effect the effect to apply
* @param duration the duration of the effect
* @param amplifier the amplifier of the effect
*/
//% promise
//% weight=0
//% blockId=minecraftEffect block="apply %effect to %target=minecraftTarget||duration %duration amplifier %amplifier"
//% expandableArgumentMode=toggle
//% duration.min=0 duration.max=600 duration.defl=10
//% amplifier.min=0 amplifier.max=255 amplifier.defl=1
//% inlineInputMode="inline"
//% effect.fieldEditor="gridpicker"
//% effect.fieldOptions.width=340 effect.fieldOptions.columns=8 effect.fieldOptions.tooltips=true
//% effect.fieldOptions.tooltipsXOffset="20" effect.fieldOptions.tooltipsYOffset="-20"
//% effect.fieldOptions.maxRows="8"
//% effect.fieldOptions.hasSearchBar=true
//% effect.fieldOptions.hideRect=true
//% deprecated=true
//% shim=mobs::effectAsync promise
function effect(effect: Effect, target: TargetSelector, duration?: number, amplifier?: number): void;
/**
* Applies a status effect to the specified target
* @param target a target selector that determines which entity will receive the effect
* @param effect the effect to apply
* @param duration the duration of the effect
* @param amplifier the amplifier of the effect
*/
//% promise
//% weight=270 help=mobs/apply-effect
//% blockId=minecraftApplyEffect block="apply %effect=minecraftEffectField|to %target=minecraftTarget|duration %duration amplifier %amplifier"
//% duration.min=0 duration.max=600 duration.defl=10
//% amplifier.min=0 amplifier.max=255 amplifier.defl=1
//% inlineInputMode="inline"
//% shim=mobs::applyEffectAsync promise
function applyEffect(effect: number, target: TargetSelector, duration?: number, amplifier?: number): void;
/**
* Clears all status effects from the specified target
* @param target a target selector that determines which entity will be cleared of effects
*/
//% promise
//% weight=260 help=mobs/clear-effect
//% blockId=minecraftClearEffect block="clear all effects from %target=minecraftTarget"
//% shim=mobs::clearEffectAsync promise
function clearEffect(target: TargetSelector): void;
/**
* Gives blocks or items from the game to the specified players
* @param target a target selector that determines which players will receive the block or item
* @param block the block or item to give
* @param amount the quantity to give, eg: 1
*/
//% help=mobs/give
//% promise
//% weight=240
//% blockId=minecraftGive block="give %target=minecraftTarget|block or item %block=minecraftBlock|amount %amount"
//% block.shadow=minecraftBlockField
//% blockExternalInputs=1
//% shim=mobs::giveAsync promise
function give(target: TargetSelector, block: number, amount: number): void;
/**
* Teleports entities to another location
* @param target a target selector that determines which entities will be teleported
* @param destination the coordinates where the selected entities will be teleported to
*/
//% help=mobs/teleport-to-position
//% promise
//% weight=230
//% blockId=minecraftTeleport block="teleport %target=minecraftTarget|to %destination=minecraftCreatePosition"
//% blockExternalInputs=1
//% shim=mobs::teleportToPositionAsync promise
function teleportToPosition(target: TargetSelector, destination: Position): void;
/**
* Teleports entities to a player
* @param target a target selector that determines which entities will be teleported
* @param destination a target selector that determines which player the entities will be teleported to
*/
//% help=mobs/teleport-to-player
//% promise
//% weight=220
//% blockId=minecraftTeleportToPlayer block="teleport %target=minecraftTarget|to %destination=minecraftTarget"
//% blockExternalInputs=1
//% shim=mobs::teleportToPlayerAsync promise
function teleportToPlayer(target: TargetSelector, destination: TargetSelector): void;
/**
* Applies a certain enchantment to the specified targets
* @param target a target selector that determines which players will receive the enchantment
* @param spell the code name of the enchantment, eg: "infinity"
* @param level the strength level of the enchantment, eg: 1
*/
//% help=mobs/enchant
//% promise
//% weight=210 blockGap=60
//% blockId=minecraftEnchant block="enchant %target=minecraftTarget|with %spell|of level %level"
//% inlineInputMode="external"
//% shim=mobs::enchantAsync promise
function enchant(target: TargetSelector, spell: string, level: number): void;
/**
* Kills the selected entities
* @param target a target selector that determines which entities will be killed
*/
//% help=mobs/kill
//% promise
//% weight=330
//% blockId=minecraftKill block="kill %target=minecraftTarget"
//% blockExternalInputs=1
//% shim=mobs::killAsync promise
function kill(target: TargetSelector): void;
/**
* Executes a command as other targets
* @param target a target selector that determines which entities will execute the command
* @param position the coordinates from which to run the command
* @param command the full command which the selected targets will execute, eg: "say Hi!"
*/
//% help=mobs/execute
//% weight=110 blockGap=30
//% blockId=minecraftExecuteAsOther block="execute as %target=minecraftTarget|at %position=minecraftCreatePosition|command %command"
//% blockExternalInputs=1
//% shim=mobs::executeAsync promise
function execute(target: TargetSelector, position: Position, command: string): void;
/**
* Executes a command if a certain block type is detected at the specified position
* @param detectPosition the position at which to detect the block
* @param detectBlock the block type to test for
* @param command the full command which the selected targets will execute if the specified block is successfully detected, eg: "say Hi!"
*/
//% help=mobs/execute-detect
//% weight=120
//% blockId=minecraftExecuteDetect block="detect block %block=minecraftBlock|at %detectPosition=minecraftCreatePosition|if found, run command %command"
//% block.shadow=minecraftBlockField
//% blockExternalInputs=1
//% shim=mobs::executeDetectAsync promise
function executeDetect(detectBlock: number, detectPosition: Position, command: string): void;
/**
* Represents an animal from the game
* @param name the type of the animal
*/
//% help=mobs/animal
//% weight=320
//% blockId=minecraftAnimal block="animal %name"
//% name.fieldEditor="gridpicker"
//% name.fieldOptions.width=340 name.fieldOptions.columns=8 name.fieldOptions.tooltips=true
//% name.fieldOptions.maxRows="8"
//% name.fieldOptions.hideRect=true
//% shim=mobs::animal
function animal(name: AnimalMob): number;
/**
* Represents a monster from the game
* @param name the type of the monster
*/
//% help=mobs/monster
//% blockId=minecraftMonster block="monster %name"
//% weight=310
//% name.fieldEditor="gridpicker"
//% name.fieldOptions.width=340 name.fieldOptions.columns=8 name.fieldOptions.tooltips=true
//% name.fieldOptions.maxRows="8"
//% name.fieldOptions.hideRect=true
//% shim=mobs::monster
function monster(name: MonsterMob): number;
/**
* Represents a projectile from the game
* @param name the type of the projectile
*/
//% help=mobs/projectile
//% blockId=minecraftProjectile block="projectile %name"
//% weight=305 blockGap=60
//% shim=mobs::projectile
function projectile(name: ProjectileMob): number;
}
declare namespace player {
/**
* Returns the name of the current player (you)
*/
//% help=player/name
//% weight=240
//% blockId=minecraftMyName block="player name"
//% shim=player::name
function name(): string;
/**
* Posts a message to the game chat
* @param message the message to display in the chat, eg: "Hi!"
*/
//% help=player/say
//% promise
//% weight=340
//% blockId=minecraftSay block="say %message"
//% message.shadowOptions.toString=true
//% shim=player::sayAsync promise
function say(message: string): void;
/**
* Whispers a message to targets
* @param target a selector of entities
* @param message the text to whisper, eg: "Hi!"
*/
//% help=player/tell
//% promise
//% weight=220
//% blockId=minecraftTell block="tell %target=minecraftTarget|%message"
//% inlineInputMode="inline"
//% message.shadowOptions.toString=true
//% shim=player::tellAsync promise
function tell(target: TargetSelector, message: string): void;
/**
* Teleports the current player to another position
* @param to the destination position
*/
//% help=player/teleport
//% promise
//% weight=330
//% blockId=minecraftPlayerTeleport block="teleport to %to=minecraftCreatePosition"
//% shim=player::teleportAsync promise
function teleport(to: Position): void;
/**
* Gets the last message, if any
*/
//%
//% shim=player::message
function message(): string;
/**
* Runs code when another player whispers you a certain message
* @param command the chat keyword that will be associated with this command (``*`` for all messages), eg: "jump"
*/
//% help=player/on-tell-command
//% promise
//% weight=120
//% blockId=minecraftOnTellCommand block="on tell command %command"
//% shim=player::onTellCommandAsync promise
function onTellCommand(command: string, handler: () => void): void;
/**
* Executes a chat command in your code
* @param command the chat command to run, eg: "jump"
*/
//% help=player/run-chat-command
//% weight=140
//% blockId=minecraftRunChatCommand block="run chat command %command"
//% shim=player::runChatCommand
function runChatCommand(command: string): void;
/**
* Executes a chat command in your code with arguments
* @param command the chat command to run, eg: "jump"
* @param arg a string containing all the arguments you wish to give to the chat command
*/
//% help=player/run-chat-command-with-args
//% weight=130
//% blockId=minecraftRunChatCommandArgs block="run chat command %command|with %arg"
//% arg.shadowOptions.toString=true
//% shim=player::runChatCommandWithArguments
function runChatCommandWithArguments(command: string, arg: string): void;
/**
* Runs code when the current player dies
*/
//% help=player/on-died
//% promise
//% weight=310 blockGap=60
//% blockId=minecraftPlayerDied block="on player died"
//% shim=player::onDiedAsync promise
function onDied(handler: () => void): void;
/**
* Runs code when the current player travels in a certain way
* @param method the travel method
*/
//% help=player/on-travelled
//% promise
//% weight=320
//% blockId=minecraftPlayerTravelled block="on player %method"
//% topblock topblockWeight=90
//% shim=player::onTravelledAsync promise
function onTravelled(method: TravelMethod, handler: () => void): void;
/**
* Runs code when the current player gets teleported
*/
//% help=player/on-teleported
//% promise
//% weight=110
//% blockId=minecraftPlayerOnTeleported block="on player teleported"
//% shim=player::onTeleportedAsync promise
function onTeleported(handler: () => void): void;
/**
* Runs code when the current player bounces on a slime
*/
//% help=player/on-bounced
//% promise
//% weight=1
//% blockId=minecraftPlayerBounced block="on player bounced"
//% deprecated=true
//% shim=player::onBouncedAsync promise
function onBounced(handler: () => void): void;
/**
* Runs code when a picture is taken with a camera
*/
//% help=player/on-camera-used
//% promise
//% weight=1
//% blockId=minecraftOnCameraUsed block="on camera used"
//% deprecated=true
//% shim=player::onCameraUsedAsync promise
function onCameraUsed(handler: () => void): void;
/**
* Runs code when the current player shoots an arrow
*/
//% help=player/on-arrow-shot
//% promise
//% weight=210 blockGap=60
//% blockId=minecraftOnArrowShot block="on arrow shot"
//% shim=player::onArrowShotAsync promise
function onArrowShot(handler: () => void): void;
/**
* Returns the world position of the current player
*/
//% help=player/position
//% promise
//% weight=250
//% blockId=minecraftMyPosition block="player world position"
//% shim=player::positionAsync promise
function position(): Position;
/**
* Executes a game command as the current player
* @param command the slash command to execute (you do not have to put the leading ``/``), eg: "say Hi!"
*/
//% help=player/execute
//% promise
//% weight=230
//% blockId=minecraftExecute block="execute %command"
//% blockExternalInputs=1
//% shim=player::executeAsync promise
function execute(command: string): void;
/**
* Runs code when a keyword is typed in the chat
* @param command the chat keyword that will be associated with this command (``*`` for all messages), eg: "jump"
*/
//%
//% shim=player::onChatCommandCoreAsync promise
function onChatCommandCore(command: string, handler: () => void): void;
/**
* Runs code when an item is used
*/
//% help=player/on-item-used
//% promise
//% weight=350
//% blockId=minecraftOnItemInteracted block="on $item|used"
//% item.shadow=minecraftItem
//% shim=player::onItemInteractedAsync promise
function onItemInteracted(item: number, handler: () => void): void;
/**
* Gets the specified argument from the latest player chat message
* @param index
*/
//%
//% shim=player::getChatArg
function getChatArg(index: number): string;
/**
* Gets the arguments for the specified command
* @param command the chat command for which to get the args
*/
//%
// NOTE: This returns a RefCollection, but because of the way our sim typings are set up, we cannot declare
// RefCollection as the return type. We instead use string[] in the signature, while actually returning a
// RefCollection cast as <any>.
//% shim=player::getChatArgs
function getChatArgs(command: string): string[];
/**
* Displays a chat command help message in the game chat.
*
* @param helpStr The formatted syntax of the command
*/
//% promise
//% shim=player::chatCommandSyntaxErrorAsync promise
function chatCommandSyntaxError(helpStr: string): void;
/**
* Displays an error in the game chat
*
* @param msg The error to display in the game chat
*/
//% promise
//% shim=player::errorMessageAsync promise
function errorMessage(msg: string, multiline?: boolean): void;
}
declare namespace positions {
/**
* Creates a new position by adding the two specified positions
* @param p1 the first position to add
* @param p2 the second position to add
*/
//% help=positions/add
//% weight=220
//% blockId=minecraftAddPosition block="%p1=minecraftCreatePosition|+ %p2=minecraftCreatePosition"
//% blockExternalInputs=1
//% shim=positions::add
function add(p1: Position, p2: Position): Position;
/**
* Creates a new relative position: ~East/West, ~up/down, ~South/North
* @param x the East (+x) or West (-x) coordinate, in blocks
* @param y the up (+y) or down (-y) coordinate, in blocks
* @param z the South (+z) or North (-z) coordinate, in blocks
*/
//% help=positions/create
//% weight=320
//% blockId=minecraftCreatePosition block="~%x|~%y|~%z"
//% shim=positions::create
function create(x: number, y: number, z: number): Position;
/**
* Creates a new world position: East/West, up/down, South/North
* @param x the East (+x) or West (-x) coordinate, in blocks
* @param y the up (+y) or down (-y) coordinate, in blocks
* @param z the South (+z) or North (-z) coordinate, in blocks
*/
//% help=positions/create-world
//% weight=310 blockGap=60
//% blockId=minecraftCreateWorldPosition block="world %x|%y|%z"
//% shim=positions::createWorld
function createWorld(x: number, y: number, z: number): Position;
/**
* Creates a new position with a mix of relative and absolute coordinates
* @param x the East (+x) or West (-x) coordinate, in blocks
* @param y the up (+y) or down (-y) coordinate, in blocks
* @param z the South (+z) or North (-z) coordinate, in blocks
*/
//%
//% shim=positions::createHybrid
function createHybrid(xRaw: string, yRaw: string, zRaw: string): Position;
/**
* Picks a random position within the specified cubic region
* @param p1 the position of the first corner of the cubic region
* @param p2 the position of the opposite corner of the cubic region
*/
//% help=positions/random
//% weight=210 blockGap=60
//% blockId=minecraftPosRandom block="pick random position|from %p1=minecraftCreatePosition|to %p2=minecraftCreatePosition"
//% blockExternalInputs=1
//% shim=positions::random
function random(p1: Position, p2: Position): Position;
/**
* Finds the ground under the given position and returns the coordinates of the next air block just above it. If
* the given block is solid, the next air block underneath is found, and the scan starts from there. Liquids are
* considered solid.
* @param pos the position under which to find the ground
*/
//% help=positions/ground-position
//% promise
//% weight=50
//% blockId=minecraftNextSolid block="ground at $pos=minecraftCreatePosition"
//% shim=positions::groundPositionAsync promise
function groundPosition(pos: Position): Position;
}
/**
* A world coordinate that may be relative (~) to the player position.
*/
//% color=#69B090
declare class Position {
/**
* Returns a string representation of this position
*/
//% help=positions/to-string
//% blockId="minecraftPositionToString" block="%position|to string"
//% blockNamespace=positions weight=110 color=#69B090
//% blockGap=60
//% shim=.toString
public toString(): string;
/**
* Adds the offset and returns a new position
*/
//%
//% shim=.add
public add(offset: Position): Position;
/**
* Creates a new world position by converting this position to a world position
*/
//% help=positions/to-world
//% promise
//% blockId=minecraftPositionToWorld block="%position|to world"
//% blockNamespace=positions weight=120 color=#69B090
//% shim=.toWorldAsync promise
public toWorld(): Position;
/**
* Gets the value of the specified coordinate: x, y or z
* @param direction the axis for which to return the coordinate value
*/
//% help=positions/get-value
//% blockId=minecraftPosGet block="%position|get value of %direction"
//% blockNamespace=positions weight=130 color=#69B090
//% shim=.getValue
public getValue(direction: Axis): number;
/**
* Gets a value that indicates if the coordinate is relative to the user
*/
//%
//% shim=.isRelative
public isRelative(direction: Axis): boolean;
/**
* Returns a position moved by the given blocks
*/
//%
//% shim=.move
public move(direction: CardinalDirection, blocks: number): Position;
}
declare namespace mobs {
/**
* Selects a set of players or mobs
* @param kind the type of entities that will be selected
*/
//% help=mobs/selectors/target
//% blockId=minecraftTarget block="%kind" weight=99 group="Selectors"
//% shim=mobs::target
function target(kind: TargetSelectorKind): TargetSelector;
/**
* Selects targets near a given position
* @param target the type of entities that will be selected
* @param pos the position near which to select targets
* @param radius the distance (in blocks) from the specified position within which targets will be selected, eg: 5
*/
//% help=mobs/selectors/near
//% blockId=minecraftTargetNear block="%target=minecraftTarget|near to %pos=minecraftCreateWorldPosition|within radius %radios" weight=39
//% blockExternalInputs=1 group="Selectors"
//% shim=mobs::near
function near(target: TargetSelector, pos: Position, radius: number): TargetSelector;
/**
* Selects all mobs (animals or monsters) of a given type
* @param type the type of mob to select
*/
//% help=mobs/selectors/entities-by-type
//% blockId=minecraftTargetSelectByType block="all %type=minecraftAnimal" weight=38 group="Selectors"
//% type.shadow=minecraftAnimal
//% shim=mobs::entitiesByType
function entitiesByType(type: number): TargetSelector;
/**
* Selects the player with the given name
* @param name the name of the player to select. eg: name
*/
//% help=mobs/selectors/player-by-name
//% blockGap=30
//% blockId=minecraftTargetSelectName block="player named %name" weight=37 group="Selectors"
//% shim=mobs::playerByName
function playerByName(name: string): TargetSelector;
/**
* Selects all players in the given game mode
* @param mode the game mode in which all players will be selected
*/
//% help=mobs/selectors/player-in-game-mode
//% blockId=minecraftTargetSelectGameMode block="players in game mode %mode" weight=37 group="Selectors"
//% shim=mobs::playersInGameMode
function playersInGameMode(mode: GameMode): TargetSelector;
/**
* Parses the given string into a TargetSelector object. This function does not check to make sure
* arguments are given the correct type or that the names of arguments are valid.
* @param str the target selector string to parse
* @returns the parsed TargetSelector object or null if the string was invalid
*/
//%
//% shim=mobs::parseSelector
function parseSelector(str: string): TargetSelector;
}
/**
* A target selector
*/
//%
declare class TargetSelector {
/**
* Sets the base coordinates for this target selector
* @param p the coordinates at which this selector should be set
*/
//% help=mobs/selectors/at-coordinates
//% blockId=minecraftSelectorAtCoordinate block="%selector| set coordinate %p=minecraftCreateWorldPosition"
//% blockNamespace=mobs weight=30 group="Selectors"
//% shim=.atCoordinate
public atCoordinate(p: Position): void;
/**
* Sets the maximum distance from this selector's base coordinates
* @param radius the maximum distance (in blocks) for this target selector, eg: 5
*/
//% help=mobs/selectors/within-radius
//% blockId=minecraftSelectorWithinRadius block="%selector| set max radius %r"
//% blockNamespace=mobs weight=20 group="Selectors"
//% shim=.withinRadius
public withinRadius(radius: number): void;
/**
* Sets the minimum distance from this selector's base coordinates
* @param radius the minimum distance (in blocks) for this target selector, eg: 10
*/
//% help=mobs/selectors/outside-radius
//% blockId=minecraftSelectorOutsideRadius block="%selector| set min radius %r"
//% blockNamespace=mobs weight=10 group="Selectors"
//% shim=.outsideRadius
public outsideRadius(radius: number): void;
/**
* Adds a rule to this target selector
* @param rule the rule to add, eg: "type"
* @param value the value for the rule, eg: "chicken"
*/
//% help=mobs/selectors/add-rule
//% blockId=minecraftSelectorAddRule block="%selector| add rule %rule| equals %value"
//% blockNamespace=mobs weight=10 group="Selectors"
//% shim=.addRule
public addRule(rule: string, value: string): void;
/**
* Returns a string containing the game notation for this target selector
*/
//% help=mobs/selectors/to-string
//% blockId=minecraftSelectorToString block="%selector|to string"
//% blockNamespace=mobs weight=9 group="Selectors"
//% shim=.toString
public toString(): string;
}
// Auto-generated. Do not edit. Really.
/**
* Give commands, communicate, and respond to events that happen in the game
*/
//% color=#0078D7 weight=100 icon="\uf007"
namespace player {
export class ChatCommandArguments {
public number: number;
public number2: number;
public string: string;
public string2: string;
public position: Position;
public position2: Position;
public selector: TargetSelector;
public selector2: TargetSelector;
}
/**
* Returns the string value of the specified ChatArgument enum value
* @param argName
*/
function getArgumentName(argName: ChatArgument): string {
return "";
}
/**
* Runs code when you type a certain message in the game chat
* @param command the chat keyword that will be associated with this command (``*`` for all messages), eg: "jump"
*/
//% help=player/on-chat-command
//% promise
//% weight=350
//% blockId=minecraftOnChatCommand block="on chat command %command"
//% mutate=objectdestructuring
//% mutatePropertyEnum=ChatArgument
//% mutateText="Command arguments"
//% mutatePrefix="with"
//% deprecated=true
export function onChatCommand(command: string, argTypes: ChatArgument[], handler: (args: ChatCommandArguments) => void): void {
}
/**
* Runs code when you type a certain message in the game chat
* @param command the chat keyword that will be associated with this command (``*`` for all messages), eg: "jump"
*/
//% help=player/on-chat-command
//% promise
//% weight=360
//% blockId=minecraftOnChat block="on chat command %command"
//% optionalVariableArgs
//% topblock topblockWeight=95
export function onChat(command: string, handler: (num1: number, num2: number, num3: number) => void) {
}
} | the_stack |
import type * as prismicT from "@prismicio/types";
import {
ClientHookReturnType,
ClientMethodParameters,
HookOnlyParameters,
useStatefulPrismicClientMethod,
} from "./useStatefulPrismicClientMethod";
/**
* A hook that queries content from the Prismic repository.
*
* @remarks
* An additional `@prismicio/client` instance can be provided at `params.client`.
*
* @typeParam TDocument - Type of Prismic documents returned
*
* @param params - Parameters to filter, sort, and paginate results
*
* @returns The composable payload {@link ClientHookReturnType}
*
* @see Underlying `@prismicio/client` method {@link proto.get}
*/
export const usePrismicDocuments = <TDocument extends prismicT.PrismicDocument>(
...args: [params?: ClientMethodParameters<"get">[0] & HookOnlyParameters]
): ClientHookReturnType<prismicT.Query<TDocument>> =>
useStatefulPrismicClientMethod("get", args);
/**
* A hook that queries content from the Prismic repository and returns only the
* first result, if any.
*
* @remarks
* An additional `@prismicio/client` instance can be provided at `params.client`.
*
* @typeParam TDocument - Type of the Prismic document returned
*
* @param params - Parameters to filter, sort, and paginate results
*
* @returns The composable payload {@link ClientHookReturnType}
*
* @see Underlying `@prismicio/client` method {@link proto.getFirst}
*/
export const useFirstPrismicDocument = <
TDocument extends prismicT.PrismicDocument,
>(
...args: [params?: ClientMethodParameters<"getFirst">[0] & HookOnlyParameters]
): ClientHookReturnType<TDocument> =>
useStatefulPrismicClientMethod("getFirst", args);
/**
* A hook that queries content from the Prismic repository and returns all
* matching content. If no predicates are provided, all documents will be fetched.
*
* @remarks
* An additional `@prismicio/client` instance can be provided at `params.client`.
*
* @typeParam TDocument - Type of Prismic documents returned
*
* @param params - Parameters to filter and sort results
*
* @returns The composable payload {@link ClientHookReturnType}
*
* @see Underlying `@prismicio/client` method {@link proto.getAll}
*/
export const useAllPrismicDocumentsDangerously = <
TDocument extends prismicT.PrismicDocument,
>(
...args: [
params?: ClientMethodParameters<"dangerouslyGetAll">[0] &
HookOnlyParameters,
]
): ClientHookReturnType<TDocument[]> =>
useStatefulPrismicClientMethod("dangerouslyGetAll", args);
/**
* A hook that queries a document from the Prismic repository with a specific ID.
*
* @remarks
* An additional `@prismicio/client` instance can be provided at `params.client`.
*
* @typeParam TDocument - Type of the Prismic document returned
*
* @param id - ID of the document
* @param params - Parameters to filter, sort, and paginate results
*
* @returns The composable payload {@link ClientHookReturnType}
*
* @see Underlying `@prismicio/client` method {@link proto.getByID}
*/
export const usePrismicDocumentByID = <
TDocument extends prismicT.PrismicDocument,
>(
...args: [
id: ClientMethodParameters<"getByID">[0],
params?: ClientMethodParameters<"getByID">[1] & HookOnlyParameters,
]
): ClientHookReturnType<TDocument> =>
useStatefulPrismicClientMethod("getByID", args);
/**
* A hook that queries documents from the Prismic repository with specific IDs.
*
* @remarks
* An additional `@prismicio/client` instance can be provided at `params.client`.
*
* @typeParam TDocument - Type of Prismic documents returned
*
* @param ids - A list of document IDs
* @param params - Parameters to filter, sort, and paginate results
*
* @returns The composable payload {@link ClientHookReturnType}
*
* @see Underlying `@prismicio/client` method {@link proto.getByIDs}
*/
export const usePrismicDocumentsByIDs = <
TDocument extends prismicT.PrismicDocument,
>(
...args: [
id: ClientMethodParameters<"getByIDs">[0],
params?: ClientMethodParameters<"getByIDs">[1] & HookOnlyParameters,
]
): ClientHookReturnType<prismicT.Query<TDocument>> =>
useStatefulPrismicClientMethod("getByIDs", args);
/**
* A hook that queries all documents from the Prismic repository with specific IDs.
*
* @remarks
* An additional `@prismicio/client` instance can be provided at `params.client`.
*
* @typeParam TDocument - Type of Prismic documents returned
*
* @param ids - A list of document IDs
* @param params - Parameters to filter and sort results
*
* @returns The composable payload {@link ClientHookReturnType}
*
* @see Underlying `@prismicio/client` method {@link proto.getAllByIDs}
*/
export const useAllPrismicDocumentsByIDs = <
TDocument extends prismicT.PrismicDocument,
>(
...args: [
id: ClientMethodParameters<"getAllByIDs">[0],
params?: ClientMethodParameters<"getAllByIDs">[1] & HookOnlyParameters,
]
): ClientHookReturnType<TDocument[]> =>
useStatefulPrismicClientMethod("getAllByIDs", args);
/**
* A hook that queries a document from the Prismic repository with a specific
* UID and Custom Type.
*
* @remarks
* An additional `@prismicio/client` instance can be provided at `params.client`.
*
* @typeParam TDocument - Type of the Prismic document returned
*
* @param documentType - The API ID of the document's Custom Type
* @param uid - UID of the document
* @param params - Parameters to filter, sort, and paginate results
*
* @returns The composable payload {@link ClientHookReturnType}
*
* @see Underlying `@prismicio/client` method {@link proto.getByUID}
*/
export const usePrismicDocumentByUID = <
TDocument extends prismicT.PrismicDocument,
>(
...args: [
documentType: ClientMethodParameters<"getByUID">[0],
uid: ClientMethodParameters<"getByUID">[1],
params?: ClientMethodParameters<"getByUID">[2] & HookOnlyParameters,
]
): ClientHookReturnType<TDocument> =>
useStatefulPrismicClientMethod("getByUID", args);
/**
* A hook that queries documents from the Prismic repository with specific UIDs
* of a Custom Type.
*
* @remarks
* An additional `@prismicio/client` instance can be provided at `params.client`.
*
* @typeParam TDocument - Type of the Prismic document returned
*
* @param documentType - The API ID of the document's Custom Type
* @param uids - A list of document UIDs.
* @param params - Parameters to filter, sort, and paginate results
*
* @returns The composable payload {@link ClientHookReturnType}
*
* @see Underlying `@prismicio/client` method {@link proto.getByUID}
*/
export const usePrismicDocumentsByUIDs = <
TDocument extends prismicT.PrismicDocument,
>(
...args: [
documentType: ClientMethodParameters<"getByUIDs">[0],
uids: ClientMethodParameters<"getByUIDs">[1],
params?: ClientMethodParameters<"getByUIDs">[2] & HookOnlyParameters,
]
): ClientHookReturnType<prismicT.Query<TDocument>> =>
useStatefulPrismicClientMethod("getByUIDs", args);
/**
* A hook that queries all documents from the Prismic repository with specific
* UIDs of a Custom Type.
*
* @remarks
* An additional `@prismicio/client` instance can be provided at `params.client`.
*
* @typeParam TDocument - Type of the Prismic document returned
*
* @param documentType - The API ID of the document's Custom Type
* @param uids - A list of document UIDs.
* @param params - Parameters to filter, sort, and paginate results
*
* @returns The composable payload {@link ClientHookReturnType}
*
* @see Underlying `@prismicio/client` method {@link proto.getByUID}
*/
export const useAllPrismicDocumentsByUIDs = <
TDocument extends prismicT.PrismicDocument,
>(
...args: [
documentType: ClientMethodParameters<"getByUIDs">[0],
uids: ClientMethodParameters<"getByUIDs">[1],
params?: ClientMethodParameters<"getByUIDs">[2] & HookOnlyParameters,
]
): ClientHookReturnType<TDocument[]> =>
useStatefulPrismicClientMethod("getAllByUIDs", args);
/**
* A hook that queries a singleton document from the Prismic repository for a
* specific Custom Type.
*
* @remarks
* An additional `@prismicio/client` instance can be provided at `params.client`.
*
* @typeParam TDocument - Type of the Prismic document returned
*
* @param documentType - The API ID of the singleton Custom Type
* @param params - Parameters to filter, sort, and paginate results
*
* @returns The composable payload {@link ClientHookReturnType}
*
* @see Underlying `@prismicio/client` method {@link proto.getSingle}
*/
export const useSinglePrismicDocument = <
TDocument extends prismicT.PrismicDocument,
>(
...args: [
documentType: ClientMethodParameters<"getSingle">[0],
params?: ClientMethodParameters<"getSingle">[1] & HookOnlyParameters,
]
): ClientHookReturnType<TDocument> =>
useStatefulPrismicClientMethod("getSingle", args);
/**
* A hook that queries documents from the Prismic repository for a specific Custom Type.
*
* @remarks
* An additional `@prismicio/client` instance can be provided at `params.client`.
*
* @typeParam TDocument - Type of Prismic documents returned
*
* @param documentType - The API ID of the Custom Type
* @param params - Parameters to filter, sort, and paginate results
*
* @returns The composable payload {@link ClientHookReturnType}
*
* @see Underlying `@prismicio/client` method {@link proto.getByType}
*/
export const usePrismicDocumentsByType = <
TDocument extends prismicT.PrismicDocument,
>(
...args: [
documentType: ClientMethodParameters<"getByType">[0],
params?: ClientMethodParameters<"getByType">[1] & HookOnlyParameters,
]
): ClientHookReturnType<prismicT.Query<TDocument>> =>
useStatefulPrismicClientMethod("getByType", args);
/**
* A hook that queries all documents from the Prismic repository for a specific
* Custom Type.
*
* @remarks
* An additional `@prismicio/client` instance can be provided at `params.client`.
*
* @typeParam TDocument - Type of Prismic documents returned
*
* @param documentType - The API ID of the Custom Type
* @param params - Parameters to filter and sort results
*
* @returns The composable payload {@link ClientHookReturnType}
*
* @see Underlying `@prismicio/client` method {@link proto.getAllByType}
*/
export const useAllPrismicDocumentsByType = <
TDocument extends prismicT.PrismicDocument,
>(
...args: [
documentType: ClientMethodParameters<"getAllByType">[0],
params?: ClientMethodParameters<"getAllByType">[1] & HookOnlyParameters,
]
): ClientHookReturnType<TDocument[]> =>
useStatefulPrismicClientMethod("getAllByType", args);
/**
* A hook that queries documents from the Prismic repository with a specific tag.
*
* @remarks
* An additional `@prismicio/client` instance can be provided at `params.client`.
*
* @typeParam TDocument - Type of Prismic documents returned
*
* @param tag - The tag that must be included on a document
* @param params - Parameters to filter, sort, and paginate results
*
* @returns The composable payload {@link ClientHookReturnType}
*
* @see Underlying `@prismicio/client` method {@link proto.getByTag}
*/
export const usePrismicDocumentsByTag = <
TDocument extends prismicT.PrismicDocument,
>(
...args: [
tag: ClientMethodParameters<"getByTag">[0],
params?: ClientMethodParameters<"getByTag">[1] & HookOnlyParameters,
]
): ClientHookReturnType<prismicT.Query<TDocument>> =>
useStatefulPrismicClientMethod("getByTag", args);
/**
* A hook that queries all documents from the Prismic repository with a specific tag.
*
* @remarks
* An additional `@prismicio/client` instance can be provided at `params.client`.
*
* @typeParam TDocument - Type of Prismic documents returned
*
* @param tag - The tag that must be included on a document
* @param params - Parameters to filter and sort results
*
* @returns The composable payload {@link ClientHookReturnType}
*
* @see Underlying `@prismicio/client` method {@link proto.getAllByTag}
*/
export const useAllPrismicDocumentsByTag = <
TDocument extends prismicT.PrismicDocument,
>(
...args: [
tag: ClientMethodParameters<"getAllByTag">[0],
params?: ClientMethodParameters<"getAllByTag">[1] & HookOnlyParameters,
]
): ClientHookReturnType<TDocument[]> =>
useStatefulPrismicClientMethod("getAllByTag", args);
/**
* A hook that queries documents from the Prismic repository with specific tags.
* A document must be tagged with at least one of the queried tags to be included.
*
* @remarks
* An additional `@prismicio/client` instance can be provided at `params.client`.
*
* @typeParam TDocument - Type of Prismic documents returned
*
* @param tags - A list of tags that must be included on a document
* @param params - Parameters to filter, sort, and paginate results
*
* @returns The composable payload {@link ClientHookReturnType}
*
* @see Underlying `@prismicio/client` method {@link proto.getByTags}
*/
export const usePrismicDocumentsBySomeTags = <
TDocument extends prismicT.PrismicDocument,
>(
...args: [
tag: ClientMethodParameters<"getBySomeTags">[0],
params?: ClientMethodParameters<"getBySomeTags">[1] & HookOnlyParameters,
]
): ClientHookReturnType<prismicT.Query<TDocument>> =>
useStatefulPrismicClientMethod("getBySomeTags", args);
/**
* A hook that queries all documents from the Prismic repository with specific
* tags. A document must be tagged with at least one of the queried tags to be included.
*
* @remarks
* An additional `@prismicio/client` instance can be provided at `params.client`.
*
* @typeParam TDocument - Type of Prismic documents returned
*
* @param tags - A list of tags that must be included on a document
* @param params - Parameters to filter and sort results
*
* @returns The composable payload {@link ClientHookReturnType}
*
* @see Underlying `@prismicio/client` method {@link proto.getAllByTags}
*/
export const useAllPrismicDocumentsBySomeTags = <
TDocument extends prismicT.PrismicDocument,
>(
...args: [
tag: ClientMethodParameters<"getAllBySomeTags">[0],
params?: ClientMethodParameters<"getAllBySomeTags">[1] & HookOnlyParameters,
]
): ClientHookReturnType<TDocument[]> =>
useStatefulPrismicClientMethod("getAllBySomeTags", args);
/**
* A hook that queries documents from the Prismic repository with specific tags.
* A document must be tagged with all of the queried tags to be included.
*
* @remarks
* An additional `@prismicio/client` instance can be provided at `params.client`.
*
* @typeParam TDocument - Type of Prismic documents returned
*
* @param tags - A list of tags that must be included on a document
* @param params - Parameters to filter, sort, and paginate results
*
* @returns The composable payload {@link ClientHookReturnType}
*
* @see Underlying `@prismicio/client` method {@link proto.getByTags}
*/
export const usePrismicDocumentsByEveryTag = <
TDocument extends prismicT.PrismicDocument,
>(
...args: [
tag: ClientMethodParameters<"getByEveryTag">[0],
params?: ClientMethodParameters<"getByEveryTag">[1] & HookOnlyParameters,
]
): ClientHookReturnType<prismicT.Query<TDocument>> =>
useStatefulPrismicClientMethod("getByEveryTag", args);
/**
* A hook that queries all documents from the Prismic repository with specific
* tags. A document must be tagged with all of the queried tags to be included.
*
* @remarks
* An additional `@prismicio/client` instance can be provided at `params.client`.
*
* @typeParam TDocument - Type of Prismic documents returned
*
* @param tags - A list of tags that must be included on a document
* @param params - Parameters to filter and sort results
*
* @returns The composable payload {@link ClientHookReturnType}
*
* @see Underlying `@prismicio/client` method {@link proto.getAllByTags}
*/
export const useAllPrismicDocumentsByEveryTag = <
TDocument extends prismicT.PrismicDocument,
>(
...args: [
tag: ClientMethodParameters<"getAllByEveryTag">[0],
params?: ClientMethodParameters<"getAllByEveryTag">[1] & HookOnlyParameters,
]
): ClientHookReturnType<TDocument[]> =>
useStatefulPrismicClientMethod("getAllByEveryTag", args); | the_stack |
export interface DomainDescription {
domain: string;
version: { major: number, minor: number };
commands: { [commandName: string]: DomainCommand };
events: { [eventName: string]: DomainEvent };
}
export interface DomainModule {
init: (domainManager: typeof DomainManager) => void;
}
export interface DomainCommand {
commandFunction: (...args: any[]) => any;
isAsync: boolean;
description: string;
parameters: DomainCommandArgument[];
returns: DomainCommandArgument[];
}
export interface DomainEvent {
parameters: DomainCommandArgument[];
}
export interface DomainCommandArgument {
name: string;
type: string;
description?: string;
}
export interface ConnectionMessage {
id: number;
domain: string;
command?: string;
event?: string;
parameters?: any[];
}
export interface ConnectionErrorMessage {
message: string;
}
export interface CommandResponse {
id: number;
response: any;
}
export interface CommandError {
id: number;
message: string;
stack: string;
}
/* eslint-enable */
export function errToMessage(err: Error): string {
let message = err.message;
if (message && err.name) {
message = err.name + ": " + message;
}
return message ? message : err.toString();
}
export function errToString(err: Error): string {
if (err.stack) {
return err.stack;
}
if (err.name && err.message) {
return err.name + ": " + err.message;
}
return err.toString();
}
/**
* @private
* @type {object}
* Map of all the registered domains
*/
const _domains: { [domainName: string]: DomainDescription } = {};
/**
* @private
* @type {Array.<Module>}
* Array of all modules we have loaded. Used for avoiding duplicate loading.
*/
const _initializedDomainModules: DomainModule[] = [];
/**
* @private
* @type {number}
* Used for generating unique IDs for events.
*/
let _eventCount = 1;
/**
* @constructor
* DomainManager is a module/class that handles the loading, registration,
* and execution of all commands and events. It is a singleton, and is passed
* to a domain in its init() method.
*/
export class DomainManager {
/**
* Returns whether a domain with the specified name exists or not.
* @param {string} domainName The domain name.
* @return {boolean} Whether the domain exists
*/
public hasDomain(domainName: string): boolean {
return !!_domains[domainName];
}
/**
* Returns a new empty domain. Throws error if the domain already exists.
* @param {string} domainName The domain name.
* @param {{major: number, minor: number}} version The domain version.
* The version has a format like {major: 1, minor: 2}. It is reported
* in the API spec, but serves no other purpose on the server. The client
* can make use of this.
*/
public registerDomain(domainName: string, version: { major: number, minor: number }) {
if (!this.hasDomain(domainName)) {
_domains[domainName] = {
domain: domainName,
version,
commands: {},
events: {}
};
process.send && process.send({
type: "refreshInterface",
spec: this.getDomainDescriptions()
});
} else {
console.error("[DomainManager] Domain " + domainName + " already registered");
}
}
/**
* Registers a new command with the specified domain. If the domain does
* not yet exist, it registers the domain with a null version.
* @param {string} domainName The domain name.
* @param {string} commandName The command name.
* @param {Function} commandFunction The callback handler for the function.
* The function is called with the arguments specified by the client in the
* command message. Additionally, if the command is asynchronous (isAsync
* parameter is true), the function is called with an automatically-
* constructed callback function of the form cb(err, result). The function
* can then use this to send a response to the client asynchronously.
* @param {boolean} isAsync See explanation for commandFunction param
* @param {?string} description Used in the API documentation
* @param {?Array.<{name: string, type: string, description:string}>} parameters
* Used in the API documentation.
* @param {?Array.<{name: string, type: string, description:string}>} returns
* Used in the API documentation.
*/
public registerCommand(
domainName: string,
commandName: string,
commandFunction: (...args: any[]) => any,
isAsync: boolean,
description: string,
parameters: DomainCommandArgument[],
returns: DomainCommandArgument[]
) {
if (!this.hasDomain(domainName)) {
throw new Error(`Domain ${domainName} doesn't exist. Call .registerDomain first!`);
}
if (!_domains[domainName].commands[commandName]) {
_domains[domainName].commands[commandName] = {
commandFunction,
isAsync,
description,
parameters,
returns
};
process.send && process.send({
type: "refreshInterface",
spec: this.getDomainDescriptions()
});
} else {
throw new Error("Command " + domainName + "." + commandName + " already registered");
}
}
/**
* Executes a command by domain name and command name. Called by a connection's
* message parser. Sends response or error (possibly asynchronously) to the
* connection.
* @param {Connection} connection The requesting connection object.
* @param {number} id The unique command ID.
* @param {string} domainName The domain name.
* @param {string} commandName The command name.
* @param {Array} parameters The parameters to pass to the command function. If
* the command is asynchronous, will be augmented with a callback function
* and progressCallback function
* (see description in registerCommand documentation)
*/
public executeCommand(
id: number,
domainName: string,
commandName: string,
parameters: any[] = []
) {
if (_domains[domainName] && _domains[domainName].commands[commandName]) {
const command = _domains[domainName].commands[commandName];
if (command.isAsync) {
const callback = (err: Error, result: any) => {
if (err) {
this.sendCommandError(id, errToMessage(err), errToString(err));
} else {
this.sendCommandResponse(id, result);
}
};
const progressCallback = (msg: any) => {
this.sendCommandProgress(id, msg);
};
parameters.push(callback, progressCallback);
command.commandFunction(...parameters);
} else { // synchronous command
try {
this.sendCommandResponse(id, command.commandFunction(...parameters));
} catch (err) {
this.sendCommandError(id, errToMessage(err), errToString(err));
}
}
} else {
this.sendCommandError(id, "no such command: " + domainName + "." + commandName);
}
}
/**
* Registers an event domain and name.
* @param {string} domainName The domain name.
* @param {string} eventName The event name.
* @param {?Array.<{name: string, type: string, description:string}>} parameters
* Used in the API documentation.
*/
public registerEvent(domainName: string, eventName: string, parameters: DomainCommandArgument[]) {
if (!this.hasDomain(domainName)) {
throw new Error(`Domain ${domainName} doesn't exist. Call .registerDomain first!`);
}
if (!_domains[domainName].events[eventName]) {
_domains[domainName].events[eventName] = {
parameters
};
process.send && process.send({
type: "refreshInterface",
spec: this.getDomainDescriptions()
});
} else {
throw new Error("[DomainManager] Event " + domainName + "." + eventName + " already registered");
}
}
/**
* Emits an event with the specified name and parameters to all connections.
*
* TODO: Future: Potentially allow individual connections to register
* for which events they want to receive. Right now, we have so few events
* that it's fine to just send all events to everyone and decide on the
* client side if the client wants to handle them.
*
* @param {string} domainName The domain name.
* @param {string} eventName The event name.
* @param {?Array} parameters The parameters. Must be JSON.stringify-able
*/
public emitEvent(domainName: string, eventName: string, parameters?: any[]) {
if (_domains[domainName] && _domains[domainName].events[eventName]) {
this.sendEventMessage(
_eventCount++,
domainName,
eventName,
parameters
);
} else {
console.error("[DomainManager] No such event: " + domainName + "." + eventName);
}
}
/**
* Loads and initializes domain modules using the specified paths. Checks to
* make sure that a module is not loaded/initialized more than once.
*
* @param {Array.<string>} paths The paths to load. The paths can be relative
* to the DomainManager or absolute. However, modules that aren't in core
* won't know where the DomainManager module is, so in general, all paths
* should be absolute.
* @return {boolean} Whether loading succeded. (Failure will throw an exception).
*/
public loadDomainModulesFromPaths(paths: string[], notify: boolean = true): boolean {
paths.forEach((path) => {
const m = require(path);
if (m && m.init) {
if (_initializedDomainModules.indexOf(m) < 0) {
m.init(this);
_initializedDomainModules.push(m); // don't init more than once
}
} else {
throw new Error(`domain at ${path} didn't return an object with 'init' property`);
}
});
if (notify) {
this.emitEvent("base", "newDomains", paths);
}
return true; // if we fail, an exception will be thrown
}
public getDomainDescriptions() {
return _domains;
}
public close() {
process.exit(0);
}
public sendError(message: string) {
this._send("error", { message });
}
public sendCommandResponse(id: number, response: Object | Buffer) {
if (Buffer.isBuffer(response)) {
// Assume the id is an unsigned 32-bit integer, which is encoded as a four-byte header
const header = new Buffer(4);
header.writeUInt32LE(id, 0);
// Prepend the header to the message
const message = Buffer.concat([header, response], response.length + 4);
this._sendBinary(message);
} else {
this._send("commandResponse", { id, response });
}
}
public sendCommandProgress(id: number, message: any) {
this._send("commandProgress", {id, message });
}
public sendCommandError(id: number, message: string, stack?: string) {
this._send("commandError", { id, message, stack });
}
public sendEventMessage(id: number, domain: string, event: string, parameters?: any[]) {
this._send("event", { id, domain, event, parameters });
}
public _receive(message: string) {
let m: ConnectionMessage;
try {
m = JSON.parse(message);
} catch (err) {
console.error(`[DomainManager] Error parsing message json -> ${err.name}: ${err.message}`);
this.sendError(`Unable to parse message: ${message}`);
return;
}
const validId = m.id != null;
const hasDomain = !!m.domain;
const hasCommand = typeof m.command === "string";
if (validId && hasDomain && hasCommand) {
// okay if m.parameters is null/undefined
try {
this.executeCommand(
m.id,
m.domain,
m.command as string,
m.parameters
);
} catch (executionError) {
this.sendCommandError(m.id, errToMessage(executionError), errToString(executionError));
}
} else {
this.sendError(`Malformed message (${validId}, ${hasDomain}, ${hasCommand}): ${message}`);
}
}
public _send(
type: string,
message: ConnectionMessage | ConnectionErrorMessage | CommandResponse | CommandError
) {
try {
process.send && process.send({
type: "receive",
msg: JSON.stringify({ type, message })
});
} catch (e) {
console.error(`[DomainManager] Unable to stringify message: ${e.message}`);
}
}
public _sendBinary(message: Buffer) {
process.send && process.send({
type: "receive",
msg: message,
options: { binary: true, mask: false }
});
}
}
const dm = new DomainManager();
export default dm; | the_stack |
import assert = require('assert');
import blpapi = require('blpapi');
import Promise = require('bluebird');
import _ = require('lodash');
import restify = require('restify');
import bunyan = require('bunyan');
import util = require('util');
import Interface = require('../interface');
import conf = require('../config');
import Subscription = require('../subscription/subscription');
import Session = require('../apisession/session');
import auth = require('./auth');
// Type used for request handlers dispatching, i.e. where the top level request includes some
// query param that we switch on to find the correct handler.
type ActionMap = {
[index: string]: (req: Interface.IOurRequest,
res: Interface.IOurResponse,
next: restify.Next) => any;
};
// Type used for subscription input from request body
type SubscriptionOption = {
correlationId: number;
security: string;
fields: string[];
options?: any;
}
type ISubscription = Interface.ISubscription;
var SUBSCRIPTION_ACTION_MAP: ActionMap = {
'start': onSubscribe,
'stop': onUnsubscribe
};
var AUTH_ACTION_MAP: ActionMap = {
'token': onGetToken,
'authorize': onAuthorize
};
type Properties = {
[index: string]: any;
}
// PRIVATE FUNCTIONS
function getSubscriptionsProp(subscriptions: ISubscription[]): Properties {
var corrIds = subscriptions.map((s: ISubscription): number => {
return s.correlationId;
});
var result: Properties = { 'correlationIds': corrIds };
return result;
}
function validatePollId(session: Interface.IAPISession,
newPollId: number): {
isValid: boolean;
fetchNewData?: boolean;
}
{
if (newPollId === undefined) {
return { isValid: false };
}
// Handle first request
if (session.lastPollId === null) {
session.lastPollId = newPollId;
return { isValid: true,
fetchNewData: true};
}
if (session.lastPollId === session.lastSuccessPollId) {
// Valid Poll Id. Poll old data
if (session.lastPollId === newPollId) {
session.lastPollId = newPollId;
return { isValid: true,
fetchNewData: false};
}
// Valid Poll Id. Poll new data
else if ((session.lastPollId + 1) === newPollId) {
session.lastPollId = newPollId;
return { isValid: true,
fetchNewData: true};
}
else {
return { isValid: false };
}
}
else {
// Valid Poll Id. Poll new data
if (session.lastPollId === newPollId) {
session.lastPollId = newPollId;
return { isValid: true,
fetchNewData: true};
}
else {
return { isValid: false };
}
}
}
function startBuffers(subscriptions: ISubscription[]): Object[]
{
var buffers: Object[] = [];
// Check if we have new data for any subscriptions
var hasNewData: boolean = _.some(subscriptions, (sub: ISubscription): boolean => {
return !sub.buffer.isEmpty();
});
if (hasNewData) { // Start a new buffer for every subscription and return back the new data
subscriptions.forEach((sub: ISubscription): void => {
var buff: Interface.IBufferedData<Object> = sub.buffer.startNewBuffer();
if (buff.buffer.length) {
buffers.push({
'correlationId': sub.correlationId,
'data': buff.buffer,
'missed_ticks': buff.overflow
});
}
});
}
return buffers;
}
function getOldBuffers(subscriptions: Interface.IMap<ISubscription>): Object[]
{
var buffers: Object[] = [];
subscriptions.forEach((sub: ISubscription): boolean => {
if (!sub.buffer.isEmpty(1)) { // Check if old buffer is empty
var buff: Interface.IBufferedData<Object> = sub.buffer.getBuffer(1);
buffers.push({
'correlationId': sub.correlationId,
'data': buff.buffer,
'missed_ticks': buff.overflow
});
}
return true;
});
return buffers;
}
// Used by routes that use the `action` query param to select the actual request handler.
function dispatchAction(actionMap: ActionMap,
req: Interface.IOurRequest,
res: Interface.IOurResponse,
next: restify.Next): void
{
var action = req.query.action;
if (!(action in actionMap)) {
var errorString = util.format('Invalid action: %s', action);
req.log.debug(errorString);
return next(new restify.BadRequestError(errorString));
}
actionMap[action](req, res, next);
}
function doRequest(uri: string,
requestName: string,
identity: blpapi.Identity,
req: Interface.IOurRequest,
res: Interface.IOurResponse,
next: restify.Next): void
{
req.blpSession.request(uri,
requestName,
req.body,
identity,
(err: Error, data: any, last: boolean): void => {
if (err) {
req.log.error(err, 'Request error.');
return next(res.sendError(err));
}
res.sendChunk(data);
if (last) {
res.sendEnd(0, 'OK');
return next();
}
});
}
function onSubscribe(req: Interface.IOurRequest,
res: Interface.IOurResponse,
next: restify.Next): void
{
// Validate input options
if (!_.isArray(req.body) || !req.body.length) {
return next(new restify.BadRequestError('Invalid subscription request body.'));
}
var errMessage: string;
var isValid: boolean = _.every(req.body, (s: SubscriptionOption): boolean => {
if (!_.has(s, 'correlationId') ||
!_.isNumber(s.correlationId) ||
!_.has(s, 'security') ||
!_.isString(s.security) ||
!_.has(s, 'fields') ||
!_.isArray(s.fields))
{
errMessage = 'Invalid subscription option.';
return false;
}
if (req.apiSession.receivedSubscriptions.has(s.correlationId)) {
errMessage = util.format('Correlation Id %d already exist.', s.correlationId);
return false;
}
return true;
});
if (!isValid) {
req.log.debug(errMessage);
return next(new restify.BadRequestError(errMessage));
}
if (req.body.length !== _(req.body).pluck('correlationId').uniq().value().length) {
errMessage = 'Duplicate correlation Id received.';
req.log.debug(errMessage);
return next(new restify.BadRequestError(errMessage));
}
// Create Subscription object array and add event listeners
var subscriptions: ISubscription[] = _.map(req.body, (s: SubscriptionOption): ISubscription => {
var sub = new Subscription(s.correlationId,
s.security,
s.fields,
s.options,
conf.get('longpoll.maxbuffersize'));
// Add event listener for each subscription
sub.on('data', (data: any): void => {
req.log.debug({data: {cid: sub.correlationId, time: process.hrtime()}},
'Data received');
// Buffer the current data
sub.buffer.pushValue(data);
});
// Must subscribe to the 'error' event; otherwise EventEmitter will throw an exception
// that was occurring from the underlying blpapi.Session. It is the assumed that the
// blpapi.Session properly cleans up the subscription (i.e., 'unsubscribe()' should not
// be called).
sub.on('error', (err: Error): void => {
req.log.error(err, 'blpapi.Session subscription error occurred.');
sub.removeAllListeners();
req.apiSession.activeSubscriptions.delete(sub.correlationId);
req.apiSession.receivedSubscriptions.delete(sub.correlationId);
});
req.apiSession.receivedSubscriptions.set(sub.correlationId, sub);
return sub;
});
// Subscribe user request through blpapi-wrapper
req.blpSession.subscribe(subscriptions, req.identity)
.then((): void => {
if (!req.apiSession.expired) {
subscriptions.forEach((s: ISubscription): void => {
req.apiSession.activeSubscriptions.set(s.correlationId, s);
});
req.log.debug('Subscribed');
res.sendWhole(0, 'Subscribed', getSubscriptionsProp(subscriptions));
} else { // Unsubscribe if session already expires
req.blpSession.unsubscribe(subscriptions);
subscriptions.forEach((s: ISubscription): void => {
s.removeAllListeners();
req.apiSession.receivedSubscriptions.delete(s.correlationId);
});
req.log.debug('Unsubscribed all active subscriptions');
}
return next();
})
.catch((err: Error): any => {
subscriptions.forEach((s: ISubscription): void => {
req.apiSession.receivedSubscriptions.delete(s.correlationId);
s.removeAllListeners();
});
req.log.error(err, 'Request error.');
return next(new restify.InternalError(err.message));
});
}
function onUnsubscribe(req: Interface.IOurRequest,
res: Interface.IOurResponse,
next: restify.Next): void
{
if (!req.apiSession.activeSubscriptions.size) {
req.log.debug('No active subscriptions.');
return next(new restify.BadRequestError('No active subscriptions.'));
}
var subscriptions: ISubscription[] = [];
// If no correlation Id specified,
// the default behavior is to unsubscribe all active subscriptions
if (!req.body) {
subscriptions = req.apiSession.activeSubscriptions.values();
} else {
// If we do receive req.body object, first check if it is valid(empty list is INVALID)
if (!_.has(req.body, 'correlationIds') ||
!_.isArray(req.body.correlationIds) ||
!req.body.correlationIds.length) {
req.log.debug('Invalid unsubscribe data.');
return next(new restify.InvalidArgumentError('Invalid unsubscribe data.'));
}
// Next, validate all correlation Ids
// Will error if any invalid correlation Id received
var errMessage: string;
var isAllValid = _.every(_.uniq(req.body.correlationIds), (cid: number): boolean => {
if (req.apiSession.activeSubscriptions.has(cid)) {
subscriptions.push(req.apiSession.activeSubscriptions.get(cid));
return true;
}
errMessage = util.format('Invalid correlation Id %d received.', cid);
return false;
});
if (!isAllValid) {
req.log.debug(errMessage);
return next(new restify.InvalidArgumentError(errMessage));
}
}
try {
req.blpSession.unsubscribe(subscriptions);
var result: Object[] = startBuffers(subscriptions);
subscriptions.forEach((sub: ISubscription): void => {
sub.removeAllListeners();
req.apiSession.activeSubscriptions.delete(sub.correlationId);
req.apiSession.receivedSubscriptions.delete(sub.correlationId);
});
req.log.debug({ activeSubscriptions:
req.apiSession.activeSubscriptions.size },
'Unsubscribed.');
// Reset poll Id to null if all subscriptions get unsubscribed
if (!req.apiSession.receivedSubscriptions.size) {
req.apiSession.lastPollId = req.apiSession.lastSuccessPollId = null;
}
res.sendChunk(result);
res.sendOtherProp(getSubscriptionsProp(subscriptions));
res.sendEnd(0, 'Unsubscribed Successfully');
return next();
} catch (err) {
req.log.error(err, 'Unsubscription error');
return next(new restify.InternalError(err.message));
}
}
function onGetToken(req: Interface.IOurRequest,
res: Interface.IOurResponse,
next: restify.Next): void
{
doRequest('//blp/apiauth', 'AuthorizationTokenRequest', null /* identity */, req, res, next);
}
function onAuthorize(req: Interface.IOurRequest,
res: Interface.IOurResponse,
next: restify.Next): void
{
if (!_.has(req, 'clientCert')) {
// We currently use the clientCert as the key when managing identities, so authorization
// requests require you to have one.
var errorString = 'Authorizing requires a client cert';
req.log.debug(errorString);
return next(new restify.BadRequestError(errorString));
}
req.blpSession.authorizeUser(req.body)
.then((identity: blpapi.Identity): void => {
auth.setIdentity(req, identity);
res.sendWhole(0, 'OK');
return next();
})
.catch((err: Error): void => {
return next(res.sendError(err));
});
}
// PUBLIC FUNCTIONS
export function verifyContentType(req: Interface.IOurRequest,
res: Interface.IOurResponse,
next: restify.Next): void
{
// Check the content type of the request
// TODO: configure acceptable content-type
if (!req.is('application/json')) {
req.log.debug('Unsupported Content-Type.');
return next(new restify.UnsupportedMediaTypeError('Unsupported Content-Type.'));
}
return next();
}
export function elevateRequest (req: Interface.IOurRequest,
res: Interface.IOurResponse,
next: restify.Next): void
{
var chunkIndex: number = 0;
var otherProperties: Properties = {};
/**
* This is called each time data is added to the response.
* @param isEnd Whether this is the last time this will be called for this http request.
* @returns {string} Text that should be added to the response before the caller adds its data.
*/
function prepareResponseText(isEnd: boolean): string {
var text: string;
if (1 === ++chunkIndex) {
// This is the first time we're adding response text. Set the headers as well.
res.statusCode = 200;
res.setHeader('content-type', 'application/json');
// If isEnd is true, then we aren't actually adding a data array to the http response.
text = isEnd ? '{' : '{"data":[';
} else {
// If isEnd is true, we must have previously added data to the response, so we need to
// close the data array.
text = isEnd ? '],' : ',';
}
assert(text, 'Response text was not set');
return text;
}
function stringifyPair ( key: string, value: any ): string {
return '"' + key.replace(/'/g, '\\$&') + '":' + JSON.stringify(value);
}
// Right now we only use restify.InternalError(500)
// TODO: Add error type differentiation
function createError(err: Error): any {
return new restify.InternalError(err.message);
}
function preparePropertiesText(properties: Properties): string {
return _.reduce(properties,
(text: string, value: string, property: string): string => {
return text + ',' + stringifyPair(property, value);
},
'' /* initial value */);
}
function prepareEndText(status: number,
message: string,
properties: Properties): string {
return util.format('%s%s,%s%s}',
prepareResponseText(true),
stringifyPair('status', status),
stringifyPair('message', message || ''),
properties ? preparePropertiesText(properties) : '');
}
res.sendChunk = (data: any): void => {
var text = prepareResponseText(false);
res.write(text + JSON.stringify(data));
};
res.sendOtherProp = (properties: Properties): void => {
// For now just cache the additional properties they will be
// bundled into the response in 'sendEnd'.
_.assign(otherProperties, properties);
};
res.sendEnd = (status: number, message: string): void => {
res.end(prepareEndText(status, message, otherProperties));
};
// Generate and send a full response.
res.sendWhole = (status: number,
message: string,
properties?: Properties,
data?: any): void => {
// Make sure we don't interlace calls to this function with
// calls to functions generating only part of the response.
assert(chunkIndex === 0 && _.isEmpty(otherProperties));
var text = '';
if (data) {
text = prepareResponseText(/* isEnd */ false) + JSON.stringify(data);
}
res.end(text + prepareEndText(status, message, properties));
};
res.sendError = (err: Error): void|any => {
// send Error if this is the first chunk
if (chunkIndex === 0) {
return createError(err);
}
// Otherwise, set -1 as status code and error message
return res.sendEnd(-1, err.message);
};
return next();
}
export function onRequest(req: Interface.IOurRequest,
res: Interface.IOurResponse,
next: restify.Next): void
{
assert(req.blpSession, 'blpSession not found');
var uri = util.format('//%s/%s', req.query.ns, req.query.service);
doRequest(uri, req.query.type, req.identity, req, res, next);
}
export function onPollSubscriptions(req: Interface.IOurRequest,
res: Interface.IOurResponse,
next: restify.Next): void
{
assert(req.apiSession, 'apiSession not found');
if (!req.apiSession.activeSubscriptions.size) {
req.log.debug('No active subscriptions.');
return next(new restify.BadRequestError('No active subscriptions.'));
}
var interval: NodeJS.Timer;
var frequency: number = conf.get('longpoll.pollfrequency');
var timeOut: number = conf.get('longpoll.polltimeout');
var pollId: number = _.parseInt(req.query.pollid);
var validateIdResult = validatePollId(req.apiSession, pollId);
if (!validateIdResult.isValid) {
req.log.debug('Invalid Poll Id ' + req.query.pollid);
return next(new restify.InvalidArgumentError('Invalid Poll Id '
+ req.query.pollid));
}
var p: Promise<Object[]>;
if (validateIdResult.fetchNewData) {
// For fetching new data
p = ((): Promise<Object[]> => {
req.log.debug('Long polling...');
var buff = startBuffers(req.apiSession.activeSubscriptions.values());
if (buff.length) {
req.apiSession.lastSuccessPollId = pollId;
req.log.debug('Got data. Sent back.');
return Promise.resolve(buff);
}
return (new Promise<Object[]>((resolve: (result: Object[]) => void,
reject: (error: Error) => void): void => {
interval = setInterval(
(): void => {
if (!req.apiSession.activeSubscriptions.size) {
clearInterval(interval);
reject(new Error('No active subscriptions'));
}
var buffer = startBuffers(req.apiSession.activeSubscriptions.values());
if (buffer.length) {
clearInterval(interval);
req.apiSession.lastSuccessPollId = pollId;
req.log.debug('Got data. Sent back.');
resolve(buffer);
}
},
frequency);
}))
.timeout(timeOut)
.cancellable();
})();
} else {
// For fetching old data
p = ((): Promise<Object[]> => {
req.log.debug('Old poll id received. Resent last sent data.');
return Promise.resolve(getOldBuffers(req.apiSession.activeSubscriptions));
})();
}
p.then((result: Object[]): void => {
res.sendChunk(result);
res.sendEnd(0, 'OK');
return next();
})
.catch(Promise.TimeoutError, (err: Error): any => {
if (interval) {
clearInterval(interval);
}
var message: string = 'No subscription data within ' + timeOut + 'ms.';
req.log.debug(message);
return next(new restify.RequestTimeoutError(message));
})
.catch(Promise.CancellationError, (err: Error): any => {
req.log.debug('OnPoll promise get canceled');
return next();
})
.catch((err: Error): any => {
if (interval) {
clearInterval(interval);
}
req.log.error(err, 'Poll error.');
return next(new restify.InternalError(err.message));
});
// connection was terminated before response.end() was called
res.once('close', (): void => {
if (interval) {
clearInterval(interval);
}
if (p.isCancellable()) {
p.cancel();
}
});
}
export function getSubscriptionActions(): string[]
{
return _.keys(SUBSCRIPTION_ACTION_MAP);
}
export function onChangeSubscriptions(req: Interface.IOurRequest,
res: Interface.IOurResponse,
next: restify.Next): void
{
dispatchAction(SUBSCRIPTION_ACTION_MAP, req, res, next);
}
export function getAuthActions(): string[]
{
return _.keys(AUTH_ACTION_MAP);
}
export function onAuth(req: Interface.IOurRequest,
res: Interface.IOurResponse,
next: restify.Next): void
{
dispatchAction(AUTH_ACTION_MAP, req, res, next);
} | the_stack |
import { Resource } from '../resource';
import { JsonRipper } from './json-ripper';
import { DocumentCollection } from '../document-collection';
import { TestFactory } from '../tests/factories/test-factory';
describe('JsonRipper for resources', () => {
let book = TestFactory.getBook('5');
book.attributes.title = 'Fahrenheit 451';
book.addRelationship(TestFactory.getAuthor('2'), 'author');
// @todo maxi: factory dont work?
// book.addRelationship(TestFactory.getPhoto('2'));
// book.addRelationship(TestFactory.getPhoto('1'));
it('A resource is converted to objects for a DataProvider', () => {
let mocked_service_data: { [key: string]: any } = { parseToServer: false };
spyOn(Resource.prototype, 'getService').and.returnValue(mocked_service_data);
let obj = JsonRipper.toResourceElements('some.key', book);
expect(obj.length).toBe(1);
expect(obj[0].key).toBe('some.key');
expect(obj[0].content.data).toMatchObject({
attributes: { title: 'Fahrenheit 451' },
id: '5',
type: 'books',
relationships: {
author: {
data: { id: '2', type: 'authors' }
}
}
});
// hasManyRelationships
// expect(obj[2].content.data.relationships.books.data.length).toBe(2);
// expect(Object.keys(obj[2].content.data.relationships.books.data[0]).length).toBe(2); // id and type
});
it('A resource with include is converted to objects for a DataProvider', () => {
let mocked_service_data: { [key: string]: any } = { parseToServer: false };
spyOn(Resource.prototype, 'getService').and.returnValue(mocked_service_data);
let obj = JsonRipper.toResourceElements('some.key', book, ['author']);
expect(obj.length).toBe(2);
expect(obj[0].key).toBe('some.key');
expect(obj[1].content.data).toMatchObject({
id: '2',
type: 'authors',
attributes: {
name: /.+/
},
relationships: {}
});
});
it('A ripped resource saved via DataProvider is converted to a Json', async done => {
let mocked_service_data: { [key: string]: any } = { parseToServer: false };
spyOn(Resource.prototype, 'getService').and.returnValue(mocked_service_data);
let jsonRipper = new JsonRipper();
await jsonRipper.saveResource(book);
let json = await jsonRipper.getResource(JsonRipper.getResourceKey(book));
expect(json.data).toMatchObject({
attributes: { title: /.+/ },
id: '5',
type: 'books',
relationships: {
author: {
data: { id: /.+/, type: 'authors' }
}
}
});
done();
}, 500);
it('A ripped resource maintain cache_last_update property', async () => {
let mocked_service_data: { [key: string]: any } = { parseToServer: false };
spyOn(Resource.prototype, 'getService').and.returnValue(mocked_service_data);
let jsonRipper = new JsonRipper();
await jsonRipper.saveResource(book);
let json = await jsonRipper.getResource(JsonRipper.getResourceKey(book));
expect(json.data.cache_last_update).toBeGreaterThanOrEqual(Date.now() - 100);
});
it('A ripped resource with include saved via DataProvider is converted to a Json', async done => {
let mocked_service_data: { [key: string]: any } = { parseToServer: false };
spyOn(Resource.prototype, 'getService').and.returnValue(mocked_service_data);
let jsonRipper = new JsonRipper();
await jsonRipper.saveResource(book, ['author']);
let json = await jsonRipper.getResource(JsonRipper.getResourceKey(book), ['author']);
expect(json.included.length).toEqual(1);
expect(json.included[0]).toMatchObject({
id: '2',
type: 'authors',
attributes: {},
relationships: {}
});
done();
}, 500);
it('A ripped resource with hasOne = null saved via DataProvider is converted to a Json', async () => {
let mocked_service_data: { [key: string]: any } = { parseToServer: false };
spyOn(Resource.prototype, 'getService').and.returnValue(mocked_service_data);
let jsonRipper = new JsonRipper();
book.relationships.author.data = null;
await jsonRipper.saveResource(book, ['author']);
let json = await jsonRipper.getResource(JsonRipper.getResourceKey(book), ['author']);
expect(json.included.length).toEqual(0);
expect(json.data.relationships.author.data).toEqual(null);
// expect(json.included[0]).toMatchObject({
// id: '2',
// type: 'authors',
// attributes: {},
// relationships: {}
// });
});
it('Requesting DataProvider not cached resource thrown an error', done => {
let jsonRipper = new JsonRipper();
jsonRipper
.getResource('extrange_type.id')
.then()
.catch(data => {
done();
});
}, 50);
});
describe('JsonRipper for collections', () => {
let authors = new DocumentCollection();
// TODO: remove books include in next line when toObject gets fixed (call jsonripper in non provided service)
authors.data.push(TestFactory.getAuthor('2', ['books']));
let author1 = TestFactory.getAuthor('1', ['books']);
author1.attributes.name = 'Ray Bradbury';
authors.data.push(author1);
author1.relationships.books.data[0].id = '1';
author1.relationships.books.data[1].id = '2';
let book1 = author1.relationships.books.data[0];
book1.addRelationship(author1, 'author');
/* Is private now
it('A collection is converted to objects for a DataProvider', () => {
spyOn(Resource.prototype, 'getService').and.returnValue({});
let obj = JsonRipper.collectionToElement('some/url', authors);
expect(obj.length).toBe(3);
expect(obj[0].key).toBe('some/url');
expect(obj[0].content.keys).toMatchObject(['authors.2', 'authors.1']); // unsorted resources is intentional
expect(obj[2].content.data).toMatchObject({
attributes: { name: 'Ray Bradbury' },
id: '1',
type: 'authors',
relationships: {
books: {
data: [{ id: '1', type: 'books' }, { id: '2', type: 'books' }]
}
}
});
// hasManyRelationships
expect(obj[2].content.data.relationships.books.data.length).toBe(2);
expect(Object.keys(obj[2].content.data.relationships.books.data[0]).length).toBe(2); // id and type
});
it('A collection with include is converted to objects for a DataProvider', () => {
spyOn(Resource.prototype, 'getService').and.returnValue({});
let obj = JsonRipper.collectionToElement('some/url/include', authors, ['books']);
expect(obj.length).toBe(5);
expect(obj[0].key).toBe('some/url/include');
expect(obj[0].content.keys).toMatchObject(['authors.2', 'authors.1']);
expect(obj[4].content.data).toMatchObject({
id: '2',
type: 'books',
attributes: {},
relationships: {}
});
});
*/
it('A ripped collection saved via DataProvider is converted to a Json', async done => {
spyOn(Resource.prototype, 'getService').and.returnValue({});
let jsonRipper = new JsonRipper();
jsonRipper.saveCollection('some/url', authors);
let json = await jsonRipper.getCollection('some/url');
expect(json.data.length).toEqual(2);
expect(json.data[1]).toMatchObject({
attributes: { name: 'Ray Bradbury' },
id: '1',
type: 'authors',
relationships: {
books: {
data: [{ id: '1', type: 'books' }, { id: '2', type: 'books' }]
}
}
});
done();
});
it('A ripped collection maintain cache_last_update property', async () => {
spyOn(Resource.prototype, 'getService').and.returnValue({});
let jsonRipper = new JsonRipper();
jsonRipper.saveCollection('some/url', authors);
let json = await jsonRipper.getCollection('some/url');
expect(json.cache_last_update).toBeGreaterThanOrEqual(Date.now() - 100);
});
it('A ripped collection with include saved via DataProvider is converted to a Json', async () => {
spyOn(Resource.prototype, 'getService').and.returnValue({});
let jsonRipper = new JsonRipper();
jsonRipper.saveCollection('some/url/include', authors, ['books']);
let json = await jsonRipper.getCollection('some/url/include', ['books']);
expect(json.data.length).toEqual(2);
expect(json.included.length).toEqual(4); // @TODO: equal to 2 when books include is removed in describe's first getAuthor
// @TODO: change to json.included[0] when books include is removed in describe's first getAuthor
expect(json.included[2]).toMatchObject({
id: '1',
type: 'books',
attributes: {},
relationships: {
author: {
data: { id: '1', type: 'authors' }
}
}
});
});
it('A ripped collection returns cache_last_update on collection and resources property', async () => {
spyOn(Resource.prototype, 'getService').and.returnValue({});
let jsonRipper = new JsonRipper();
jsonRipper.saveCollection('some/url/include', authors, ['books']);
let json = await jsonRipper.getCollection('some/url/include', ['books']);
expect(json.cache_last_update).toBeGreaterThan(0);
// collection.fill responsability to fill, but ripper need to comunicate last update
expect(json.data[1].cache_last_update).toBeGreaterThan(0);
}, 50);
it('Requesting a DataProvider not cached collection thrown an error', async done => {
let jsonRipper = new JsonRipper();
jsonRipper
.getCollection('some/bad/url')
.then()
.catch(data => {
done();
});
});
}); | the_stack |
// clang-format off
import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js';
import 'chrome://resources/cr_elements/cr_input/cr_input.m.js';
import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js';
import {CrInputElement} from 'chrome://resources/cr_elements/cr_input/cr_input.m.js';
import {keyDownOn, keyEventOn} from 'chrome://resources/polymer/v3_0/iron-test-helpers/mock-interactions.js';
import {assertEquals, assertFalse, assertNotEquals, assertNotReached, assertTrue} from 'chrome://webui-test/chai_assert.js';
import {eventToPromise, flushTasks} from 'chrome://webui-test/test_util.js';
// clang-format on
suite('cr-dialog', function() {
function pressEnter(element: HTMLElement) {
keyEventOn(element, 'keypress', 13, undefined, 'Enter');
}
/**
* Creates and shows two nested cr-dialogs.
* @return An array of 2 dialogs. The first dialog
* is the outer dialog, and the second is the inner dialog.
*/
function createAndShowNestedDialogs(): [CrDialogElement, CrDialogElement] {
document.body.innerHTML = `
<cr-dialog id="outer">
<div slot="title">outer dialog title</div>
<div slot="body">
<cr-dialog id="inner">
<div slot="title">inner dialog title</div>
<div slot="body">body</div>
</cr-dialog>
</div>
</cr-dialog>`;
const outer = document.body.querySelector<CrDialogElement>('#outer');
assertTrue(!!outer);
const inner = document.body.querySelector<CrDialogElement>('#inner');
assertTrue(!!inner);
outer!.showModal();
inner!.showModal();
return [outer!, inner!];
}
setup(function() {
document.body.innerHTML = '';
// Ensure svg, which is referred to by a relative URL, is loaded from
// chrome://resources and not chrome://test
const base = document.createElement('base');
base.href = 'chrome://resources/cr_elements/';
document.head.appendChild(base);
});
test('cr-dialog-open event fires when opened', function() {
document.body.innerHTML = `
<cr-dialog>
<div slot="title">title</div>
<div slot="body">body</div>
</cr-dialog>`;
const dialog = document.body.querySelector('cr-dialog')!;
const whenFired = eventToPromise('cr-dialog-open', dialog);
dialog.showModal();
return whenFired;
});
test('close event bubbles', function() {
document.body.innerHTML = `
<cr-dialog>
<div slot="title">title</div>
<div slot="body">body</div>
</cr-dialog>`;
const dialog = document.body.querySelector('cr-dialog')!;
dialog.showModal();
const whenFired = eventToPromise('close', dialog);
dialog.close();
return whenFired.then(() => {
assertEquals('success', dialog.getNative().returnValue);
});
});
// cr-dialog has to catch and re-fire 'close' events fired from it's native
// <dialog> child to force them to bubble in Shadow DOM V1. Ensure that this
// mechanism does not interfere with nested <cr-dialog> 'close' events.
test('close events not fired from <dialog> are not affected', function() {
const dialogs = createAndShowNestedDialogs();
const outer = dialogs[0];
const inner = dialogs[1];
let whenFired = eventToPromise('close', window);
inner.close();
return whenFired
.then(e => {
// Check that the event's target is the inner dialog.
assertEquals(inner, e.target);
whenFired = eventToPromise('close', window);
outer.close();
return whenFired;
})
.then(e => {
// Check that the event's target is the outer dialog.
assertEquals(outer, e.target);
});
});
test('cancel and close events bubbles when cancelled', function() {
document.body.innerHTML = `
<cr-dialog>
<div slot="title">title</div>
<div slot="body">body</div>
</cr-dialog>`;
const dialog = document.body.querySelector('cr-dialog')!;
dialog.showModal();
const whenCancelFired = eventToPromise('cancel', dialog);
const whenCloseFired = eventToPromise('close', dialog);
dialog.cancel();
return Promise.all([whenCancelFired, whenCloseFired]).then(() => {
assertEquals('', dialog.getNative().returnValue);
});
});
// cr-dialog has to catch and re-fire 'cancel' events fired from it's native
// <dialog> child to force them to bubble in Shadow DOM V1. Ensure that this
// mechanism does not interfere with nested <cr-dialog> 'cancel' events.
test('cancel events not fired from <dialog> are not affected', function() {
const dialogs = createAndShowNestedDialogs();
const outer = dialogs[0];
const inner = dialogs[1];
let whenFired = eventToPromise('cancel', window);
inner.cancel();
return whenFired
.then(e => {
// Check that the event's target is the inner dialog.
assertEquals(inner, e.target);
whenFired = eventToPromise('cancel', window);
outer.cancel();
return whenFired;
})
.then(e => {
// Check that the event's target is the outer dialog.
assertEquals(outer, e.target);
});
});
test('focuses title on show', function() {
document.body.innerHTML = `
<cr-dialog>
<div slot="title">title</div>
<div slot="body"><button>button</button></div>
</cr-dialog>`;
const dialog = document.body.querySelector('cr-dialog')!;
const button = document.body.querySelector('button');
assertNotEquals(dialog, document.activeElement);
assertNotEquals(button, document.activeElement);
dialog.showModal();
assertEquals(dialog, document.activeElement);
assertNotEquals(button, document.activeElement);
});
test('enter keys should trigger action buttons once', function() {
document.body.innerHTML = `
<cr-dialog>
<div slot="title">title</div>
<div slot="body">
<button class="action-button">button</button>
<button id="other-button">other button</button>
</div>
</cr-dialog>`;
const dialog = document.body.querySelector('cr-dialog')!;
const actionButton =
document.body.querySelector<HTMLElement>('.action-button')!;
dialog.showModal();
// MockInteractions triggers event listeners synchronously.
let clickedCounter = 0;
actionButton.addEventListener('click', function() {
clickedCounter++;
});
function simulateEnterOnButton(button: HTMLElement) {
pressEnter(button);
// Also call manually click() since normally this is done by the browser.
button.click();
}
// Enter key on the action button should only fire the click handler once.
simulateEnterOnButton(actionButton);
assertEquals(1, clickedCounter);
// Enter keys on other buttons should be ignored.
clickedCounter = 0;
const otherButton =
document.body.querySelector<HTMLElement>('#other-button');
assertTrue(!!otherButton);
simulateEnterOnButton(otherButton!);
assertEquals(0, clickedCounter);
// Enter keys on the close icon in the top-right corner should be ignored.
pressEnter(dialog.$.close);
assertEquals(0, clickedCounter);
});
test('enter keys find the first non-hidden non-disabled button', function() {
document.body.innerHTML = `
<cr-dialog>
<div slot="title">title</div>
<div slot="body">
<button id="hidden" class="action-button" hidden>hidden</button>
<button class="action-button" disabled>disabled</button>
<button class="action-button" disabled hidden>disabled hidden</button>
<button id="active" class="action-button">active</button>
</div>
</cr-dialog>`;
const dialog = document.body.querySelector('cr-dialog')!;
const hiddenButton = document.body.querySelector<HTMLElement>('#hidden')!;
const actionButton = document.body.querySelector<HTMLElement>('#active')!;
dialog.showModal();
// MockInteractions triggers event listeners synchronously.
hiddenButton.addEventListener('click', function() {
assertNotReached('Hidden button received a click.');
});
let clicked = false;
actionButton.addEventListener('click', function() {
clicked = true;
});
pressEnter(dialog);
assertTrue(clicked);
});
test('enter keys from certain inputs only are processed', function() {
document.body.innerHTML = `
<cr-dialog>
<div slot="title">title</div>
<div slot="body">
<foobar></foobar>
<input type="checkbox">
<input type="text">
<cr-input type="search"></cr-input>
<cr-input type="text"></cr-input>
<div id="withShadow"></div>
<button class="action-button">active</button>
</div>
</cr-dialog>`;
const otherElement = document.body.querySelector<HTMLElement>('foobar')!;
const inputCheckboxElement =
document.body.querySelector<HTMLElement>('input[type="checkbox"]')!;
const inputTextElement =
document.body.querySelector<HTMLElement>('input[type="text"]')!;
const crTextInputElement =
document.body.querySelector<CrInputElement>('cr-input[type="text"]')!;
const crSearchInputElement =
document.body.querySelector<CrInputElement>('cr-input[type="search"]')!;
// Attach a cr-input element nested within another element.
const containerElement = document.body.querySelector('#withShadow')!;
const shadow = containerElement.attachShadow({mode: 'open'});
const crInputNested = document.createElement('cr-input');
shadow.appendChild(crInputNested);
const actionButton = document.body.querySelector('.action-button')!;
// MockInteractions triggers event listeners synchronously.
let clickedCounter = 0;
actionButton.addEventListener('click', function() {
clickedCounter++;
});
// Enter on anything other than cr-input should not be accepted.
pressEnter(otherElement);
assertEquals(0, clickedCounter);
pressEnter(inputCheckboxElement);
assertEquals(0, clickedCounter);
pressEnter(inputTextElement);
assertEquals(0, clickedCounter);
// Enter on a cr-input with type "search" should not be accepted.
pressEnter(crSearchInputElement);
assertEquals(0, clickedCounter);
// Enter on a cr-input with type "text" should be accepted.
pressEnter(crTextInputElement);
assertEquals(1, clickedCounter);
// Enter on a nested <cr-input> should be accepted.
pressEnter(crInputNested);
assertEquals(2, clickedCounter);
});
test('focuses [autofocus] instead of title when present', function() {
document.body.innerHTML = `
<cr-dialog>
<div slot="title">title</div>
<div slot="body"><button autofocus>button</button></div>
</cr-dialog>`;
const dialog = document.body.querySelector('cr-dialog')!;
const button = document.body.querySelector('button');
assertNotEquals(dialog, document.activeElement);
assertNotEquals(button, document.activeElement);
dialog.showModal();
assertNotEquals(dialog, document.activeElement);
assertEquals(button, document.activeElement);
});
// Ensuring that intersectionObserver does not fire any callbacks before the
// dialog has been opened.
test('body scrollable border not added before modal shown', function() {
document.body.innerHTML = `
<cr-dialog>
<div slot="title">title</div>
<div slot="body">body</div>
</cr-dialog>`;
const dialog = document.body.querySelector('cr-dialog')!;
assertFalse(dialog.open);
const bodyContainer = dialog.$$('.body-container');
assertTrue(!!bodyContainer);
const topShadow = dialog.$$('#cr-container-shadow-top');
assertTrue(!!topShadow);
const bottomShadow = dialog.$$('#cr-container-shadow-bottom');
assertTrue(!!bottomShadow);
return flushTasks().then(() => {
assertFalse(topShadow!.classList.contains('has-shadow'));
assertFalse(bottomShadow!.classList.contains('has-shadow'));
});
});
test('dialog body scrollable border when appropriate', function(done) {
document.body.innerHTML = `
<cr-dialog>
<div slot="title">title</div>
<div slot="body">
<div style="height: 100px">tall content</div>
</div>
</cr-dialog>`;
const dialog = document.body.querySelector('cr-dialog')!;
const bodyContainer =
dialog.shadowRoot!.querySelector<HTMLElement>('.body-container');
assertTrue(!!bodyContainer);
const topShadow = dialog.$$('#cr-container-shadow-top');
assertTrue(!!topShadow);
const bottomShadow = dialog.$$('#cr-container-shadow-bottom');
assertTrue(!!bottomShadow);
dialog.showModal(); // Attach the dialog for the first time here.
let observerCount = 0;
// Needs to setup the observer before attaching, since InteractionObserver
// calls callback before MutationObserver does.
const observer = new MutationObserver(function(changes) {
// Only care about class mutations.
if (changes[0]!.attributeName !== 'class') {
return;
}
observerCount++;
switch (observerCount) {
case 1: // Triggered when scrolled to bottom.
assertFalse(bottomShadow!.classList.contains('has-shadow'));
assertTrue(topShadow!.classList.contains('has-shadow'));
bodyContainer!.scrollTop = 0;
break;
case 2: // Triggered when scrolled back to top.
assertTrue(bottomShadow!.classList.contains('has-shadow'));
assertFalse(topShadow!.classList.contains('has-shadow'));
bodyContainer!.scrollTop = 2;
break;
case 3: // Triggered when finally scrolling to middle.
assertTrue(bottomShadow!.classList.contains('has-shadow'));
assertTrue(topShadow!.classList.contains('has-shadow'));
observer.disconnect();
done();
break;
}
});
observer.observe(topShadow!, {attributes: true});
observer.observe(bottomShadow!, {attributes: true});
// Height is normally set via CSS, but mixin doesn't work with innerHTML.
bodyContainer!.style.height = '60px'; // Element has "min-height: 60px".
bodyContainer!.scrollTop = 100;
});
test('dialog `open` attribute updated when Escape is pressed', function() {
document.body.innerHTML = `
<cr-dialog>
<div slot="title">title</div>
</cr-dialog>`;
const dialog = document.body.querySelector('cr-dialog')!;
dialog.showModal();
assertTrue(dialog.open);
assertTrue(dialog.hasAttribute('open'));
const e = new CustomEvent('cancel', {cancelable: true});
dialog.getNative().dispatchEvent(e);
assertFalse(dialog.open);
assertFalse(dialog.hasAttribute('open'));
});
test('dialog cannot be cancelled when `no-cancel` is set', function() {
document.body.innerHTML = `
<cr-dialog no-cancel>
<div slot="title">title</div>
</cr-dialog>`;
const dialog = document.body.querySelector('cr-dialog')!;
dialog.showModal();
assertTrue(dialog.$.close.hidden);
// Hitting escape fires a 'cancel' event. Cancelling that event prevents the
// dialog from closing.
let e = new CustomEvent('cancel', {cancelable: true});
dialog.getNative().dispatchEvent(e);
assertTrue(e.defaultPrevented);
dialog.noCancel = false;
e = new CustomEvent('cancel', {cancelable: true});
dialog.getNative().dispatchEvent(e);
assertFalse(e.defaultPrevented);
});
test('dialog close button shown when showCloseButton is true', function() {
document.body.innerHTML = `
<cr-dialog show-close-button>
<div slot="title">title</div>
</cr-dialog>`;
const dialog = document.body.querySelector('cr-dialog')!;
dialog.showModal();
assertTrue(dialog.open);
assertFalse(dialog.$.close.hidden);
assertEquals('flex', window.getComputedStyle(dialog.$.close).display);
dialog.$.close.click();
assertFalse(dialog.open);
});
test('dialog close button hidden when showCloseButton is false', function() {
document.body.innerHTML = `
<cr-dialog>
<div slot="title">title</div>
</cr-dialog>`;
const dialog = document.body.querySelector('cr-dialog')!;
dialog.showModal();
assertTrue(dialog.$.close.hidden);
assertEquals('none', window.getComputedStyle(dialog.$.close).display);
});
test('keydown should be consumed when the property is true', function() {
document.body.innerHTML = `
<cr-dialog consume-keydown-event>
<div slot="title">title</div>
</cr-dialog>`;
const dialog = document.body.querySelector('cr-dialog')!;
dialog.showModal();
assertTrue(dialog.open);
assertTrue(dialog.consumeKeydownEvent);
function assertKeydownNotReached() {
assertNotReached('keydown event was propagated');
}
document.addEventListener('keydown', assertKeydownNotReached);
return flushTasks().then(() => {
keyDownOn(dialog, 65, undefined, 'a');
keyDownOn(document.body, 65, undefined, 'a');
document.removeEventListener('keydown', assertKeydownNotReached);
});
});
test('keydown should be propagated when the property is false', function() {
document.body.innerHTML = `
<cr-dialog>
<div slot="title">title</div>
</cr-dialog>`;
const dialog = document.body.querySelector('cr-dialog')!;
dialog.showModal();
assertTrue(dialog.open);
assertFalse(dialog.consumeKeydownEvent);
let keydownCounter = 0;
function assertKeydownCount() {
keydownCounter++;
}
document.addEventListener('keydown', assertKeydownCount);
return flushTasks().then(() => {
keyDownOn(dialog, 65, undefined, 'a');
assertEquals(1, keydownCounter);
document.removeEventListener('keydown', assertKeydownCount);
});
});
test('show on attach', () => {
document.body.innerHTML = `
<cr-dialog show-on-attach>
<div slot="title">title</div>
</cr-dialog>`;
const dialog = document.body.querySelector('cr-dialog')!;
assertTrue(dialog.open);
});
}); | the_stack |
import { ConversationModel } from './../../../../models/conversation';
import { ChatManager } from './../../../../chat21-core/providers/chat-manager';
import { ConversationHandlerService } from '../../../../chat21-core/providers/abstract/conversation-handler.service';
import { MessagingService } from './../../../providers/messaging.service';
import { TypingService } from '../../../../chat21-core/providers/abstract/typing.service';
import { TYPE_MSG_TEXT, TYPE_MSG_IMAGE, TYPE_MSG_FILE } from './../../../../chat21-core/utils/constants';
import { Globals } from './../../../utils/globals';
import { Component, ElementRef, EventEmitter, Input, OnInit, Output, SimpleChange, SimpleChanges, OnChanges, ViewChild } from '@angular/core';
import { UploadModel } from '../../../../chat21-core/models/upload';
import { convertColorToRGBA, htmlEntities, replaceEndOfLine } from '../../../../chat21-core/utils/utils';
import { FileDetector } from 'protractor';
import { UploadService } from '../../../../chat21-core/providers/abstract/upload.service';
import { LoggerService } from '../../../../chat21-core/providers/abstract/logger.service';
import { LoggerInstance } from '../../../../chat21-core/providers/logger/loggerInstance';
@Component({
selector: 'chat-conversation-footer',
templateUrl: './conversation-footer.component.html',
styleUrls: ['./conversation-footer.component.scss']
})
export class ConversationFooterComponent implements OnInit, OnChanges {
@Input() conversationWith: string;
@Input() attributes: string;
@Input() senderId: string;
@Input() tenant: string;
@Input() projectid: string;
@Input() channelType: string;
@Input() userFullname: string;
@Input() userEmail: string;
@Input() widgetTitle: string;
@Input() showAttachmentButton: boolean;
// @Input() showWidgetNameInConversation: boolean
@Input() isConversationArchived: boolean;
@Input() hideTextReply: boolean;
@Input() footerMessagePlaceholder: string;
@Input() fileUploadAccept: string;
@Input() stylesMap: Map<string, string>
@Input() translationMap: Map< string, string>;
@Output() onBeforeMessageSent = new EventEmitter();
@Output() onAfterSendMessage = new EventEmitter();
@Output() onChangeTextArea = new EventEmitter<any>();
@Output() onAttachmentButtonClicked = new EventEmitter<any>();
@ViewChild('chat21_file') public chat21_file: ElementRef;
// ========= begin:: send image ======= //
selectedFiles: FileList;
isFilePendingToUpload: Boolean = false;
arrayFilesLoad: Array<any> = [];
isFileSelected: Boolean = false;
HEIGHT_DEFAULT = '20px';
// ========= end:: send image ========= //
// isNewConversation = true;
textInputTextArea: string;
conversationHandlerService: ConversationHandlerService
convertColorToRGBA = convertColorToRGBA;
private logger: LoggerService = LoggerInstance.getInstance()
constructor(public g: Globals,
//public upSvc: UploadService,
private chatManager: ChatManager,
private typingService: TypingService,
private uploadService: UploadService) { }
ngOnInit() {
}
ngOnChanges(changes: SimpleChanges){
if(changes['conversationWith'] && changes['conversationWith'].currentValue !== undefined){
this.conversationHandlerService = this.chatManager.getConversationHandlerByConversationId(this.conversationWith);
}
if(changes['hideTextReply'] && changes['hideTextReply'].currentValue !== undefined){
this.restoreTextArea();
}
}
ngAfterViewInit() {
this.logger.debug('[CONV-FOOTER] --------ngAfterViewInit: conversation-footer-------- ');
}
// ========= begin:: functions send image ======= //
// START LOAD IMAGE //
/**
* carico in locale l'immagine selezionata e apro pop up anteprima
*/
detectFiles(event) {
this.logger.debug('[CONV-FOOTER] detectFiles: ', event);
if (event) {
this.selectedFiles = event.target.files;
this.logger.debug('[CONV-FOOTER] AppComponent:detectFiles::selectedFiles', this.selectedFiles);
// this.onAttachmentButtonClicked.emit(this.selectedFiles)
if (this.selectedFiles == null) {
this.isFilePendingToUpload = false;
} else {
this.isFilePendingToUpload = true;
}
this.logger.debug('[CONV-FOOTER] AppComponent:detectFiles::selectedFiles::isFilePendingToUpload', this.isFilePendingToUpload);
this.logger.debug('[CONV-FOOTER] fileChange: ', event.target.files);
if (event.target.files.length <= 0) {
this.isFilePendingToUpload = false;
} else {
this.isFilePendingToUpload = true;
}
const that = this;
if (event.target.files && event.target.files[0]) {
const nameFile = event.target.files[0].name;
const typeFile = event.target.files[0].type;
const reader = new FileReader();
that.logger.debug('[CONV-FOOTER] OK preload: ', nameFile, typeFile, reader);
reader.addEventListener('load', function () {
that.logger.debug('[CONV-FOOTER] addEventListener load', reader.result);
that.isFileSelected = true;
// se inizia con image
if (typeFile.startsWith('image') && !typeFile.includes('svg')) {
const imageXLoad = new Image;
that.logger.debug('[CONV-FOOTER] onload ', imageXLoad);
imageXLoad.src = reader.result.toString();
imageXLoad.title = nameFile;
imageXLoad.onload = function () {
that.logger.debug('[CONV-FOOTER] onload immagine');
// that.arrayFilesLoad.push(imageXLoad);
const uid = (new Date().getTime()).toString(36); // imageXLoad.src.substring(imageXLoad.src.length - 16);
that.arrayFilesLoad[0] = { uid: uid, file: imageXLoad, type: typeFile };
that.logger.debug('[CONV-FOOTER] OK: ', that.arrayFilesLoad[0]);
// INVIO MESSAGGIO
that.loadFile();
};
} else {
that.logger.debug('[CONV-FOOTER] onload file');
const fileXLoad = {
src: reader.result.toString(),
title: nameFile
};
// that.arrayFilesLoad.push(imageXLoad);
const uid = (new Date().getTime()).toString(36); // imageXLoad.src.substring(imageXLoad.src.length - 16);
that.arrayFilesLoad[0] = { uid: uid, file: fileXLoad, type: typeFile };
that.logger.debug('[CONV-FOOTER] OK: ', that.arrayFilesLoad[0]);
// INVIO MESSAGGIO
that.loadFile();
}
}, false);
if (event.target.files[0]) {
reader.readAsDataURL(event.target.files[0]);
that.logger.debug('[CONV-FOOTER] reader-result: ', event.target.files[0]);
}
}
}
}
loadFile() {
this.logger.debug('[CONV-FOOTER] that.fileXLoad: ', this.arrayFilesLoad);
// al momento gestisco solo il caricamento di un'immagine alla volta
if (this.arrayFilesLoad[0] && this.arrayFilesLoad[0].file) {
const fileXLoad = this.arrayFilesLoad[0].file;
const uid = this.arrayFilesLoad[0].uid;
const type = this.arrayFilesLoad[0].type;
this.logger.debug('[CONV-FOOTER] that.fileXLoad: ', type);
let metadata;
if (type.startsWith('image') && !type.includes('svg')) {
metadata = {
'name': fileXLoad.title,
'src': fileXLoad.src,
'width': fileXLoad.width,
'height': fileXLoad.height,
'type': type,
'uid': uid
};
} else {
metadata = {
'name': fileXLoad.title,
'src': fileXLoad.src,
'type': type,
'uid': uid
};
}
this.logger.debug('[CONV-FOOTER] metadata -------> ', metadata);
// this.scrollToBottom();
// 1 - aggiungo messaggio localmente
// this.addLocalMessageImage(metadata);
// 2 - carico immagine
const file = this.selectedFiles.item(0);
this.onAttachmentButtonClicked.emit({attachments: [{metadata, file}], message: this.textInputTextArea}) //GABBBBBBBB
this.restoreTextArea();
this.chat21_file.nativeElement.value = ''; //BUG-FIXED: allow you to re-load the same previous file
// this.uploadSingle(metadata, file);
// this.isSelected = false;
}
}
/**
*
*/
uploadSingle(metadata, file, messageText?: string) {
const that = this;
const send_order_btn = <HTMLInputElement>document.getElementById('chat21-start-upload-doc');
send_order_btn.disabled = true;
that.logger.debug('[CONV-FOOTER] AppComponent::uploadSingle::', metadata, file);
// const file = this.selectedFiles.item(0);
const currentUpload = new UploadModel(file);
// console.log(currentUpload.file);
// const uploadTask = this.upSvc.pushUpload(currentUpload);
// uploadTask.then(snapshot => {
// return snapshot.ref.getDownloadURL(); // Will return a promise with the download link
// }).then(downloadURL => {
// that.logger.debug('[CONV-FOOTER] AppComponent::uploadSingle:: downloadURL', downloadURL]);
// that.g.wdLog([`Successfully uploaded file and got download link - ${downloadURL}`]);
// metadata.src = downloadURL;
// let type_message = TYPE_MSG_TEXT;
// let message = 'File: ' + metadata.src;
// if (metadata.type.startsWith('image')) {
// type_message = TYPE_MSG_IMAGE;
// message = ''; // 'Image: ' + metadata.src;
// }
// that.sendMessage(message, type_message, metadata);
// that.isFilePendingToUpload = false;
// // return downloadURL;
// }).catch(error => {
// // Use to signal error if something goes wrong.
// console.error(`AppComponent::uploadSingle:: Failed to upload file and get link - ${error}`);
// });
// this.resetLoadImage();
this.uploadService.upload(this.senderId, currentUpload).then(downloadURL => {
that.logger.debug('[CONV-FOOTER] AppComponent::uploadSingle:: downloadURL', downloadURL);
that.logger.debug(`[CONV-FOOTER] Successfully uploaded file and got download link - ${downloadURL}`);
metadata.src = downloadURL;
let type_message = TYPE_MSG_TEXT;
// let message = 'File: ' + metadata.src;
let message = `[${metadata.name}](${metadata.src})`
if (metadata.type.startsWith('image') && !metadata.type.includes('svg')) {
type_message = TYPE_MSG_IMAGE;
// message = '';
message = messageText
} else if ((metadata.type.startsWith('image') && metadata.type.includes('svg')) || !metadata.type.startsWith('image')){
type_message = TYPE_MSG_FILE
// type_message = metadata.type
message = message + '\n' + messageText
} else if (!metadata.type.startsWith('image')){
type_message = TYPE_MSG_FILE
// type_message = metadata.type
message = message + '\n' + messageText
}
that.sendMessage(message, type_message, metadata);
that.chat21_file.nativeElement.value = ''; //BUG-FIXED: allow you to re-load the same previous file
that.isFilePendingToUpload = false;
// return downloadURL;
}).catch(error => {
// Use to signal error if something goes wrong.
that.logger.error(`[CONV-FOOTER] uploadSingle:: Failed to upload file and get link - ${error}`);
that.isFilePendingToUpload = false;
});
that.logger.debug('[CONV-FOOTER] reader-result: ', file);
}
/**
* invio del messaggio
* @param msg
* @param type
* @param metadata
* @param additional_attributes
*/
sendMessage(msg: string, type: string, metadata?: any, additional_attributes?: any) { // sponziello
(metadata) ? metadata = metadata : metadata = '';
this.logger.debug('[CONV-FOOTER] SEND MESSAGE: ', msg, type, metadata, additional_attributes);
if (msg && msg.trim() !== '' || type === TYPE_MSG_IMAGE || type === TYPE_MSG_FILE ) {
// msg = htmlEntities(msg);
// msg = replaceEndOfLine(msg);
// msg = msg.trim();
let recipientFullname = this.translationMap.get('GUEST_LABEL');
// sponziello: adds ADDITIONAL ATTRIBUTES TO THE MESSAGE
const g_attributes = this.attributes;
// added <any> to resolve the Error occurred during the npm installation: Property 'userFullname' does not exist on type '{}'
const attributes = <any>{};
if (g_attributes) {
for (const [key, value] of Object.entries(g_attributes)) {
attributes[key] = value;
}
}
if (additional_attributes) {
for (const [key, value] of Object.entries(additional_attributes)) {
attributes[key] = value;
}
}
// fine-sponziello
// console.log('this.conversationswith', this.conversationWith)
// this.conversationHandlerService = this.chatManager.getConversationHandlerByConversationId(this.conversationWith)
const senderId = this.senderId;
const projectid = this.projectid;
const channelType = this.channelType;
const userFullname = this.userFullname;
const userEmail = this.userEmail;
// const showWidgetNameInConversation = this.showWidgetNameInConversation;
const widgetTitle = this.widgetTitle;
const conversationWith = this.conversationWith;
// this.triggerBeforeSendMessageEvent(
// recipientFullname,
// msg,
// type,
// metadata,
// conversationWith,
// recipientFullname,
// attributes,
// projectid,
// channelType
// );
if (userFullname) {
recipientFullname = userFullname;
} else if (userEmail) {
recipientFullname = userEmail;
} else if (attributes && attributes['userFullname']) {
recipientFullname = attributes['userFullname'];
} else {
recipientFullname = this.translationMap.get('GUEST_LABEL');
}
// if (showWidgetNameInConversation && showWidgetNameInConversation === true) {
// recipientFullname += ' - ' + widgetTitle;
// }
this.onBeforeMessageSent.emit({
senderFullname: recipientFullname,
text: msg,
type: type,
metadata: metadata,
conversationWith: conversationWith,
recipientFullname: recipientFullname,
attributes : attributes,
projectid: projectid,
channelType: channelType
})
const messageSent = this.conversationHandlerService.sendMessage(
msg,
type,
metadata,
conversationWith,
recipientFullname,
senderId,
recipientFullname,
channelType ,
attributes
);
// this.triggerAfterSendMessageEvent(messageSent);
this.onAfterSendMessage.emit(messageSent)
// this.isNewConversation = false;
//TODO-GAB: da rivedere
try {
const target = document.getElementById('chat21-main-message-context') as HTMLInputElement;
target.value = '';
target.style.height = this.HEIGHT_DEFAULT;
// console.log('target.style.height: ', target.style.height);
} catch (e) {
this.logger.error('[CONV-FOOTER] > Error :' + e);
}
this.restoreTextArea();
}
}
//MOVED TO TRIGGERHANDLER
// private triggerBeforeSendMessageEvent(senderFullname, text, type, metadata, conversationWith, recipientFullname, attributes, projectid, channel_type) {
// try {
// // tslint:disable-next-line:max-line-length
// const onBeforeMessageSend = new CustomEvent('onBeforeMessageSend', { detail: { senderFullname: senderFullname, text: text, type: type, metadata, conversationWith: conversationWith, recipientFullname: recipientFullname, attributes: attributes, projectid: projectid, channelType: channel_type } });
// const windowContext = this.g.windowContext;
// if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) {
// windowContext.tiledesk.tiledeskroot.dispatchEvent(onBeforeMessageSend);
// this.g.windowContext = windowContext;
// } else {
// this.el.nativeElement.dispatchEvent(onBeforeMessageSend);
// }
// } catch (e) {
// this.logger.debug('[CONV-FOOTER] > Error :' + e]);
// }
// }
//MOVED TO TRIGGERHANDLER
// private triggerAfterSendMessageEvent(message) {
// try {
// // tslint:disable-next-line:max-line-length
// const onAfterMessageSend = new CustomEvent('onAfterMessageSend', { detail: { message: message } });
// const windowContext = this.g.windowContext;
// if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) {
// windowContext.tiledesk.tiledeskroot.dispatchEvent(onAfterMessageSend);
// this.g.windowContext = windowContext;
// } else {
// this.el.nativeElement.dispatchEvent(onAfterMessageSend);
// }
// } catch (e) {
// this.logger.debug('[CONV-FOOTER] > Error :' + e]);
// }
// }
private restoreTextArea() {
// that.logger.debug('[CONV-FOOTER] AppComponent:restoreTextArea::restoreTextArea');
this.resizeInputField();
const textArea = (<HTMLInputElement>document.getElementById('chat21-main-message-context'));
this.textInputTextArea = ''; // clear the textarea
if (textArea) {
textArea.value = ''; // clear the textarea
textArea.placeholder = this.translationMap.get('LABEL_PLACEHOLDER'); // restore the placholder
this.logger.debug('[CONV-FOOTER] AppComponent:restoreTextArea::restoreTextArea::textArea:', 'restored');
} else {
this.logger.error('[CONV-FOOTER] restoreTextArea::textArea:', 'not restored');
}
this.setFocusOnId('chat21-main-message-context');
}
/**
* ridimensiona la textarea
* chiamato ogni volta che cambia il contenuto della textarea
* imposto stato 'typing'
*/
resizeInputField() {
try {
const target = document.getElementById('chat21-main-message-context') as HTMLInputElement;
// tslint:disable-next-line:max-line-length
// that.logger.debug('[CONV-FOOTER] H:: this.textInputTextArea', (document.getElementById('chat21-main-message-context') as HTMLInputElement).value , target.style.height, target.scrollHeight, target.offsetHeight, target.clientHeight);
target? target.style.height = '100%': null;
if (target && target.value === '\n') {
target.value = '';
target.style.height = this.HEIGHT_DEFAULT;
} else if (target && target.scrollHeight > target.offsetHeight) {
target.style.height = target.scrollHeight + 2 + 'px';
target.style.minHeight = this.HEIGHT_DEFAULT;
} else if (target) {
// that.logger.debug('[CONV-FOOTER] PASSO 3');
target.style.height = this.HEIGHT_DEFAULT;
// segno sto scrivendo
// target.offsetHeight - 15 + 'px';
}
//this.setWritingMessages(target.value);
this.onChangeTextArea.emit({textAreaEl: target, minHeightDefault: this.HEIGHT_DEFAULT})
} catch (e) {
this.logger.error('[CONV-FOOTER] > Error :' + e);
}
// tslint:disable-next-line:max-line-length
// that.logger.debug('[CONV-FOOTER] H:: this.textInputTextArea', this.textInputTextArea, target.style.height, target.scrollHeight, target.offsetHeight, target.clientHeight);
}
onTextAreaChange(){
this.resizeInputField()
this.setWritingMessages(this.textInputTextArea)
}
onSendPressed(event) {
this.logger.debug('[CONV-FOOTER] onSendPressed:event', event);
this.logger.debug('[CONV-FOOTER] AppComponent::onSendPressed::isFilePendingToUpload:', this.isFilePendingToUpload);
if (this.isFilePendingToUpload) {
this.logger.debug('[CONV-FOOTER] AppComponent::onSendPressed', 'is a file');
// its a file
this.loadFile();
this.isFilePendingToUpload = false;
// disabilito pulsanti
this.logger.debug('[CONV-FOOTER] AppComponent::onSendPressed::isFilePendingToUpload:', this.isFilePendingToUpload);
} else {
if ( this.textInputTextArea && this.textInputTextArea.length > 0 ) {
this.logger.debug('[CONV-FOOTER] AppComponent::onSendPressed', 'is a message');
// its a message
if (this.textInputTextArea.trim() !== '') {
// that.logger.debug('[CONV-FOOTER] sendMessage -> ', this.textInputTextArea);
// this.resizeInputField();
// this.messagingService.sendMessage(msg, TYPE_MSG_TEXT);
// this.setDepartment();
// this.textInputTextArea = replaceBr(this.textInputTextArea);
this.sendMessage(this.textInputTextArea, TYPE_MSG_TEXT);
// this.restoreTextArea();
}
// restore the text area
// this.restoreTextArea();
}
}
}
setFocusOnId(id) {
setTimeout(function () {
const textarea = document.getElementById(id);
if (textarea) {
// that.logger.debug('[CONV-FOOTER] 1--------> FOCUSSSSSS : ', textarea);
textarea.setAttribute('value', ' ');
textarea.focus();
}
}, 500);
}
removeFocusOnId(id){
const textarea = document.getElementById(id);
if (textarea) {
textarea.blur()
}
}
/**
*
* @param str
*/
setWritingMessages(str) {
//this.messagingService.setWritingMessages(str, this.g.channelType);
this.typingService.setTyping(this.conversationWith, str, this.senderId, this.getUserFUllName() )
}
getUserFUllName(): string {
const userFullName = this.userFullname
if(userFullName){
return userFullName
}else{
return this.translationMap.get('GUEST_LABEL')
}
}
/**
* quando premo un tasto richiamo questo metodo che:
* verifica se è stato premuto 'invio'
* se si azzera testo
* imposta altezza campo come min di default
* leva il focus e lo reimposta dopo pochi attimi
* (questa è una toppa per mantenere il focus e eliminare il br dell'invio!!!)
* invio messaggio
* @param event
*/
onkeypress(event) {
const keyCode = event.which || event.keyCode;
// console.log('keycode', keyCode)
this.textInputTextArea = ((document.getElementById('chat21-main-message-context') as HTMLInputElement).value);
// this.logger.debug('[CONV-FOOTER] onkeypress **************', this.textInputTextArea, keyCode]);
if (keyCode === 13) {
if (this.textInputTextArea && this.textInputTextArea.trim() !== '') {
// that.logger.debug('[CONV-FOOTER] sendMessage -> ', this.textInputTextArea);
// this.resizeInputField();
// this.messagingService.sendMessage(msg, TYPE_MSG_TEXT);
// this.setDepartment();
// this.textInputTextArea = replaceBr(this.textInputTextArea);
this.sendMessage(this.textInputTextArea, TYPE_MSG_TEXT);
// this.restoreTextArea();
}
} else if (keyCode === 9) {
// console.log('TAB pressedddd')
event.preventDefault();
}
}
/**
* HANDLE: cmd+enter, shiftKey+enter, alt+enter, ctrl+enter
* @param event
*/
onkeydown(event){
const keyCode = event.which || event.keyCode;
// metaKey -> COMMAND , shiftKey -> SHIFT, altKey -> ALT, ctrlKey -> CONTROL
if( (event.metaKey || event.shiftKey || event.altKey || event.ctrlKey) && keyCode===13){
event.preventDefault();
this.textInputTextArea += '\r\n';
this.resizeInputField();
}
}
onPaste(event){
this.resizeInputField()
const items = (event.clipboardData || event.originalEvent.clipboardData).items;
let file = null;
this.logger.debug('[CONV-FOOTER] onPaste items ', items);
for (const item of items) {
this.logger.debug('[CONV-FOOTER] onPaste item ', item);
this.logger.debug('[CONV-FOOTER] onPaste item.type ', item.type);
if (item.type.startsWith("image")) {
// SEND TEXT MESSAGE IF EXIST
// if(this.textInputTextArea){
// this.logger.debug('[CONV-FOOTER] onPaste texttt ', this.textInputTextArea);
// this.sendMessage(this.textInputTextArea, TYPE_MSG_TEXT)
// }
try {
this.restoreTextArea();
} catch(e) {
this.logger.error('[CONV-FOOTER] onPaste - error while restoring textArea:',e)
}
this.logger.debug('[CONV-FOOTER] onPaste item.type', item.type);
file = item.getAsFile();
const data = {target: new ClipboardEvent('').clipboardData || new DataTransfer()};
data.target.items.add(new File([file], file.name, { type: file.type }));
this.logger.debug('[CONV-FOOTER] onPaste data', data);
this.logger.debug('[CONV-FOOTER] onPaste file ', file);
this.detectFiles(data)
}
}
}
} | the_stack |
import { randomBytes } from "crypto";
import * as path from "path";
import { container } from "tsyringe";
import {
CodeAction,
CodeActionKind,
CodeActionParams,
Connection,
TextEdit,
} from "vscode-languageserver";
import { URI } from "vscode-uri";
import { ISourceFile } from "../../compiler/forest";
import * as utils from "../../compiler/utils/elmUtils";
import { ElmWorkspaceMatcher } from "../../util/elmWorkspaceMatcher";
import { Settings } from "../../util/settings";
import { IDiagnostic, IElmIssue } from "./diagnosticsProvider";
import { ElmDiagnosticsHelper } from "./elmDiagnosticsHelper";
import execa = require("execa");
import { IProgram } from "../../compiler/program";
const ELM_MAKE = "Elm";
export const NAMING_ERROR = "NAMING ERROR";
const RANDOM_ID = randomBytes(16).toString("hex");
export const CODE_ACTION_ELM_MAKE = `elmLS.elmMakeFixer-${RANDOM_ID}`;
export interface IElmCompilerError {
type: string;
errors: IError[];
}
export interface IElmError {
title: string;
type: string;
path: string;
message: (string | IStyledString)[];
}
export interface IError {
path: string | null;
name: string;
problems: IProblem[];
}
export interface IProblem {
title: string;
region: {
start: { line: number; column: number };
end: { line: number; column: number };
};
message: (string | IStyledString)[];
}
export interface IStyledString {
bold: boolean;
underline: boolean;
color: string;
string: string;
}
export class ElmMakeDiagnostics {
private elmWorkspaceMatcher: ElmWorkspaceMatcher<URI>;
private settings: Settings;
private connection: Connection;
constructor() {
this.settings = container.resolve("Settings");
this.connection = container.resolve<Connection>("Connection");
this.elmWorkspaceMatcher = new ElmWorkspaceMatcher((uri) => uri);
}
public createDiagnostics = async (
sourceFile: ISourceFile,
): Promise<Map<string, IDiagnostic[]>> => {
const filePath = URI.parse(sourceFile.uri);
const program = this.elmWorkspaceMatcher.getProgramFor(filePath);
return await this.checkForErrors(program, sourceFile).then((issues) => {
return issues.length === 0
? new Map([[filePath.toString(), []]])
: ElmDiagnosticsHelper.issuesToDiagnosticMap(
issues,
program.getRootPath(),
);
});
};
public onCodeAction(params: CodeActionParams): CodeAction[] {
const { uri } = params.textDocument;
const elmMakeDiagnostics: IDiagnostic[] = this.filterElmMakeDiagnostics(
params.context.diagnostics as IDiagnostic[],
);
return this.convertDiagnosticsToCodeActions(elmMakeDiagnostics, uri);
}
private hasType(error: any): error is IElmError | IElmCompilerError {
return "type" in error;
}
private convertDiagnosticsToCodeActions(
diagnostics: IDiagnostic[],
uri: string,
): CodeAction[] {
const result: CodeAction[] = [];
diagnostics.forEach((diagnostic) => {
if (
diagnostic.message.startsWith(NAMING_ERROR) ||
diagnostic.message.startsWith("BAD IMPORT") ||
diagnostic.message.startsWith("UNKNOWN LICENSE") ||
diagnostic.message.startsWith("UNKNOWN PACKAGE") ||
diagnostic.message.startsWith("UNKNOWN EXPORT")
) {
// Offer the name suggestions from elm make to our users
const regex = /^\s{4}#(.*)#$/gm;
let matches;
while ((matches = regex.exec(diagnostic.message)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (matches.index === regex.lastIndex) {
regex.lastIndex++;
}
matches
.filter((_, groupIndex) => groupIndex === 1)
.forEach((match) => {
result.push(
this.createQuickFix(
uri,
match,
diagnostic,
`Change to \`${match}\``,
),
);
});
}
} else if (
diagnostic.message.startsWith("MODULE NAME MISMATCH") ||
diagnostic.message.startsWith("UNEXPECTED SYMBOL")
) {
// Offer the name suggestions from elm make to our users
const regex = /# -> #(.*)#$/gm;
const matches = regex.exec(diagnostic.message);
if (matches !== null) {
result.push(
this.createQuickFix(
uri,
matches[1],
diagnostic,
`Change to \`${matches[1]}\``,
),
);
}
}
});
return result;
}
private createQuickFix(
uri: string,
replaceWith: string,
diagnostic: IDiagnostic,
title: string,
): CodeAction {
const map: {
[uri: string]: TextEdit[];
} = {};
if (!map[uri]) {
map[uri] = [];
}
map[uri].push(TextEdit.replace(diagnostic.range, replaceWith));
return {
diagnostics: [diagnostic],
edit: { changes: map },
kind: CodeActionKind.QuickFix,
title,
};
}
private filterElmMakeDiagnostics(diagnostics: IDiagnostic[]): IDiagnostic[] {
return diagnostics.filter((diagnostic) => diagnostic.source === ELM_MAKE);
}
private async checkForErrors(
program: IProgram,
sourceFile: ISourceFile,
): Promise<IElmIssue[]> {
const settings = await this.settings.getClientSettings();
const workspaceRootPath = program.getRootPath().fsPath;
const fileToRelativePath = (file: ISourceFile): string =>
path.relative(workspaceRootPath, URI.parse(file.uri).fsPath);
const sourceFilePath = fileToRelativePath(sourceFile);
const treeMap = program.getForest().treeMap;
const forestFiles: Array<ISourceFile> = Array.from(treeMap.values());
const allFiles = forestFiles.some((file) => file.uri === sourceFile.uri)
? forestFiles
: forestFiles.concat(sourceFile);
const projectFiles = allFiles.filter((file) => !file.isDependency);
const testFilesForSure = projectFiles.filter((file) => file.isTestFile);
const otherFiles = projectFiles.filter((file) => !file.isTestFile);
const entrypointsForSure = otherFiles.filter((file) => {
switch (file.project.type) {
case "application":
return file.exposing?.has("main") ?? false;
case "package":
return file.moduleName === undefined
? false
: file.project.exposedModules.has(file.moduleName);
}
});
const urisReferencedByEntrypoints = this.getUrisReferencedByEntrypoints(
treeMap,
entrypointsForSure,
);
const urisReferencedByTestsForSure = this.getUrisReferencedByEntrypoints(
treeMap,
testFilesForSure,
);
const onlyRunElmTest = entrypointsForSure.every((file) =>
urisReferencedByTestsForSure.has(file.uri),
);
// Files that aren’t imported from any entrypoint. These could be:
//
// - Tests inside `src/`.
// - New files that aren’t imported by anything yet.
// - Old leftover files that aren’t imported by anything.
// - Files that _are_ used and aren’t tests but that still end up here
// because of:
// - The project doesn’t use `main =`, like `review/` for elm-review.
// - The user has accidentally remove `main =` or not exposed it.
//
// Since these _could_ be test, we compile them with `elm-test make` rather
// than `elm make`, so that "test-dependencies" are allowed. If they _aren’t_
// tests, the only downside of this is that if you accidentally import a
// test-dependency, you won’t get an error for that. It should be an OK tradeoff.
const possiblyTestFiles = otherFiles.filter(
(file) => !urisReferencedByEntrypoints.has(file.uri),
);
const argsElm = (files: Array<ISourceFile>): Array<string> => [
"make",
...files.map(fileToRelativePath),
"--report",
"json",
"--output",
"/dev/null",
];
const argsElmTest = (files: Array<ISourceFile>): Array<string> => [
"make",
...files.map(fileToRelativePath),
"--report",
"json",
];
const elmNotFound =
"The 'elm' compiler is not available. Install Elm via 'npm install -g elm'.";
const elmTestNotFound =
"'elm-test' is not available. Install Elm via 'npm install -g elm-test'.";
// - If all entrypoints are covered by tests, we only need to run `elm-test make`.
// - Otherwise, call `elm make` for all entrypoints (if any).
// - Call `elm-test make` for all tests (if any), plus potential tests.
// - If there’s no `tests/` folder but files that _could_ be tests, try to
// call `elm-test make` but fall back to `elm make` in case they’re not
// tests and the user hasn’t got elm-test installed.
const results = await Promise.allSettled([
entrypointsForSure.length > 0 && !onlyRunElmTest
? utils.execCmd(
[settings.elmPath, argsElm(entrypointsForSure)],
[["elm", argsElm(entrypointsForSure)]],
{ notFoundText: elmNotFound },
workspaceRootPath,
this.connection,
)
: undefined,
testFilesForSure.length === 0 && possiblyTestFiles.length > 0
? utils.execCmd(
[settings.elmTestPath, argsElmTest(possiblyTestFiles)],
// These files _could_ be tests, but since there’s no `tests/` folder we can’t
// know if we should expect the user to have elm-test installed. If they don’t,
// they’ll get errors imports from "test-dependencies".
[
["elm-test", argsElmTest(possiblyTestFiles)],
["elm", argsElm(possiblyTestFiles)],
],
{
notFoundText:
settings.elmTestPath === ""
? elmTestNotFound
: // This uses `elmNotFound` since "elm" is the last alternative above.
elmNotFound,
},
workspaceRootPath,
this.connection,
)
: undefined,
testFilesForSure.length > 0
? utils.execCmd(
[
settings.elmTestPath,
argsElmTest(testFilesForSure.concat(possiblyTestFiles)),
],
// Since there’s a `tests/` folder we expect the user to have elm-test installed.
[
[
"elm-test",
argsElmTest(testFilesForSure.concat(possiblyTestFiles)),
],
],
{ notFoundText: elmTestNotFound },
workspaceRootPath,
this.connection,
)
: undefined,
]);
const lines: IElmIssue[] = [];
const linesSet = new Set<string>();
for (const result of results) {
if (result.status === "fulfilled") {
continue;
}
const error = result.reason as unknown;
if (typeof error === "string") {
continue;
} else {
const execaError = error as execa.ExecaReturnValue<string>;
execaError.stderr.split("\n").forEach((line: string) => {
let errorObject: unknown;
try {
errorObject = JSON.parse(line);
} catch (error) {
this.connection.console.warn(
"Received an invalid json, skipping error.",
);
}
if (
errorObject &&
this.hasType(errorObject) &&
errorObject.type === "compile-errors"
) {
const compilerError = errorObject as IElmCompilerError;
compilerError.errors.forEach((error: IError) => {
error.problems.forEach((problem: IProblem) => {
const issue: IElmIssue = {
details: problem.message
.map((message: string | IStyledString) =>
typeof message === "string"
? message
: `#${message.string}#`,
)
.join(""),
file: error.path
? path.isAbsolute(error.path)
? path.relative(workspaceRootPath, error.path)
: error.path
: sourceFilePath,
overview: problem.title,
region: problem.region,
subregion: "",
tag: "error",
type: "error",
};
const issueString = JSON.stringify(issue);
if (!linesSet.has(issueString)) {
lines.push(issue);
linesSet.add(issueString);
}
});
});
} else if (
errorObject &&
this.hasType(errorObject) &&
errorObject.type === "error"
) {
const error = errorObject as IElmError;
this.checkIfVersionMismatchesAndCreateMessage(error);
const issue: IElmIssue = {
details: error.message
.map((message: string | IStyledString) =>
typeof message === "string" ? message : message.string,
)
.join(""),
// elm-test might supply absolute paths to files
file: error.path
? path.relative(workspaceRootPath, error.path)
: sourceFilePath,
overview: error.title,
region: {
end: {
column: 1,
line: 1,
},
start: {
column: 1,
line: 1,
},
},
subregion: "",
tag: "error",
type: "error",
};
lines.push(issue);
const issueString = JSON.stringify(issue);
if (!linesSet.has(issueString)) {
lines.push(issue);
linesSet.add(issueString);
}
}
});
}
}
return lines;
}
private checkIfVersionMismatchesAndCreateMessage(
errorObject: IElmError,
): void {
if (errorObject.title === "ELM VERSION MISMATCH") {
this.connection.window.showErrorMessage(
errorObject.message
.map((message: string | IStyledString) =>
typeof message === "string" ? message : message.string,
)
.join(""),
);
}
}
private getUrisReferencedByEntrypoints(
treeMap: Map<string, ISourceFile>,
entrypoints: ISourceFile[],
): Set<string> {
const stack: ISourceFile[] = entrypoints.slice();
const result = new Set<string>(entrypoints.map((file) => file.uri));
for (let i = 0; i < stack.length; i++) {
const file = stack[i];
if (file.resolvedModules !== undefined) {
for (const uri of file.resolvedModules.values()) {
const nextFile = treeMap.get(uri);
if (
nextFile !== undefined &&
!nextFile.isDependency &&
!result.has(nextFile.uri)
) {
result.add(nextFile.uri);
stack.push(nextFile);
}
}
}
}
return result;
}
} | the_stack |
import { RowModel } from '..'
import { TableFeature } from '../core/instance'
import {
BuiltInSortingFn,
reSplitAlphaNumeric,
sortingFns,
} from '../sortingFns'
import {
Column,
OnChangeFn,
TableGenerics,
TableInstance,
Row,
Updater,
} from '../types'
import { isFunction, makeStateUpdater, Overwrite } from '../utils'
export type SortDirection = 'asc' | 'desc'
export type ColumnSort = {
id: string
desc: boolean
}
export type SortingState = ColumnSort[]
export type SortingTableState = {
sorting: SortingState
}
export type SortingFn<TGenerics extends TableGenerics> = {
(rowA: Row<TGenerics>, rowB: Row<TGenerics>, columnId: string): number
}
export type CustomSortingFns<TGenerics extends TableGenerics> = Record<
string,
SortingFn<TGenerics>
>
export type SortingFnOption<TGenerics extends TableGenerics> =
| 'auto'
| BuiltInSortingFn
| keyof TGenerics['SortingFns']
| SortingFn<TGenerics>
export type SortingColumnDef<TGenerics extends TableGenerics> = {
sortingFn?: SortingFnOption<Overwrite<TGenerics, { Value: any }>>
sortDescFirst?: boolean
enableSorting?: boolean
enableMultiSort?: boolean
invertSorting?: boolean
sortUndefined?: false | -1 | 1
}
export type SortingColumn<TGenerics extends TableGenerics> = {
getAutoSortingFn: () => SortingFn<TGenerics>
getAutoSortDir: () => SortDirection
getSortingFn: () => SortingFn<TGenerics>
getNextSortingOrder: () => SortDirection | false
getCanSort: () => boolean
getCanMultiSort: () => boolean
getSortIndex: () => number
getIsSorted: () => false | SortDirection
clearSorting: () => void
toggleSorting: (desc?: boolean, isMulti?: boolean) => void
getToggleSortingHandler: () => undefined | ((event: unknown) => void)
}
export type SortingOptions<TGenerics extends TableGenerics> = {
manualSorting?: boolean
sortingFns?: TGenerics['SortingFns']
onSortingChange?: OnChangeFn<SortingState>
enableSorting?: boolean
enableSortingRemoval?: boolean
enableMultiRemove?: boolean
enableMultiSort?: boolean
sortDescFirst?: boolean
getSortedRowModel?: (instance: TableInstance<any>) => () => RowModel<any>
maxMultiSortColCount?: number
isMultiSortEvent?: (e: unknown) => boolean
}
export type SortingInstance<TGenerics extends TableGenerics> = {
setSorting: (updater: Updater<SortingState>) => void
resetSorting: (defaultState?: boolean) => void
getPreSortedRowModel: () => RowModel<TGenerics>
getSortedRowModel: () => RowModel<TGenerics>
_getSortedRowModel?: () => RowModel<TGenerics>
}
//
export const Sorting: TableFeature = {
getInitialState: (state): SortingTableState => {
return {
sorting: [],
...state,
}
},
getDefaultColumnDef: <
TGenerics extends TableGenerics
>(): SortingColumnDef<TGenerics> => {
return {
sortingFn: 'auto',
}
},
getDefaultOptions: <TGenerics extends TableGenerics>(
instance: TableInstance<TGenerics>
): SortingOptions<TGenerics> => {
return {
onSortingChange: makeStateUpdater('sorting', instance),
isMultiSortEvent: (e: unknown) => {
return (e as MouseEvent).shiftKey
},
}
},
createColumn: <TGenerics extends TableGenerics>(
column: Column<TGenerics>,
instance: TableInstance<TGenerics>
): SortingColumn<TGenerics> => {
return {
getAutoSortingFn: () => {
const firstRows = instance.getFilteredRowModel().flatRows.slice(10)
let isString = false
for (const row of firstRows) {
const value = row?.getValue(column.id)
if (Object.prototype.toString.call(value) === '[object Date]') {
return sortingFns.datetime
}
if (typeof value === 'string') {
isString = true
if (value.split(reSplitAlphaNumeric).length > 1) {
return sortingFns.alphanumeric
}
}
}
if (isString) {
return sortingFns.text
}
return sortingFns.basic
},
getAutoSortDir: () => {
const firstRow = instance.getFilteredRowModel().flatRows[0]
const value = firstRow?.getValue(column.id)
if (typeof value === 'string') {
return 'asc'
}
return 'desc'
},
getSortingFn: () => {
const userSortingFn = instance.options.sortingFns
if (!column) {
throw new Error()
}
return isFunction(column.columnDef.sortingFn)
? column.columnDef.sortingFn
: column.columnDef.sortingFn === 'auto'
? column.getAutoSortingFn()
: (userSortingFn as Record<string, any>)?.[
column.columnDef.sortingFn as string
] ??
(sortingFns[
column.columnDef.sortingFn as BuiltInSortingFn
] as SortingFn<TGenerics>)
},
toggleSorting: (desc, multi) => {
// if (column.columns.length) {
// column.columns.forEach((c, i) => {
// if (c.id) {
// instance.toggleColumnSorting(c.id, undefined, multi || !!i)
// }
// })
// return
// }
// this needs to be outside of instance.setSorting to be in sync with rerender
const nextSortingOrder = column.getNextSortingOrder()
instance.setSorting(old => {
// Find any existing sorting for this column
const existingSorting = old?.find(d => d.id === column.id)
const existingIndex = old?.findIndex(d => d.id === column.id)
const hasDescDefined = typeof desc !== 'undefined' && desc !== null
let newSorting: SortingState = []
// What should we do with this sort action?
let sortAction: 'add' | 'remove' | 'toggle' | 'replace'
if (column.getCanMultiSort() && multi) {
if (existingSorting) {
sortAction = 'toggle'
} else {
sortAction = 'add'
}
} else {
// Normal mode
if (old?.length && existingIndex !== old.length - 1) {
sortAction = 'replace'
} else if (existingSorting) {
sortAction = 'toggle'
} else {
sortAction = 'replace'
}
}
// Handle toggle states that will remove the sorting
if (
sortAction === 'toggle' && // Must be toggling
(instance.options.enableSortingRemoval ?? true) && // If enableSortRemove, enable in general
!hasDescDefined && // Must not be setting desc
(multi ? instance.options.enableMultiRemove ?? true : true) && // If multi, don't allow if enableMultiRemove
!nextSortingOrder // Finally, detect if it should indeed be removed
) {
sortAction = 'remove'
}
if (sortAction === 'replace') {
newSorting = [
{
id: column.id,
desc: hasDescDefined ? desc! : nextSortingOrder! === 'desc',
},
]
} else if (sortAction === 'add' && old?.length) {
newSorting = [
...old,
{
id: column.id,
desc: hasDescDefined ? desc! : nextSortingOrder! === 'desc',
},
]
// Take latest n columns
newSorting.splice(
0,
newSorting.length -
(instance.options.maxMultiSortColCount ??
Number.MAX_SAFE_INTEGER)
)
} else if (sortAction === 'toggle' && old?.length) {
// This flips (or sets) the
newSorting = old.map(d => {
if (d.id === column.id) {
return {
...d,
desc: hasDescDefined ? desc! : nextSortingOrder! === 'desc',
}
}
return d
})
} else if (sortAction === 'remove' && old?.length) {
newSorting = old.filter(d => d.id !== column.id)
}
return newSorting
})
},
getNextSortingOrder: () => {
const sortDescFirst =
column.columnDef.sortDescFirst ??
instance.options.sortDescFirst ??
column.getAutoSortDir() === 'desc'
const firstSortDirection = sortDescFirst ? 'desc' : 'asc'
const isSorted = column.getIsSorted()
if (!isSorted) {
return firstSortDirection
}
if (isSorted === firstSortDirection) {
return isSorted === 'desc' ? 'asc' : 'desc'
} else {
return false
}
},
getCanSort: () => {
return (
(column.columnDef.enableSorting ?? true) &&
(instance.options.enableSorting ?? true) &&
!!column.accessorFn
)
},
getCanMultiSort: () => {
return (
column.columnDef.enableMultiSort ??
instance.options.enableMultiSort ??
!!column.accessorFn
)
},
getIsSorted: () => {
const columnSort = instance
.getState()
.sorting?.find(d => d.id === column.id)
return !columnSort ? false : columnSort.desc ? 'desc' : 'asc'
},
getSortIndex: () =>
instance.getState().sorting?.findIndex(d => d.id === column.id) ?? -1,
clearSorting: () => {
//clear sorting for just 1 column
instance.setSorting(old =>
old?.length ? old.filter(d => d.id !== column.id) : []
)
},
getToggleSortingHandler: () => {
const canSort = column.getCanSort()
return (e: unknown) => {
if (!canSort) return
;(e as any).persist?.()
column.toggleSorting?.(
undefined,
column.getCanMultiSort()
? instance.options.isMultiSortEvent?.(e)
: false
)
}
},
}
},
createInstance: <TGenerics extends TableGenerics>(
instance: TableInstance<TGenerics>
): SortingInstance<TGenerics> => {
return {
setSorting: updater => instance.options.onSortingChange?.(updater),
resetSorting: defaultState => {
instance.setSorting(
defaultState ? [] : instance.initialState?.sorting ?? []
)
},
getPreSortedRowModel: () => instance.getGroupedRowModel(),
getSortedRowModel: () => {
if (
!instance._getSortedRowModel &&
instance.options.getSortedRowModel
) {
instance._getSortedRowModel =
instance.options.getSortedRowModel(instance)
}
if (instance.options.manualSorting || !instance._getSortedRowModel) {
return instance.getPreSortedRowModel()
}
return instance._getSortedRowModel()
},
}
},
} | the_stack |
import "jest-extended";
import * as Hapi from "@hapi/hapi";
import * as Hoek from "@hapi/hoek";
import * as Teamwork from "@hapi/teamwork";
import { Client, plugin } from "@packages/core-p2p/src/hapi-nes";
import { Socket } from "@packages/core-p2p/src/hapi-nes/socket";
import { parseNesMessage } from "@packages/core-p2p/src/hapi-nes/utils";
jest.setTimeout(60000);
describe("Listener", () => {
it("refuses connection while stopping", async () => {
const server = Hapi.server();
const onConnection = (socket) => {
const orig = socket.disconnect;
socket.disconnect = async () => {
await Hoek.wait(50);
return orig.call(socket);
};
};
await server.register({ plugin: plugin, options: { onConnection } });
await server.start();
const team = new Teamwork.Team({ meetings: 20 });
const clients = [];
for (let i = 0; i < 20; ++i) {
const client = new Client("http://localhost:" + server.info.port);
client.onDisconnect = () => team.attend();
client.onError = Hoek.ignore;
await client.connect();
// @ts-ignore
clients.push(client);
}
const client2 = new Client("http://localhost:" + server.info.port);
client2.onError = Hoek.ignore;
server.stop();
await expect(client2.connect()).toReject();
await team.work;
});
it("limits number of connections", async () => {
const server = Hapi.server();
await server.register({ plugin: plugin, options: { maxConnections: 1 } });
await server.start();
const client = new Client("http://localhost:" + server.info.port);
await client.connect();
const client2 = new Client("http://localhost:" + server.info.port);
client2.onError = Hoek.ignore;
await expect(client2.connect()).toReject();
await client.disconnect();
await client2.disconnect();
await server.stop();
});
it("rejects unknown origin", async () => {
const server = Hapi.server();
await server.register({ plugin: plugin, options: { origin: ["http://localhost:12345"] } });
await server.start();
const client = new Client("http://localhost:" + server.info.port);
await expect(client.connect()).toReject();
await client.disconnect();
await server.stop();
});
it("accepts known origin", async () => {
const server = Hapi.server();
await server.register({ plugin: plugin, options: { origin: ["http://localhost:12345"] } });
await server.start();
const client = new Client("http://localhost:" + server.info.port, { ws: { origin: "http://localhost:12345" } });
await client.connect();
await client.disconnect();
await server.stop();
});
it("handles socket errors", async () => {
const server = Hapi.server();
const onConnection = (socket) => {
socket._ws.emit("error", new Error());
};
await server.register({ plugin: plugin, options: { onConnection } });
await server.start();
const client = new Client("http://localhost:" + server.info.port, { ws: { origin: "http://localhost:12345" } });
client.onError = Hoek.ignore;
await client.connect();
await server.stop();
});
describe("maxPayload", () => {
let server;
let response;
let payload;
beforeEach(async () => {
response = Buffer.from("a".repeat(10));
payload = Buffer.from("b".repeat(10));
server = Hapi.server();
await server.register({ plugin: plugin, options: { maxPayload: 100 } });
server.route({
method: "POST",
path: "/",
handler: async () => {
return response;
},
});
});
it("should resolve if payload and response are less than maxPayload", async () => {
await server.start();
const client = new Client("http://localhost:" + server.info.port);
await client.connect();
await expect(client.request({ path: "/", payload })).resolves.toEqual({
payload: response,
statusCode: 200,
});
await client.disconnect();
await server.stop();
});
it("should resolve if response is greater than maxPayload", async () => {
response = Buffer.from("a".repeat(200));
await server.start();
const client = new Client("http://localhost:" + server.info.port);
await client.connect();
await expect(client.request({ path: "/", payload })).resolves.toEqual({
payload: response,
statusCode: 200,
});
await client.disconnect();
await server.stop();
});
it("should throw if payload is greater than maxPayload", async () => {
payload = "b".repeat(110);
await server.start();
const client = new Client("http://localhost:" + server.info.port);
await client.connect();
await expect(client.request({ path: "/", payload })).rejects.toThrowError(
"Request failed - server disconnected",
);
await client.disconnect();
await server.stop();
});
});
describe("_beat()", () => {
it("disconnects client after timeout", async () => {
const server = Hapi.server();
await server.register({ plugin: plugin, options: { heartbeat: { interval: 20, timeout: 10 } } });
await server.start();
const client = new Client("http://localhost:" + server.info.port);
client.onError = Hoek.ignore;
const team = new Teamwork.Team();
client.onDisconnect = () => team.attend();
await client.connect();
// @ts-ignore
expect(client._heartbeatTimeout).toEqual(30);
// @ts-ignore
client._onMessage = Hoek.ignore; // Stop processing messages
await team.work;
await client.disconnect();
await server.stop();
});
it("disables heartbeat", async () => {
const server = Hapi.server();
await server.register({ plugin: plugin, options: { heartbeat: false } });
await server.start();
const client = new Client("http://localhost:" + server.info.port);
await client.connect();
// @ts-ignore
expect(client._heartbeatTimeout).toBeFalse();
await client.disconnect();
await server.stop();
});
it("pauses heartbeat timeout while replying to client", async () => {
const server = Hapi.server();
await server.register({
plugin: plugin,
options: { heartbeat: { interval: 1200, timeout: 1180 } },
});
server.route({
method: "POST",
path: "/",
handler: async () => {
await Hoek.wait(1440);
return "hello";
},
});
await server.start();
const client = new Client("http://localhost:" + server.info.port);
let e = 0;
client.onError = (err) => {
++e;
if (e === 1) {
expect(err.message).toEqual("Disconnecting due to heartbeat timeout");
}
};
let d = 0;
client.onDisconnect = (willReconnect, log) => ++d;
await client.connect();
// @ts-ignore
expect(client._heartbeatTimeout).toEqual(2380);
await client.request("/");
await Hoek.wait(2520);
expect(d).toEqual(0);
// @ts-ignore
client._onMessage = Hoek.ignore; // Stop processing messages
await Hoek.wait(2480);
expect(d).toEqual(1);
await client.disconnect();
await server.stop();
});
it("does not disconnect newly connecting sockets", async () => {
const server = Hapi.server();
let disconnected = 0;
const onDisconnection = () => disconnected++;
await server.register({
plugin: plugin,
options: { onDisconnection, heartbeat: { timeout: 1050, interval: 1055 } },
});
await server.start();
const client = new Client("http://localhost:" + server.info.port);
const canary = new Client("http://localhost:" + server.info.port);
await canary.connect();
const helloTeam = new Teamwork.Team();
// @ts-ignore
const socketOnMessage = Socket.prototype._onMessage;
// @ts-ignore
Socket.prototype._onMessage = async function (message) {
if (parseNesMessage(message).type === "hello") {
await helloTeam.work;
}
return socketOnMessage.call(this, message);
};
const pingTeam = new Teamwork.Team();
// @ts-ignore
const _onMessage = canary._onMessage.bind(canary);
// @ts-ignore
canary._onMessage = function (message) {
if (parseNesMessage(message.data).type === "ping") {
pingTeam.attend();
}
return _onMessage(message);
};
// wait for the next ping
await pingTeam.work;
await Hoek.wait(1030);
const connectPromise = client.connect().catch((message) => {
throw new Error(message);
});
// client should not time out for another 50 milliseconds
await Hoek.wait(1040);
// release "hello" message before the timeout hits
helloTeam.attend();
await connectPromise;
await Hoek.wait(1060); // ping should have been answered and connection still active
expect(disconnected).toEqual(0);
// @ts-ignore
Socket.prototype._onMessage = socketOnMessage;
await canary.disconnect();
await client.disconnect();
await server.stop();
});
it("disconnects sockets that have not fully connected in a long time", async () => {
const server = Hapi.server();
await server.register({ plugin: plugin, options: { heartbeat: { interval: 20, timeout: 10 } } });
// @ts-ignore
const socketOnMessage = Socket.prototype._onMessage;
// @ts-ignore
Socket.prototype._onMessage = Hoek.ignore; // Do not process messages
await server.start();
const client = new Client("http://localhost:" + server.info.port);
client.onError = Hoek.ignore;
const team = new Teamwork.Team();
client.onDisconnect = () => team.attend();
client.connect().catch(Hoek.ignore);
await team.work;
// @ts-ignore
Socket.prototype._onMessage = socketOnMessage;
await client.disconnect();
await server.stop();
});
});
describe("_generateId()", () => {
it("rolls over when reached max sockets per millisecond", async () => {
const server = Hapi.server();
await server.register({ plugin: plugin, options: {} });
const listener = server.plugins.nes._listener;
listener._socketCounter = 99999;
let id = listener._generateId();
expect(id.split(":")[4]).toEqual("99999");
id = listener._generateId();
expect(id.split(":")[4]).toEqual("10000");
});
});
}); | the_stack |
import React, { useState, useEffect } from 'react'
import { HelpOutline } from '@mui/icons-material'
import { UnControlled } from 'react-codemirror2'
import { useTheme } from '@mui/material/styles'
import { Dialog, DialogTitle, DialogContent, DialogActions, Button, Paper, Tooltip, Drawer,
Tab, Tabs, Chip, Box, useMediaQuery, Autocomplete, TextField, Grid, Checkbox, Select,
FormControlLabel, MenuItem, FormControl, InputLabel } from '@mui/material'
import { useGlobalData, usePlugin } from '../Context'
import { parseComponent, stringifyTextComponent } from '../utils'
import MojangSON, { parse, stringify, Int, Byte, Short } from 'nbt-ts'
import lang, { minecraft } from '../../languages'
import set from 'lodash/set'
import * as icons from '../../minecraftIcons.json'
import type { PaperProps } from '@mui/material/Paper'
export interface Enchantment extends MojangSON.TagObject {
id: string
lvl: MojangSON.Short
}
export interface Display extends MojangSON.TagObject {
Name?: string
Color?: MojangSON.Int
Lore?: string[]
}
export interface AttributeModifier extends MojangSON.TagObject {
Operation: MojangSON.Byte
Amount: MojangSON.Float
UUID: string
Slot: string
AttributeName: string
Name: string
}
export interface Tag extends MojangSON.TagObject {
Damage: MojangSON.Int
Enchantments?: Enchantment[]
display?: Display
AttributeModifiers?: AttributeModifier[]
Unbreakable?: MojangSON.Byte
SkullOwner?: {
Id?: number[],
Properties?: { textures: Array<{ Value: string }> }
}
}
export interface NBT extends MojangSON.TagObject {
Count: MojangSON.Byte
id: string
tag?: Tag
}
export interface Item {
type: string
name?: string
icon?: string
hasEnchants?: boolean
amount?: number
nbt?: string
}
export const isBlock = (name: string) => ('item.minecraft.' + name) in minecraft
export const getName = (name: string) => minecraft['item.minecraft.' + name] || minecraft['block.minecraft.' + name] || ''
export const getEnchantmentName = (it: string | Enchantment) => {
const name = minecraft['enchantment.' + (typeof it === 'string' ? it : it.id).replace(/:/g, '.')] || lang.itemEditor.unknownEnchantment
return typeof it === 'string' ? name : name + ' ' + it.lvl.value
}
export enum InvType {
// eslint-disable-next-line no-unused-vars
PLAYER = 'PLAYER',
// eslint-disable-next-line no-unused-vars
ENDER_CHEST = 'ENDER_CHEST',
// eslint-disable-next-line no-unused-vars
GLOBAL_ITEMS = 'GLOBAL_ITEMS',
// eslint-disable-next-line no-unused-vars
BLOCK = 'BLOCK',
// eslint-disable-next-line no-unused-vars
ENTITY = 'ENTITY'
}
export type ItemViewerProps = Omit<PaperProps, 'onDrop' | 'onDrag'> & {
item?: Item | null
data?: any
onDrag?: (data: any) => void
onDrop?: (item: Item, data: any) => void
onEdit?: (item?: Item | null | false) => void
}
const ItemViewer: React.FC<ItemViewerProps> = ({ item, data, onDrag, onDrop, onEdit, onClick, ...props }) => {
const globalData = useGlobalData()
const lowerCase = item ? item.type.toLowerCase() : ''
const type = item ? item.icon || lowerCase : ''
const hasEnchants = item?.hasEnchants && type in icons
const nbt: NBT | null = item?.nbt ? parse(item.nbt) as any as NBT : null
const elm = <Paper
{...props}
onDragOver={globalData.hasNBTAPI && onDrop
? e => {
e.preventDefault()
e.dataTransfer.dropEffect = 'move'
}
: undefined}
onDrop={globalData.hasNBTAPI && onDrop
? e => {
e.preventDefault()
const obj = JSON.parse(e.dataTransfer.getData('application/json'))
if (obj.item) onDrop(obj.item, obj.data)
}
: undefined}
onClick={onClick || (globalData.hasNBTAPI && onEdit
? () => openItemEditor(item).then(onEdit)
: undefined)}
sx={{
width: '40px',
height: '40px',
display: 'inline-block',
margin: 0.5,
position: 'relative',
overflow: 'hidden',
userSelect: 'none',
cursor: globalData.hasNBTAPI && (onEdit || onDrag) ? 'pointer' : undefined,
backgroundColor: theme => theme.palette.mode === 'dark' ? 'rgba(255,255,255,.06)' : 'rgba(0,0,0,.06)',
'& span': {
position: 'absolute',
right: 2,
bottom: -5,
pointerEvents: 'none',
textShadow: theme => theme.palette.mode === 'light'
? '#fff 1px 0 0, #fff 0 1px 0, #fff -1px 0 0, #fff 0 -1px 0'
: '#000 1px 0 0, #000 0 1px 0, #000 -1px 0 0, #000 0 -1px 0'
}
}}
>
{item && <div
onMouseDown={() => window.getSelection()?.removeAllRanges()}
draggable={!!onDrag}
onDragStart={onDrag
? e => {
e.dataTransfer.effectAllowed = 'copyMove'
e.dataTransfer.setData('application/json', JSON.stringify({ item, data }))
onDrag(data)
}
: undefined}
style={{
position: 'absolute',
top: 0,
right: 0,
left: 0,
bottom: 0,
backgroundSize: 'cover',
imageRendering: 'pixelated',
filter: hasEnchants ? 'brightness(1.5)' : undefined,
WebkitMaskSize: 'cover',
maskImage: !hasEnchants && type in icons ? `url(/icons/minecraft/${type}.png)` : undefined,
WebkitMaskImage: !hasEnchants && type in icons ? `url(/icons/minecraft/${type}.png)` : undefined,
backgroundImage: item && type in icons ? `url(/icons/minecraft/${type}.png)` : undefined
}}
>
{item && (item.type === 'PLAYER_HEAD' && nbt?.tag?.SkullOwner?.Id
? <img
crossOrigin='anonymous'
src={`https://mc-heads.net/head/${nbt.tag.SkullOwner.Id.reduce((s, it) => s + (it >>> 0).toString(16), '')}/30`}
/>
: !(type in icons) && type !== 'air' && <HelpOutline sx={{ position: 'absolute', left: 8, top: 8 }} />)}
{hasEnchants && type !== 'air' && <div style={{
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0,
opacity: 0.5,
WebkitMaskSize: 'cover',
filter: 'blur(1px) brightness(1.7)',
maskImage: `url(/icons/minecraft/${type}.png)`,
WebkitMaskImage: `url(/icons/minecraft/${type}.png)`,
animation: 'enchants-animation 6s infinite linear',
backgroundPositionY: 128,
backgroundImage: 'url(/icons/minecraft/enchanted_item_glint.png)'
}} />}
</div>}
{item && item.amount && item.amount > 1 ? <span>{item.amount}</span> : null}
</Paper>
const nbtTexts = nbt
? <>
{nbt.tag?.display?.Lore?.map((it, i) => <React.Fragment key={i}>{parseComponent(JSON.parse(it))}<br /></React.Fragment>)}
{nbt.tag?.Enchantments?.length
? nbt.tag?.Enchantments.map((it, i) => <React.Fragment key={i}><br />{getEnchantmentName(it)}</React.Fragment>)
: null}
{nbt.tag?.Unbreakable?.value === 1 && <><br />{minecraft['item.unbreakable']}</>}
</>
: null
return item
? <Tooltip title={<>
<h3 style={{ margin: 0 }}>{nbt?.tag?.display?.Name
? parseComponent(JSON.parse(nbt.tag.display.Name))
: item.name ? parseComponent(item.name) : getName(lowerCase)}</h3>
{nbtTexts}
</>}>{elm}</Tooltip>
: elm
}
export default ItemViewer
let _setItem: any
let _resolve: any
export const openItemEditor = (it?: Item | null): Promise<Item | null | undefined | false> => _setItem
? new Promise(resolve => {
_resolve = resolve
_setItem(it ? { ...it } : { type: 'AIR', amount: 1, hasEnchants: false })
})
: Promise.resolve(it)
let enchantments: string[] = []
const ItemEditor: React.FC = () => {
const plugin = usePlugin()
const theme = useTheme()
const [item, setItem] = useState<Item | undefined>()
const [types, setTypes] = useState<string[]>([])
const [tab, setTab] = useState(0)
const [level, setLevel] = useState(1)
const [enchantment, setEnchantment] = useState<string | undefined>()
const [nbtText, setNBTText] = useState('')
const nbt: NBT = item?.nbt ? parse(item.nbt) : { id: 'minecraft:' + (item?.type || 'air').toLowerCase(), Count: new Byte(1) } as any
useEffect(() => {
if (!item || types.length) return
plugin.emit('item:fetch', (a: string[], b: string[]) => {
setTypes(a)
enchantments = b
})
}, [item])
useEffect(() => {
_setItem = (it: any) => {
setItem(it)
setNBTText(it.nbt ? stringify(parse(it.nbt), { pretty: true }) : '')
}
return () => { _setItem = null }
}, [])
const cancel = () => {
setItem(undefined)
if (_resolve) {
_resolve(false)
_resolve = null
}
}
const update = () => {
const newItem: any = { ...item }
if (nbt) {
newItem.nbt = stringify(nbt as any)
setNBTText(stringify(nbt, { pretty: true }))
}
setItem(newItem)
}
const isAir = item?.type === 'AIR'
const name = nbt?.tag?.display?.Name
const enchantmentMap: Record<string, true> = { }
return <Dialog open={!!item} onClose={cancel}>
<DialogTitle>{lang.itemEditor.title}</DialogTitle>
<DialogContent sx={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'center' }}>
{item && <Box sx={{ display: 'flex', width: '100%', justifyContent: 'center' }}>
<ItemViewer item={item} />
<Autocomplete
options={types}
sx={{ maxWidth: 300, marginLeft: 1, flexGrow: 1 }}
value={item?.type}
onChange={(_, it) => {
item.type = it || 'AIR'
if (nbt) nbt.id = 'minecraft:' + (it ? it.toLowerCase() : 'air')
update()
}}
getOptionLabel={it => {
const locatedName = getName(it.toLowerCase())
return (locatedName ? locatedName + ' ' : '') + it
}}
renderInput={(params) => <TextField {...params} label={lang.itemEditor.itemType} size='small' variant='standard' />}
/>
</Box>}
<Tabs centered value={tab} onChange={(_, it) => setTab(it)} sx={{ marginBottom: 2 }}>
<Tab label={lang.itemEditor.baseAttribute} disabled={isAir} />
<Tab label={minecraft['container.enchant']} disabled={isAir} />
<Tab label='NBT' disabled={isAir} />
</Tabs>
{nbt && tab === 0 && <Grid container spacing={1} rowSpacing={1}>
<Grid item xs={12} md={6}><TextField
fullWidth
label={lang.itemEditor.count}
type='number'
variant='standard'
value={nbt.Count}
disabled={isAir}
onChange={e => {
nbt.Count = new Byte(item!.amount = parseInt(e.target.value))
update()
}}
/></Grid>
<Grid item xs={12} md={6}><TextField
fullWidth
label={lang.itemEditor.damage}
type='number'
variant='standard'
value={nbt.tag?.Damage}
disabled={isAir}
onChange={e => {
set(nbt, 'tag.Damage', parseInt(e.target.value))
update()
}}
/></Grid>
<Grid item xs={12} md={6}>
<TextField
fullWidth
label={lang.itemEditor.displayName}
variant='standard'
disabled={isAir}
value={name ? stringifyTextComponent(JSON.parse(name)) : ''}
onChange={e => {
set(nbt, 'tag.display.Name', JSON.stringify(item!.name = e.target.value))
update()
}}
/>
<FormControlLabel
label={minecraft['item.unbreakable']}
disabled={isAir}
checked={nbt.tag?.Unbreakable?.value === 1}
control={<Checkbox
checked={nbt.tag?.Unbreakable?.value === 1}
onChange={e => {
set(nbt, 'tag.Unbreakable', new Byte(+e.target.checked))
update()
}} />
}
/>
</Grid>
<Grid item xs={12} md={6}><TextField
fullWidth
multiline
label={lang.itemEditor.lore}
variant='standard'
maxRows={5}
disabled={isAir}
value={nbt.tag?.display?.Lore?.map(l => stringifyTextComponent(JSON.parse(l)))?.join('\n') || ''}
onChange={e => {
set(nbt, 'tag.display.Lore', e.target.value.split('\n').map(text => JSON.stringify(text)))
update()
}}
/></Grid>
</Grid>}
{nbt && tab === 1 && <Grid container spacing={1} sx={{ width: '100%' }}>
{nbt.tag?.Enchantments?.map((it, i) => {
enchantmentMap[it.id] = true
return <Grid item key={i}><Chip label={getEnchantmentName(it)} onDelete={() => {
nbt?.tag?.Enchantments?.splice(i, 1)
update()
}} /></Grid>
})}
<Grid item><Chip label={lang.itemEditor.newEnchantment} color='primary' onClick={() => {
setEnchantment('')
setLevel(1)
}} /></Grid>
<Dialog onClose={() => setEnchantment(undefined)} open={enchantment != null}>
<DialogTitle>{lang.itemEditor.newEnchantmentTitle}</DialogTitle>
<DialogContent>
<Box component='form' sx={{ display: 'flex', flexWrap: 'wrap' }}>
<FormControl variant='standard' sx={{ m: 1, minWidth: 120 }}>
<InputLabel htmlFor='item-editor-enchantment-selector'>{minecraft['container.enchant']}</InputLabel>
<Select
id='item-editor-enchantment-selector'
label={minecraft['container.enchant']}
value={enchantment || ''}
onChange={e => setEnchantment(e.target.value)}
>{enchantments
.filter(e => !(e in enchantmentMap))
.map(it => <MenuItem key={it} value={it}>{getEnchantmentName(it)}</MenuItem>)}
</Select>
</FormControl>
<FormControl sx={{ m: 1, minWidth: 120 }}>
<TextField
label={lang.itemEditor.level}
type='number'
variant='standard'
value={level}
onChange={e => setLevel(parseInt(e.target.value))}
/>
</FormControl>
</Box>
</DialogContent>
<DialogActions>
<Button onClick={() => setEnchantment(undefined)}>{minecraft['gui.cancel']}</Button>
<Button disabled={!enchantment || isNaN(level)} onClick={() => {
if (nbt) {
if (!nbt.tag) nbt.tag = { Damage: new Int(0) }
;(nbt.tag.Enchantments || (nbt.tag.Enchantments = [])).push({ id: enchantment!, lvl: new Short(level) })
}
setEnchantment(undefined)
update()
}}>{minecraft['gui.ok']}</Button>
</DialogActions>
</Dialog>
</Grid>}
</DialogContent>
{nbt && tab === 2 && <Box sx={{
'& .CodeMirror': { width: '100%' },
'& .CodeMirror-dialog, .CodeMirror-scrollbar-filler': { backgroundColor: theme.palette.background.paper + '!important' }
}}>
<UnControlled
value={nbtText}
options={{
mode: 'javascript',
phrases: lang.codeMirrorPhrases,
theme: theme.palette.mode === 'dark' ? 'material' : 'one-light'
}}
onChange={(_: any, __: any, nbt: string) => {
const n = parse(nbt) as any as NBT
const newItem: any = { ...item, nbt }
if (n.Count?.value != null) newItem.amount = n.Count.value
setItem(newItem)
}}
/>
</Box>}
<DialogActions>
<Button onClick={cancel}>{minecraft['gui.cancel']}</Button>
<Button onClick={() => {
setItem(undefined)
if (_resolve) {
_resolve(!item || item.type === 'AIR' ? null : item)
_resolve = null
}
}}>{minecraft['gui.ok']}</Button>
</DialogActions>
</Dialog>
}
export const GlobalItems: React.FC<{ open: boolean, onClose: () => void }> = ({ open, onClose }) => {
const matches = useMediaQuery((theme: any) => theme.breakpoints.down('md'))
const [flag, update] = useState(0)
const [copyItemLeft, setCopyItemLeft] = useState<Item | undefined>()
const [copyItemRight, setCopyItemRight] = useState<Item | undefined>()
const items: Array<Item | undefined> = JSON.parse(localStorage.getItem('NekoMaid:items') || '[]')
const save = () => {
localStorage.setItem('NekoMaid:items', JSON.stringify(items))
process.nextTick(update, flag + 1)
}
return <Drawer anchor='bottom' variant='persistent' elevation={16} open={open} PaperProps={{ elevation: 16 }}>
<Box sx={{ padding: 2, display: 'flex', justifyContent: 'center', paddingBottom: 0, alignItems: 'center' }}>
<ItemViewer
item={copyItemLeft}
data={{ type: InvType.GLOBAL_ITEMS }}
onDrag={() => process.nextTick(setCopyItemLeft)}
onDrop={it => {
setCopyItemLeft(it)
setCopyItemRight(it)
}}
/> {`< ${lang.itemEditor.clone} >`} <ItemViewer
item={copyItemRight}
data={{ type: InvType.GLOBAL_ITEMS }}
onDrag={() => process.nextTick(setCopyItemRight)}
onDrop={it => {
setCopyItemLeft(it)
setCopyItemRight(it)
}}
/>
</Box>
<Box sx={{ padding: 2, display: 'flex', justifyContent: 'center', flexWrap: 'wrap' }}>
{Array.from({ length: 14 }, (_, i) => <ItemViewer
key={i}
item={items[i]}
data={{ type: InvType.GLOBAL_ITEMS }}
onDrag={() => {
items[i] = undefined
save()
if (matches) process.nextTick(onClose)
}}
onDrop={it => {
items[i] = it
save()
}}
onEdit={item => {
if (item === false) return
items[i] = item || undefined
save()
}}
/>)}
</Box>
<ItemEditor />
</Drawer>
} | the_stack |
import {
DataTexture,
DataTexture3D,
Euler,
FloatType,
Matrix4,
Mesh,
OrthographicCamera,
PerspectiveCamera,
PlaneBufferGeometry,
Quaternion,
RGBAFormat,
Scene,
ShaderMaterial,
ShaderMaterialParameters,
UniformsUtils,
UnsignedByteType,
Vector2,
Vector3,
WebGLRenderTarget,
} from "three";
import { LinearFilter, NearestFilter } from "three/src/constants";
import { denoiseFragmentShaderSrc, denoiseShaderUniforms, denoiseVertexShaderSrc } from "./constants/denoiseShader";
import {
pathTracingFragmentShaderSrc,
pathTracingUniforms,
pathTracingVertexShaderSrc,
} from "./constants/volumePTshader";
import { LUT_ARRAY_LENGTH } from "./Histogram";
import Volume from "./Volume";
import { Bounds, isOrthographicCamera } from "./types";
import { ThreeJsPanel } from "./ThreeJsPanel";
import VolumeDrawable from "./VolumeDrawable";
import { Light } from "./Light";
export default class PathTracedVolume {
private volume: Volume;
private viewChannels: number[]; // should have 4 or less elements
private scale: Vector3;
private translation: Vector3;
private rotation: Euler;
private pixelSamplingRate: number;
private pathTracingUniforms: typeof pathTracingUniforms;
private volumeTexture: DataTexture3D;
private maskChannelIndex: number;
private maskAlpha: number;
private bounds: Bounds;
private cameraIsMoving: boolean;
private sampleCounter: number;
private frameCounter: number;
private stepSizePrimaryRayVoxels: number;
private stepSizeSecondaryRayVoxels: number;
private pathTracingScene: Scene;
private screenTextureScene: Scene;
private quadCamera: OrthographicCamera;
private fullTargetResolution: Vector2;
private pathTracingRenderTarget: WebGLRenderTarget;
private screenTextureRenderTarget: WebGLRenderTarget;
private screenTextureShader: ShaderMaterialParameters;
private screenOutputShader: ShaderMaterialParameters;
private pathTracingGeometry: PlaneBufferGeometry;
private pathTracingMaterial: ShaderMaterial;
private pathTracingMesh: Mesh;
private screenTextureGeometry: PlaneBufferGeometry;
private screenTextureMaterial: ShaderMaterial;
private screenTextureMesh: Mesh;
private screenOutputGeometry: PlaneBufferGeometry;
private screenOutputMaterial: ShaderMaterial;
private denoiseShaderUniforms = denoiseShaderUniforms();
private screenOutputDenoiseMaterial: ShaderMaterial;
private screenOutputMesh: Mesh;
private gradientDelta: number;
private renderUpdateListener?: (number) => void;
constructor(volume: Volume) {
// need?
this.volume = volume;
this.viewChannels = [-1, -1, -1, -1];
this.scale = new Vector3(1, 1, 1);
this.translation = new Vector3(0, 0, 0);
this.rotation = new Euler();
// scale factor is a huge optimization. Maybe use 1/dpi scale
this.pixelSamplingRate = 0.75;
this.pathTracingUniforms = pathTracingUniforms;
// create volume texture
const sx = volume.x,
sy = volume.y,
sz = volume.z;
const data = new Uint8Array(sx * sy * sz * 4).fill(0);
// defaults to rgba and unsignedbytetype so dont need to supply format this time.
this.volumeTexture = new DataTexture3D(data, volume.x, volume.y, volume.z);
this.volumeTexture.minFilter = this.volumeTexture.magFilter = LinearFilter;
this.volumeTexture.generateMipmaps = false;
this.volumeTexture.needsUpdate = true;
this.maskChannelIndex = -1;
this.maskAlpha = 1.0;
// create Lut textures
// empty array
const lutData = new Uint8Array(LUT_ARRAY_LENGTH * 4).fill(1);
const lut0 = new DataTexture(lutData, 256, 4, RGBAFormat, UnsignedByteType);
lut0.minFilter = lut0.magFilter = LinearFilter;
lut0.needsUpdate = true;
this.pathTracingUniforms.gLutTexture.value = lut0;
this.bounds = {
bmin: new Vector3(-0.5, -0.5, -0.5),
bmax: new Vector3(0.5, 0.5, 0.5),
};
this.cameraIsMoving = false;
this.sampleCounter = 0;
this.frameCounter = 0;
this.stepSizePrimaryRayVoxels = 1.0;
this.stepSizeSecondaryRayVoxels = 1.0;
this.pathTracingScene = new Scene();
this.screenTextureScene = new Scene();
// quadCamera is simply the camera to help render the full screen quad (2 triangles),
// hence the name. It is an Orthographic camera that sits facing the view plane, which serves as
// the window into our 3d world. This camera will not move or rotate for the duration of the app.
this.quadCamera = new OrthographicCamera(-1, 1, 1, -1, 0, 1);
this.fullTargetResolution = new Vector2(2, 2);
this.pathTracingRenderTarget = new WebGLRenderTarget(2, 2, {
minFilter: NearestFilter,
magFilter: NearestFilter,
format: RGBAFormat,
type: FloatType,
depthBuffer: false,
stencilBuffer: false,
});
this.pathTracingRenderTarget.texture.generateMipmaps = false;
this.screenTextureRenderTarget = new WebGLRenderTarget(2, 2, {
minFilter: NearestFilter,
magFilter: NearestFilter,
format: RGBAFormat,
type: FloatType,
depthBuffer: false,
stencilBuffer: false,
});
this.screenTextureRenderTarget.texture.generateMipmaps = false;
this.screenTextureShader = {
uniforms: UniformsUtils.merge([
{
tTexture0: {
type: "t",
value: null,
},
},
]),
vertexShader: [
"precision highp float;",
"precision highp int;",
"out vec2 vUv;",
"void main()",
"{",
"vUv = uv;",
"gl_Position = vec4( position, 1.0 );",
"}",
].join("\n"),
fragmentShader: [
"precision highp float;",
"precision highp int;",
"precision highp sampler2D;",
"uniform sampler2D tTexture0;",
"in vec2 vUv;",
"void main()",
"{",
"pc_fragColor = texture(tTexture0, vUv);",
"}",
].join("\n"),
};
this.screenOutputShader = {
uniforms: UniformsUtils.merge([
{
gInvExposure: {
type: "f",
value: 1.0 / (1.0 - 0.75),
},
tTexture0: {
type: "t",
value: null,
},
},
]),
vertexShader: [
"precision highp float;",
"precision highp int;",
"out vec2 vUv;",
"void main()",
"{",
"vUv = uv;",
"gl_Position = vec4( position, 1.0 );",
"}",
].join("\n"),
fragmentShader: [
"precision highp float;",
"precision highp int;",
"precision highp sampler2D;",
"uniform float gInvExposure;",
"uniform sampler2D tTexture0;",
"in vec2 vUv;",
// Used to convert from XYZ to linear RGB space
"const mat3 XYZ_2_RGB = (mat3(",
" 3.2404542, -1.5371385, -0.4985314,",
" -0.9692660, 1.8760108, 0.0415560,",
" 0.0556434, -0.2040259, 1.0572252",
"));",
"vec3 XYZtoRGB(vec3 xyz) {",
"return xyz * XYZ_2_RGB;",
"}",
"void main()",
"{",
"vec4 pixelColor = texture(tTexture0, vUv);",
"pixelColor.rgb = XYZtoRGB(pixelColor.rgb);",
//'pixelColor.rgb = pow(pixelColor.rgb, vec3(1.0/2.2));',
"pixelColor.rgb = 1.0-exp(-pixelColor.rgb*gInvExposure);",
"pixelColor = clamp(pixelColor, 0.0, 1.0);",
"pc_fragColor = pixelColor;", // sqrt(pixelColor);',
//'out_FragColor = pow(pixelColor, vec4(1.0/2.2));',
"}",
].join("\n"),
};
this.pathTracingGeometry = new PlaneBufferGeometry(2, 2);
// initialize texture.
this.pathTracingUniforms.volumeTexture.value = this.volumeTexture;
this.pathTracingUniforms.tPreviousTexture.value = this.screenTextureRenderTarget.texture;
this.pathTracingMaterial = new ShaderMaterial({
uniforms: this.pathTracingUniforms,
// defines: pathTracingDefines,
vertexShader: pathTracingVertexShaderSrc,
fragmentShader: pathTracingFragmentShaderSrc,
depthTest: false,
depthWrite: false,
});
this.pathTracingMesh = new Mesh(this.pathTracingGeometry, this.pathTracingMaterial);
this.pathTracingScene.add(this.pathTracingMesh);
this.screenTextureGeometry = new PlaneBufferGeometry(2, 2);
this.screenTextureMaterial = new ShaderMaterial({
uniforms: this.screenTextureShader.uniforms,
vertexShader: this.screenTextureShader.vertexShader,
fragmentShader: this.screenTextureShader.fragmentShader,
depthWrite: false,
depthTest: false,
});
this.screenTextureMaterial.uniforms.tTexture0.value = this.pathTracingRenderTarget.texture;
this.screenTextureMesh = new Mesh(this.screenTextureGeometry, this.screenTextureMaterial);
this.screenTextureScene.add(this.screenTextureMesh);
this.screenOutputGeometry = new PlaneBufferGeometry(2, 2);
this.screenOutputMaterial = new ShaderMaterial({
uniforms: this.screenOutputShader.uniforms,
vertexShader: this.screenOutputShader.vertexShader,
fragmentShader: this.screenOutputShader.fragmentShader,
depthWrite: false,
depthTest: false,
});
this.denoiseShaderUniforms = denoiseShaderUniforms();
this.screenOutputDenoiseMaterial = new ShaderMaterial({
uniforms: this.denoiseShaderUniforms,
vertexShader: denoiseVertexShaderSrc,
fragmentShader: denoiseFragmentShaderSrc,
depthWrite: false,
depthTest: false,
});
this.screenOutputMaterial.uniforms.tTexture0.value = this.pathTracingRenderTarget.texture;
this.screenOutputDenoiseMaterial.uniforms.tTexture0.value = this.pathTracingRenderTarget.texture;
this.screenOutputMesh = new Mesh(this.screenOutputGeometry, this.screenOutputMaterial);
this.gradientDelta = 1.0 / Math.max(sx, Math.max(sy, sz));
const invGradientDelta = 1.0 / this.gradientDelta; // a voxel count...
this.pathTracingUniforms.gGradientDeltaX.value = new Vector3(this.gradientDelta, 0, 0);
this.pathTracingUniforms.gGradientDeltaY.value = new Vector3(0, this.gradientDelta, 0);
this.pathTracingUniforms.gGradientDeltaZ.value = new Vector3(0, 0, this.gradientDelta);
// can this be a per-x,y,z value?
this.pathTracingUniforms.gInvGradientDelta.value = invGradientDelta; // a voxel count
this.pathTracingUniforms.gGradientFactor.value = 50.0; // related to voxel counts also
this.setRayStepSizes(1.0, 1.0);
// bounds will go from 0 to physicalSize
const physicalSize = volume.normalizedPhysicalSize;
this.pathTracingUniforms.gInvAaBbMax.value = new Vector3(
1.0 / physicalSize.x,
1.0 / physicalSize.y,
1.0 / physicalSize.z
);
this.updateClipRegion(0, 1, 0, 1, 0, 1);
this.updateLightsSecondary();
}
public cleanup(): void {
// warning do not use after cleanup is called!
this.volumeTexture.dispose();
}
public setRenderUpdateListener(callback?: (iteration: number) => void): void {
this.renderUpdateListener = callback;
}
public resetProgress(): void {
if (this.sampleCounter !== 0 && this.renderUpdateListener) {
this.renderUpdateListener(0);
}
this.sampleCounter = 0;
}
public setVisible(_isVisible: boolean): void {
// this.visible = isVisible;
}
public setShowBoundingBox(_showBoundingBox: boolean): void {
// TODO: NOT IMPLEMENTED YET
}
public setBoundingBoxColor(_color: [number, number, number]): void {
// TODO: NOT IMPLEMENTED YET
}
public doRender(canvas: ThreeJsPanel): void {
if (!this.volumeTexture) {
return;
}
if (this.cameraIsMoving) {
this.resetProgress();
this.frameCounter += 1.0;
} else {
this.sampleCounter += 1.0;
this.frameCounter += 1.0;
if (this.renderUpdateListener) {
this.renderUpdateListener(this.sampleCounter);
}
}
this.pathTracingUniforms.uSampleCounter.value = this.sampleCounter;
this.pathTracingUniforms.uFrameCounter.value = this.frameCounter;
// CAMERA
// force the camera to update its world matrix.
canvas.camera.updateMatrixWorld(true);
const cam = canvas.camera;
// rotate lights with camera, as if we are tumbling the volume with a fixed camera and world lighting.
// this code is analogous to this threejs code from View3d.preRender:
// this.scene.getObjectByName('lightContainer').rotation.setFromRotationMatrix(this.canvas3d.camera.matrixWorld);
const mycamxform = cam.matrixWorld.clone();
mycamxform.setPosition(new Vector3(0, 0, 0));
this.updateLightsSecondary(mycamxform);
let mydir = new Vector3();
mydir = cam.getWorldDirection(mydir);
const myup = new Vector3().copy(cam.up);
// don't rotate this vector. we are using translation as the pivot point of the object, and THEN rotating.
const mypos = new Vector3().copy(cam.position);
// apply volume translation and rotation:
// rotate camera.up, camera.direction, and camera position by inverse of volume's modelview
const m = new Matrix4().makeRotationFromQuaternion(new Quaternion().setFromEuler(this.rotation).invert());
mypos.sub(this.translation);
mypos.applyMatrix4(m);
myup.applyMatrix4(m);
mydir.applyMatrix4(m);
this.pathTracingUniforms.gCamera.value.mIsOrtho = isOrthographicCamera(cam) ? 1 : 0;
this.pathTracingUniforms.gCamera.value.mFrom.copy(mypos);
this.pathTracingUniforms.gCamera.value.mN.copy(mydir);
this.pathTracingUniforms.gCamera.value.mU.crossVectors(this.pathTracingUniforms.gCamera.value.mN, myup).normalize();
this.pathTracingUniforms.gCamera.value.mV
.crossVectors(this.pathTracingUniforms.gCamera.value.mU, this.pathTracingUniforms.gCamera.value.mN)
.normalize();
// the choice of y = scale/aspect or x = scale*aspect is made here to match up with the other raymarch volume
const fScale = isOrthographicCamera(cam)
? canvas.orthoScale
: Math.tan((0.5 * (cam as PerspectiveCamera).fov * Math.PI) / 180.0);
const aspect = this.pathTracingUniforms.uResolution.value.x / this.pathTracingUniforms.uResolution.value.y;
this.pathTracingUniforms.gCamera.value.mScreen.set(
-fScale * aspect,
fScale * aspect,
// the "0" Y pixel will be at +Scale.
fScale,
-fScale
);
const scr = this.pathTracingUniforms.gCamera.value.mScreen;
this.pathTracingUniforms.gCamera.value.mInvScreen.set(
// the amount to increment for each pixel
(scr.y - scr.x) / this.pathTracingUniforms.uResolution.value.x,
(scr.w - scr.z) / this.pathTracingUniforms.uResolution.value.y
);
const denoiseLerpC = 0.33 * (Math.max(this.sampleCounter - 1, 1.0) * 0.035);
if (denoiseLerpC > 0.0 && denoiseLerpC < 1.0) {
this.screenOutputDenoiseMaterial.uniforms.gDenoiseLerpC.value = denoiseLerpC;
this.screenOutputMesh.material = this.screenOutputDenoiseMaterial;
} else {
this.screenOutputMesh.material = this.screenOutputMaterial;
}
this.screenOutputDenoiseMaterial.uniforms.gDenoisePixelSize.value.x = this.pathTracingUniforms.uResolution.value.x;
this.screenOutputDenoiseMaterial.uniforms.gDenoisePixelSize.value.y = this.pathTracingUniforms.uResolution.value.y;
// RENDERING in 3 steps
// STEP 1
// Perform PathTracing and Render(save) into pathTracingRenderTarget
// This is currently rendered as a fullscreen quad with no camera transform in the vertex shader!
// It is also composited with screenTextureRenderTarget's texture.
// (Read previous screenTextureRenderTarget to use as a new starting point to blend with)
canvas.renderer.setRenderTarget(this.pathTracingRenderTarget);
canvas.renderer.render(this.pathTracingScene, this.quadCamera);
// STEP 2
// Render(copy) the final pathTracingScene output(above) into screenTextureRenderTarget
// This will be used as a new starting point for Step 1 above
canvas.renderer.setRenderTarget(this.screenTextureRenderTarget);
canvas.renderer.render(this.screenTextureScene, this.quadCamera);
// STEP 3
// Render full screen quad with generated pathTracingRenderTarget in STEP 1 above.
// After the image is gamma corrected, it will be shown on the screen as the final accumulated output
// DMT - this step is handled by the threeJsPanel.
// tell the threejs panel to use the quadCamera to render this scene.
// renderer.render( this.screenOutputScene, this.quadCamera );
canvas.renderer.setRenderTarget(null);
}
public get3dObject(): Mesh {
return this.screenOutputMesh;
}
public onChannelData(_batch: number[]): void {
// no op
}
public setScale(scale: Vector3): void {
this.scale = scale;
}
public setRayStepSizes(primary: number, secondary: number): void {
// reset render if changed
if (this.stepSizePrimaryRayVoxels !== primary || this.stepSizeSecondaryRayVoxels !== secondary) {
this.resetProgress();
}
this.stepSizePrimaryRayVoxels = primary;
this.stepSizeSecondaryRayVoxels = secondary;
this.pathTracingUniforms.gStepSize.value = this.stepSizePrimaryRayVoxels * this.gradientDelta;
this.pathTracingUniforms.gStepSizeShadow.value = this.stepSizeSecondaryRayVoxels * this.gradientDelta;
}
public setTranslation(vec3xyz: Vector3): void {
this.translation.copy(vec3xyz);
this.resetProgress();
}
public setRotation(eulerXYZ: Euler): void {
this.rotation.copy(eulerXYZ);
this.resetProgress();
}
public setOrthoScale(_value: number): void {
// no op
}
public setGamma(_gmin: number, _glevel: number, _gmax: number): void {
// no op
}
public setFlipAxes(flipX: number, flipY: number, flipZ: number): void {
this.pathTracingUniforms.flipVolume.value = new Vector3(flipX, flipY, flipZ);
// TODO: only reset if changed!
this.resetProgress();
}
public setResolution(x: number, y: number): void {
this.fullTargetResolution = new Vector2(x, y);
const dpr = window.devicePixelRatio ? window.devicePixelRatio : 1.0;
const nx = Math.floor((x * this.pixelSamplingRate) / dpr);
const ny = Math.floor((y * this.pixelSamplingRate) / dpr);
this.pathTracingUniforms.uResolution.value.x = nx;
this.pathTracingUniforms.uResolution.value.y = ny;
// TODO optimization: scale this value down when nx,ny is small. For now can leave it at 3 (a 7x7 pixel filter).
const denoiseFilterR = 3;
this.screenOutputDenoiseMaterial.uniforms.gDenoiseWindowRadius.value = denoiseFilterR;
this.screenOutputDenoiseMaterial.uniforms.gDenoiseInvWindowArea.value =
1.0 / ((2.0 * denoiseFilterR + 1.0) * (2.0 * denoiseFilterR + 1.0));
this.pathTracingRenderTarget.setSize(nx, ny);
this.screenTextureRenderTarget.setSize(nx, ny);
this.resetProgress();
}
setPixelSamplingRate(rate: number): void {
this.pixelSamplingRate = rate;
this.setResolution(this.fullTargetResolution.x, this.fullTargetResolution.y);
this.resetProgress();
}
setDensity(density: number): void {
this.pathTracingUniforms.gDensityScale.value = density * 150.0;
this.resetProgress();
}
// TODO brightness and exposure should be the same thing? or gamma?
setBrightness(brightness: number): void {
// convert to an exposure value
if (brightness === 1.0) {
brightness = 0.999;
}
this.updateExposure(brightness);
}
// -0.5 .. 0.5
setAxisClip(axis: number, minval: number, maxval: number, _isOrthoAxis: boolean): void {
this.bounds.bmax[axis] = maxval;
this.bounds.bmin[axis] = minval;
const physicalSize = this.volume.normalizedPhysicalSize;
this.pathTracingUniforms.gClippedAaBbMin.value = new Vector3(
this.bounds.bmin.x * physicalSize.x,
this.bounds.bmin.y * physicalSize.y,
this.bounds.bmin.z * physicalSize.z
);
this.pathTracingUniforms.gClippedAaBbMax.value = new Vector3(
this.bounds.bmax.x * physicalSize.x,
this.bounds.bmax.y * physicalSize.y,
this.bounds.bmax.z * physicalSize.z
);
this.resetProgress();
}
setChannelAsMask(channelIndex: number): boolean {
if (!this.volume.channels[channelIndex] || !this.volume.channels[channelIndex].loaded) {
return false;
}
if (this.maskChannelIndex !== channelIndex) {
this.maskChannelIndex = channelIndex;
this.updateVolumeData4();
this.resetProgress();
}
return true;
}
setMaskAlpha(maskAlpha: number): void {
this.maskAlpha = maskAlpha;
this.updateVolumeData4();
this.resetProgress();
}
setOrthoThickness(_value: number): void {
// no op
}
setIsOrtho(isOrthoAxis: boolean): void {
this.pathTracingUniforms.gCamera.value.mIsOrtho = isOrthoAxis ? 1 : 0;
this.resetProgress();
}
//////////////////////////////////////////
//////////////////////////////////////////
onStartControls(): void {
this.cameraIsMoving = true;
}
onChangeControls(): void {
// this.cameraIsMoving = true;
}
onEndControls(): void {
this.cameraIsMoving = false;
this.resetProgress();
}
viewpointMoved(): void {
this.resetProgress();
}
updateActiveChannels(image: VolumeDrawable): void {
const ch = [-1, -1, -1, -1];
let activeChannel = 0;
const NC = this.volume.num_channels;
const maxch = 4;
for (let i = 0; i < NC && activeChannel < maxch; ++i) {
if (image.isVolumeChannelEnabled(i) && image.getChannel(i).loaded) {
ch[activeChannel] = i;
activeChannel++;
}
}
const unchanged = ch.every((elem, index) => {
return elem === this.viewChannels[index];
}, this);
if (unchanged) {
return;
}
this.pathTracingUniforms.gNChannels.value = activeChannel;
this.viewChannels = ch;
// update volume data according to channels selected.
this.updateVolumeData4();
this.resetProgress();
this.updateLuts(image);
this.updateMaterial(image);
// console.log(this.pathTracingUniforms);
}
updateVolumeData4(): void {
const sx = this.volume.x,
sy = this.volume.y,
sz = this.volume.z;
const data = new Uint8Array(sx * sy * sz * 4);
data.fill(0);
for (let i = 0; i < 4; ++i) {
const ch = this.viewChannels[i];
if (ch === -1) {
continue;
}
for (let iz = 0; iz < sz; ++iz) {
for (let iy = 0; iy < sy; ++iy) {
for (let ix = 0; ix < sx; ++ix) {
data[i + ix * 4 + iy * 4 * sx + iz * 4 * sx * sy] = this.volume.getChannel(ch).getIntensity(ix, iy, iz);
}
}
}
if (this.maskChannelIndex !== -1 && this.maskAlpha < 1.0) {
const maskChannel = this.volume.getChannel(this.maskChannelIndex);
// const maskMax = maskChannel.getHistogram().dataMax;
let maskVal = 1.0;
const maskAlpha = this.maskAlpha;
for (let iz = 0; iz < sz; ++iz) {
for (let iy = 0; iy < sy; ++iy) {
for (let ix = 0; ix < sx; ++ix) {
// nonbinary masking
// maskVal = maskChannel.getIntensity(ix,iy,iz) * maskAlpha / maskMax;
// binary masking
maskVal = maskChannel.getIntensity(ix, iy, iz) > 0 ? 1.0 : maskAlpha;
data[i + ix * 4 + iy * 4 * sx + iz * 4 * sx * sy] *= maskVal;
}
}
}
}
}
// defaults to rgba and unsignedbytetype so dont need to supply format this time.
this.volumeTexture.image.data.set(data);
this.volumeTexture.needsUpdate = true;
}
updateLuts(image: VolumeDrawable): void {
for (let i = 0; i < this.pathTracingUniforms.gNChannels.value; ++i) {
const channel = this.viewChannels[i];
const combinedLut = image.getChannel(channel).combineLuts(image.getChannelColor(channel));
this.pathTracingUniforms.gLutTexture.value.image.data.set(combinedLut, i * LUT_ARRAY_LENGTH);
this.pathTracingUniforms.gIntensityMax.value.setComponent(
i,
this.volume.channels[channel].histogram.getMax() / 255.0
);
this.pathTracingUniforms.gIntensityMin.value.setComponent(
i,
this.volume.channels[channel].histogram.getMin() / 255.0
);
}
this.pathTracingUniforms.gLutTexture.value.needsUpdate = true;
this.resetProgress();
}
// image is a material interface that supports per-channel color, spec,
// emissive, glossiness
updateMaterial(image: VolumeDrawable): void {
for (let c = 0; c < this.viewChannels.length; ++c) {
const i = this.viewChannels[c];
if (i > -1) {
// diffuse color is actually blended into the LUT now.
const combinedLut = image.getChannel(i).combineLuts(image.getChannelColor(i));
this.pathTracingUniforms.gLutTexture.value.image.data.set(combinedLut, c * LUT_ARRAY_LENGTH);
this.pathTracingUniforms.gLutTexture.value.needsUpdate = true;
this.pathTracingUniforms.gDiffuse.value[c] = new Vector3(1.0, 1.0, 1.0);
this.pathTracingUniforms.gSpecular.value[c] = new Vector3()
.fromArray(image.specular[i])
.multiplyScalar(1.0 / 255.0);
this.pathTracingUniforms.gEmissive.value[c] = new Vector3()
.fromArray(image.emissive[i])
.multiplyScalar(1.0 / 255.0);
this.pathTracingUniforms.gGlossiness.value[c] = image.glossiness[i];
}
}
this.resetProgress();
}
updateShadingMethod(brdf: number): void {
this.pathTracingUniforms.gShadingType.value = brdf;
this.resetProgress();
}
updateShowLights(showlights: number): void {
this.pathTracingUniforms.uShowLights.value = showlights;
this.resetProgress();
}
updateExposure(e: number): void {
// 1.0 causes division by zero.
if (e > 0.99999) {
e = 0.99999;
}
this.screenOutputMaterial.uniforms.gInvExposure.value = 1.0 / (1.0 - e) - 1.0;
this.screenOutputDenoiseMaterial.uniforms.gInvExposure.value = 1.0 / (1.0 - e) - 1.0;
this.resetProgress();
}
updateCamera(fov: number, focalDistance: number, apertureSize: number): void {
this.pathTracingUniforms.gCamera.value.mApertureSize = apertureSize;
this.pathTracingUniforms.gCamera.value.mFocalDistance = focalDistance;
this.resetProgress();
}
updateLights(state: Light[]): void {
// 0th light in state array is sphere light
this.pathTracingUniforms.gLights.value[0].mColorTop = new Vector3().copy(state[0].mColorTop);
this.pathTracingUniforms.gLights.value[0].mColorMiddle = new Vector3().copy(state[0].mColorMiddle);
this.pathTracingUniforms.gLights.value[0].mColorBottom = new Vector3().copy(state[0].mColorBottom);
// 1st light in state array is area light
this.pathTracingUniforms.gLights.value[1].mColor = new Vector3().copy(state[1].mColor);
this.pathTracingUniforms.gLights.value[1].mTheta = state[1].mTheta;
this.pathTracingUniforms.gLights.value[1].mPhi = state[1].mPhi;
this.pathTracingUniforms.gLights.value[1].mDistance = state[1].mDistance;
this.pathTracingUniforms.gLights.value[1].mWidth = state[1].mWidth;
this.pathTracingUniforms.gLights.value[1].mHeight = state[1].mHeight;
this.updateLightsSecondary();
this.resetProgress();
}
updateLightsSecondary(cameraMatrix?: Matrix4): void {
const physicalSize = this.volume.normalizedPhysicalSize;
const bbctr = new Vector3(physicalSize.x * 0.5, physicalSize.y * 0.5, physicalSize.z * 0.5);
for (let i = 0; i < 2; ++i) {
const lt = this.pathTracingUniforms.gLights.value[i];
lt.update(bbctr, cameraMatrix);
}
}
// 0..1 ranges as input
updateClipRegion(xmin: number, xmax: number, ymin: number, ymax: number, zmin: number, zmax: number): void {
this.bounds = {
bmin: new Vector3(xmin - 0.5, ymin - 0.5, zmin - 0.5),
bmax: new Vector3(xmax - 0.5, ymax - 0.5, zmax - 0.5),
};
const physicalSize = this.volume.normalizedPhysicalSize;
this.pathTracingUniforms.gClippedAaBbMin.value = new Vector3(
xmin * physicalSize.x - 0.5 * physicalSize.x,
ymin * physicalSize.y - 0.5 * physicalSize.y,
zmin * physicalSize.z - 0.5 * physicalSize.z
);
this.pathTracingUniforms.gClippedAaBbMax.value = new Vector3(
xmax * physicalSize.x - 0.5 * physicalSize.x,
ymax * physicalSize.y - 0.5 * physicalSize.y,
zmax * physicalSize.z - 0.5 * physicalSize.z
);
this.resetProgress();
}
} | the_stack |
import traverse, { NodePath } from '@babel/traverse';
import * as t from '@babel/types';
import {
commands,
CreateFile,
Position,
Range,
TextDocumentEdit,
TextEdit,
Uri,
window,
workspace,
WorkspaceEdit,
} from 'coc.nvim';
import * as fs from 'fs';
import LinesAndColumns from 'lines-and-columns';
import * as path from 'path';
import {
codeFromNode,
codeToAst,
findComponentMemberReferences,
isFunctionBinding,
isJSX,
isPathInRange,
isPathRemoved,
jsxToAst,
} from './ast';
import { askForName, generateClassComponent, generatePureComponent } from './utils';
import pickBy = require('lodash.pickby');
/**
* Extract code to function action
*/
export const extractToFunction = async () => {
try {
const name = await askForName();
if (!name) return;
const doc = await workspace.document;
if (!doc) return;
const mode = await workspace.nvim.call('visualmode');
const range = await workspace.getSelectedRange(mode, doc);
if (!range) return;
const documentText = doc.textDocument.getText();
const [start, end] = getIndexesForSelection(documentText, range);
const result = executeCodeAction(name, documentText, start, end);
if (!result) {
window.showMessage('Extract JSX to function failed', 'error');
return;
}
const edits: TextEdit[] = [
TextEdit.replace(range, result.replaceJSXCode),
TextEdit.insert(Position.create(result.insertAt, 0), result.componentCode + '\n\n'),
];
await doc.applyEdits(edits);
await commands.executeCommand('editor.action.format');
} catch (error) {
console.error('Extract JSX to function:', error);
window.showMessage('Extract JSX to function failed', 'error');
}
};
const fileTypeMap = {
javascript: '.js',
typescript: '.ts',
javascriptreact: '.jsx',
typescriptreact: '.tsx',
};
/**
* Extract code to file action
*/
export const extractToFile = async () => {
try {
const name = await askForName();
if (!name) return;
const doc = await workspace.document;
if (!doc) return;
const documentDir = path.dirname(Uri.parse(doc.uri).fsPath);
const newFilePath = path.join(documentDir, name + fileTypeMap[doc.filetype]);
if (fs.existsSync(newFilePath)) {
window.showMessage(`${newFilePath} exists`, 'error');
return;
}
const mode = await workspace.nvim.call('visualmode');
const range = await workspace.getSelectedRange(mode, doc);
if (!range) return;
const documentText = doc.textDocument.getText();
const [start, end] = getIndexesForSelection(documentText, range);
const produceClass = workspace.getConfiguration('react-refactor').get('produceClass', true);
const result = executeCodeAction(name, documentText, start, end, produceClass);
if (!result) {
window.showMessage(`Extract to file failed`, 'error');
return;
}
const newFileUri = Uri.parse(newFilePath).toString();
const createFile: CreateFile = { kind: 'create', uri: newFileUri };
const replaceEdit: TextDocumentEdit = {
textDocument: doc.textDocument,
edits: [TextEdit.replace(range, result.replaceJSXCode)],
};
const importEdit: TextDocumentEdit = {
textDocument: doc.textDocument,
edits: [TextEdit.insert(Position.create(0, 0), `import { ${name} } from './${name}';\n`)],
};
const edit: WorkspaceEdit = {
documentChanges: [createFile, replaceEdit, importEdit],
};
await workspace.applyEdit(edit);
const newDoc = await workspace.loadFile(newFileUri);
await workspace.jumpTo(newFileUri);
await newDoc.applyEdits([TextEdit.insert(Position.create(0, 0), result.componentCode)]);
await commands.executeCommand('editor.action.format');
ensureReactIsImported();
} catch (error) {
console.error(`Extract to file:`, error);
window.showMessage(`Extract to file failed`, 'error');
}
};
/**
* Get start and end index of selection or range
*
* @param documentText
* @param selectionOrRange
*/
const getIndexesForSelection = (documentText: string, selectionOrRange: Range): number[] => {
const lines = new LinesAndColumns(documentText);
const { start, end } = selectionOrRange;
const startIndex = lines.indexForLocation({
line: start.line,
column: start.character,
});
const endIndex = lines.indexForLocation({
line: end.line,
column: end.character,
});
return [startIndex!, endIndex!];
};
/**
* Check is React imported to document and if not import
*
* @param editor
*/
const ensureReactIsImported = async () => {
const doc = await workspace.document;
const ast = codeToAst(doc.textDocument.getText());
let matched = false;
traverse(ast, {
ImportDeclaration(path: any) {
if (path.node.source.value === 'react') {
matched = true;
path.stop();
}
},
});
if (!matched) {
await doc.applyEdits([TextEdit.insert(Position.create(0, 0), 'import React from "react";\n')]);
}
};
/**
* Extraction Result Type
*/
type RefactorResult = {
replaceJSXCode: string;
componentCode: string;
insertAt: number;
};
/**
* Execute code action
*
* @param name
* @param code
* @param start
* @param end
* @param produceClass
*/
const executeCodeAction = (
name: string,
code: string,
start: number,
end: number,
produceClass = false
): RefactorResult => {
let selectionCode = code.substring(start, end);
if (!isJSX(selectionCode)) {
throw new Error('Invalid JSX selected;');
}
if (!jsxToAst(selectionCode)) {
selectionCode = `<div>${selectionCode}</div>`;
code = code.substring(0, start) + selectionCode + code.substring(end);
end = start + selectionCode.length;
}
const ast = codeToAst(code);
const selectedPath = findSelectedJSXElement(ast, start, end);
if (!selectedPath) {
throw new Error('Invalid JSX selected');
}
const parentPath = findParentComponent(selectedPath);
const referencePaths = findComponentMemberReferences(parentPath, selectedPath);
const paths = referencePaths.filter(isPathInRange(start, end));
const passedProps = {};
const keyAttribute = copyAndRemoveKeyAttribute(selectedPath);
if (keyAttribute) {
passedProps['key'] = keyAttribute;
}
const objects = getContainerObjects(paths);
paths
.filter((path) => !isPathRemoved(path))
.forEach((path) => {
const expression = codeFromNode(path.node);
let name, container;
if (path.isMemberExpression()) {
if (isFunctionBinding(path)) {
path = path.parentPath;
name = path.node.callee.object.property.name;
} else {
name = path.node.property.name;
container = objects.find((o) => expression.startsWith(o.object));
}
} else {
name = path.node.name;
}
if (container) {
name = matchRouteInObject(container, expression);
if (!passedProps[container.property]) {
passedProps[container.property] = t.identifier(container.object);
}
} else {
name = ensurePropertyIsUnique(passedProps, name, expression);
if (!passedProps[name]) {
passedProps[name] = t.cloneDeep(path.node);
}
}
path.replaceWith(createPropsExpression(produceClass, name));
});
const extractedJSX = codeFromNode(selectedPath.node);
const createComponent = produceClass ? generateClassComponent : generatePureComponent;
const replaceJSXCode = codeFromNode(createJSXElement(name, passedProps));
const componentCode = createComponent(name, extractedJSX);
const insertAt = getComponentStartAt(parentPath);
return {
replaceJSXCode,
componentCode,
insertAt,
};
};
/**
* Find parent component class or arrow function declarator
*
* @param path
*/
const findParentComponent = (path: NodePath) => {
const parentPath = path.findParent(
(path) => path.isClassDeclaration() || path.isVariableDeclarator() || path.isFunctionDeclaration()
);
if (!parentPath) {
throw new Error('Invalid component');
}
return parentPath;
};
/**
* Find the frist path in a range
* @param ast
* @param start
* @param end
*/
const findSelectedJSXElement = (ast, start, end) => {
let selectedPath;
traverse(ast, {
JSXElement(path) {
if (path.node.start >= start && path.node.end <= end) {
selectedPath = path;
path.stop();
}
},
});
return selectedPath;
};
/**
* Find common container objects from a list of member expressions
* @param paths
*/
const getContainerObjects = (paths: NodePath[]): { object: string; property: string }[] => {
let objectMap = {};
paths
.filter(
(path) =>
(t.isMemberExpression(path.node) && !t.isThisExpression(path.node.object)) || !t.isMemberExpression(path.node)
)
.forEach((path) => {
const object = codeFromNode(t.isMemberExpression(path.node) ? path.node.object : path.node);
objectMap[object] = objectMap[object] || 0;
objectMap[object]++;
});
objectMap = pickBy(objectMap, (val, key) => val > 1 && !isPropsObject(key));
objectMap = pickBy(objectMap, (_val, key) => !objectMap[key.slice(0, key.lastIndexOf('.'))]);
return Object.keys(objectMap).map((object) => ({
object,
property: object.slice(object.lastIndexOf('.') + 1),
}));
};
const getComponentStartAt = (path) => {
if (path.node.leadingComments && path.node.leadingComments.length) {
return path.node.leadingComments[0].start;
}
return path.node.start;
};
const ensurePropertyIsUnique = (propsMap: Record<string, any>, name: string, value: any) => {
if (!propsMap[name] || codeFromNode(propsMap[name]) === value) {
return name;
}
return ensurePropertyIsUnique(propsMap, `_${name}`, value);
};
const matchRouteInObject = (object: { object: string; property: string }, childObject) =>
[object.property, childObject.slice(object.object.length + 1)].filter((o) => !!o).join('.');
const isPropsObject = (expressionCode: string) =>
expressionCode === 'this.props' || expressionCode === 'this.state' || expressionCode === 'props';
const createPropsExpression = (produceClass, propertyName: string) =>
produceClass
? t.memberExpression(t.memberExpression(t.thisExpression(), t.identifier('props')), t.identifier(propertyName))
: t.memberExpression(t.identifier('props'), t.identifier(propertyName));
const createJSXElement = (name: string, attributes: Record<string, any>) => {
const jsxElement = t.jsxElement(
t.jsxOpeningElement(t.jsxIdentifier(name), []),
t.jsxClosingElement(t.jsxIdentifier(name)),
[],
true
);
Object.keys(attributes).forEach((id) => {
jsxElement.openingElement.attributes.push(
t.jsxAttribute(t.jsxIdentifier(id), t.jsxExpressionContainer(attributes[id]))
);
});
return jsxElement;
};
const copyAndRemoveKeyAttribute = (jsxElementPath: any) => {
if (!jsxElementPath.isJSXElement()) {
return;
}
const openingElement = jsxElementPath.node.openingElement;
let keyAttributePath;
jsxElementPath.traverse({
JSXAttribute(path) {
if (path.node.name.name === 'key' && path.parentPath.node === openingElement) {
keyAttributePath = path;
}
},
});
if (keyAttributePath) {
const value = t.cloneDeep(keyAttributePath.node.value.expression);
keyAttributePath.remove();
return value;
}
}; | the_stack |
import {console as Console} from 'global/window';
import keymirror from 'keymirror';
import {DataFilterExtension} from '@deck.gl/extensions';
import {COORDINATE_SYSTEM} from '@deck.gl/core';
import {TextLayer} from '@deck.gl/layers';
import DefaultLayerIcon from './default-layer-icon';
import {diffUpdateTriggers} from './layer-update';
import {
ALL_FIELD_TYPES,
NO_VALUE_COLOR,
SCALE_TYPES,
CHANNEL_SCALES,
FIELD_OPTS,
SCALE_FUNC,
CHANNEL_SCALE_SUPPORTED_FIELDS,
MAX_GPU_FILTERS
} from 'constants/default-settings';
import {ColorRange, COLOR_RANGES} from 'constants/color-ranges';
import {DataVizColors} from 'constants/custom-color-ranges';
import {
LAYER_VIS_CONFIGS,
DEFAULT_TEXT_LABEL,
DEFAULT_COLOR_UI,
UNKNOWN_COLOR_KEY,
DEFAULT_HIGHLIGHT_COLOR,
DEFAULT_LAYER_LABEL,
LayerVisConfig,
LayerVisConfigSettings
} from './layer-factory';
import {generateHashId, isPlainObject} from 'utils/utils';
import {getLatLngBounds, notNullorUndefined} from 'utils/data-utils';
import {getSampleData} from 'utils/table-utils/data-container-utils';
import {hexToRgb, getColorGroupByName, reverseColorRange} from 'utils/color-utils';
import {RGBColor, RGBAColor, MapState, Filter, Datasets, ValueOf, NestedPartial} from 'reducers';
import {LayerTextLabel, ColorUI} from './layer-factory';
import {KeplerTable} from '../utils';
import {DataContainerInterface} from 'utils/table-utils/data-container-interface';
import {Field, GpuFilter} from 'utils/table-utils/kepler-table';
import React from 'react';
export type LayerColumn = {value: string | null; fieldIdx: number; optional?: boolean};
export type LayerColumns = {
[key: string]: LayerColumn;
};
export type VisualChannelDomain = number[] | string[];
export type VisualChannelField = Field | null;
export type VisualChannelScale = keyof typeof SCALE_TYPES;
export type LayerBaseConfig = {
dataId: string | null;
label: string;
color: RGBColor;
columns: LayerColumns;
isVisible: boolean;
isConfigActive: boolean;
highlightColor: RGBColor | RGBAColor;
hidden: boolean;
visConfig: LayerVisConfig;
textLabel: LayerTextLabel[];
colorUI: {
color: ColorUI;
colorRange: ColorUI;
};
animation: {
enabled: boolean;
domain?: null;
};
};
export type LayerColorConfig = {
colorField: VisualChannelField;
colorDomain: VisualChannelDomain;
colorScale: VisualChannelScale;
};
export type LayerSizeConfig = {
// color by size, domain is set by filters, field, scale type
sizeDomain: VisualChannelDomain;
sizeScale: VisualChannelScale;
sizeField: VisualChannelField;
};
export type LayerHeightConfig = {
heightField: VisualChannelField;
heightDomain: VisualChannelDomain;
heightScale: VisualChannelScale;
};
export type LayerStrokeColorConfig = {
strokeColorField: VisualChannelField;
strokeColorDomain: VisualChannelDomain;
strokeColorScale: VisualChannelScale;
};
export type LayerCoverageConfig = {
coverageField: VisualChannelField;
coverageDomain: VisualChannelDomain;
coverageScale: VisualChannelScale;
};
export type LayerRadiusConfig = {
radiusField: VisualChannelField;
radiusDomain: VisualChannelDomain;
radiusScale: VisualChannelScale;
};
export type LayerWeightConfig = {
weightField: VisualChannelField;
};
export type VisualChannels = {[key: string]: VisualChannel};
export type VisualChannelAggregation = 'colorAggregation' | 'sizeAggregation';
export type VisualChannel = {
property: string;
field: string;
scale: string;
domain: string;
range: string;
key: string;
channelScaleType: string;
nullValue?: any;
defaultMeasure?: any;
accessor?: string;
condition?: (config: any) => boolean;
getAttributeValue?: (config: any) => (d: any) => any;
// TODO: define defaultValue
defaultValue?: any;
// TODO: define fixed
fixed?: any;
supportedFieldTypes?: Array<keyof typeof ALL_FIELD_TYPES>;
aggregation?: VisualChannelAggregation;
};
export type VisualChannelDescription = {
label: string;
measure: string;
};
export type ColumnPairs = {[key: string]: {pair: string; fieldPairKey: string}};
type ColumnValidator = (column: LayerColumn, columns: LayerColumns, allFields: Field[]) => boolean;
export type UpdateTriggers = {
[key: string]: UpdateTrigger;
};
export type UpdateTrigger = {
[key: string]: {};
};
export type LayerBounds = [number, number, number, number];
export type FindDefaultLayerPropsReturnValue = {props: any[]; foundLayers?: any[]};
/**
* Approx. number of points to sample in a large data set
*/
export const LAYER_ID_LENGTH = 6;
const MAX_SAMPLE_SIZE = 5000;
const defaultDomain: [number, number] = [0, 1];
const dataFilterExtension = new DataFilterExtension({filterSize: MAX_GPU_FILTERS});
const defaultDataAccessor = dc => d => d;
const defaultGetFieldValue = (field, d) => field.valueAccessor(d);
export const OVERLAY_TYPE = keymirror({
deckgl: null,
mapboxgl: null
});
export const layerColors = Object.values(DataVizColors).map(hexToRgb);
function* generateColor(): Generator<RGBColor> {
let index = 0;
while (index < layerColors.length + 1) {
if (index === layerColors.length) {
index = 0;
}
yield layerColors[index++];
}
}
export const colorMaker = generateColor();
class Layer {
id: string;
// TODO: define meta
meta: {};
visConfigSettings: {
[key: string]: ValueOf<LayerVisConfigSettings>;
};
config: LayerBaseConfig;
// TODO: define _oldDataUpdateTriggers
_oldDataUpdateTriggers: any;
constructor(
props: {
id?: string;
} & Partial<LayerBaseConfig> = {}
) {
this.id = props.id || generateHashId(LAYER_ID_LENGTH);
// meta
this.meta = {};
// visConfigSettings
this.visConfigSettings = {};
this.config = this.getDefaultLayerConfig({
columns: this.getLayerColumns(),
...props
});
}
get layerIcon(): React.ElementType {
return DefaultLayerIcon;
}
get overlayType(): keyof typeof OVERLAY_TYPE {
return OVERLAY_TYPE.deckgl;
}
get type(): string | null {
return null;
}
get name() {
return this.type;
}
get isAggregated() {
return false;
}
get requiredLayerColumns(): string[] {
return [];
}
get optionalColumns(): string[] {
return [];
}
get noneLayerDataAffectingProps() {
return ['label', 'opacity', 'thickness', 'isVisible', 'hidden'];
}
get visualChannels(): VisualChannels {
return {
color: {
property: 'color',
field: 'colorField',
scale: 'colorScale',
domain: 'colorDomain',
range: 'colorRange',
key: 'color',
channelScaleType: CHANNEL_SCALES.color,
nullValue: NO_VALUE_COLOR,
defaultValue: config => config.color
},
size: {
property: 'size',
field: 'sizeField',
scale: 'sizeScale',
domain: 'sizeDomain',
range: 'sizeRange',
key: 'size',
channelScaleType: CHANNEL_SCALES.size,
nullValue: 0,
defaultValue: 1
}
};
}
get columnValidators(): {[key: string]: ColumnValidator} {
return {};
}
/*
* Column pairs maps layer column to a specific field pairs,
* By default, it is set to null
*/
get columnPairs(): ColumnPairs | null {
return null;
}
/*
* Default point column pairs, can be used for point based layers: point, icon etc.
*/
get defaultPointColumnPairs(): ColumnPairs {
return {
lat: {pair: 'lng', fieldPairKey: 'lat'},
lng: {pair: 'lat', fieldPairKey: 'lng'}
};
}
/*
* Default link column pairs, can be used for link based layers: arc, line etc
*/
get defaultLinkColumnPairs(): ColumnPairs {
return {
lat0: {pair: 'lng0', fieldPairKey: 'lat'},
lng0: {pair: 'lat0', fieldPairKey: 'lng'},
lat1: {pair: 'lng1', fieldPairKey: 'lat'},
lng1: {pair: 'lat1', fieldPairKey: 'lng'}
};
}
/**
* Return a React component for to render layer instructions in a modal
* @returns {object} - an object
* @example
* return {
* id: 'iconInfo',
* template: IconInfoModal,
* modalProps: {
* title: 'How to draw icons'
* };
* }
*/
get layerInfoModal(): any {
return null;
}
/*
* Given a dataset, automatically find props to create layer based on it
* and return the props and previous found layers.
* By default, no layers will be found
*/
static findDefaultLayerProps(
dataset: KeplerTable,
foundLayers?: any[]
): FindDefaultLayerPropsReturnValue {
return {props: [], foundLayers};
}
/**
* Given a array of preset required column names
* found field that has the same name to set as layer column
*
* @param {object} defaultFields
* @param {object[]} allFields
* @returns {object[] | null} all possible required layer column pairs
*/
static findDefaultColumnField(defaultFields, allFields) {
// find all matched fields for each required col
const requiredColumns = Object.keys(defaultFields).reduce((prev, key) => {
const requiredFields = allFields.filter(
f => f.name === defaultFields[key] || defaultFields[key].includes(f.name)
);
prev[key] = requiredFields.length
? requiredFields.map(f => ({
value: f.name,
fieldIdx: f.fieldIdx
}))
: null;
return prev;
}, {});
if (!Object.values(requiredColumns).every(Boolean)) {
// if any field missing, return null
return null;
}
return this.getAllPossibleColumnParis(requiredColumns);
}
static getAllPossibleColumnParis(requiredColumns) {
// for multiple matched field for one required column, return multiple
// combinations, e. g. if column a has 2 matched, column b has 3 matched
// 6 possible column pairs will be returned
const allKeys = Object.keys(requiredColumns);
const pointers = allKeys.map((k, i) => (i === allKeys.length - 1 ? -1 : 0));
const countPerKey = allKeys.map(k => requiredColumns[k].length);
// TODO: Better typings
const pairs: any[] = [];
/* eslint-disable no-loop-func */
while (incrementPointers(pointers, countPerKey, pointers.length - 1)) {
const newPair = pointers.reduce((prev, cuur, i) => {
prev[allKeys[i]] = requiredColumns[allKeys[i]][cuur];
return prev;
}, {});
pairs.push(newPair);
}
/* eslint-enable no-loop-func */
// recursively increment pointers
function incrementPointers(pts, counts, index) {
if (index === 0 && pts[0] === counts[0] - 1) {
// nothing to increment
return false;
}
if (pts[index] + 1 < counts[index]) {
pts[index] = pts[index] + 1;
return true;
}
pts[index] = 0;
return incrementPointers(pts, counts, index - 1);
}
return pairs;
}
static hexToRgb(c) {
return hexToRgb(c);
}
getDefaultLayerConfig(
props: Partial<LayerBaseConfig> = {}
): LayerBaseConfig & Partial<LayerColorConfig & LayerSizeConfig> {
return {
dataId: props.dataId || null,
label: props.label || DEFAULT_LAYER_LABEL,
color: props.color || colorMaker.next().value,
columns: props.columns || {},
isVisible: props.isVisible || false,
isConfigActive: props.isConfigActive || false,
highlightColor: props.highlightColor || DEFAULT_HIGHLIGHT_COLOR,
hidden: props.hidden || false,
// TODO: refactor this into separate visual Channel config
// color by field, domain is set by filters, field, scale type
colorField: null,
colorDomain: [0, 1],
colorScale: SCALE_TYPES.quantile,
// color by size, domain is set by filters, field, scale type
sizeDomain: [0, 1],
sizeScale: SCALE_TYPES.linear,
sizeField: null,
visConfig: {},
textLabel: [DEFAULT_TEXT_LABEL],
colorUI: {
color: DEFAULT_COLOR_UI,
colorRange: DEFAULT_COLOR_UI
},
animation: {enabled: false}
};
}
/**
* Get the description of a visualChannel config
* @param key
* @returns
*/
getVisualChannelDescription(key: string): VisualChannelDescription {
// e.g. label: Color, measure: Vehicle Type
const channel = this.visualChannels[key];
if (!channel) return {label: '', measure: ''};
const rangeSettings = this.visConfigSettings[channel.range];
const fieldSettings = this.config[channel.field];
const label = rangeSettings?.label;
return {
label: typeof label === 'function' ? label(this.config) : label,
measure: fieldSettings
? fieldSettings.displayName || fieldSettings.name
: channel.defaultMeasure
};
}
/**
* Assign a field to layer column, return column config
* @param key - Column Key
* @param field - Selected field
* @returns {{}} - Column config
*/
assignColumn(key: string, field: Field): LayerColumns {
// field value could be null for optional columns
const update = field
? {
value: field.name,
fieldIdx: field.fieldIdx
}
: {value: null, fieldIdx: -1};
return {
...this.config.columns,
[key]: {
...this.config.columns[key],
...update
}
};
}
/**
* Assign a field pair to column config, return column config
* @param key - Column Key
* @param pair - field Pair
* @returns {object} - Column config
*/
assignColumnPairs(key, pair) {
if (!this.columnPairs || !this.columnPairs?.[key]) {
// should not end in this state
return this.config.columns;
}
const {pair: partnerKey, fieldPairKey} = this.columnPairs?.[key];
const {fieldPairKey: partnerFieldPairKey} = this.columnPairs?.[partnerKey];
return {
...this.config.columns,
[key]: pair[fieldPairKey],
[partnerKey]: pair[partnerFieldPairKey]
};
}
/**
* Calculate a radius zoom multiplier to render points, so they are visible in all zoom level
* @param {object} mapState
* @param {number} mapState.zoom - actual zoom
* @param {number | void} mapState.zoomOffset - zoomOffset when render in the plot container for export image
* @returns {number}
*/
getZoomFactor({zoom, zoomOffset = 0}) {
return Math.pow(2, Math.max(14 - zoom + zoomOffset, 0));
}
/**
* Calculate a elevation zoom multiplier to render points, so they are visible in all zoom level
* @param {object} mapState
* @param {number} mapState.zoom - actual zoom
* @param {number | void} mapState.zoomOffset - zoomOffset when render in the plot container for export image
* @returns {number}
*/
getElevationZoomFactor({zoom, zoomOffset = 0}: {zoom: number; zoomOffset?: number}) {
return this.config.visConfig.enableElevationZoomFactor
? Math.pow(2, Math.max(8 - zoom + zoomOffset, 0))
: 1;
}
formatLayerData(datasets: Datasets, oldLayerData?: any) {
return {};
}
renderLayer(...args: any[]): any[] {
return [];
}
getHoverData(object, dataContainer: DataContainerInterface, fields: Field[]) {
if (!object) {
return null;
}
// By default, each entry of layerData should have an index of a row in the original data container.
// Each layer can implement its own getHoverData method
return dataContainer.row(object.index);
}
/**
* When change layer type, try to copy over layer configs as much as possible
* @param configToCopy - config to copy over
* @param visConfigSettings - visConfig settings of config to copy
*/
assignConfigToLayer(configToCopy, visConfigSettings) {
// don't deep merge visualChannel field
// don't deep merge color range, reversed: is not a key by default
const shallowCopy = ['colorRange', 'strokeColorRange'].concat(
Object.values(this.visualChannels).map(v => v.field)
);
// don't copy over domain and animation
const notToCopy = ['animation'].concat(Object.values(this.visualChannels).map(v => v.domain));
// if range is for the same property group copy it, otherwise, not to copy
Object.values(this.visualChannels).forEach(v => {
if (
configToCopy.visConfig[v.range] &&
this.visConfigSettings[v.range] &&
visConfigSettings[v.range].group !== this.visConfigSettings[v.range].group
) {
notToCopy.push(v.range);
}
});
// don't copy over visualChannel range
const currentConfig = this.config;
const copied = this.copyLayerConfig(currentConfig, configToCopy, {
shallowCopy,
notToCopy
});
this.updateLayerConfig(copied);
// validate visualChannel field type and scale types
Object.keys(this.visualChannels).forEach(channel => {
this.validateVisualChannel(channel);
});
}
/*
* Recursively copy config over to an empty layer
* when received saved config, or copy config over from a different layer type
* make sure to only copy over value to existing keys
* @param {object} currentConfig - existing config to be override
* @param {object} configToCopy - new Config to copy over
* @param {string[]} shallowCopy - array of properties to not to be deep copied
* @param {string[]} notToCopy - array of properties not to copy
* @returns {object} - copied config
*/
copyLayerConfig(
currentConfig,
configToCopy,
{shallowCopy = [], notToCopy = []}: {shallowCopy?: string[]; notToCopy?: string[]} = {}
) {
const copied = {};
Object.keys(currentConfig).forEach(key => {
if (
isPlainObject(currentConfig[key]) &&
isPlainObject(configToCopy[key]) &&
!shallowCopy.includes(key) &&
!notToCopy.includes(key)
) {
// recursively assign object value
copied[key] = this.copyLayerConfig(currentConfig[key], configToCopy[key], {
shallowCopy,
notToCopy
});
} else if (notNullorUndefined(configToCopy[key]) && !notToCopy.includes(key)) {
// copy
copied[key] = configToCopy[key];
} else {
// keep existing
copied[key] = currentConfig[key];
}
});
return copied;
}
registerVisConfig(layerVisConfigs: {
[key: string]: keyof LayerVisConfigSettings | ValueOf<LayerVisConfigSettings>;
}) {
Object.keys(layerVisConfigs).forEach(item => {
const configItem = layerVisConfigs[item];
if (typeof configItem === 'string' && LAYER_VIS_CONFIGS[configItem]) {
// if assigned one of default LAYER_CONFIGS
this.config.visConfig[item] = LAYER_VIS_CONFIGS[configItem].defaultValue;
this.visConfigSettings[item] = LAYER_VIS_CONFIGS[configItem];
} else if (
typeof configItem === 'object' &&
['type', 'defaultValue'].every(p => configItem.hasOwnProperty(p))
) {
// if provided customized visConfig, and has type && defaultValue
// TODO: further check if customized visConfig is valid
this.config.visConfig[item] = configItem.defaultValue;
this.visConfigSettings[item] = configItem;
}
});
}
getLayerColumns() {
const columnValidators = this.columnValidators;
const required = this.requiredLayerColumns.reduce(
(accu, key) => ({
...accu,
[key]: columnValidators[key]
? {value: null, fieldIdx: -1, validator: columnValidators[key]}
: {value: null, fieldIdx: -1}
}),
{}
);
const optional = this.optionalColumns.reduce(
(accu, key) => ({
...accu,
[key]: {value: null, fieldIdx: -1, optional: true}
}),
{}
);
return {...required, ...optional};
}
updateLayerConfig<LayerConfig extends LayerBaseConfig = LayerBaseConfig>(
newConfig: Partial<LayerConfig>
): Layer {
this.config = {...this.config, ...newConfig};
return this;
}
updateLayerVisConfig(newVisConfig) {
this.config.visConfig = {...this.config.visConfig, ...newVisConfig};
return this;
}
updateLayerColorUI(prop: string, newConfig: NestedPartial<ColorUI>): Layer {
const {colorUI: previous, visConfig} = this.config;
if (!isPlainObject(newConfig) || typeof prop !== 'string') {
return this;
}
const colorUIProp = Object.entries(newConfig).reduce((accu, [key, value]) => {
return {
...accu,
[key]: isPlainObject(accu[key]) && isPlainObject(value) ? {...accu[key], ...value} : value
};
}, previous[prop] || DEFAULT_COLOR_UI);
const colorUI = {
...previous,
[prop]: colorUIProp
};
this.updateLayerConfig({colorUI});
// if colorUI[prop] is colorRange
const isColorRange = visConfig[prop] && visConfig[prop].colors;
if (isColorRange) {
this.updateColorUIByColorRange(newConfig, prop);
this.updateColorRangeByColorUI(newConfig, previous, prop);
this.updateCustomPalette(newConfig, previous, prop);
}
return this;
}
updateCustomPalette(newConfig, previous, prop) {
if (!newConfig.colorRangeConfig || !newConfig.colorRangeConfig.custom) {
return;
}
const {colorUI, visConfig} = this.config;
if (!visConfig[prop]) return;
const {colors} = visConfig[prop];
const customPalette = {
...colorUI[prop].customPalette,
name: 'Custom Palette',
colors: [...colors]
};
this.updateLayerConfig({
colorUI: {
...colorUI,
[prop]: {
...colorUI[prop],
customPalette
}
}
});
}
/**
* if open dropdown and prop is color range
* Automatically set colorRangeConfig's step and reversed
* @param {*} newConfig
* @param {*} prop
*/
updateColorUIByColorRange(newConfig, prop) {
if (typeof newConfig.showDropdown !== 'number') return;
const {colorUI, visConfig} = this.config;
this.updateLayerConfig({
colorUI: {
...colorUI,
[prop]: {
...colorUI[prop],
colorRangeConfig: {
...colorUI[prop].colorRangeConfig,
steps: visConfig[prop].colors.length,
reversed: Boolean(visConfig[prop].reversed)
}
}
}
});
}
updateColorRangeByColorUI(newConfig, previous, prop) {
// only update colorRange if changes in UI is made to 'reversed', 'steps' or steps
const shouldUpdate =
newConfig.colorRangeConfig &&
['reversed', 'steps'].some(
key =>
newConfig.colorRangeConfig.hasOwnProperty(key) &&
newConfig.colorRangeConfig[key] !==
(previous[prop] || DEFAULT_COLOR_UI).colorRangeConfig[key]
);
if (!shouldUpdate) return;
const {colorUI, visConfig} = this.config;
const {steps, reversed} = colorUI[prop].colorRangeConfig;
const colorRange = visConfig[prop];
// find based on step or reversed
let update;
if (newConfig.colorRangeConfig.hasOwnProperty('steps')) {
const group = getColorGroupByName(colorRange);
if (group) {
const sameGroup = COLOR_RANGES.filter(cr => getColorGroupByName(cr) === group);
update = sameGroup.find(cr => cr.colors.length === steps);
if (update && colorRange.reversed) {
update = reverseColorRange(true, update);
}
}
}
if (newConfig.colorRangeConfig.hasOwnProperty('reversed')) {
update = reverseColorRange(reversed, update || colorRange);
}
if (update) {
this.updateLayerVisConfig({[prop]: update});
}
}
/**
* Check whether layer has all columns
* @returns yes or no
*/
hasAllColumns(): boolean {
const {columns} = this.config;
return (
columns &&
Object.values(columns).every(v => {
return Boolean(v.optional || (v.value && v.fieldIdx > -1));
})
);
}
/**
* Check whether layer has data
*
* @param {Array | Object} layerData
* @returns {boolean} yes or no
*/
hasLayerData(layerData) {
if (!layerData) {
return false;
}
return Boolean(layerData.data && layerData.data.length);
}
isValidToSave(): boolean {
return Boolean(this.type && this.hasAllColumns());
}
shouldRenderLayer(data): boolean {
return (
Boolean(this.type) &&
this.hasAllColumns() &&
this.hasLayerData(data) &&
typeof this.renderLayer === 'function'
);
}
getColorScale(colorScale: string, colorDomain: VisualChannelDomain, colorRange: ColorRange) {
if (Array.isArray(colorRange.colorMap)) {
const cMap = new Map();
colorRange.colorMap.forEach(([k, v]) => {
cMap.set(k, typeof v === 'string' ? hexToRgb(v) : v);
});
const scale = SCALE_FUNC[SCALE_TYPES.ordinal]()
.domain(cMap.keys())
.range(cMap.values())
.unknown(cMap.get(UNKNOWN_COLOR_KEY) || NO_VALUE_COLOR);
return scale;
}
return this.getVisChannelScale(colorScale, colorDomain, colorRange.colors.map(hexToRgb));
}
/**
* Mapping from visual channels to deck.gl accesors
* @param {Object} param Parameters
* @param {Function} param.dataAccessor Access kepler.gl layer data from deck.gl layer
* @param {import('utils/table-utils/data-container-interface').DataContainerInterface} param.dataContainer DataContainer to use use with dataAccessor
* @return {Object} attributeAccessors - deck.gl layer attribute accessors
*/
getAttributeAccessors({
dataAccessor = defaultDataAccessor,
dataContainer
}: {
dataAccessor?: typeof defaultDataAccessor;
dataContainer: DataContainerInterface;
}) {
const attributeAccessors: {[key: string]: any} = {};
Object.keys(this.visualChannels).forEach(channel => {
const {
field,
fixed,
scale,
domain,
range,
accessor,
defaultValue,
getAttributeValue,
nullValue,
channelScaleType
} = this.visualChannels[channel];
if (accessor) {
const shouldGetScale = this.config[field];
if (shouldGetScale) {
const isFixed = fixed && this.config.visConfig[fixed];
const scaleFunction =
channelScaleType === CHANNEL_SCALES.color
? this.getColorScale(
this.config[scale],
this.config[domain],
this.config.visConfig[range]
)
: this.getVisChannelScale(
this.config[scale],
this.config[domain],
this.config.visConfig[range],
isFixed
);
attributeAccessors[accessor] = d =>
this.getEncodedChannelValue(
scaleFunction,
dataAccessor(dataContainer)(d),
this.config[field],
nullValue
);
} else if (typeof getAttributeValue === 'function') {
attributeAccessors[accessor] = getAttributeValue(this.config);
} else {
attributeAccessors[accessor] =
typeof defaultValue === 'function' ? defaultValue(this.config) : defaultValue;
}
if (!attributeAccessors[accessor]) {
Console.warn(`Failed to provide accessor function for ${accessor || channel}`);
}
}
});
return attributeAccessors;
}
getVisChannelScale(
scale: string,
domain: VisualChannelDomain,
range: any,
fixed?: boolean
): () => any | null {
return SCALE_FUNC[fixed ? 'linear' : scale]()
.domain(domain)
.range(fixed ? domain : range);
}
/**
* Get longitude and latitude bounds of the data.
* @param {import('utils/table-utils/data-container-interface').DataContainerInterface} dataContainer DataContainer to calculate bounds for.
* @param {(d: {index: number}, dc: import('utils/table-utils/data-container-interface').DataContainerInterface) => number[]} getPosition Access kepler.gl layer data from deck.gl layer
* @return {number[]|null} bounds of the data.
*/
getPointsBounds(dataContainer, getPosition) {
// no need to loop through the entire dataset
// get a sample of data to calculate bounds
const sampleData =
dataContainer.numRows() > MAX_SAMPLE_SIZE
? getSampleData(dataContainer, MAX_SAMPLE_SIZE)
: dataContainer;
const points = sampleData.mapIndex(getPosition);
const latBounds = getLatLngBounds(points, 1, [-90, 90]);
const lngBounds = getLatLngBounds(points, 0, [-180, 180]);
if (!latBounds || !lngBounds) {
return null;
}
return [lngBounds[0], latBounds[0], lngBounds[1], latBounds[1]];
}
getChangedTriggers(dataUpdateTriggers) {
const triggerChanged = diffUpdateTriggers(dataUpdateTriggers, this._oldDataUpdateTriggers);
this._oldDataUpdateTriggers = dataUpdateTriggers;
return triggerChanged;
}
getEncodedChannelValue(
scale: (value) => any,
data: any[],
field: VisualChannelField,
nullValue = NO_VALUE_COLOR,
getValue = defaultGetFieldValue
) {
// @ts-expect-error TODO: VisualChannelField better typing
const {type} = field;
const value = getValue(field, data);
if (!notNullorUndefined(value)) {
return nullValue;
}
let attributeValue;
if (type === ALL_FIELD_TYPES.timestamp) {
// shouldn't need to convert here
// scale Function should take care of it
attributeValue = scale(new Date(value));
} else {
attributeValue = scale(value);
}
if (!notNullorUndefined(attributeValue)) {
attributeValue = nullValue;
}
return attributeValue;
}
updateMeta(meta) {
this.meta = {...this.meta, ...meta};
}
// @ts-expect-error
getDataUpdateTriggers({filteredIndex, id, allData}: KeplerTable): any {
const {columns} = this.config;
return {
getData: {datasetId: id, allData, columns, filteredIndex},
getMeta: {datasetId: id, allData, columns},
...(this.config.textLabel || []).reduce(
(accu, tl, i) => ({
...accu,
[`getLabelCharacterSet-${i}`]: tl.field ? tl.field.name : null
}),
{}
)
};
}
updateData(datasets, oldLayerData) {
if (!this.config.dataId) {
return {};
}
const layerDataset = datasets[this.config.dataId];
const {dataContainer} = layerDataset;
const getPosition = this.getPositionAccessor(dataContainer);
const dataUpdateTriggers = this.getDataUpdateTriggers(layerDataset);
const triggerChanged = this.getChangedTriggers(dataUpdateTriggers);
if (triggerChanged && triggerChanged.getMeta) {
this.updateLayerMeta(dataContainer, getPosition);
}
let data = [];
if (!(triggerChanged && triggerChanged.getData) && oldLayerData && oldLayerData.data) {
// same data
data = oldLayerData.data;
} else {
data = this.calculateDataAttribute(layerDataset, getPosition);
}
return {data, triggerChanged};
}
/**
* helper function to update one layer domain when state.data changed
* if state.data change is due ot update filter, newFiler will be passed
* called by updateAllLayerDomainData
* @param datasets
* @param newFilter
* @returns layer
*/
updateLayerDomain(datasets: Datasets, newFilter?: Filter): Layer {
const table = this.getDataset(datasets);
if (!table) {
return this;
}
Object.values(this.visualChannels).forEach(channel => {
const {scale} = channel;
const scaleType = this.config[scale];
// ordinal domain is based on dataContainer, if only filter changed
// no need to update ordinal domain
if (!newFilter || scaleType !== SCALE_TYPES.ordinal) {
const {domain} = channel;
const updatedDomain = this.calculateLayerDomain(table, channel);
this.updateLayerConfig({[domain]: updatedDomain});
}
});
return this;
}
getDataset(datasets) {
return this.config.dataId ? datasets[this.config.dataId] : null;
}
/**
* Validate visual channel field and scales based on supported field & scale type
* @param channel
*/
validateVisualChannel(channel: string) {
this.validateFieldType(channel);
this.validateScale(channel);
}
/**
* Validate field type based on channelScaleType
*/
validateFieldType(channel: string) {
const visualChannel = this.visualChannels[channel];
const {field, channelScaleType, supportedFieldTypes} = visualChannel;
if (this.config[field]) {
// if field is selected, check if field type is supported
const channelSupportedFieldTypes =
supportedFieldTypes || CHANNEL_SCALE_SUPPORTED_FIELDS[channelScaleType];
if (!channelSupportedFieldTypes.includes(this.config[field].type)) {
// field type is not supported, set it back to null
// set scale back to default
this.updateLayerConfig({[field]: null});
}
}
}
/**
* Validate scale type based on aggregation
*/
validateScale(channel) {
const visualChannel = this.visualChannels[channel];
const {scale} = visualChannel;
if (!scale) {
// visualChannel doesn't have scale
return;
}
const scaleOptions = this.getScaleOptions(channel);
// check if current selected scale is
// supported, if not, change to default
if (!scaleOptions.includes(this.config[scale])) {
this.updateLayerConfig({[scale]: scaleOptions[0]});
}
}
/**
* Get scale options based on current field
* @param {string} channel
* @returns {string[]}
*/
getScaleOptions(channel) {
const visualChannel = this.visualChannels[channel];
const {field, scale, channelScaleType} = visualChannel;
return this.config[field]
? FIELD_OPTS[this.config[field].type].scale[channelScaleType]
: [this.getDefaultLayerConfig()[scale]];
}
updateLayerVisualChannel(dataset: KeplerTable, channel: string) {
const visualChannel = this.visualChannels[channel];
this.validateVisualChannel(channel);
// calculate layer channel domain
const updatedDomain = this.calculateLayerDomain(dataset, visualChannel);
this.updateLayerConfig({[visualChannel.domain]: updatedDomain});
}
getVisualChannelUpdateTriggers(): UpdateTriggers {
const updateTriggers: UpdateTriggers = {};
Object.values(this.visualChannels).forEach(visualChannel => {
// field range scale domain
const {accessor, field, scale, domain, range, defaultValue, fixed} = visualChannel;
if (accessor) {
updateTriggers[accessor] = {
[field]: this.config[field],
[scale]: this.config[scale],
[domain]: this.config[domain],
[range]: this.config.visConfig[range],
defaultValue:
typeof defaultValue === 'function' ? defaultValue(this.config) : defaultValue,
...(fixed ? {[fixed]: this.config.visConfig[fixed]} : {})
};
}
});
return updateTriggers;
}
calculateLayerDomain(dataset, visualChannel) {
const {scale} = visualChannel;
const scaleType = this.config[scale];
const field = this.config[visualChannel.field];
if (!field) {
// if colorField or sizeField were set back to null
return defaultDomain;
}
return dataset.getColumnLayerDomain(field, scaleType) || defaultDomain;
}
hasHoveredObject(objectInfo) {
return this.isLayerHovered(objectInfo) && objectInfo.object ? objectInfo.object : null;
}
isLayerHovered(objectInfo): boolean {
return objectInfo?.picked && objectInfo?.layer?.props?.id === this.id;
}
getRadiusScaleByZoom(mapState: MapState, fixedRadius?: boolean) {
const radiusChannel = Object.values(this.visualChannels).find(vc => vc.property === 'radius');
if (!radiusChannel) {
return 1;
}
const field = radiusChannel.field;
const fixed = fixedRadius === undefined ? this.config.visConfig.fixedRadius : fixedRadius;
const {radius} = this.config.visConfig;
return fixed ? 1 : (this.config[field] ? 1 : radius) * this.getZoomFactor(mapState);
}
shouldCalculateLayerData(props: string[]) {
return props.some(p => !this.noneLayerDataAffectingProps.includes(p));
}
getBrushingExtensionProps(interactionConfig, brushingTarget?) {
const {brush} = interactionConfig;
return {
// brushing
autoHighlight: !brush.enabled,
brushingRadius: brush.config.size * 1000,
brushingTarget: brushingTarget || 'source',
brushingEnabled: brush.enabled
};
}
getDefaultDeckLayerProps({
idx,
gpuFilter,
mapState,
visible
}: {
idx: number;
gpuFilter: GpuFilter;
mapState: MapState;
visible: boolean;
}) {
return {
id: this.id,
idx,
coordinateSystem: COORDINATE_SYSTEM.LNGLAT,
pickable: true,
wrapLongitude: true,
parameters: {depthTest: Boolean(mapState.dragRotate || this.config.visConfig.enable3d)},
hidden: this.config.hidden,
// visconfig
opacity: this.config.visConfig.opacity,
highlightColor: this.config.highlightColor,
// data filtering
extensions: [dataFilterExtension],
filterRange: gpuFilter ? gpuFilter.filterRange : undefined,
// layer should be visible and if splitMap, shown in to one of panel
visible: this.config.isVisible && visible
};
}
getDefaultHoverLayerProps() {
return {
id: `${this.id}-hovered`,
pickable: false,
wrapLongitude: true,
coordinateSystem: COORDINATE_SYSTEM.LNGLAT
};
}
renderTextLabelLayer({getPosition, getPixelOffset, updateTriggers, sharedProps}, renderOpts) {
const {data, mapState} = renderOpts;
const {textLabel} = this.config;
return data.textLabels.reduce((accu, d, i) => {
if (d.getText) {
accu.push(
new TextLayer({
...sharedProps,
id: `${this.id}-label-${textLabel[i].field?.name}`,
data: data.data,
getText: d.getText,
getPosition,
characterSet: d.characterSet,
getPixelOffset: getPixelOffset(textLabel[i]),
getSize: 1,
sizeScale: textLabel[i].size,
getTextAnchor: textLabel[i].anchor,
getAlignmentBaseline: textLabel[i].alignment,
getColor: textLabel[i].color,
parameters: {
// text will always show on top of all layers
depthTest: false
},
getFilterValue: data.getFilterValue,
updateTriggers: {
...updateTriggers,
getText: textLabel[i].field?.name,
getPixelOffset: {
...updateTriggers.getRadius,
mapState,
anchor: textLabel[i].anchor,
alignment: textLabel[i].alignment
},
getTextAnchor: textLabel[i].anchor,
getAlignmentBaseline: textLabel[i].alignment,
getColor: textLabel[i].color
}
})
);
}
return accu;
}, []);
}
calculateDataAttribute(keplerTable: KeplerTable, getPosition): any {
// implemented in subclasses
return [];
}
updateLayerMeta(dataContainer: DataContainerInterface, getPosition) {
// implemented in subclasses
}
getPositionAccessor(dataContainer?: DataContainerInterface): (...args: any[]) => any {
// implemented in subclasses
return () => null;
}
}
export default Layer; | the_stack |
import * as $protobuf from 'protobufjs';
/** Namespace tensorflow. */
export namespace tensorflow {
/** Properties of an Any. */
interface IAny {
/** Any typeUrl */
typeUrl?: (string|null);
/** Any value */
value?: (Uint8Array|null);
}
/** Represents an Any. */
class Any implements IAny {
/**
* Constructs a new Any.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.IAny);
/** Any typeUrl. */
public typeUrl: string;
/** Any value. */
public value: Uint8Array;
/**
* Decodes an Any message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns Any
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.Any;
}
/** DataType enum. */
enum DataType {
DT_INVALID = 0,
DT_FLOAT = 1,
DT_DOUBLE = 2,
DT_INT32 = 3,
DT_UINT8 = 4,
DT_INT16 = 5,
DT_INT8 = 6,
DT_STRING = 7,
DT_COMPLEX64 = 8,
DT_INT64 = 9,
DT_BOOL = 10,
DT_QINT8 = 11,
DT_QUINT8 = 12,
DT_QINT32 = 13,
DT_BFLOAT16 = 14,
DT_FLOAT_REF = 101,
DT_DOUBLE_REF = 102,
DT_INT32_REF = 103,
DT_UINT8_REF = 104,
DT_INT16_REF = 105,
DT_INT8_REF = 106,
DT_STRING_REF = 107,
DT_COMPLEX64_REF = 108,
DT_INT64_REF = 109,
DT_BOOL_REF = 110,
DT_QINT8_REF = 111,
DT_QUINT8_REF = 112,
DT_QINT32_REF = 113,
DT_BFLOAT16_REF = 114
}
/** Properties of a TensorShape. */
interface ITensorShape {
/** TensorShape dim */
dim?: (tensorflow.TensorShape.IDim[]|null);
/** TensorShape unknownRank */
unknownRank?: (boolean|null);
}
/** Represents a TensorShape. */
class TensorShape implements ITensorShape {
/**
* Constructs a new TensorShape.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.ITensorShape);
/** TensorShape dim. */
public dim: tensorflow.TensorShape.IDim[];
/** TensorShape unknownRank. */
public unknownRank: boolean;
/**
* Decodes a TensorShape message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns TensorShape
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.TensorShape;
}
namespace TensorShape {
/** Properties of a Dim. */
interface IDim {
/** Dim size */
size?: (number|Long|null);
/** Dim name */
name?: (string|null);
}
/** Represents a Dim. */
class Dim implements IDim {
/**
* Constructs a new Dim.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.TensorShape.IDim);
/** Dim size. */
public size: (number|Long);
/** Dim name. */
public name: string;
/**
* Decodes a Dim message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns Dim
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.TensorShape.Dim;
}
}
/** Properties of a Tensor. */
interface ITensor {
/** Tensor dtype */
dtype?: (tensorflow.DataType|null);
/** Tensor tensorShape */
tensorShape?: (tensorflow.ITensorShape|null);
/** Tensor versionNumber */
versionNumber?: (number|null);
/** Tensor tensorContent */
tensorContent?: (Uint8Array|null);
/** Tensor floatVal */
floatVal?: (number[]|null);
/** Tensor doubleVal */
doubleVal?: (number[]|null);
/** Tensor intVal */
intVal?: (number[]|null);
/** Tensor stringVal */
stringVal?: (Uint8Array[]|null);
/** Tensor scomplexVal */
scomplexVal?: (number[]|null);
/** Tensor int64Val */
int64Val?: ((number | Long)[]|null);
/** Tensor boolVal */
boolVal?: (boolean[]|null);
/** Tensor uint32Val */
uint32Val?: (number[]|null);
/** Tensor uint64Val */
uint64Val?: ((number | Long)[]|null);
}
/** Represents a Tensor. */
class Tensor implements ITensor {
/**
* Constructs a new Tensor.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.ITensor);
/** Tensor dtype. */
public dtype: tensorflow.DataType;
/** Tensor tensorShape. */
public tensorShape?: (tensorflow.ITensorShape|null);
/** Tensor versionNumber. */
public versionNumber: number;
/** Tensor tensorContent. */
public tensorContent: Uint8Array;
/** Tensor floatVal. */
public floatVal: number[];
/** Tensor doubleVal. */
public doubleVal: number[];
/** Tensor intVal. */
public intVal: number[];
/** Tensor stringVal. */
public stringVal: Uint8Array[];
/** Tensor scomplexVal. */
public scomplexVal: number[];
/** Tensor int64Val. */
public int64Val: (number|Long)[];
/** Tensor boolVal. */
public boolVal: boolean[];
/** Tensor uint32Val. */
public uint32Val: number[];
/** Tensor uint64Val. */
public uint64Val: (number|Long)[];
/**
* Decodes a Tensor message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns Tensor
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.Tensor;
}
/** Properties of an AttrValue. */
interface IAttrValue {
/** AttrValue list */
list?: (tensorflow.AttrValue.IListValue|null);
/** AttrValue s */
s?: (Uint8Array|null);
/** AttrValue i */
i?: (number|Long|null);
/** AttrValue f */
f?: (number|null);
/** AttrValue b */
b?: (boolean|null);
/** AttrValue type */
type?: (tensorflow.DataType|null);
/** AttrValue shape */
shape?: (tensorflow.ITensorShape|null);
/** AttrValue tensor */
tensor?: (tensorflow.ITensor|null);
/** AttrValue placeholder */
placeholder?: (string|null);
/** AttrValue func */
func?: (tensorflow.INameAttrList|null);
}
/** Represents an AttrValue. */
class AttrValue implements IAttrValue {
/**
* Constructs a new AttrValue.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.IAttrValue);
/** AttrValue list. */
public list?: (tensorflow.AttrValue.IListValue|null);
/** AttrValue s. */
public s: Uint8Array;
/** AttrValue i. */
public i: (number|Long);
/** AttrValue f. */
public f: number;
/** AttrValue b. */
public b: boolean;
/** AttrValue type. */
public type: tensorflow.DataType;
/** AttrValue shape. */
public shape?: (tensorflow.ITensorShape|null);
/** AttrValue tensor. */
public tensor?: (tensorflow.ITensor|null);
/** AttrValue placeholder. */
public placeholder: string;
/** AttrValue func. */
public func?: (tensorflow.INameAttrList|null);
/** AttrValue value. */
public value?: ('list'|'s'|'i'|'f'|'b'|'type'|'shape'|'tensor'|
'placeholder'|'func');
/**
* Decodes an AttrValue message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns AttrValue
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.AttrValue;
}
namespace AttrValue {
/** Properties of a ListValue. */
interface IListValue {
/** ListValue s */
s?: (Uint8Array[]|null);
/** ListValue i */
i?: ((number | Long)[]|null);
/** ListValue f */
f?: (number[]|null);
/** ListValue b */
b?: (boolean[]|null);
/** ListValue type */
type?: (tensorflow.DataType[]|null);
/** ListValue shape */
shape?: (tensorflow.ITensorShape[]|null);
/** ListValue tensor */
tensor?: (tensorflow.ITensor[]|null);
/** ListValue func */
func?: (tensorflow.INameAttrList[]|null);
}
/** Represents a ListValue. */
class ListValue implements IListValue {
/**
* Constructs a new ListValue.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.AttrValue.IListValue);
/** ListValue s. */
public s: Uint8Array[];
/** ListValue i. */
public i: (number|Long)[];
/** ListValue f. */
public f: number[];
/** ListValue b. */
public b: boolean[];
/** ListValue type. */
public type: tensorflow.DataType[];
/** ListValue shape. */
public shape: tensorflow.ITensorShape[];
/** ListValue tensor. */
public tensor: tensorflow.ITensor[];
/** ListValue func. */
public func: tensorflow.INameAttrList[];
/**
* Decodes a ListValue message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns ListValue
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.AttrValue.ListValue;
}
}
/** Properties of a NameAttrList. */
interface INameAttrList {
/** NameAttrList name */
name?: (string|null);
/** NameAttrList attr */
attr?: ({[k: string]: tensorflow.IAttrValue}|null);
}
/** Represents a NameAttrList. */
class NameAttrList implements INameAttrList {
/**
* Constructs a new NameAttrList.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.INameAttrList);
/** NameAttrList name. */
public name: string;
/** NameAttrList attr. */
public attr: {[k: string]: tensorflow.IAttrValue};
/**
* Decodes a NameAttrList message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns NameAttrList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.NameAttrList;
}
/** Properties of a NodeDef. */
interface INodeDef {
/** NodeDef name */
name?: (string|null);
/** NodeDef op */
op?: (string|null);
/** NodeDef input */
input?: (string[]|null);
/** NodeDef device */
device?: (string|null);
/** NodeDef attr */
attr?: ({[k: string]: tensorflow.IAttrValue}|null);
}
/** Represents a NodeDef. */
class NodeDef implements INodeDef {
/**
* Constructs a new NodeDef.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.INodeDef);
/** NodeDef name. */
public name: string;
/** NodeDef op. */
public op: string;
/** NodeDef input. */
public input: string[];
/** NodeDef device. */
public device: string;
/** NodeDef attr. */
public attr: {[k: string]: tensorflow.IAttrValue};
/**
* Decodes a NodeDef message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns NodeDef
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.NodeDef;
}
/** Properties of a VersionDef. */
interface IVersionDef {
/** VersionDef producer */
producer?: (number|null);
/** VersionDef minConsumer */
minConsumer?: (number|null);
/** VersionDef badConsumers */
badConsumers?: (number[]|null);
}
/** Represents a VersionDef. */
class VersionDef implements IVersionDef {
/**
* Constructs a new VersionDef.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.IVersionDef);
/** VersionDef producer. */
public producer: number;
/** VersionDef minConsumer. */
public minConsumer: number;
/** VersionDef badConsumers. */
public badConsumers: number[];
/**
* Decodes a VersionDef message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns VersionDef
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.VersionDef;
}
/** Properties of a GraphDef. */
interface IGraphDef {
/** GraphDef node */
node?: (tensorflow.INodeDef[]|null);
/** GraphDef versions */
versions?: (tensorflow.IVersionDef|null);
/** GraphDef library */
library?: (tensorflow.IFunctionDefLibrary|null);
}
/** Represents a GraphDef. */
class GraphDef implements IGraphDef {
/**
* Constructs a new GraphDef.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.IGraphDef);
/** GraphDef node. */
public node: tensorflow.INodeDef[];
/** GraphDef versions. */
public versions?: (tensorflow.IVersionDef|null);
/** GraphDef library. */
public library?: (tensorflow.IFunctionDefLibrary|null);
/**
* Decodes a GraphDef message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns GraphDef
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.GraphDef;
}
/** Properties of a CollectionDef. */
interface ICollectionDef {
/** CollectionDef nodeList */
nodeList?: (tensorflow.CollectionDef.INodeList|null);
/** CollectionDef bytesList */
bytesList?: (tensorflow.CollectionDef.IBytesList|null);
/** CollectionDef int64List */
int64List?: (tensorflow.CollectionDef.IInt64List|null);
/** CollectionDef floatList */
floatList?: (tensorflow.CollectionDef.IFloatList|null);
/** CollectionDef anyList */
anyList?: (tensorflow.CollectionDef.IAnyList|null);
}
/** Represents a CollectionDef. */
class CollectionDef implements ICollectionDef {
/**
* Constructs a new CollectionDef.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.ICollectionDef);
/** CollectionDef nodeList. */
public nodeList?: (tensorflow.CollectionDef.INodeList|null);
/** CollectionDef bytesList. */
public bytesList?: (tensorflow.CollectionDef.IBytesList|null);
/** CollectionDef int64List. */
public int64List?: (tensorflow.CollectionDef.IInt64List|null);
/** CollectionDef floatList. */
public floatList?: (tensorflow.CollectionDef.IFloatList|null);
/** CollectionDef anyList. */
public anyList?: (tensorflow.CollectionDef.IAnyList|null);
/** CollectionDef kind. */
public kind?: ('nodeList'|'bytesList'|'int64List'|'floatList'|'anyList');
/**
* Decodes a CollectionDef message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns CollectionDef
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.CollectionDef;
}
namespace CollectionDef {
/** Properties of a NodeList. */
interface INodeList {
/** NodeList value */
value?: (string[]|null);
}
/** Represents a NodeList. */
class NodeList implements INodeList {
/**
* Constructs a new NodeList.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.CollectionDef.INodeList);
/** NodeList value. */
public value: string[];
/**
* Decodes a NodeList message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns NodeList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.CollectionDef.NodeList;
}
/** Properties of a BytesList. */
interface IBytesList {
/** BytesList value */
value?: (Uint8Array[]|null);
}
/** Represents a BytesList. */
class BytesList implements IBytesList {
/**
* Constructs a new BytesList.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.CollectionDef.IBytesList);
/** BytesList value. */
public value: Uint8Array[];
/**
* Decodes a BytesList message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns BytesList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.CollectionDef.BytesList;
}
/** Properties of an Int64List. */
interface IInt64List {
/** Int64List value */
value?: ((number | Long)[]|null);
}
/** Represents an Int64List. */
class Int64List implements IInt64List {
/**
* Constructs a new Int64List.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.CollectionDef.IInt64List);
/** Int64List value. */
public value: (number|Long)[];
/**
* Decodes an Int64List message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns Int64List
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.CollectionDef.Int64List;
}
/** Properties of a FloatList. */
interface IFloatList {
/** FloatList value */
value?: (number[]|null);
}
/** Represents a FloatList. */
class FloatList implements IFloatList {
/**
* Constructs a new FloatList.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.CollectionDef.IFloatList);
/** FloatList value. */
public value: number[];
/**
* Decodes a FloatList message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns FloatList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.CollectionDef.FloatList;
}
/** Properties of an AnyList. */
interface IAnyList {
/** AnyList value */
value?: (tensorflow.IAny[]|null);
}
/** Represents an AnyList. */
class AnyList implements IAnyList {
/**
* Constructs a new AnyList.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.CollectionDef.IAnyList);
/** AnyList value. */
public value: tensorflow.IAny[];
/**
* Decodes an AnyList message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns AnyList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.CollectionDef.AnyList;
}
}
/** Properties of a SaverDef. */
interface ISaverDef {
/** SaverDef filenameTensorName */
filenameTensorName?: (string|null);
/** SaverDef saveTensorName */
saveTensorName?: (string|null);
/** SaverDef restoreOpName */
restoreOpName?: (string|null);
/** SaverDef maxToKeep */
maxToKeep?: (number|null);
/** SaverDef sharded */
sharded?: (boolean|null);
/** SaverDef keepCheckpointEveryNHours */
keepCheckpointEveryNHours?: (number|null);
/** SaverDef version */
version?: (tensorflow.SaverDef.CheckpointFormatVersion|null);
}
/** Represents a SaverDef. */
class SaverDef implements ISaverDef {
/**
* Constructs a new SaverDef.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.ISaverDef);
/** SaverDef filenameTensorName. */
public filenameTensorName: string;
/** SaverDef saveTensorName. */
public saveTensorName: string;
/** SaverDef restoreOpName. */
public restoreOpName: string;
/** SaverDef maxToKeep. */
public maxToKeep: number;
/** SaverDef sharded. */
public sharded: boolean;
/** SaverDef keepCheckpointEveryNHours. */
public keepCheckpointEveryNHours: number;
/** SaverDef version. */
public version: tensorflow.SaverDef.CheckpointFormatVersion;
/**
* Decodes a SaverDef message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns SaverDef
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.SaverDef;
}
namespace SaverDef {
/** CheckpointFormatVersion enum. */
enum CheckpointFormatVersion { LEGACY = 0, V1 = 1, V2 = 2 }
}
/** Properties of a TensorInfo. */
interface ITensorInfo {
/** TensorInfo name */
name?: (string|null);
/** TensorInfo cooSparse */
cooSparse?: (tensorflow.TensorInfo.ICooSparse|null);
/** TensorInfo dtype */
dtype?: (tensorflow.DataType|null);
/** TensorInfo tensorShape */
tensorShape?: (tensorflow.ITensorShape|null);
}
/** Represents a TensorInfo. */
class TensorInfo implements ITensorInfo {
/**
* Constructs a new TensorInfo.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.ITensorInfo);
/** TensorInfo name. */
public name: string;
/** TensorInfo cooSparse. */
public cooSparse?: (tensorflow.TensorInfo.ICooSparse|null);
/** TensorInfo dtype. */
public dtype: tensorflow.DataType;
/** TensorInfo tensorShape. */
public tensorShape?: (tensorflow.ITensorShape|null);
/** TensorInfo encoding. */
public encoding?: ('name'|'cooSparse');
/**
* Decodes a TensorInfo message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns TensorInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.TensorInfo;
}
namespace TensorInfo {
/** Properties of a CooSparse. */
interface ICooSparse {
/** CooSparse valuesTensorName */
valuesTensorName?: (string|null);
/** CooSparse indicesTensorName */
indicesTensorName?: (string|null);
/** CooSparse denseShapeTensorName */
denseShapeTensorName?: (string|null);
}
/** Represents a CooSparse. */
class CooSparse implements ICooSparse {
/**
* Constructs a new CooSparse.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.TensorInfo.ICooSparse);
/** CooSparse valuesTensorName. */
public valuesTensorName: string;
/** CooSparse indicesTensorName. */
public indicesTensorName: string;
/** CooSparse denseShapeTensorName. */
public denseShapeTensorName: string;
/**
* Decodes a CooSparse message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns CooSparse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.TensorInfo.CooSparse;
}
}
/** Properties of a SignatureDef. */
interface ISignatureDef {
/** SignatureDef inputs */
inputs?: ({[k: string]: tensorflow.ITensorInfo}|null);
/** SignatureDef outputs */
outputs?: ({[k: string]: tensorflow.ITensorInfo}|null);
/** SignatureDef methodName */
methodName?: (string|null);
}
/** Represents a SignatureDef. */
class SignatureDef implements ISignatureDef {
/**
* Constructs a new SignatureDef.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.ISignatureDef);
/** SignatureDef inputs. */
public inputs: {[k: string]: tensorflow.ITensorInfo};
/** SignatureDef outputs. */
public outputs: {[k: string]: tensorflow.ITensorInfo};
/** SignatureDef methodName. */
public methodName: string;
/**
* Decodes a SignatureDef message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns SignatureDef
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.SignatureDef;
}
/** Properties of an AssetFileDef. */
interface IAssetFileDef {
/** AssetFileDef tensorInfo */
tensorInfo?: (tensorflow.ITensorInfo|null);
/** AssetFileDef filename */
filename?: (string|null);
}
/** Represents an AssetFileDef. */
class AssetFileDef implements IAssetFileDef {
/**
* Constructs a new AssetFileDef.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.IAssetFileDef);
/** AssetFileDef tensorInfo. */
public tensorInfo?: (tensorflow.ITensorInfo|null);
/** AssetFileDef filename. */
public filename: string;
/**
* Decodes an AssetFileDef message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns AssetFileDef
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.AssetFileDef;
}
/** Properties of an OpDef. */
interface IOpDef {
/** OpDef name */
name?: (string|null);
/** OpDef inputArg */
inputArg?: (tensorflow.OpDef.IArgDef[]|null);
/** OpDef outputArg */
outputArg?: (tensorflow.OpDef.IArgDef[]|null);
/** OpDef attr */
attr?: (tensorflow.OpDef.IAttrDef[]|null);
/** OpDef deprecation */
deprecation?: (tensorflow.OpDef.IOpDeprecation|null);
/** OpDef summary */
summary?: (string|null);
/** OpDef description */
description?: (string|null);
/** OpDef isCommutative */
isCommutative?: (boolean|null);
/** OpDef isAggregate */
isAggregate?: (boolean|null);
/** OpDef isStateful */
isStateful?: (boolean|null);
/** OpDef allowsUninitializedInput */
allowsUninitializedInput?: (boolean|null);
}
/** Represents an OpDef. */
class OpDef implements IOpDef {
/**
* Constructs a new OpDef.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.IOpDef);
/** OpDef name. */
public name: string;
/** OpDef inputArg. */
public inputArg: tensorflow.OpDef.IArgDef[];
/** OpDef outputArg. */
public outputArg: tensorflow.OpDef.IArgDef[];
/** OpDef attr. */
public attr: tensorflow.OpDef.IAttrDef[];
/** OpDef deprecation. */
public deprecation?: (tensorflow.OpDef.IOpDeprecation|null);
/** OpDef summary. */
public summary: string;
/** OpDef description. */
public description: string;
/** OpDef isCommutative. */
public isCommutative: boolean;
/** OpDef isAggregate. */
public isAggregate: boolean;
/** OpDef isStateful. */
public isStateful: boolean;
/** OpDef allowsUninitializedInput. */
public allowsUninitializedInput: boolean;
/**
* Decodes an OpDef message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns OpDef
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.OpDef;
}
namespace OpDef {
/** Properties of an ArgDef. */
interface IArgDef {
/** ArgDef name */
name?: (string|null);
/** ArgDef description */
description?: (string|null);
/** ArgDef type */
type?: (tensorflow.DataType|null);
/** ArgDef typeAttr */
typeAttr?: (string|null);
/** ArgDef numberAttr */
numberAttr?: (string|null);
/** ArgDef typeListAttr */
typeListAttr?: (string|null);
/** ArgDef isRef */
isRef?: (boolean|null);
}
/** Represents an ArgDef. */
class ArgDef implements IArgDef {
/**
* Constructs a new ArgDef.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.OpDef.IArgDef);
/** ArgDef name. */
public name: string;
/** ArgDef description. */
public description: string;
/** ArgDef type. */
public type: tensorflow.DataType;
/** ArgDef typeAttr. */
public typeAttr: string;
/** ArgDef numberAttr. */
public numberAttr: string;
/** ArgDef typeListAttr. */
public typeListAttr: string;
/** ArgDef isRef. */
public isRef: boolean;
/**
* Decodes an ArgDef message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns ArgDef
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.OpDef.ArgDef;
}
/** Properties of an AttrDef. */
interface IAttrDef {
/** AttrDef name */
name?: (string|null);
/** AttrDef type */
type?: (string|null);
/** AttrDef defaultValue */
defaultValue?: (tensorflow.IAttrValue|null);
/** AttrDef description */
description?: (string|null);
/** AttrDef hasMinimum */
hasMinimum?: (boolean|null);
/** AttrDef minimum */
minimum?: (number|Long|null);
/** AttrDef allowedValues */
allowedValues?: (tensorflow.IAttrValue|null);
}
/** Represents an AttrDef. */
class AttrDef implements IAttrDef {
/**
* Constructs a new AttrDef.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.OpDef.IAttrDef);
/** AttrDef name. */
public name: string;
/** AttrDef type. */
public type: string;
/** AttrDef defaultValue. */
public defaultValue?: (tensorflow.IAttrValue|null);
/** AttrDef description. */
public description: string;
/** AttrDef hasMinimum. */
public hasMinimum: boolean;
/** AttrDef minimum. */
public minimum: (number|Long);
/** AttrDef allowedValues. */
public allowedValues?: (tensorflow.IAttrValue|null);
/**
* Decodes an AttrDef message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns AttrDef
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.OpDef.AttrDef;
}
/** Properties of an OpDeprecation. */
interface IOpDeprecation {
/** OpDeprecation version */
version?: (number|null);
/** OpDeprecation explanation */
explanation?: (string|null);
}
/** Represents an OpDeprecation. */
class OpDeprecation implements IOpDeprecation {
/**
* Constructs a new OpDeprecation.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.OpDef.IOpDeprecation);
/** OpDeprecation version. */
public version: number;
/** OpDeprecation explanation. */
public explanation: string;
/**
* Decodes an OpDeprecation message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns OpDeprecation
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.OpDef.OpDeprecation;
}
}
/** Properties of an OpList. */
interface IOpList {
/** OpList op */
op?: (tensorflow.IOpDef[]|null);
}
/** Represents an OpList. */
class OpList implements IOpList {
/**
* Constructs a new OpList.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.IOpList);
/** OpList op. */
public op: tensorflow.IOpDef[];
/**
* Decodes an OpList message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns OpList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.OpList;
}
/** Properties of a MetaGraphDef. */
interface IMetaGraphDef {
/** MetaGraphDef metaInfoDef */
metaInfoDef?: (tensorflow.MetaGraphDef.IMetaInfoDef|null);
/** MetaGraphDef graphDef */
graphDef?: (tensorflow.IGraphDef|null);
/** MetaGraphDef saverDef */
saverDef?: (tensorflow.ISaverDef|null);
/** MetaGraphDef collectionDef */
collectionDef?: ({[k: string]: tensorflow.ICollectionDef}|null);
/** MetaGraphDef signatureDef */
signatureDef?: ({[k: string]: tensorflow.ISignatureDef}|null);
/** MetaGraphDef assetFileDef */
assetFileDef?: (tensorflow.IAssetFileDef[]|null);
}
/** Represents a MetaGraphDef. */
class MetaGraphDef implements IMetaGraphDef {
/**
* Constructs a new MetaGraphDef.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.IMetaGraphDef);
/** MetaGraphDef metaInfoDef. */
public metaInfoDef?: (tensorflow.MetaGraphDef.IMetaInfoDef|null);
/** MetaGraphDef graphDef. */
public graphDef?: (tensorflow.IGraphDef|null);
/** MetaGraphDef saverDef. */
public saverDef?: (tensorflow.ISaverDef|null);
/** MetaGraphDef collectionDef. */
public collectionDef: {[k: string]: tensorflow.ICollectionDef};
/** MetaGraphDef signatureDef. */
public signatureDef: {[k: string]: tensorflow.ISignatureDef};
/** MetaGraphDef assetFileDef. */
public assetFileDef: tensorflow.IAssetFileDef[];
/**
* Decodes a MetaGraphDef message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns MetaGraphDef
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.MetaGraphDef;
}
namespace MetaGraphDef {
/** Properties of a MetaInfoDef. */
interface IMetaInfoDef {
/** MetaInfoDef metaGraphVersion */
metaGraphVersion?: (string|null);
/** MetaInfoDef strippedOpList */
strippedOpList?: (tensorflow.IOpList|null);
/** MetaInfoDef anyInfo */
anyInfo?: (tensorflow.IAny|null);
/** MetaInfoDef tags */
tags?: (string[]|null);
/** MetaInfoDef tensorflowVersion */
tensorflowVersion?: (string|null);
/** MetaInfoDef tensorflowGitVersion */
tensorflowGitVersion?: (string|null);
}
/** Represents a MetaInfoDef. */
class MetaInfoDef implements IMetaInfoDef {
/**
* Constructs a new MetaInfoDef.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.MetaGraphDef.IMetaInfoDef);
/** MetaInfoDef metaGraphVersion. */
public metaGraphVersion: string;
/** MetaInfoDef strippedOpList. */
public strippedOpList?: (tensorflow.IOpList|null);
/** MetaInfoDef anyInfo. */
public anyInfo?: (tensorflow.IAny|null);
/** MetaInfoDef tags. */
public tags: string[];
/** MetaInfoDef tensorflowVersion. */
public tensorflowVersion: string;
/** MetaInfoDef tensorflowGitVersion. */
public tensorflowGitVersion: string;
/**
* Decodes a MetaInfoDef message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns MetaInfoDef
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.MetaGraphDef.MetaInfoDef;
}
}
/** Properties of a SavedModel. */
interface ISavedModel {
/** SavedModel savedModelSchemaVersion */
savedModelSchemaVersion?: (number|Long|null);
/** SavedModel metaGraphs */
metaGraphs?: (tensorflow.IMetaGraphDef[]|null);
}
/** Represents a SavedModel. */
class SavedModel implements ISavedModel {
/**
* Constructs a new SavedModel.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.ISavedModel);
/** SavedModel savedModelSchemaVersion. */
public savedModelSchemaVersion: (number|Long);
/** SavedModel metaGraphs. */
public metaGraphs: tensorflow.IMetaGraphDef[];
/**
* Decodes a SavedModel message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns SavedModel
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.SavedModel;
}
/** Properties of a FunctionDefLibrary. */
interface IFunctionDefLibrary {
/** FunctionDefLibrary function */
'function'?: (tensorflow.IFunctionDef[]|null);
/** FunctionDefLibrary gradient */
gradient?: (tensorflow.IGradientDef[]|null);
}
/** Represents a FunctionDefLibrary. */
class FunctionDefLibrary implements IFunctionDefLibrary {
/**
* Constructs a new FunctionDefLibrary.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.IFunctionDefLibrary);
/** FunctionDefLibrary function. */
public function: tensorflow.IFunctionDef[];
/** FunctionDefLibrary gradient. */
public gradient: tensorflow.IGradientDef[];
/**
* Decodes a FunctionDefLibrary message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns FunctionDefLibrary
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.FunctionDefLibrary;
}
/** Properties of a FunctionDef. */
interface IFunctionDef {
/** FunctionDef signature */
signature?: (tensorflow.IOpDef|null);
/** FunctionDef attr */
attr?: ({[k: string]: tensorflow.IAttrValue}|null);
/** FunctionDef nodeDef */
nodeDef?: (tensorflow.INodeDef[]|null);
/** FunctionDef ret */
ret?: ({[k: string]: string}|null);
}
/** Represents a FunctionDef. */
class FunctionDef implements IFunctionDef {
/**
* Constructs a new FunctionDef.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.IFunctionDef);
/** FunctionDef signature. */
public signature?: (tensorflow.IOpDef|null);
/** FunctionDef attr. */
public attr: {[k: string]: tensorflow.IAttrValue};
/** FunctionDef nodeDef. */
public nodeDef: tensorflow.INodeDef[];
/** FunctionDef ret. */
public ret: {[k: string]: string};
/**
* Decodes a FunctionDef message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns FunctionDef
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.FunctionDef;
}
/** Properties of a GradientDef. */
interface IGradientDef {
/** GradientDef functionName */
functionName?: (string|null);
/** GradientDef gradientFunc */
gradientFunc?: (string|null);
}
/** Represents a GradientDef. */
class GradientDef implements IGradientDef {
/**
* Constructs a new GradientDef.
* @param [p] Properties to set
*/
constructor(p?: tensorflow.IGradientDef);
/** GradientDef functionName. */
public functionName: string;
/** GradientDef gradientFunc. */
public gradientFunc: string;
/**
* Decodes a GradientDef message from the specified reader or buffer.
* @param r Reader or buffer to decode from
* @param [l] Message length if known beforehand
* @returns GradientDef
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(r: ($protobuf.Reader|Uint8Array), l?: number):
tensorflow.GradientDef;
}
} | the_stack |
import { join, normalize } from '@angular-devkit/core';
import { chain, noop, Tree } from '@angular-devkit/schematics';
import { formatFiles, readWorkspace, updateJsonInTree } from '@nrwl/workspace';
import * as assert from 'assert';
import type { Linter } from 'eslint';
/**
* We want to update the JSON in such a way that we:
* - extend from our Nx shareable configs where applicable
* - remove as much duplication between the JSON and the underlying
* shareable config as is safely possible
*/
function updateRootESLintConfig(host: Tree) {
return host.exists('.eslintrc.json')
? updateJsonInTree('.eslintrc.json', (json) => {
updateExtendsAndRemoveDuplication(
json,
currentTypescriptConfig,
true,
'plugin:@nrwl/nx/typescript'
);
/**
* We always want to explicitly include the @nrwl/nx plugin
* because we continue to use the @nrwl/nx/enforce-module-boundaries
* in the first party config and it helps make things clearer
*/
updatePluginsAndRemoveDuplication(
json,
currentTypescriptConfig,
true,
'@nrwl/nx'
);
updateParserOptionsAndRemoveDuplication(json, currentTypescriptConfig);
/**
* In the case of the existing Nx root .eslintrc.json out of the box,
* there is a single overrides for .tsx files. This is now covered
* by the shared config, so if the user still has that defined we can
* also remove that safely.
*/
updateOverridesAndRemoveDuplication(
json,
currentTypescriptConfig,
true
);
updateObjPropAndRemoveDuplication(
json,
currentTypescriptConfig,
'rules',
false
);
if (json.parser === currentTypescriptConfig.parser) {
delete json.parser;
}
return json;
})
: noop();
}
function updateReactESLintConfigs(host: Tree) {
const workspace = readWorkspace(host);
return chain([
...Object.keys(workspace.projects).map((k) => {
const p = workspace.projects[k];
const eslintConfigPath = join(normalize(p.root), '.eslintrc.json');
if (!host.exists(eslintConfigPath)) {
return noop();
}
return updateJsonInTree(eslintConfigPath, (json) => {
/**
* There isn't a way to know for sure if a project was started with the Nx
* original inline React ESLint config (for applications it is easy to know
* from the workspace.json, but that is not the case for all libraries).
*
* We therefore try and infer it based on the presence of react eslint plugins
* within the config that is currently there.
*/
if (
json.plugins?.includes('react') ||
json.plugins?.includes('react-hooks') ||
json.plugins?.includes('jsx-a11y')
) {
updateExtendsAndRemoveDuplication(
json,
currentReactConfig,
true,
'plugin:@nrwl/nx/react'
);
updatePluginsAndRemoveDuplication(json, currentReactConfig, true);
updateObjPropAndRemoveDuplication(
json,
currentReactConfig,
'rules',
false
);
updateObjPropAndRemoveDuplication(
json,
currentReactConfig,
'env',
true
);
updateObjPropAndRemoveDuplication(
json,
currentReactConfig,
'settings',
true
);
}
return json;
});
}),
]);
}
export default function () {
return chain([
updateRootESLintConfig,
updateReactESLintConfigs,
formatFiles(),
]);
}
const currentReactConfig: Linter.Config = {
rules: {
'array-callback-return': 'warn',
'dot-location': ['warn', 'property'],
eqeqeq: ['warn', 'smart'],
'new-parens': 'warn',
'no-caller': 'warn',
'no-cond-assign': ['warn', 'except-parens'],
'no-const-assign': 'warn',
'no-control-regex': 'warn',
'no-delete-var': 'warn',
'no-dupe-args': 'warn',
'no-dupe-keys': 'warn',
'no-duplicate-case': 'warn',
'no-empty-character-class': 'warn',
'no-empty-pattern': 'warn',
'no-eval': 'warn',
'no-ex-assign': 'warn',
'no-extend-native': 'warn',
'no-extra-bind': 'warn',
'no-extra-label': 'warn',
'no-fallthrough': 'warn',
'no-func-assign': 'warn',
'no-implied-eval': 'warn',
'no-invalid-regexp': 'warn',
'no-iterator': 'warn',
'no-label-var': 'warn',
'no-labels': ['warn', { allowLoop: true, allowSwitch: false }],
'no-lone-blocks': 'warn',
'no-loop-func': 'warn',
'no-mixed-operators': [
'warn',
{
groups: [
['&', '|', '^', '~', '<<', '>>', '>>>'],
['==', '!=', '===', '!==', '>', '>=', '<', '<='],
['&&', '||'],
['in', 'instanceof'],
],
allowSamePrecedence: false,
},
],
'no-multi-str': 'warn',
'no-native-reassign': 'warn',
'no-negated-in-lhs': 'warn',
'no-new-func': 'warn',
'no-new-object': 'warn',
'no-new-symbol': 'warn',
'no-new-wrappers': 'warn',
'no-obj-calls': 'warn',
'no-octal': 'warn',
'no-octal-escape': 'warn',
'no-redeclare': 'warn',
'no-regex-spaces': 'warn',
'no-restricted-syntax': ['warn', 'WithStatement'],
'no-script-url': 'warn',
'no-self-assign': 'warn',
'no-self-compare': 'warn',
'no-sequences': 'warn',
'no-shadow-restricted-names': 'warn',
'no-sparse-arrays': 'warn',
'no-template-curly-in-string': 'warn',
'no-this-before-super': 'warn',
'no-throw-literal': 'warn',
'no-restricted-globals': [
'error',
'addEventListener',
'blur',
'close',
'closed',
'confirm',
'defaultStatus',
'defaultstatus',
'event',
'external',
'find',
'focus',
'frameElement',
'frames',
'history',
'innerHeight',
'innerWidth',
'length',
'location',
'locationbar',
'menubar',
'moveBy',
'moveTo',
'name',
'onblur',
'onerror',
'onfocus',
'onload',
'onresize',
'onunload',
'open',
'opener',
'opera',
'outerHeight',
'outerWidth',
'pageXOffset',
'pageYOffset',
'parent',
'print',
'removeEventListener',
'resizeBy',
'resizeTo',
'screen',
'screenLeft',
'screenTop',
'screenX',
'screenY',
'scroll',
'scrollbars',
'scrollBy',
'scrollTo',
'scrollX',
'scrollY',
'self',
'status',
'statusbar',
'stop',
'toolbar',
'top',
],
'no-unexpected-multiline': 'warn',
'no-unreachable': 'warn',
'no-unused-expressions': 'off',
'no-unused-labels': 'warn',
'no-useless-computed-key': 'warn',
'no-useless-concat': 'warn',
'no-useless-escape': 'warn',
'no-useless-rename': [
'warn',
{
ignoreDestructuring: false,
ignoreImport: false,
ignoreExport: false,
},
],
'no-with': 'warn',
'no-whitespace-before-property': 'warn',
'react-hooks/exhaustive-deps': 'warn',
'require-yield': 'warn',
'rest-spread-spacing': ['warn', 'never'],
strict: ['warn', 'never'],
'unicode-bom': ['warn', 'never'],
'use-isnan': 'warn',
'valid-typeof': 'warn',
'no-restricted-properties': [
'error',
{
object: 'require',
property: 'ensure',
message:
'Please use import() instead. More info: https://facebook.github.io/create-react-app/docs/code-splitting',
},
{
object: 'System',
property: 'import',
message:
'Please use import() instead. More info: https://facebook.github.io/create-react-app/docs/code-splitting',
},
],
'getter-return': 'warn',
'import/first': 'error',
'import/no-amd': 'error',
'import/no-webpack-loader-syntax': 'error',
'react/forbid-foreign-prop-types': ['warn', { allowInPropTypes: true }],
'react/jsx-no-comment-textnodes': 'warn',
'react/jsx-no-duplicate-props': 'warn',
'react/jsx-no-target-blank': 'warn',
'react/jsx-no-undef': 'error',
'react/jsx-pascal-case': ['warn', { allowAllCaps: true, ignore: [] }],
'react/jsx-uses-react': 'warn',
'react/jsx-uses-vars': 'warn',
'react/no-danger-with-children': 'warn',
'react/no-direct-mutation-state': 'warn',
'react/no-is-mounted': 'warn',
'react/no-typos': 'error',
'react/react-in-jsx-scope': 'error',
'react/require-render-return': 'error',
'react/style-prop-object': 'warn',
'react/jsx-no-useless-fragment': 'warn',
'jsx-a11y/accessible-emoji': 'warn',
'jsx-a11y/alt-text': 'warn',
'jsx-a11y/anchor-has-content': 'warn',
'jsx-a11y/anchor-is-valid': [
'warn',
{ aspects: ['noHref', 'invalidHref'] },
],
'jsx-a11y/aria-activedescendant-has-tabindex': 'warn',
'jsx-a11y/aria-props': 'warn',
'jsx-a11y/aria-proptypes': 'warn',
'jsx-a11y/aria-role': 'warn',
'jsx-a11y/aria-unsupported-elements': 'warn',
'jsx-a11y/heading-has-content': 'warn',
'jsx-a11y/iframe-has-title': 'warn',
'jsx-a11y/img-redundant-alt': 'warn',
'jsx-a11y/no-access-key': 'warn',
'jsx-a11y/no-distracting-elements': 'warn',
'jsx-a11y/no-redundant-roles': 'warn',
'jsx-a11y/role-has-required-aria-props': 'warn',
'jsx-a11y/role-supports-aria-props': 'warn',
'jsx-a11y/scope': 'warn',
'react-hooks/rules-of-hooks': 'error',
'default-case': 'off',
'no-dupe-class-members': 'off',
'no-undef': 'off',
'@typescript-eslint/consistent-type-assertions': 'warn',
'no-array-constructor': 'off',
'@typescript-eslint/no-array-constructor': 'warn',
'@typescript-eslint/no-namespace': 'error',
'no-use-before-define': 'off',
'@typescript-eslint/no-use-before-define': [
'warn',
{
functions: false,
classes: false,
variables: false,
typedefs: false,
},
],
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': [
'warn',
{ args: 'none', ignoreRestSiblings: true },
],
'no-useless-constructor': 'off',
'@typescript-eslint/no-useless-constructor': 'warn',
'@typescript-eslint/no-unused-expressions': [
'error',
{
allowShortCircuit: true,
allowTernary: true,
allowTaggedTemplates: true,
},
],
},
env: {
browser: true,
commonjs: true,
es6: true,
jest: true,
node: true,
},
settings: { react: { version: 'detect' } },
plugins: ['import', 'jsx-a11y', 'react', 'react-hooks'],
};
const currentTypescriptConfig: Linter.Config = {
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 2020,
sourceType: 'module',
},
plugins: ['@typescript-eslint'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
'prettier',
'prettier/@typescript-eslint',
],
rules: {
'@typescript-eslint/explicit-member-accessibility': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-parameter-properties': 'off',
},
overrides: [
{
files: ['*.tsx'],
rules: {
'@typescript-eslint/no-unused-vars': 'off',
},
},
],
};
function ensureStringArray(val: string | string[]): string[] {
if (typeof val === 'string') {
return [val];
}
return val || [];
}
export function updateExtendsAndRemoveDuplication(
json: Linter.Config,
configBeingExtended: Linter.Config,
deleteIfUltimatelyEmpty: boolean,
extendsToAdd: string
): void {
// Extends can be a string or an array, normalize first
json.extends = ensureStringArray(json.extends);
configBeingExtended.extends = ensureStringArray(configBeingExtended.extends);
json.extends.unshift(extendsToAdd);
json.extends = json.extends.filter(
(extended) => !configBeingExtended.extends.includes(extended)
);
json.extends = Array.from(new Set(json.extends));
if (deleteIfUltimatelyEmpty && json.extends.length === 0) {
delete json.extends;
}
}
export function updatePluginsAndRemoveDuplication(
json: Linter.Config,
configBeingExtended: Linter.Config,
deleteIfUltimatelyEmpty: boolean,
ensurePlugin?: string
): void {
json.plugins ||= [];
configBeingExtended.plugins ||= [];
if (ensurePlugin && !json.plugins.includes(ensurePlugin)) {
json.plugins.unshift(ensurePlugin);
}
json.plugins = json.plugins.filter(
(extended: string) => !configBeingExtended.plugins.includes(extended)
);
json.plugins = Array.from(new Set(json.plugins));
if (deleteIfUltimatelyEmpty && json.plugins.length === 0) {
delete json.plugins;
}
}
export function updateParserOptionsAndRemoveDuplication(
json: Linter.Config,
configBeingExtended: Linter.Config
): void {
json.parserOptions ||= {};
configBeingExtended.parserOptions ||= {};
/**
* If the user is still using the 2018 ecmaVersion that Nx set for them
* previously we can just remove it and let them inherit the new 2020 value.
* If the user has set something else (other than 2018 or 2020), we just leave it.
*/
if (
Number(json.parserOptions.ecmaVersion) === 2018 ||
Number(json.parserOptions.ecmaVersion) ===
Number(configBeingExtended.parserOptions.ecmaVersion)
) {
delete json.parserOptions.ecmaVersion;
}
for (const [parserOptionName, parserOptionVal] of Object.entries(
json.parserOptions
)) {
if (
parserOptionVal === configBeingExtended.parserOptions[parserOptionName]
) {
delete json.parserOptions[parserOptionName];
}
}
}
export function updateObjPropAndRemoveDuplication(
json: Linter.Config,
configBeingExtended: Linter.Config,
objPropName: string,
deleteIfUltimatelyEmpty: boolean
): void {
json[objPropName] ||= {};
configBeingExtended[objPropName] ||= {};
for (const [name, val] of Object.entries(json[objPropName])) {
const valueOfSamePropInExtendedConfig =
configBeingExtended[objPropName][name];
try {
assert.deepStrictEqual(val, valueOfSamePropInExtendedConfig);
delete json[objPropName][name];
} catch {}
}
if (deleteIfUltimatelyEmpty && Object.keys(json[objPropName]).length === 0) {
delete json[objPropName];
}
}
export function updateOverridesAndRemoveDuplication(
json: Linter.Config,
configBeingExtended: Linter.Config,
deleteIfUltimatelyEmpty: boolean
): void {
if (!Array.isArray(json.overrides) || !json.overrides.length) {
return;
}
if (
!Array.isArray(configBeingExtended.overrides) ||
!configBeingExtended.overrides.length
) {
return;
}
json.overrides = json.overrides.filter((o) => {
for (const extendedOverride of configBeingExtended.overrides) {
try {
assert.deepStrictEqual(o, extendedOverride);
return false;
} catch {}
}
return false;
});
if (deleteIfUltimatelyEmpty && json.overrides.length === 0) {
delete json.overrides;
}
} | the_stack |
import {AriaButtonProps} from '@react-types/button';
import ChevronDownMedium from '@spectrum-icons/ui/ChevronDownMedium';
import {
classNames,
useFocusableRef,
useIsMobileDevice,
useResizeObserver,
useUnwrapDOMRef
} from '@react-spectrum/utils';
import comboboxStyles from './combobox.css';
import {DismissButton, useOverlayPosition} from '@react-aria/overlays';
import {DOMRefValue, FocusableRef, FocusableRefValue} from '@react-types/shared';
import {Field} from '@react-spectrum/label';
import {FieldButton} from '@react-spectrum/button';
import {FocusRing} from '@react-aria/focus';
// @ts-ignore
import intlMessages from '../intl/*.json';
import {ListBoxBase, useListBoxLayout} from '@react-spectrum/listbox';
import {MobileComboBox} from './MobileComboBox';
import {Placement} from '@react-types/overlays';
import {Popover} from '@react-spectrum/overlays';
import {PressResponder, useHover} from '@react-aria/interactions';
import {ProgressCircle} from '@react-spectrum/progress';
import React, {
InputHTMLAttributes,
ReactElement,
RefObject,
useCallback,
useEffect,
useRef,
useState
} from 'react';
import {SpectrumComboBoxProps} from '@react-types/combobox';
import styles from '@adobe/spectrum-css-temp/components/inputgroup/vars.css';
import {TextFieldBase} from '@react-spectrum/textfield';
import textfieldStyles from '@adobe/spectrum-css-temp/components/textfield/vars.css';
import {useComboBox} from '@react-aria/combobox';
import {useComboBoxState} from '@react-stately/combobox';
import {useFilter} from '@react-aria/i18n';
import {useLayoutEffect} from '@react-aria/utils';
import {useMessageFormatter} from '@react-aria/i18n';
import {useProvider, useProviderProps} from '@react-spectrum/provider';
function ComboBox<T extends object>(props: SpectrumComboBoxProps<T>, ref: FocusableRef<HTMLElement>) {
props = useProviderProps(props);
let isMobile = useIsMobileDevice();
if (isMobile) {
// menuTrigger=focus/manual don't apply to mobile combobox
return <MobileComboBox {...props} menuTrigger="input" ref={ref} />;
} else {
return <ComboBoxBase {...props} ref={ref} />;
}
}
const ComboBoxBase = React.forwardRef(function ComboBoxBase<T extends object>(props: SpectrumComboBoxProps<T>, ref: FocusableRef<HTMLElement>) {
let {
menuTrigger = 'input',
shouldFlip = true,
direction = 'bottom',
isQuiet,
loadingState,
onLoadMore
} = props;
let formatMessage = useMessageFormatter(intlMessages);
let isAsync = loadingState != null;
let popoverRef = useRef<DOMRefValue<HTMLDivElement>>();
let unwrappedPopoverRef = useUnwrapDOMRef(popoverRef);
let buttonRef = useRef<FocusableRefValue<HTMLElement>>();
let unwrappedButtonRef = useUnwrapDOMRef(buttonRef);
let listBoxRef = useRef();
let inputRef = useRef<HTMLInputElement>();
let domRef = useFocusableRef(ref, inputRef);
let {contains} = useFilter({sensitivity: 'base'});
let state = useComboBoxState(
{
...props,
defaultFilter: contains,
allowsEmptyCollection: isAsync
}
);
let layout = useListBoxLayout(state);
let {buttonProps, inputProps, listBoxProps, labelProps, descriptionProps, errorMessageProps} = useComboBox(
{
...props,
keyboardDelegate: layout,
buttonRef: unwrappedButtonRef,
popoverRef: unwrappedPopoverRef,
listBoxRef,
inputRef: inputRef,
menuTrigger
},
state
);
let {overlayProps, placement, updatePosition} = useOverlayPosition({
targetRef: unwrappedButtonRef,
overlayRef: unwrappedPopoverRef,
scrollRef: listBoxRef,
placement: `${direction} end` as Placement,
shouldFlip: shouldFlip,
isOpen: state.isOpen,
onClose: state.close
});
// Measure the width of the inputfield and the button to inform the width of the menu (below).
let [menuWidth, setMenuWidth] = useState(null);
let {scale} = useProvider();
let onResize = useCallback(() => {
if (unwrappedButtonRef.current && inputRef.current) {
let buttonWidth = unwrappedButtonRef.current.offsetWidth;
let inputWidth = inputRef.current.offsetWidth;
setMenuWidth(buttonWidth + inputWidth);
}
}, [unwrappedButtonRef, inputRef, setMenuWidth]);
useResizeObserver({
ref: domRef,
onResize: onResize
});
useLayoutEffect(onResize, [scale, onResize]);
// Update position once the ListBox has rendered. This ensures that
// it flips properly when it doesn't fit in the available space.
// TODO: add ResizeObserver to useOverlayPosition so we don't need this.
useLayoutEffect(() => {
if (state.isOpen) {
requestAnimationFrame(() => {
updatePosition();
});
}
}, [state.isOpen, updatePosition]);
let style = {
...overlayProps.style,
width: isQuiet ? null : menuWidth,
minWidth: isQuiet ? `calc(${menuWidth}px + calc(2 * var(--spectrum-dropdown-quiet-offset)))` : menuWidth
};
return (
<>
<Field
{...props}
descriptionProps={descriptionProps}
errorMessageProps={errorMessageProps}
labelProps={labelProps}
ref={domRef}>
<ComboBoxInput
{...props}
isOpen={state.isOpen}
loadingState={loadingState}
inputProps={inputProps}
inputRef={inputRef}
triggerProps={buttonProps}
triggerRef={buttonRef} />
</Field>
<Popover
isOpen={state.isOpen}
UNSAFE_style={style}
UNSAFE_className={classNames(styles, 'spectrum-InputGroup-popover', {'spectrum-InputGroup-popover--quiet': isQuiet})}
ref={popoverRef}
placement={placement}
hideArrow
isNonModal
isDismissable={false}>
<ListBoxBase
{...listBoxProps}
ref={listBoxRef}
disallowEmptySelection
autoFocus={state.focusStrategy}
shouldSelectOnPressUp
focusOnPointerEnter
layout={layout}
state={state}
shouldUseVirtualFocus
isLoading={loadingState === 'loadingMore'}
onLoadMore={onLoadMore}
renderEmptyState={() => isAsync && (
<span className={classNames(comboboxStyles, 'no-results')}>
{loadingState === 'loading' ? formatMessage('loading') : formatMessage('noResults')}
</span>
)} />
<DismissButton onDismiss={() => state.close()} />
</Popover>
</>
);
});
interface ComboBoxInputProps extends SpectrumComboBoxProps<unknown> {
inputProps: InputHTMLAttributes<HTMLInputElement>,
inputRef: RefObject<HTMLInputElement | HTMLTextAreaElement>,
triggerProps: AriaButtonProps,
triggerRef: RefObject<FocusableRefValue<HTMLElement>>,
style?: React.CSSProperties,
className?: string,
isOpen?: boolean
}
const ComboBoxInput = React.forwardRef(function ComboBoxInput(props: ComboBoxInputProps, ref: RefObject<HTMLElement>) {
let {
isQuiet,
isDisabled,
isReadOnly,
validationState,
inputProps,
inputRef,
triggerProps,
triggerRef,
autoFocus,
style,
className,
loadingState,
isOpen,
menuTrigger
} = props;
let {hoverProps, isHovered} = useHover({});
let formatMessage = useMessageFormatter(intlMessages);
let timeout = useRef(null);
let [showLoading, setShowLoading] = useState(false);
let loadingCircle = (
<ProgressCircle
aria-label={formatMessage('loading')}
size="S"
isIndeterminate
UNSAFE_className={classNames(
textfieldStyles,
'spectrum-Textfield-circleLoader',
classNames(
styles,
'spectrum-InputGroup-input-circleLoader'
)
)} />
);
let isLoading = loadingState === 'loading' || loadingState === 'filtering';
let inputValue = inputProps.value;
let lastInputValue = useRef(inputValue);
useEffect(() => {
if (isLoading && !showLoading) {
if (timeout.current === null) {
timeout.current = setTimeout(() => {
setShowLoading(true);
}, 500);
}
// If user is typing, clear the timer and restart since it is a new request
if (inputValue !== lastInputValue.current) {
clearTimeout(timeout.current);
timeout.current = setTimeout(() => {
setShowLoading(true);
}, 500);
}
} else if (!isLoading) {
// If loading is no longer happening, clear any timers and hide the loading circle
setShowLoading(false);
clearTimeout(timeout.current);
timeout.current = null;
}
lastInputValue.current = inputValue;
}, [isLoading, showLoading, inputValue]);
return (
<FocusRing
within
isTextInput
focusClass={classNames(styles, 'is-focused')}
focusRingClass={classNames(styles, 'focus-ring')}
autoFocus={autoFocus}>
<div
{...hoverProps}
ref={ref as RefObject<HTMLDivElement>}
style={style}
className={
classNames(
styles,
'spectrum-InputGroup',
{
'spectrum-InputGroup--quiet': isQuiet,
'is-disabled': isDisabled,
'spectrum-InputGroup--invalid': validationState === 'invalid',
'is-hovered': isHovered
},
className
)
}>
<TextFieldBase
inputProps={inputProps}
inputRef={inputRef}
UNSAFE_className={
classNames(
styles,
'spectrum-InputGroup-field'
)
}
inputClassName={
classNames(
styles,
'spectrum-InputGroup-input'
)
}
validationIconClassName={
classNames(
styles,
'spectrum-InputGroup-input-validationIcon'
)
}
isDisabled={isDisabled}
isQuiet={isQuiet}
validationState={validationState}
// loading circle should only be displayed if menu is open, if menuTrigger is "manual", or first time load (to stop circle from showing up when user selects an option)
// TODO: add special case for completionMode: complete as well
isLoading={showLoading && (isOpen || menuTrigger === 'manual' || loadingState === 'loading')}
loadingIndicator={loadingState != null && loadingCircle} />
<PressResponder preventFocusOnPress isPressed={isOpen}>
<FieldButton
{...triggerProps}
ref={triggerRef}
UNSAFE_className={
classNames(
styles,
'spectrum-FieldButton'
)
}
isDisabled={isDisabled || isReadOnly}
isQuiet={isQuiet}
validationState={validationState}>
<ChevronDownMedium UNSAFE_className={classNames(styles, 'spectrum-Dropdown-chevron')} />
</FieldButton>
</PressResponder>
</div>
</FocusRing>
);
});
/**
* ComboBoxes combine a text entry with a picker menu, allowing users to filter longer lists to only the selections matching a query.
*/
const _ComboBox = React.forwardRef(ComboBox) as <T>(props: SpectrumComboBoxProps<T> & {ref?: FocusableRef<HTMLElement>}) => ReactElement;
export {_ComboBox as ComboBox}; | the_stack |
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Modal } from 'antd';
import { ColumnsType, FilterDropdownProps, SorterResult } from 'antd/es/table/interface';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import Badge, { BadgeType } from 'components/Badge';
import FilterCounter from 'components/FilterCounter';
import Icon from 'components/Icon';
import Page from 'components/Page';
import ResponsiveTable from 'components/ResponsiveTable';
import tableCss from 'components/ResponsiveTable.module.scss';
import {
archivedRenderer, defaultRowClassName, experimentNameRenderer, experimentProgressRenderer,
ExperimentRenderer, expermentDurationRenderer, getFullPaginationConfig,
relativeTimeRenderer, stateRenderer, userRenderer,
} from 'components/Table';
import TableBatch from 'components/TableBatch';
import TableFilterDropdown from 'components/TableFilterDropdown';
import TableFilterSearch from 'components/TableFilterSearch';
import TagList from 'components/TagList';
import TaskActionDropdown from 'components/TaskActionDropdown';
import { useStore } from 'contexts/Store';
import handleError, { ErrorLevel, ErrorType } from 'ErrorHandler';
import useExperimentTags from 'hooks/useExperimentTags';
import { useFetchUsers } from 'hooks/useFetch';
import usePolling from 'hooks/usePolling';
import useSettings from 'hooks/useSettings';
import {
activateExperiment, archiveExperiment, cancelExperiment, deleteExperiment, getExperimentLabels,
getExperiments, killExperiment, openOrCreateTensorboard, pauseExperiment, unarchiveExperiment,
} from 'services/api';
import { Determinedexperimentv1State, V1GetExperimentsRequestSortBy } from 'services/api-ts-sdk';
import { encodeExperimentState } from 'services/decoder';
import { validateDetApiEnum, validateDetApiEnumList } from 'services/utils';
import {
ExperimentAction as Action, ArchiveFilter, CommandTask, ExperimentItem, RecordKey, RunState,
} from 'types';
import { isBoolean, isEqual } from 'utils/data';
import { alphanumericSorter } from 'utils/sort';
import { capitalize } from 'utils/string';
import {
cancellableRunStates, deletableRunStates, experimentToTask, isTaskKillable, terminalRunStates,
} from 'utils/types';
import { openCommand } from 'wait';
import settingsConfig, { Settings } from './ExperimentList.settings';
const filterKeys: Array<keyof Settings> = [ 'archived', 'label', 'search', 'state', 'user' ];
const ExperimentList: React.FC = () => {
const { users, auth: { user } } = useStore();
const [ canceler ] = useState(new AbortController());
const [ experiments, setExperiments ] = useState<ExperimentItem[]>();
const [ labels, setLabels ] = useState<string[]>([]);
const [ isLoading, setIsLoading ] = useState(true);
const [ total, setTotal ] = useState(0);
const {
activeSettings,
resetSettings,
settings,
updateSettings,
} = useSettings<Settings>(settingsConfig);
const experimentMap = useMemo(() => {
return (experiments || []).reduce((acc, experiment) => {
acc[experiment.id] = experiment;
return acc;
}, {} as Record<RecordKey, ExperimentItem>);
}, [ experiments ]);
const filterCount = useMemo(() => activeSettings(filterKeys).length, [ activeSettings ]);
const {
hasActivatable,
hasArchivable,
hasCancelable,
hasDeletable,
hasKillable,
hasPausable,
hasUnarchivable,
} = useMemo(() => {
const tracker = {
hasActivatable: false,
hasArchivable: false,
hasCancelable: false,
hasDeletable: false,
hasKillable: false,
hasPausable: false,
hasUnarchivable: false,
};
for (const id of settings.row || []) {
const experiment = experimentMap[id];
if (!experiment) continue;
const isArchivable = !experiment.archived && terminalRunStates.has(experiment.state);
const isCancelable = cancellableRunStates.includes(experiment.state);
const isDeletable = deletableRunStates.has(experiment.state) &&
user && (user.isAdmin || user.username === experiment.username);
const isKillable = isTaskKillable(experiment);
const isActivatable = experiment.state === RunState.Paused;
const isPausable = experiment.state === RunState.Active;
if (!tracker.hasArchivable && isArchivable) tracker.hasArchivable = true;
if (!tracker.hasUnarchivable && experiment.archived) tracker.hasUnarchivable = true;
if (!tracker.hasCancelable && isCancelable) tracker.hasCancelable = true;
if (!tracker.hasDeletable && isDeletable) tracker.hasDeletable = true;
if (!tracker.hasKillable && isKillable) tracker.hasKillable = true;
if (!tracker.hasActivatable && isActivatable) tracker.hasActivatable = true;
if (!tracker.hasPausable && isPausable) tracker.hasPausable = true;
}
return tracker;
}, [ experimentMap, settings.row, user ]);
const fetchUsers = useFetchUsers(canceler);
const fetchExperiments = useCallback(async (): Promise<void> => {
try {
const states = (settings.state || []).map(state => encodeExperimentState(state as RunState));
const response = await getExperiments(
{
archived: settings.archived,
labels: settings.label,
limit: settings.tableLimit,
name: settings.search,
offset: settings.tableOffset,
orderBy: settings.sortDesc ? 'ORDER_BY_DESC' : 'ORDER_BY_ASC',
sortBy: validateDetApiEnum(V1GetExperimentsRequestSortBy, settings.sortKey),
states: validateDetApiEnumList(Determinedexperimentv1State, states),
users: settings.user,
},
{ signal: canceler.signal },
);
setTotal(response.pagination.total || 0);
setExperiments(prev => {
if (isEqual(prev, response.experiments)) return prev;
return response.experiments;
});
setIsLoading(false);
} catch (e) {
handleError({ message: 'Unable to fetch experiments.', silent: true, type: ErrorType.Api });
setIsLoading(false);
}
}, [ canceler,
settings.archived,
settings.label,
settings.search,
settings.sortDesc,
settings.sortKey,
settings.state,
settings.tableLimit,
settings.tableOffset,
settings.user ]);
const fetchLabels = useCallback(async () => {
try {
const labels = await getExperimentLabels({ signal: canceler.signal });
labels.sort((a, b) => alphanumericSorter(a, b));
setLabels(labels);
} catch (e) {}
}, [ canceler.signal ]);
const fetchAll = useCallback(() => {
fetchExperiments();
fetchLabels();
fetchUsers();
}, [ fetchExperiments, fetchLabels, fetchUsers ]);
usePolling(fetchAll);
const experimentTags = useExperimentTags(fetchAll);
const handleActionComplete = useCallback(() => fetchExperiments(), [ fetchExperiments ]);
const handleArchiveFilterApply = useCallback((archived: string[]) => {
const archivedFilter = archived.length === 1
? archived[0] === ArchiveFilter.Archived : undefined;
updateSettings({ archived: archivedFilter, row: undefined });
}, [ updateSettings ]);
const handleArchiveFilterReset = useCallback(() => {
updateSettings({ archived: undefined, row: undefined });
}, [ updateSettings ]);
const archiveFilterDropdown = useCallback((filterProps: FilterDropdownProps) => (
<TableFilterDropdown
{...filterProps}
values={isBoolean(settings.archived)
? [ settings.archived ? ArchiveFilter.Archived : ArchiveFilter.Unarchived ]
: undefined}
onFilter={handleArchiveFilterApply}
onReset={handleArchiveFilterReset}
/>
), [ handleArchiveFilterApply, handleArchiveFilterReset, settings.archived ]);
const tableSearchIcon = useCallback(() => <Icon name="search" size="tiny" />, []);
const handleNameSearchApply = useCallback((newSearch: string) => {
updateSettings({ row: undefined, search: newSearch || undefined });
}, [ updateSettings ]);
const handleNameSearchReset = useCallback(() => {
updateSettings({ row: undefined, search: undefined });
}, [ updateSettings ]);
const nameFilterSearch = useCallback((filterProps: FilterDropdownProps) => (
<TableFilterSearch
{...filterProps}
value={settings.search || ''}
onReset={handleNameSearchReset}
onSearch={handleNameSearchApply}
/>
), [ handleNameSearchApply, handleNameSearchReset, settings.search ]);
const handleLabelFilterApply = useCallback((labels: string[]) => {
updateSettings({
label: labels.length !== 0 ? labels : undefined,
row: undefined,
});
}, [ updateSettings ]);
const handleLabelFilterReset = useCallback(() => {
updateSettings({ label: undefined, row: undefined });
}, [ updateSettings ]);
const labelFilterDropdown = useCallback((filterProps: FilterDropdownProps) => (
<TableFilterDropdown
{...filterProps}
multiple
searchable
values={settings.label}
onFilter={handleLabelFilterApply}
onReset={handleLabelFilterReset}
/>
), [ handleLabelFilterApply, handleLabelFilterReset, settings.label ]);
const handleStateFilterApply = useCallback((states: string[]) => {
updateSettings({
row: undefined,
state: states.length !== 0 ? states as RunState[] : undefined,
});
}, [ updateSettings ]);
const handleStateFilterReset = useCallback(() => {
updateSettings({ row: undefined, state: undefined });
}, [ updateSettings ]);
const stateFilterDropdown = useCallback((filterProps: FilterDropdownProps) => (
<TableFilterDropdown
{...filterProps}
multiple
values={settings.state}
onFilter={handleStateFilterApply}
onReset={handleStateFilterReset} />
), [ handleStateFilterApply, handleStateFilterReset, settings.state ]);
const handleUserFilterApply = useCallback((users: string[]) => {
updateSettings({
row: undefined,
user: users.length !== 0 ? users : undefined,
});
}, [ updateSettings ]);
const handleUserFilterReset = useCallback(() => {
updateSettings({ row: undefined, user: undefined });
}, [ updateSettings ]);
const userFilterDropdown = useCallback((filterProps: FilterDropdownProps) => (
<TableFilterDropdown
{...filterProps}
multiple
searchable
values={settings.user}
onFilter={handleUserFilterApply}
onReset={handleUserFilterReset} />
), [ handleUserFilterApply, handleUserFilterReset, settings.user ]);
const columns = useMemo(() => {
const labelsRenderer = (value: string, record: ExperimentItem) => (
<TagList
compact
tags={record.labels}
onChange={experimentTags.handleTagListChange(record.id)}
/>
);
const actionRenderer: ExperimentRenderer = (_, record) => (
<TaskActionDropdown
curUser={user}
task={experimentToTask(record)}
onComplete={handleActionComplete} />
);
const tableColumns: ColumnsType<ExperimentItem> = [
{
dataIndex: 'id',
key: V1GetExperimentsRequestSortBy.ID,
render: experimentNameRenderer,
sorter: true,
title: 'ID',
},
{
dataIndex: 'name',
filterDropdown: nameFilterSearch,
filterIcon: tableSearchIcon,
key: V1GetExperimentsRequestSortBy.NAME,
onHeaderCell: () => settings.search ? { className: tableCss.headerFilterOn } : {},
render: experimentNameRenderer,
sorter: true,
title: 'Name',
width: 240,
},
{
dataIndex: 'labels',
filterDropdown: labelFilterDropdown,
filters: labels.map(label => ({ text: label, value: label })),
key: 'labels',
onHeaderCell: () => settings.label ? { className: tableCss.headerFilterOn } : {},
render: labelsRenderer,
title: 'Labels',
width: 120,
},
{
key: V1GetExperimentsRequestSortBy.STARTTIME,
render: (_: number, record: ExperimentItem): React.ReactNode =>
relativeTimeRenderer(new Date(record.startTime)),
sorter: true,
title: 'Start Time',
},
{
key: 'duration',
render: expermentDurationRenderer,
title: 'Duration',
},
{
dataIndex: 'numTrials',
key: V1GetExperimentsRequestSortBy.NUMTRIALS,
sorter: true,
title: 'Trials',
},
{
filterDropdown: stateFilterDropdown,
filters: Object.values(RunState)
.filter(value => value !== RunState.Unspecified)
.map((value) => ({
text: <Badge state={value} type={BadgeType.State} />,
value,
})),
key: V1GetExperimentsRequestSortBy.STATE,
onHeaderCell: () => settings.state ? { className: tableCss.headerFilterOn } : {},
render: stateRenderer,
sorter: true,
title: 'State',
},
{
dataIndex: 'resourcePool',
key: 'resourcePool',
sorter: true,
title: 'Resource Pool',
},
{
key: V1GetExperimentsRequestSortBy.PROGRESS,
render: experimentProgressRenderer,
sorter: true,
title: 'Progress',
},
{
dataIndex: 'archived',
filterDropdown: archiveFilterDropdown,
filters: [
{ text: capitalize(ArchiveFilter.Archived), value: ArchiveFilter.Archived },
{ text: capitalize(ArchiveFilter.Unarchived), value: ArchiveFilter.Unarchived },
],
key: 'archived',
onHeaderCell: () => settings.archived != null ? { className: tableCss.headerFilterOn } : {},
render: archivedRenderer,
title: 'Archived',
},
{
filterDropdown: userFilterDropdown,
filters: users.map(user => ({ text: user.username, value: user.username })),
key: V1GetExperimentsRequestSortBy.USER,
onHeaderCell: () => settings.user ? { className: tableCss.headerFilterOn } : {},
render: userRenderer,
sorter: true,
title: 'User',
},
{
align: 'right',
className: 'fullCell',
fixed: 'right',
key: 'action',
render: actionRenderer,
title: '',
width: 40,
},
];
return tableColumns.map(column => {
column.sortOrder = null;
if (column.key === settings.sortKey) {
column.sortOrder = settings.sortDesc ? 'descend' : 'ascend';
}
return column;
});
}, [
user,
archiveFilterDropdown,
handleActionComplete,
experimentTags,
labelFilterDropdown,
labels,
nameFilterSearch,
settings,
stateFilterDropdown,
tableSearchIcon,
userFilterDropdown,
users,
]);
const sendBatchActions = useCallback((action: Action): Promise<void[] | CommandTask> => {
if (action === Action.OpenTensorBoard) {
return openOrCreateTensorboard({ experimentIds: settings.row });
}
return Promise.all((settings.row || []).map(experimentId => {
switch (action) {
case Action.Activate:
return activateExperiment({ experimentId });
case Action.Archive:
return archiveExperiment({ experimentId });
case Action.Cancel:
return cancelExperiment({ experimentId });
case Action.Delete:
return deleteExperiment({ experimentId });
case Action.Kill:
return killExperiment({ experimentId });
case Action.Pause:
return pauseExperiment({ experimentId });
case Action.Unarchive:
return unarchiveExperiment({ experimentId });
default:
return Promise.resolve();
}
}));
}, [ settings.row ]);
const submitBatchAction = useCallback(async (action: Action) => {
try {
const result = await sendBatchActions(action);
if (action === Action.OpenTensorBoard && result) {
openCommand(result as CommandTask);
}
/*
* Deselect selected rows since their states may have changed where they
* are no longer part of the filter criteria.
*/
updateSettings({ row: undefined });
// Refetch experiment list to get updates based on batch action.
await fetchExperiments();
} catch (e) {
const publicSubject = action === Action.OpenTensorBoard ?
'Unable to View TensorBoard for Selected Experiments' :
`Unable to ${action} Selected Experiments`;
handleError({
error: e,
level: ErrorLevel.Error,
message: e.message,
publicMessage: 'Please try again later.',
publicSubject,
silent: false,
type: ErrorType.Server,
});
}
}, [ fetchExperiments, sendBatchActions, updateSettings ]);
const showConfirmation = useCallback((action: Action) => {
Modal.confirm({
content: `
Are you sure you want to ${action.toLocaleLowerCase()}
all the eligible selected experiments?
`,
icon: <ExclamationCircleOutlined />,
okText: /cancel/i.test(action) ? 'Confirm' : action,
onOk: () => submitBatchAction(action),
title: 'Confirm Batch Action',
});
}, [ submitBatchAction ]);
const handleBatchAction = useCallback((action?: string) => {
if (action === Action.OpenTensorBoard) {
submitBatchAction(action);
} else {
showConfirmation(action as Action);
}
}, [ submitBatchAction, showConfirmation ]);
const handleTableChange = useCallback((tablePagination, tableFilters, tableSorter) => {
if (Array.isArray(tableSorter)) return;
const { columnKey, order } = tableSorter as SorterResult<ExperimentItem>;
if (!columnKey || !columns.find(column => column.key === columnKey)) return;
const newSettings = {
sortDesc: order === 'descend',
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
sortKey: columnKey as any,
tableLimit: tablePagination.pageSize,
tableOffset: (tablePagination.current - 1) * tablePagination.pageSize,
};
const shouldPush = settings.tableOffset !== newSettings.tableOffset;
updateSettings(newSettings, shouldPush);
}, [ columns, settings.tableOffset, updateSettings ]);
const handleTableRowSelect = useCallback(rowKeys => {
updateSettings({ row: rowKeys });
}, [ updateSettings ]);
const clearSelected = useCallback(() => {
updateSettings({ row: undefined });
}, [ updateSettings ]);
const resetFilters = useCallback(() => {
resetSettings([ ...filterKeys, 'tableOffset' ]);
}, [ resetSettings ]);
/*
* Get new experiments based on changes to the
* filters, pagination, search and sorter.
*/
useEffect(() => {
fetchExperiments();
setIsLoading(true);
}, [
fetchExperiments,
settings.archived,
settings.label,
settings.search,
settings.sortDesc,
settings.sortKey,
settings.state,
settings.tableLimit,
settings.tableOffset,
settings.user,
]);
useEffect(() => {
return () => canceler.abort();
}, [ canceler ]);
return (
<Page
id="experiments"
options={<FilterCounter activeFilterCount={filterCount} onReset={resetFilters} />}
title="Experiments">
<TableBatch
actions={[
{ label: Action.OpenTensorBoard, value: Action.OpenTensorBoard },
{ disabled: !hasActivatable, label: Action.Activate, value: Action.Activate },
{ disabled: !hasPausable, label: Action.Pause, value: Action.Pause },
{ disabled: !hasArchivable, label: Action.Archive, value: Action.Archive },
{ disabled: !hasUnarchivable, label: Action.Unarchive, value: Action.Unarchive },
{ disabled: !hasCancelable, label: Action.Cancel, value: Action.Cancel },
{ disabled: !hasKillable, label: Action.Kill, value: Action.Kill },
{ disabled: !hasDeletable, label: Action.Delete, value: Action.Delete },
]}
selectedRowCount={(settings.row ?? []).length}
onAction={handleBatchAction}
onClear={clearSelected}
/>
<ResponsiveTable<ExperimentItem>
columns={columns}
dataSource={experiments}
loading={isLoading}
pagination={getFullPaginationConfig({
limit: settings.tableLimit,
offset: settings.tableOffset,
}, total)}
rowClassName={defaultRowClassName({ clickable: false })}
rowKey="id"
rowSelection={{
onChange: handleTableRowSelect,
preserveSelectedRowKeys: true,
selectedRowKeys: settings.row ?? [],
}}
showSorterTooltip={false}
size="small"
onChange={handleTableChange}
/>
</Page>
);
};
export default ExperimentList; | the_stack |
import { gunzipSync } from 'fflate';
import { KdbxError } from '../errors/kdbx-error';
import { ErrorCodes } from '../defs/consts';
import * as XmlNames from '../defs/xml-names';
import { arrayToBuffer, base64ToBytes, bytesToBase64 } from './byte-utils';
import { Int64 } from './int64';
import { KdbxUuid } from '../format/kdbx-uuid';
import { ProtectedValue } from '../crypto/protected-value';
import { ProtectSaltGenerator } from '../crypto/protect-salt-generator';
import { KdbxBinaries, KdbxBinaryOrRef } from '../format/kdbx-binaries';
const DateRegex = /\.\d\d\d/;
const EpochSeconds = 62135596800;
const TagsSplitRegex = /\s*[;,:]\s*/;
declare global {
interface Node {
protectedValue: ProtectedValue | undefined;
lineNumber: number | undefined;
}
}
function createDOMParser() {
if (global.DOMParser) {
return new global.DOMParser();
}
const parserArg = {
errorHandler: {
warning: (e: Error) => {
throw e;
},
error: (e: Error) => {
throw e;
},
fatalError: (e: Error) => {
throw e;
}
}
};
/* eslint-disable @typescript-eslint/no-var-requires,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-call */
const { DOMParser } = require('@xmldom/xmldom');
return <typeof global.DOMParser>new DOMParser(parserArg);
/* eslint-enable */
}
function createXMLSerializer() {
if (global.XMLSerializer) {
return new global.XMLSerializer();
}
/* eslint-disable @typescript-eslint/no-var-requires,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-call */
const { XMLSerializer } = require('@xmldom/xmldom');
return <typeof global.XMLSerializer>new XMLSerializer();
/* eslint-enable */
}
export function parse(xml: string): Document {
const parser = createDOMParser();
let doc;
// eslint-disable-next-line no-control-regex
xml = xml.replace(/[\x00-\x09\x0B-\x0C\x0E-\x1F]/g, '');
try {
doc = parser.parseFromString(xml, 'application/xml');
} catch (e) {
const errMsg = e instanceof Error ? e.message : String(e);
throw new KdbxError(ErrorCodes.FileCorrupt, `bad xml: ${errMsg}`);
}
if (!doc.documentElement) {
throw new KdbxError(ErrorCodes.FileCorrupt, 'bad xml');
}
const parserError = doc.getElementsByTagName('parsererror')[0];
if (parserError) {
throw new KdbxError(ErrorCodes.FileCorrupt, `bad xml: ${parserError.textContent}`);
}
return doc;
}
export function serialize(doc: Document, prettyPrint = false): string {
if (prettyPrint) {
prettyPrintXmlNode(doc, 0);
}
let xml = createXMLSerializer().serializeToString(doc);
if (prettyPrint && xml.startsWith('<?')) {
xml = xml.replace(/^(<\?.*?\?>)</, '$1\n<');
}
return xml;
}
function prettyPrintXmlNode(node: Node, indentationLevel: number): void {
const numChildNodes = node.childNodes.length;
if (numChildNodes === 0) {
return;
}
const formatStr = '\n' + ' '.repeat(indentationLevel);
const prevFormatStr = indentationLevel > 0 ? '\n' + ' '.repeat(indentationLevel - 1) : '';
const doc = node.ownerDocument || <Document>node;
const childNodes = [];
let childNode;
for (let i = 0; i < numChildNodes; i++) {
childNode = node.childNodes[i];
if (
childNode.nodeType !== doc.TEXT_NODE &&
childNode.nodeType !== doc.PROCESSING_INSTRUCTION_NODE
) {
childNodes.push(childNode);
}
}
for (let j = 0; j < childNodes.length; j++) {
childNode = childNodes[j];
const isFirstDocumentNode = indentationLevel === 0 && j === 0;
if (!isFirstDocumentNode) {
const textNodeBefore = doc.createTextNode(formatStr);
node.insertBefore(textNodeBefore, childNode);
}
if (!childNode.nextSibling && indentationLevel > 0) {
const textNodeAfter = doc.createTextNode(prevFormatStr);
node.appendChild(textNodeAfter);
}
prettyPrintXmlNode(childNode, indentationLevel + 1);
}
}
export function create(rootNode: string): Document {
return parse('<?xml version="1.0" encoding="utf-8" standalone="yes"?><' + rootNode + '/>');
}
export function getChildNode(node: Node | null, tagName: string): Node | null;
export function getChildNode(node: Node | null, tagName: string, errorMsgIfAbsent: string): Node;
export function getChildNode(
node: Node | null,
tagName: string,
errorMsgIfAbsent?: string
): Node | null {
if (node && node.childNodes) {
for (let i = 0, cn = node.childNodes, len = cn.length; i < len; i++) {
if ((<Element>cn[i]).tagName === tagName) {
return cn[i];
}
}
}
if (errorMsgIfAbsent) {
throw new KdbxError(ErrorCodes.FileCorrupt, errorMsgIfAbsent);
} else {
return null;
}
}
export function addChildNode(node: Node, tagName: string): Element {
return node.appendChild((node.ownerDocument || <Document>node).createElement(tagName));
}
export function getText(node: Node | null): string | undefined {
if (!node?.childNodes) {
return undefined;
}
return node.protectedValue ? node.protectedValue.getText() : node.textContent ?? undefined;
}
export function setText(node: Node, text: string | undefined): void {
node.textContent = text || '';
}
export function getTags(node: Node): string[] {
const text = getText(node);
if (!text) {
return [];
}
return text
.split(TagsSplitRegex)
.map((t) => t.trim())
.filter((s) => s);
}
export function setTags(node: Node, tags: string[]): void {
setText(node, tags.join(', '));
}
export function getBytes(node: Node): ArrayBuffer | undefined {
const text = getText(node);
return text ? arrayToBuffer(base64ToBytes(text)) : undefined;
}
export function setBytes(node: Node, bytes: ArrayBuffer | Uint8Array | string | undefined): void {
if (typeof bytes === 'string') {
bytes = base64ToBytes(bytes);
}
setText(node, bytes ? bytesToBase64(arrayToBuffer(bytes)) : undefined);
}
export function getDate(node: Node): Date | undefined {
const text = getText(node);
if (!text) {
return undefined;
}
if (text.indexOf(':') > 0) {
return new Date(text);
}
const bytes = new DataView(arrayToBuffer(base64ToBytes(text)));
const secondsFrom00 = new Int64(bytes.getUint32(0, true), bytes.getUint32(4, true)).value;
const diff = (secondsFrom00 - EpochSeconds) * 1000;
return new Date(diff);
}
export function setDate(node: Node, date: Date | undefined, binary = false): void {
if (date) {
if (binary) {
const secondsFrom00 = Math.floor(date.getTime() / 1000) + EpochSeconds;
const bytes = new DataView(new ArrayBuffer(8));
const val64 = Int64.from(secondsFrom00);
bytes.setUint32(0, val64.lo, true);
bytes.setUint32(4, val64.hi, true);
setText(node, bytesToBase64(bytes.buffer));
} else {
setText(node, date.toISOString().replace(DateRegex, ''));
}
} else {
setText(node, '');
}
}
export function getNumber(node: Node): number | undefined {
const text = getText(node);
return text ? +text : undefined;
}
export function setNumber(node: Node, number: number | undefined): void {
setText(node, typeof number === 'number' && !isNaN(number) ? number.toString() : undefined);
}
export function getBoolean(node: Node): boolean | null | undefined {
const text = getText(node);
return text ? strToBoolean(text) : undefined;
}
export function setBoolean(node: Node, boolean: boolean | null | undefined): void {
setText(
node,
boolean === undefined ? '' : boolean === null ? 'null' : boolean ? 'True' : 'False'
);
}
export function strToBoolean(str: string | null | undefined): boolean | null | undefined {
switch (str?.toLowerCase()) {
case 'true':
return true;
case 'false':
return false;
case 'null':
return null;
}
return undefined;
}
export function getUuid(node: Node): KdbxUuid | undefined {
const bytes = getBytes(node);
return bytes ? new KdbxUuid(bytes) : undefined;
}
export function setUuid(
node: Node,
uuid: KdbxUuid | ArrayBuffer | Uint8Array | string | undefined
): void {
const uuidBytes = uuid instanceof KdbxUuid ? uuid.toBytes() : uuid;
setBytes(node, uuidBytes);
}
export function getProtectedText(node: Node): ProtectedValue | string | undefined {
return (node.protectedValue || node.textContent) ?? undefined;
}
export function setProtectedText(node: Node, text: ProtectedValue | string): void {
if (text instanceof ProtectedValue) {
node.protectedValue = text;
(<Element>node).setAttribute(XmlNames.Attr.Protected, 'True');
} else {
setText(node, text);
}
}
export function getProtectedBinary(node: Node): KdbxBinaryOrRef | undefined {
if (node.protectedValue) {
return node.protectedValue;
}
const text = node.textContent;
const ref = (<Element>node).getAttribute(XmlNames.Attr.Ref);
if (ref) {
return { ref };
}
if (!text) {
return undefined;
}
const compressed = strToBoolean((<Element>node).getAttribute(XmlNames.Attr.Compressed));
let bytes = base64ToBytes(text);
if (compressed) {
bytes = gunzipSync(bytes);
}
return arrayToBuffer(bytes);
}
export function setProtectedBinary(node: Node, binary: KdbxBinaryOrRef): void {
if (binary instanceof ProtectedValue) {
node.protectedValue = binary;
(<Element>node).setAttribute(XmlNames.Attr.Protected, 'True');
} else if (KdbxBinaries.isKdbxBinaryRef(binary)) {
(<Element>node).setAttribute(XmlNames.Attr.Ref, binary.ref);
} else {
setBytes(node, binary);
}
}
export function traverse(node: Node, callback: (node: Element) => void): void {
callback(<Element>node);
for (let i = 0, cn = node.childNodes, len = cn.length; i < len; i++) {
const childNode = <Element>cn[i];
if (childNode.tagName) {
traverse(childNode, callback);
}
}
}
export function setProtectedValues(node: Node, protectSaltGenerator: ProtectSaltGenerator): void {
traverse(node, (node) => {
if (strToBoolean(node.getAttribute(XmlNames.Attr.Protected))) {
try {
const value = arrayToBuffer(base64ToBytes(node.textContent || ''));
if (value.byteLength) {
const salt = protectSaltGenerator.getSalt(value.byteLength);
node.protectedValue = new ProtectedValue(value, salt);
}
} catch (e) {
throw new KdbxError(
ErrorCodes.FileCorrupt,
`bad protected value at line ${node.lineNumber}: ${e}`
);
}
}
});
}
export function updateProtectedValuesSalt(
node: Node,
protectSaltGenerator: ProtectSaltGenerator
): void {
traverse(node, (node) => {
if (strToBoolean(node.getAttribute(XmlNames.Attr.Protected)) && node.protectedValue) {
const newSalt = protectSaltGenerator.getSalt(node.protectedValue.byteLength);
node.protectedValue.setSalt(newSalt);
node.textContent = node.protectedValue.toString();
}
});
}
export function unprotectValues(node: Node): void {
traverse(node, (node) => {
if (strToBoolean(node.getAttribute(XmlNames.Attr.Protected)) && node.protectedValue) {
node.removeAttribute(XmlNames.Attr.Protected);
node.setAttribute(XmlNames.Attr.ProtectedInMemPlainXml, 'True');
node.textContent = node.protectedValue.getText();
}
});
}
export function protectUnprotectedValues(node: Node): void {
traverse(node, (node) => {
if (
strToBoolean(node.getAttribute(XmlNames.Attr.ProtectedInMemPlainXml)) &&
node.protectedValue
) {
node.removeAttribute(XmlNames.Attr.ProtectedInMemPlainXml);
node.setAttribute(XmlNames.Attr.Protected, 'True');
node.textContent = node.protectedValue.toString();
}
});
}
export function protectPlainValues(node: Node): void {
traverse(node, (node) => {
if (strToBoolean(node.getAttribute(XmlNames.Attr.ProtectedInMemPlainXml))) {
node.protectedValue = ProtectedValue.fromString(node.textContent || '');
node.textContent = node.protectedValue.toString();
node.removeAttribute(XmlNames.Attr.ProtectedInMemPlainXml);
node.setAttribute(XmlNames.Attr.Protected, 'True');
}
});
} | the_stack |
module Kiwi.Components {
/**
* The AnimationManager is used to handle the creation and use of spritesheet Animations on a GameObject based on the TextureAtlas it has.
* If the When the AnimationManager is instantiated it will loop through all of the Sequences on the TextureAtlas of the GameObject being used and will create a new Animation for each one.
* Now when you create a new Animation that animation will automatically be added as a new Sequence to the corresponding Texture.
* This way you don't need to create new Animations for a each Sprite that use's the same Texture.
*
* @class AnimationManager
* @extends Kiwi.Component
* @namespace Kiwi.Components
* @constructor
* @param entity {Kiwi.Entity} The entity that this animation component belongs to.
* @param [inheritSequences=true] {Boolean} If a new Animation should be created for each Sequence on the Entities TextureAtlas it is a part of or not.
* @return {Kiwi.Components.AnimationManager}
*/
export class AnimationManager extends Component {
constructor(entity: Kiwi.Entity, inheritSequences: boolean = true) {
super(entity, 'Animation');
//Get the entity and the animation.
this.entity = entity;
this._atlas = this.entity.atlas;
this._animations = {};
//Create all of the default animations.
if (inheritSequences == true) {
for (var i = 0; i < this._atlas.sequences.length; i++) {
this.createFromSequence(this._atlas.sequences[i], false);
}
}
//If a default animation already exists
if (this._animations['default']) {
this.currentAnimation = this._animations['default'];
//Otherwise create one.
} else {
var defaultCells = [];
for (var i = 0; i < this._atlas.cells.length; i++) {
defaultCells.push(i);
}
this.currentAnimation = this.add('default', defaultCells, 0.1, true, false);
}
//Signals
this.onChange = new Kiwi.Signal;
this.onPlay = new Kiwi.Signal;
this.onStop = new Kiwi.Signal;
this.onUpdate = new Kiwi.Signal;
}
/**
* Dispatches callbacks each time an animation is told to play through this AnimationManager.
* Functions dispatched from this signal have ONE Parameter.
* One - The Animation object of that is now playing.
* @property onPlay
* @type Kiwi.Signal
* @public
*/
public onPlay: Kiwi.Signal;
/**
* Dispatches callbacks each time an animation stops.
* Functions dispatched from this signal have ONE parameter.
* One - The current animation.
* @property onStop
* @type Kiwi.Signal
* @public
*/
public onStop: Kiwi.Signal;
/**
* Dispatches callbacks each time the cell of the Sprite this AnimationManager belongs to updates/changes.
* Note: This method will be dispatching events EVERY time the cell changes, so this will include when changing/switching animations.
* @property onUpdate
* @type Kiwi.Signal
* @public
*/
public onUpdate: Kiwi.Signal
/**
* Dispatches callbacks each time the current animation is switched NOT when the cells of a animation change.
* Function's dispatched from this event have TWO parameters,
* One - Name of the animation switched to.
* Two - The Animation object that is now the current.
* @property onChange
* @type Kiwi.Signal
* @public
*/
public onChange: Kiwi.Signal;
/**
* The entity that this animation belongs to and thus is effecting.
* @property entity
* @type Kiwi.Entity
* @public
*/
public entity: Kiwi.Entity;
/**
* The texture atlas that this animation is taking effect on.
* The value of this should be the same as the Entity.
* @property _atlas
* @type Kiwi.Textures.TextureAtlas
* @private
*/
private _atlas: Kiwi.Textures.TextureAtlas;
/**
* A Object containing all of the animations that are avaiable to be used.
* @property _animations
* @type Object
* @private
*/
private _animations: {};
/**
* A reference to the animation that is currently being played.
* @property currentAnimation
* @type Kiwi.Animations.Animation
* @public
*/
public currentAnimation: Kiwi.Animations.Animation = null;
/**
* Returns a boolean indicating whether or not the current animation is playing. This is READ ONLY.
* @property isPlaying
* @type boolean
* @public
*/
public get isPlaying(): boolean {
return this.currentAnimation.isPlaying;
}
/**
* Returns a string indicating the type of object that this is.
* @method objType
* @return {String} "AnimationManager"
* @public
*/
public objType() {
return "AnimationManager";
}
/**
* Creates a new Animation (by creating a Sequence) that can then be played on this AnimationManager.
* If you pass to this the name of a Animation that already exists, then the previous Animation will be overridden by this new one.
* Note: If the Animation you have overridden was the currentAnimation, then the previous Animation will keep playing until a different Animation is switched to.
* By default new Animation Sequences are also added to the TextureAtlas, which can then be inherited.
* Returns the Animation that was created.
*
* @method add
* @param name {string} The name of the animation that is to be created.
* @param cells {Array} An array of numbers, which are reference to each cell that is to be played in the Animation in order.
* @param speed {number} The amount of time that each cell in the Animation should stay on screen for. In seconds.
* @param [loop=false] {boolean} If when the Animation reaches the last frame, it should go back to the start again.
* @param [play=false] {boolean} If once created the animation should played right away.
* @param [addToAtlas=true] {boolean} If the new Sequence created should be added to the TextureAtlas or not.
* @return {Kiwi.Animations.Animation} The Animation that was created.
* @public
*/
public add(name: string, cells: number[], speed: number, loop: boolean= false, play: boolean= false, addToAtlas:boolean=true): Kiwi.Animations.Animation {
var newSequence = new Kiwi.Animations.Sequence(name, cells, speed, loop);
if(addToAtlas == true) this._atlas.sequences.push(newSequence);
return this.createFromSequence(newSequence, play);
}
/**
* Creates a new Animation based on a Sequence that is passed.
* If you pass to this the name of a Animation that already exists, then the previous Animation will be overridden by this new one.
* Note: If the Animation you have overridden was the currentAnimation, then the previous Animation will keep playing until a different Animation is switched to.
* Returns the Animation that was created.
*
* @method createFromSequence
* @param sequence {Kiwi.Sequence} The sequence that the Animation is based on.
* @param [play=false] {boolean} If the Animation should played once it has been created
* @return {Kiwi.Animations.Animation} The Animation that was created.
* @public
*/
public createFromSequence(sequence: Kiwi.Animations.Sequence, play: boolean= false): Kiwi.Animations.Animation {
this._animations[sequence.name] = new Kiwi.Animations.Animation(sequence.name, sequence, null, this);
if (play) this.play(sequence.name);
return this._animations[sequence.name];
}
/**
* Plays either the current animation or the name of the animation that you pass.
*
* @method play
* @param [name] {String} The name of the animation that you want to play. If not passed it plays the current animation.
* @param [resetTime=true] {Boolean} When set to false, this will prevent a new Animation from playing if it is already the currentAnimation that is already playing.
* @return {Kiwi.Animations.Animation} Returns the current Animation that is now playing.
* @public
*/
public play(name: string = this.currentAnimation.name, resetTime: boolean = true): Kiwi.Animations.Animation {
//If the current animation playing
if (resetTime == false && this.currentAnimation.name === name && this.currentAnimation.isPlaying == true) {
return this.currentAnimation;
} else {
return this._play(name);
}
}
/**
* Plays an Animation at a particular frameIndex.
* Note: The frameIndex is a particular index of a cell in the Sequence of the Animation you would like to play.
* Example: If you had a Animation with a Sequence [0, 1, 2, 3] and you told it to play at index '2', then the cell that it would be at is '3'.
*
* @method playAt
* @param index {Number} The index of the frame in the Sequence that you would like to play.
* @param [name] {String} The name of the animation that you want to play. If not passed, it attempts to play it on the current animation.
* @return {Kiwi.Animations.Animation} Returns the current Animation that is now playing.
* @public
*/
public playAt(index: number, name: string = this.currentAnimation.name): Kiwi.Animations.Animation {
return this._play(name, index);
}
/**
* An internal method used to actually play a Animation at a Index.
*
* @method _play
* @param name {string} The name of the animation that is to be switched to.
* @param [index=null] {number} The index of the frame in the Sequence that is to play. If null, then it restarts the animation at the cell it currently is at.
* @return {Kiwi.Animations.Animation} Returns the current Animation that is now playing.
* @private
*/
private _play(name: string, index: number=null): Kiwi.Animations.Animation {
this._setCurrentAnimation(name);
if (index !== null)
this.currentAnimation.playAt(index);
else
this.currentAnimation.play();
this.onPlay.dispatch(this.currentAnimation);
this.updateCellIndex();
return this.currentAnimation;
}
/**
* Stops the current animation from playing.
*
* @method stop
* @public
*/
public stop() {
if (this.isPlaying === true) {
this.currentAnimation.stop();
this.onStop.dispatch(this.currentAnimation);
}
}
/**
* Pauses the current animation.
* @method pause
* @public
*/
public pause() {
this.currentAnimation.pause();
}
/**
* Resumes the current animation.
* The animation should have already been paused.
*
* @method resume
* @public
*/
public resume() {
this.currentAnimation.resume();
}
/**
* Either switches to a particular animation OR a particular frame in the current animation depending on if you pass the name of an animation that exists on this Manager (as a string) or a number refering to a frame index on the Animation.
* When you switch to a particular animation then
* You can also force the animation to play or to stop by passing a boolean in. But if left as null, the state of the Animation will based off what is currently happening.
* So if the animation is currently 'playing' then once switched to the animation will play. If not currently playing it will switch to and stop.
* If the previous animation played is non-looping and has reached its final frame, it is no longer considered playing, and as such, switching to another animation will not play unless the argument to the play parameter is true.
*
* @method switchTo
* @param val {string|number}
* @param [play=null] {boolean} Force the animation to play or stop. If null the animation base's it off what is currently happening.
* @public
*/
public switchTo(val: any, play:boolean=null) {
var switched = false;
switch (typeof val) {
case "string":
if (this.currentAnimation.name !== val) {
this._setCurrentAnimation(val);
switched = true;
}
break;
case "number":
this.currentAnimation.frameIndex = val;
switched = true;
break;
}
//Play if the dev forced it to OR if the animation was already playing
if (play || play === null && this.isPlaying && switched) this.play();
if (play == false && this.isPlaying) this.stop();
this.updateCellIndex();
}
/**
* Makes the current animation go to the next frame. If the animation is at the end of the sequence it then goes back to the start.
* @method nextFrame
* @public
*/
public nextFrame() {
this.currentAnimation.nextFrame();
this.updateCellIndex();
}
/**
* Makes the current animation go to the prev frame. If the animation is at the start, the animation will go the end of the sequence.
* @method prevFrame
* @public
*/
public prevFrame() {
this.currentAnimation.prevFrame();
this.updateCellIndex();
}
/**
* Internal method that sets the current animation to a Animation passed.
*
* @method _setCurrentAnimation
* @param name {string} Name of the Animation that is to be switched to.
* @param [inheritFromTexture=true] {booelan} If the animation component should look on the texture atlas for a sequence with that name.
* @private
*/
private _setCurrentAnimation(name: string, inheritFromTexture: boolean=true) {
if (this.currentAnimation.name !== name) {
if ( this.currentAnimation !== null ) this.currentAnimation.stop();
if (this._animations[name]) {
//Switch to the animation if it exists
this.currentAnimation = this._animations[name];
this.onChange.dispatch(name, this.currentAnimation);
} else if (inheritFromTexture) {
//Check to see if that animation exists on the atlas.
//If so create a new version of it.
for (var i = 0; i < this._atlas.sequences.length; i++) {
if (this._atlas.sequences[i].name === name) {
this.currentAnimation = this.createFromSequence(this._atlas.sequences[i], false);
this.onChange.dispatch(name, this.currentAnimation);
}
}
}
}
}
/**
* The update loop for this component.
* Only updates the currentAnimation and only if it is playing.
*
* @method update
* @public
*/
public update() {
if (this.currentAnimation) {
this.currentAnimation.update();
}
}
/**
* Gets the cell that the current Animation is current at. This is READ ONLY.
* @property currentCell
* @type number
* @public
*/
public get currentCell():number {
return this.currentAnimation.currentCell;
}
/**
* Gets the current frame index of the cell in the Sequence that is currently playing. This is READ ONLY.
* @property frameIndex
* @type number
* @public
*/
public get frameIndex():number {
return this.currentAnimation.frameIndex;
}
/**
* Returns the length (Number of cells) of the current Animation that is playing. This is READ ONLY.
* @property length
* @type number
* @public
*/
public get length(): number {
return this.currentAnimation.length;
}
/**
* Returns a Animation that is on this AnimationComponent
* Does not check to see if that Animation exists or not.
*
* @method getAnimation
* @param name {string} The name of the Animation you would like to get.
* @return {Kiwi.Animations.Animation} The Animation that is found. Will be 'undefined' if a Animation with that name did not exist.
* @public
*/
public getAnimation(name: string): Kiwi.Animations.Animation {
return this._animations[name];
}
/**
* An internal method that is used to update the cell index of an entity when an animation says it needs to update.
* @method updateCellIndex
* @protected
*/
public updateCellIndex() {
if (typeof this.currentAnimation !== "undefined") {
this.entity.cellIndex = this.currentAnimation.currentCell;
this.onUpdate.dispatch(this.currentAnimation);
}
}
/**
* Destroys the animation component and runs the destroy method on all of the anims that it has.
* @method destroy
* @public
*/
public destroy() {
super.destroy();
for (var key in this._animations) {
this._animations[key].destroy();
delete this._animations[key];
}
delete this._animations;
delete this.currentAnimation;
delete this._atlas;
}
}
} | the_stack |
import 'mocha';
import { EventRecorder, expect, PickEvent } from '@integration/testing-tools';
import { ImplementationPendingError, Serenity } from '@serenity-js/core';
import { SceneFinished, SceneStarts, SceneTagged, TaskFinished, TaskStarts, TestRunnerDetected } from '@serenity-js/core/lib/events';
import { FileSystemLocation, ModuleLoader, Path, Version } from '@serenity-js/core/lib/io';
import { Category, ExecutionFailedWithError, ExecutionSkipped, ExecutionSuccessful, FeatureTag, ImplementationPending, Name, ScenarioDetails } from '@serenity-js/core/lib/model';
import { EventEmitter } from 'events';
import * as sinon from 'sinon';
import { JSONObject } from 'tiny-types';
import { AmbiguousStepDefinitionError } from '../../../src/errors';
import { createListener } from '../../../src/listeners/legacy';
describe('CucumberEventProtocolAdapter', () => {
type CucumberHook = (event?: object) => // eslint-disable-line @typescript-eslint/ban-types
Promise<void> | void;
let afterHook: CucumberHook;
const fakeCucumber = {
BeforeAll: (hook: CucumberHook) => Promise.resolve(hook()),
Before: (hook: CucumberHook) => Promise.resolve(hook()),
After: (hook: CucumberHook) => { afterHook = hook; },
AfterAll: (hook: CucumberHook) => Promise.resolve(hook()),
};
let recorder: EventRecorder,
serenity: Serenity,
log: typeof console.log,
eventBroadcaster: EventEmitter,
moduleLoader: sinon.SinonStubbedInstance<ModuleLoader>,
adapter: any;
beforeEach(() => {
log = sinon.spy();
moduleLoader = sinon.createStubInstance(ModuleLoader);
serenity = new Serenity();
recorder = new EventRecorder();
eventBroadcaster = new EventEmitter();
serenity.configure({
crew: [recorder],
});
moduleLoader.hasAvailable.withArgs('@cucumber/cucumber').returns(false);
moduleLoader.hasAvailable.withArgs('cucumber').returns(true);
moduleLoader.versionOf.withArgs('cucumber').returns(new Version('5.0.0'));
moduleLoader.require.withArgs('cucumber').returns(fakeCucumber);
const listener = createListener(serenity, moduleLoader);
adapter = new listener({ eventBroadcaster, log }); // eslint-disable-line @typescript-eslint/no-unused-vars
});
it('correctly recognises Cucumber Event Protocol events', () => {
eventBroadcaster.on('test-case-finished', () => afterHook({ result: { duration: 2, status: 'passed' } }));
emitAllFrom(require('./samples/scenario-with-hooks.json'));
const expectedScenarioDetails = new ScenarioDetails(
new Name('Hooks'),
new Category('Event Protocol'),
new FileSystemLocation(
new Path('features/tasty-cucumber.feature'),
3,
3,
),
);
return serenity.waitForNextCue().then(() => {
PickEvent.from(recorder.events)
.next(SceneStarts, e => expect(e.details).to.equal(expectedScenarioDetails))
.next(TestRunnerDetected, e => expect(e.name).to.equal(new Name('Cucumber')))
.next(SceneTagged, e => expect(e.tag).to.equal(new FeatureTag('Event Protocol')))
.next(TaskStarts, e => expect(e.details.name).to.equal(new Name('Given I have a tasty cucumber in my belly')))
.next(TaskFinished, e => {
expect(e.details.name).to.equal(new Name('Given I have a tasty cucumber in my belly'));
expect(e.outcome).to.equal(new ExecutionSuccessful());
})
.next(TaskStarts, e => expect(e.details.name).to.equal(new Name(`Then I'm very happy`)))
.next(TaskFinished, e => {
expect(e.details.name).to.equal(new Name(`Then I'm very happy`));
expect(e.outcome).to.equal(new ExecutionSuccessful());
})
.next(SceneFinished, e => {
expect(e.details).to.equal(expectedScenarioDetails);
expect(e.outcome).to.equal(new ExecutionSuccessful());
})
;
});
});
it('correctly recognises undefined steps', () => {
eventBroadcaster.on('test-case-finished', () => afterHook({ result: { duration: 0, status: 'undefined' } }));
emitAllFrom(require('./samples/scenario-with-undefined-steps.json'));
const expectedScenarioDetails = new ScenarioDetails(
new Name('Undefined steps'),
new Category('Event Protocol'),
new FileSystemLocation(
new Path('features/undefined-steps.feature'),
3,
3,
),
);
return serenity.waitForNextCue().then(() => {
PickEvent.from(recorder.events)
.next(SceneStarts, e => expect(e.details).to.equal(expectedScenarioDetails))
.next(TestRunnerDetected, e => expect(e.name).to.equal(new Name('Cucumber')))
.next(SceneTagged, e => expect(e.tag).to.equal(new FeatureTag('Event Protocol')))
.next(TaskStarts, e => expect(e.details.name).to.equal(new Name('Given I have an undefined step')))
.next(TaskFinished, e => {
expect(e.details.name).to.equal(new Name('Given I have an undefined step'));
expect(e.outcome).to.be.instanceOf(ImplementationPending);
})
.next(TaskStarts, e => expect(e.details.name).to.equal(new Name(`Then I should implement it`)))
.next(TaskFinished, e => {
expect(e.details.name).to.equal(new Name('Then I should implement it'));
expect(e.outcome).to.be.instanceOf(ImplementationPending);
})
.next(SceneFinished, e => {
expect(e.details).to.equal(expectedScenarioDetails);
expect(e.outcome).to.be.instanceOf(ImplementationPending);
})
;
});
});
it('correctly recognises pending steps', () => {
eventBroadcaster.on('test-case-finished', () => afterHook({ result: { duration: 0, status: 'pending' } }));
emitAllFrom(require('./samples/scenario-with-pending-steps.json'));
const expectedScenarioDetails = new ScenarioDetails(
new Name('Pending steps'),
new Category('Event Protocol'),
new FileSystemLocation(
new Path('features/pending-steps.feature'),
3,
3,
),
);
return serenity.waitForNextCue().then(() => {
PickEvent.from(recorder.events)
.next(SceneStarts, e => expect(e.details).to.equal(expectedScenarioDetails))
.next(TestRunnerDetected, e => expect(e.name).to.equal(new Name('Cucumber')))
.next(SceneTagged, e => expect(e.tag).to.equal(new FeatureTag('Event Protocol')))
.next(TaskStarts, e => expect(e.details.name).to.equal(new Name('Given I have a pending step')))
.next(TaskFinished, e => {
expect(e.details.name).to.equal(new Name('Given I have a pending step'));
expect(e.outcome).to.be.instanceOf(ImplementationPending);
})
.next(TaskStarts, e => expect(e.details.name).to.equal(new Name(`Then I should implement it`)))
.next(TaskFinished, e => {
expect(e.details.name).to.equal(new Name('Then I should implement it'));
expect(e.outcome).to.be.instanceOf(ExecutionSkipped);
})
.next(SceneFinished, e => {
expect(e.details).to.equal(expectedScenarioDetails);
expect(e.outcome).to.be.instanceOf(ImplementationPending);
})
;
});
});
it('correctly recognises ambiguous steps', () => {
eventBroadcaster.on('test-case-finished', () => afterHook({
result: {
duration: 0,
status: 'ambiguous',
exception: 'Multiple step definitions match:\n /^I have an ambiguous step definition$/ - step_definitions/ambiguous.steps.ts:3\n /^I have an ambiguous step definition$/ - step_definitions/ambiguous.steps.ts:7'
},
}));
emitAllFrom(require('./samples/scenario-with-ambiguous-steps.json'));
const expectedScenarioDetails = new ScenarioDetails(
new Name('Ambiguous steps'),
new Category('Event Protocol'),
new FileSystemLocation(
new Path('features/ambiguous-steps.feature'),
3,
3,
),
);
return serenity.waitForNextCue().then(() => {
PickEvent.from(recorder.events)
.next(SceneStarts, e => expect(e.details).to.equal(expectedScenarioDetails))
.next(TestRunnerDetected, e => expect(e.name).to.equal(new Name('Cucumber')))
.next(SceneTagged, e => expect(e.tag).to.equal(new FeatureTag('Event Protocol')))
.next(TaskStarts, e => expect(e.details.name).to.equal(new Name('Given I have an ambiguous step definition')))
.next(TaskFinished, e => {
expect(e.details.name).to.equal(new Name('Given I have an ambiguous step definition'));
expect(e.outcome).to.be.instanceOf(ExecutionFailedWithError);
expect((e.outcome as ExecutionFailedWithError).error).to.be.instanceOf(AmbiguousStepDefinitionError);
})
.next(TaskStarts, e => expect(e.details.name).to.equal(new Name(`Then I should correct it`)))
.next(TaskFinished, e => {
expect(e.details.name).to.equal(new Name('Then I should correct it'));
expect(e.outcome).to.be.instanceOf(ExecutionSkipped);
})
.next(SceneFinished, e => {
expect(e.details).to.equal(expectedScenarioDetails);
expect(e.outcome).to.be.instanceOf(ExecutionFailedWithError);
expect((e.outcome as ExecutionFailedWithError).error).to.be.instanceOf(AmbiguousStepDefinitionError);
})
;
});
});
it('correctly recognises errors thrown in steps', () => {
eventBroadcaster.on('test-case-finished', () => afterHook({
result: {
duration: 0,
status: 'failed',
exception: `Error: We're sorry, something happened\n at World.<anonymous> (step_definitions/errors.steps.ts:4:11)`
},
}));
emitAllFrom(require('./samples/scenario-with-errors.json'));
const expectedScenarioDetails = new ScenarioDetails(
new Name('Errors in steps'),
new Category('Event Protocol'),
new FileSystemLocation(
new Path('features/errors-in-steps.feature'),
3,
3,
),
);
return serenity.waitForNextCue().then(() => {
PickEvent.from(recorder.events)
.next(SceneStarts, e => expect(e.details).to.equal(expectedScenarioDetails))
.next(TestRunnerDetected, e => expect(e.name).to.equal(new Name('Cucumber')))
.next(SceneTagged, e => expect(e.tag).to.equal(new FeatureTag('Event Protocol')))
.next(TaskStarts, e => expect(e.details.name).to.equal(new Name('Given I have a step that throws an error')))
.next(TaskFinished, e => {
expect(e.details.name).to.equal(new Name('Given I have a step that throws an error'));
expect(e.outcome).to.be.instanceOf(ExecutionFailedWithError);
expect((e.outcome as ExecutionFailedWithError).error).to.be.instanceOf(Error);
expect((e.outcome as ExecutionFailedWithError).error.message).to.equal(`We're sorry, something happened`);
})
.next(SceneFinished, e => {
expect(e.details).to.equal(expectedScenarioDetails);
expect(e.outcome).to.be.instanceOf(ExecutionFailedWithError);
expect((e.outcome as ExecutionFailedWithError).error).to.be.instanceOf(Error);
expect((e.outcome as ExecutionFailedWithError).error.message).to.equal(`We're sorry, something happened`);
})
;
});
});
it('correctly recognises scenario outlines', () => {
eventBroadcaster.on('test-case-finished', () => afterHook({
result: {
duration: 0,
status: 'passed',
},
}));
emitAllFrom(require('./samples/scenario-outline.json'));
// eslint-disable-next-line unicorn/consistent-function-scoping
const expectedScenarioDetails = (line: number) => new ScenarioDetails(
new Name('The things I like'),
new Category('Event Protocol'),
new FileSystemLocation(
new Path('features/outlines.feature'),
line,
7,
),
);
return serenity.waitForNextCue().then(() => {
PickEvent.from(recorder.events)
.next(SceneStarts, e => expect(e.details).to.equal(expectedScenarioDetails(10)))
.next(TestRunnerDetected, e => expect(e.name).to.equal(new Name('Cucumber')))
.next(SceneTagged, e => expect(e.tag).to.equal(new FeatureTag('Event Protocol')))
.next(TaskStarts, e => expect(e.details.name).to.equal(new Name('Given I like programming')))
.next(TaskFinished, e => expect(e.details.name).to.equal(new Name('Given I like programming')))
.next(SceneFinished, e => expect(e.details).to.equal(expectedScenarioDetails(10)))
.next(SceneStarts, e => expect(e.details).to.equal(expectedScenarioDetails(11)))
.next(TestRunnerDetected, e => expect(e.name).to.equal(new Name('Cucumber')))
.next(SceneTagged, e => expect(e.tag).to.equal(new FeatureTag('Event Protocol')))
.next(TaskStarts, e => expect(e.details.name).to.equal(new Name('Given I like to play guitar')))
.next(TaskFinished, e => expect(e.details.name).to.equal(new Name('Given I like to play guitar')))
.next(SceneFinished, e => expect(e.details).to.equal(expectedScenarioDetails(11)))
.next(SceneStarts, e => expect(e.details).to.equal(expectedScenarioDetails(12)))
.next(TestRunnerDetected, e => expect(e.name).to.equal(new Name('Cucumber')))
.next(SceneTagged, e => expect(e.tag).to.equal(new FeatureTag('Event Protocol')))
.next(TaskStarts, e => expect(e.details.name).to.equal(new Name('Given I like martial arts')))
.next(TaskFinished, e => expect(e.details.name).to.equal(new Name('Given I like martial arts')))
.next(SceneFinished, e => expect(e.details).to.equal(expectedScenarioDetails(12)))
;
});
});
it('considers a scenario with no steps and no hooks to be pending implementation', () => {
eventBroadcaster.on('test-case-finished', () => afterHook({
result: {
duration: 0,
status: 'passed',
},
}));
emitAllFrom(require('./samples/pending-scenario.json'));
const expectedScenarioDetails = new ScenarioDetails(
new Name('Implement me'),
new Category('Event Protocol'),
new FileSystemLocation(
new Path('features/pending-scenario.feature'),
3,
3,
),
);
return serenity.waitForNextCue().then(() => {
PickEvent.from(recorder.events)
.next(SceneStarts, e => expect(e.details).to.equal(expectedScenarioDetails))
.next(TestRunnerDetected, e => expect(e.name).to.equal(new Name('Cucumber')))
.next(SceneTagged, e => expect(e.tag).to.equal(new FeatureTag('Event Protocol')))
.next(SceneFinished, e => {
expect(e.details).to.equal(expectedScenarioDetails);
expect(e.outcome).to.be.instanceOf(ImplementationPending);
expect((e.outcome as ImplementationPending).error).to.be.instanceOf(ImplementationPendingError);
expect((e.outcome as ImplementationPending).error.message).to.equal(`"Implement me" has no test steps`);
})
;
});
});
function emitAllFrom(events: JSONObject[]): void {
events.forEach(event => {
// I can't use the convenient { type, ...body } construct because ESDoc/Babylon doesn't understand it; falling back to es5:
const emitted = Object.assign({}, event);
delete emitted.type;
eventBroadcaster.emit(event.type as string, emitted);
});
}
}); | the_stack |
import * as B from "./observable/observables"
import * as CSS from "csstype"
import * as H from "./harmaja"
type ChildrenType = H.HarmajaChildren | H.HarmajaChild
export const h = H.createElement
type WithObservablesInFields<T> = {
[K in keyof T]: T[K] | B.NativeProperty<T[K]>
}
type NativeElement = Element
// Notice the types below are copied from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts
// TODO: bivarianceHack!?
type NativeEvent = Event
type NativeAnimationEvent = AnimationEvent
type NativeClipboardEvent = ClipboardEvent
type NativeCompositionEvent = CompositionEvent
type NativeDragEvent = DragEvent
type NativeFocusEvent = FocusEvent
type NativeKeyboardEvent = KeyboardEvent
type NativeMouseEvent = MouseEvent
type NativeTouchEvent = TouchEvent
type NativePointerEvent = PointerEvent
type NativeTransitionEvent = TransitionEvent
type NativeUIEvent = UIEvent
type NativeWheelEvent = WheelEvent
type Booleanish = boolean | "true" | "false"
declare global {
namespace JSX {
function h(
type: H.JSXElementType,
props: H.HarmajaProps,
...children: H.HarmajaChildren
): H.HarmajaOutput
export interface IntrinsicElements {
// HTML
a: DetailedHTMLProps<
AnchorHTMLAttributes<HTMLAnchorElement>,
HTMLAnchorElement
>
abbr: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
address: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
area: DetailedHTMLProps<
AreaHTMLAttributes<HTMLAreaElement>,
HTMLAreaElement
>
article: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
aside: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
audio: DetailedHTMLProps<
AudioHTMLAttributes<HTMLAudioElement>,
HTMLAudioElement
>
b: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
base: DetailedHTMLProps<
BaseHTMLAttributes<HTMLBaseElement>,
HTMLBaseElement
>
bdi: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
bdo: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
big: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
blockquote: DetailedHTMLProps<
BlockquoteHTMLAttributes<HTMLElement>,
HTMLElement
>
body: DetailedHTMLProps<
HTMLAttributes<HTMLBodyElement>,
HTMLBodyElement
>
br: DetailedHTMLProps<HTMLAttributes<HTMLBRElement>, HTMLBRElement>
button: DetailedHTMLProps<
ButtonHTMLAttributes<HTMLButtonElement>,
HTMLButtonElement
>
canvas: DetailedHTMLProps<
CanvasHTMLAttributes<HTMLCanvasElement>,
HTMLCanvasElement
>
caption: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
cite: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
code: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
col: DetailedHTMLProps<
ColHTMLAttributes<HTMLTableColElement>,
HTMLTableColElement
>
colgroup: DetailedHTMLProps<
ColgroupHTMLAttributes<HTMLTableColElement>,
HTMLTableColElement
>
data: DetailedHTMLProps<
DataHTMLAttributes<HTMLDataElement>,
HTMLDataElement
>
datalist: DetailedHTMLProps<
HTMLAttributes<HTMLDataListElement>,
HTMLDataListElement
>
dd: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
del: DetailedHTMLProps<DelHTMLAttributes<HTMLElement>, HTMLElement>
details: DetailedHTMLProps<
DetailsHTMLAttributes<HTMLElement>,
HTMLElement
>
dfn: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
dialog: DetailedHTMLProps<
DialogHTMLAttributes<HTMLDialogElement>,
HTMLDialogElement
>
div: DetailedHTMLProps<
HTMLAttributes<HTMLDivElement>,
HTMLDivElement
>
dl: DetailedHTMLProps<
HTMLAttributes<HTMLDListElement>,
HTMLDListElement
>
dt: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
em: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
embed: DetailedHTMLProps<
EmbedHTMLAttributes<HTMLEmbedElement>,
HTMLEmbedElement
>
fieldset: DetailedHTMLProps<
FieldsetHTMLAttributes<HTMLFieldSetElement>,
HTMLFieldSetElement
>
figcaption: DetailedHTMLProps<
HTMLAttributes<HTMLElement>,
HTMLElement
>
figure: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
footer: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
form: DetailedHTMLProps<
FormHTMLAttributes<HTMLFormElement>,
HTMLFormElement
>
h1: DetailedHTMLProps<
HTMLAttributes<HTMLHeadingElement>,
HTMLHeadingElement
>
h2: DetailedHTMLProps<
HTMLAttributes<HTMLHeadingElement>,
HTMLHeadingElement
>
h3: DetailedHTMLProps<
HTMLAttributes<HTMLHeadingElement>,
HTMLHeadingElement
>
h4: DetailedHTMLProps<
HTMLAttributes<HTMLHeadingElement>,
HTMLHeadingElement
>
h5: DetailedHTMLProps<
HTMLAttributes<HTMLHeadingElement>,
HTMLHeadingElement
>
h6: DetailedHTMLProps<
HTMLAttributes<HTMLHeadingElement>,
HTMLHeadingElement
>
head: DetailedHTMLProps<
HTMLAttributes<HTMLHeadElement>,
HTMLHeadElement
>
header: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
hgroup: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
hr: DetailedHTMLProps<HTMLAttributes<HTMLHRElement>, HTMLHRElement>
html: DetailedHTMLProps<
HtmlHTMLAttributes<HTMLHtmlElement>,
HTMLHtmlElement
>
i: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
iframe: DetailedHTMLProps<
IframeHTMLAttributes<HTMLIFrameElement>,
HTMLIFrameElement
>
img: DetailedHTMLProps<
ImgHTMLAttributes<HTMLImageElement>,
HTMLImageElement
>
input: DetailedHTMLProps<
InputHTMLAttributes<HTMLInputElement>,
HTMLInputElement
>
ins: DetailedHTMLProps<
InsHTMLAttributes<HTMLModElement>,
HTMLModElement
>
kbd: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
keygen: DetailedHTMLProps<
KeygenHTMLAttributes<HTMLElement>,
HTMLElement
>
label: DetailedHTMLProps<
LabelHTMLAttributes<HTMLLabelElement>,
HTMLLabelElement
>
legend: DetailedHTMLProps<
HTMLAttributes<HTMLLegendElement>,
HTMLLegendElement
>
li: DetailedHTMLProps<
LiHTMLAttributes<HTMLLIElement>,
HTMLLIElement
>
link: DetailedHTMLProps<
LinkHTMLAttributes<HTMLLinkElement>,
HTMLLinkElement
>
main: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
map: DetailedHTMLProps<
MapHTMLAttributes<HTMLMapElement>,
HTMLMapElement
>
mark: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
menu: DetailedHTMLProps<
MenuHTMLAttributes<HTMLElement>,
HTMLElement
>
menuitem: DetailedHTMLProps<
HTMLAttributes<HTMLElement>,
HTMLElement
>
meta: DetailedHTMLProps<
MetaHTMLAttributes<HTMLMetaElement>,
HTMLMetaElement
>
meter: DetailedHTMLProps<
MeterHTMLAttributes<HTMLElement>,
HTMLElement
>
nav: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
noindex: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
noscript: DetailedHTMLProps<
HTMLAttributes<HTMLElement>,
HTMLElement
>
object: DetailedHTMLProps<
ObjectHTMLAttributes<HTMLObjectElement>,
HTMLObjectElement
>
ol: DetailedHTMLProps<
OlHTMLAttributes<HTMLOListElement>,
HTMLOListElement
>
optgroup: DetailedHTMLProps<
OptgroupHTMLAttributes<HTMLOptGroupElement>,
HTMLOptGroupElement
>
option: DetailedHTMLProps<
OptionHTMLAttributes<HTMLOptionElement>,
HTMLOptionElement
>
output: DetailedHTMLProps<
OutputHTMLAttributes<HTMLElement>,
HTMLElement
>
p: DetailedHTMLProps<
HTMLAttributes<HTMLParagraphElement>,
HTMLParagraphElement
>
param: DetailedHTMLProps<
ParamHTMLAttributes<HTMLParamElement>,
HTMLParamElement
>
picture: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
pre: DetailedHTMLProps<
HTMLAttributes<HTMLPreElement>,
HTMLPreElement
>
progress: DetailedHTMLProps<
ProgressHTMLAttributes<HTMLProgressElement>,
HTMLProgressElement
>
q: DetailedHTMLProps<
QuoteHTMLAttributes<HTMLQuoteElement>,
HTMLQuoteElement
>
rp: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
rt: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
ruby: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
s: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
samp: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
slot: DetailedHTMLProps<
SlotHTMLAttributes<HTMLSlotElement>,
HTMLSlotElement
>
script: DetailedHTMLProps<
ScriptHTMLAttributes<HTMLScriptElement>,
HTMLScriptElement
>
section: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
select: DetailedHTMLProps<
SelectHTMLAttributes<HTMLSelectElement>,
HTMLSelectElement
>
small: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
source: DetailedHTMLProps<
SourceHTMLAttributes<HTMLSourceElement>,
HTMLSourceElement
>
span: DetailedHTMLProps<
HTMLAttributes<HTMLSpanElement>,
HTMLSpanElement
>
strong: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
style: DetailedHTMLProps<
StyleHTMLAttributes<HTMLStyleElement>,
HTMLStyleElement
>
sub: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
summary: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
sup: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
table: DetailedHTMLProps<
TableHTMLAttributes<HTMLTableElement>,
HTMLTableElement
>
template: DetailedHTMLProps<
HTMLAttributes<HTMLTemplateElement>,
HTMLTemplateElement
>
tbody: DetailedHTMLProps<
HTMLAttributes<HTMLTableSectionElement>,
HTMLTableSectionElement
>
td: DetailedHTMLProps<
TdHTMLAttributes<HTMLTableDataCellElement>,
HTMLTableDataCellElement
>
textarea: DetailedHTMLProps<
TextareaHTMLAttributes<HTMLTextAreaElement>,
HTMLTextAreaElement
>
tfoot: DetailedHTMLProps<
HTMLAttributes<HTMLTableSectionElement>,
HTMLTableSectionElement
>
th: DetailedHTMLProps<
ThHTMLAttributes<HTMLTableHeaderCellElement>,
HTMLTableHeaderCellElement
>
thead: DetailedHTMLProps<
HTMLAttributes<HTMLTableSectionElement>,
HTMLTableSectionElement
>
time: DetailedHTMLProps<
TimeHTMLAttributes<HTMLElement>,
HTMLElement
>
title: DetailedHTMLProps<
HTMLAttributes<HTMLTitleElement>,
HTMLTitleElement
>
tr: DetailedHTMLProps<
HTMLAttributes<HTMLTableRowElement>,
HTMLTableRowElement
>
track: DetailedHTMLProps<
TrackHTMLAttributes<HTMLTrackElement>,
HTMLTrackElement
>
u: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
ul: DetailedHTMLProps<
HTMLAttributes<HTMLUListElement>,
HTMLUListElement
>
var: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
video: DetailedHTMLProps<
VideoHTMLAttributes<HTMLVideoElement>,
HTMLVideoElement
>
wbr: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
// SVG
svg: SVGProps<SVGSVGElement>
animate: SVGProps<SVGElement> // TODO: It is SVGAnimateElement but is not in TypeScript's lib.dom.d.ts for now.
animateMotion: SVGProps<SVGElement>
animateTransform: SVGProps<SVGElement> // TODO: It is SVGAnimateTransformElement but is not in TypeScript's lib.dom.d.ts for now.
circle: SVGProps<SVGCircleElement>
clipPath: SVGProps<SVGClipPathElement>
defs: SVGProps<SVGDefsElement>
desc: SVGProps<SVGDescElement>
ellipse: SVGProps<SVGEllipseElement>
feBlend: SVGProps<SVGFEBlendElement>
feColorMatrix: SVGProps<SVGFEColorMatrixElement>
feComponentTransfer: SVGProps<SVGFEComponentTransferElement>
feComposite: SVGProps<SVGFECompositeElement>
feConvolveMatrix: SVGProps<SVGFEConvolveMatrixElement>
feDiffuseLighting: SVGProps<SVGFEDiffuseLightingElement>
feDisplacementMap: SVGProps<SVGFEDisplacementMapElement>
feDistantLight: SVGProps<SVGFEDistantLightElement>
feDropShadow: SVGProps<SVGFEDropShadowElement>
feFlood: SVGProps<SVGFEFloodElement>
feFuncA: SVGProps<SVGFEFuncAElement>
feFuncB: SVGProps<SVGFEFuncBElement>
feFuncG: SVGProps<SVGFEFuncGElement>
feFuncR: SVGProps<SVGFEFuncRElement>
feGaussianBlur: SVGProps<SVGFEGaussianBlurElement>
feImage: SVGProps<SVGFEImageElement>
feMerge: SVGProps<SVGFEMergeElement>
feMergeNode: SVGProps<SVGFEMergeNodeElement>
feMorphology: SVGProps<SVGFEMorphologyElement>
feOffset: SVGProps<SVGFEOffsetElement>
fePointLight: SVGProps<SVGFEPointLightElement>
feSpecularLighting: SVGProps<SVGFESpecularLightingElement>
feSpotLight: SVGProps<SVGFESpotLightElement>
feTile: SVGProps<SVGFETileElement>
feTurbulence: SVGProps<SVGFETurbulenceElement>
filter: SVGProps<SVGFilterElement>
foreignObject: SVGProps<SVGForeignObjectElement>
g: SVGProps<SVGGElement>
image: SVGProps<SVGImageElement>
line: SVGProps<SVGLineElement>
linearGradient: SVGProps<SVGLinearGradientElement>
marker: SVGProps<SVGMarkerElement>
mask: SVGProps<SVGMaskElement>
metadata: SVGProps<SVGMetadataElement>
mpath: SVGProps<SVGElement>
path: SVGProps<SVGPathElement>
pattern: SVGProps<SVGPatternElement>
polygon: SVGProps<SVGPolygonElement>
polyline: SVGProps<SVGPolylineElement>
radialGradient: SVGProps<SVGRadialGradientElement>
rect: SVGProps<SVGRectElement>
stop: SVGProps<SVGStopElement>
switch: SVGProps<SVGSwitchElement>
symbol: SVGProps<SVGSymbolElement>
text: SVGProps<SVGTextElement>
textPath: SVGProps<SVGTextPathElement>
tspan: SVGProps<SVGTSpanElement>
use: SVGProps<SVGUseElement>
view: SVGProps<SVGViewElement>
}
export type Element = H.HarmajaOutput
//
// Event System
// ----------------------------------------------------------------------
// TODO: change any to unknown when moving to TS v3
//
// Event System
// ----------------------------------------------------------------------
/**
*
* Harmaja typing for native events. Point is that currentTarget has more specific type than EventTarget.
*
* @typeparam E = native event (this one has better types)
* @typeparam C = current target
* @typeparam T = target
*/
interface HarmajaEvent<C = any, E = Event> {
/**
* Returns the object whose event listener's callback is currently being invoked.
*/
currentTarget: C & EventTarget
/**
* Returns the object to which event is dispatched (its target).
*/
target: EventTarget
bubbles: boolean
/**
* Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method.
*/
cancelable: boolean
/**
* Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.
*/
defaultPrevented: boolean
/**
* Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.
*/
eventPhase: number
/**
* Returns true if event was dispatched by the user agent, and false otherwise.
*/
isTrusted: boolean
/**
* If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled.
*/
preventDefault(): void
/**
* Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects.
*/
stopImmediatePropagation(): void
/**
* When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object.
*/
stopPropagation(): void
/**
* Returns the event's timestamp as the number of milliseconds measured relative to the time origin.
*/
timeStamp: number
/**
* Returns the type of event, e.g. "click", "hashchange", or "submit".
*/
type: string
}
// TODO: verify that these events match native events (no react synthetic stuff)
interface ClipboardEvent<T = Element>
extends HarmajaEvent<T, NativeClipboardEvent> {
clipboardData: DataTransfer
}
interface CompositionEvent<T = Element>
extends HarmajaEvent<T, NativeCompositionEvent> {
data: string
}
interface DragEvent<T = Element>
extends MouseEvent<T, NativeDragEvent> {
dataTransfer: DataTransfer
}
interface PointerEvent<T = Element>
extends MouseEvent<T, NativePointerEvent> {
pointerId: number
pressure: number
tangentialPressure: number
tiltX: number
tiltY: number
twist: number
width: number
height: number
pointerType: "mouse" | "pen" | "touch"
isPrimary: boolean
}
interface FocusEvent<T = Element>
extends HarmajaEvent<T, NativeFocusEvent> {
relatedTarget: EventTarget | null
target: EventTarget & T
}
// tslint:disable-next-line:no-empty-interface
interface FormEvent<T = Element> extends HarmajaEvent<T> {}
interface InvalidEvent<T = Element> extends HarmajaEvent<T> {
target: EventTarget & T
}
interface ChangeEvent<T = Element> extends HarmajaEvent<T> {
target: EventTarget & T
}
interface InputEvent<T = Element> extends HarmajaEvent<T> {
target: EventTarget & T
}
interface KeyboardEvent<T = Element>
extends HarmajaEvent<T, NativeKeyboardEvent> {
altKey: boolean
/** @deprecated */
charCode: number
ctrlKey: boolean
/**
* See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method.
*/
getModifierState(key: string): boolean
/**
* See the [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#named-key-attribute-values). for possible values
*/
key: string
/** @deprecated */
keyCode: number
locale: string
location: number
metaKey: boolean
repeat: boolean
shiftKey: boolean
/** @deprecated */
which: number
}
interface MouseEvent<T = Element, E = NativeMouseEvent>
extends UIEvent<T, E> {
altKey: boolean
button: number
buttons: number
clientX: number
clientY: number
ctrlKey: boolean
/**
* See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method.
*/
getModifierState(key: string): boolean
metaKey: boolean
movementX: number
movementY: number
pageX: number
pageY: number
relatedTarget: EventTarget | null
screenX: number
screenY: number
shiftKey: boolean
}
interface TouchEvent<T = Element> extends UIEvent<T, NativeTouchEvent> {
altKey: boolean
changedTouches: TouchList
ctrlKey: boolean
/**
* See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method.
*/
getModifierState(key: string): boolean
metaKey: boolean
shiftKey: boolean
targetTouches: TouchList
touches: TouchList
}
interface UIEvent<T = Element, E = NativeUIEvent>
extends HarmajaEvent<T, E> {
detail: number
view: AbstractView
}
interface WheelEvent<T = Element>
extends MouseEvent<T, NativeWheelEvent> {
deltaMode: number
deltaX: number
deltaY: number
deltaZ: number
}
interface AnimationEvent<T = Element>
extends HarmajaEvent<T, NativeAnimationEvent> {
animationName: string
elapsedTime: number
pseudoElement: string
}
interface TransitionEvent<T = Element>
extends HarmajaEvent<T, NativeTransitionEvent> {
elapsedTime: number
propertyName: string
pseudoElement: string
}
//
// Event Handler Types
// ----------------------------------------------------------------------
type EventHandler<E extends HarmajaEvent<any>> = {
bivarianceHack(event: E): void
}["bivarianceHack"]
type ClipboardEventHandler<T = Element> = EventHandler<ClipboardEvent>
type CompositionEventHandler<
T = Element
> = EventHandler<CompositionEvent>
type DragEventHandler<T = Element> = EventHandler<DragEvent>
type FocusEventHandler<T = Element> = EventHandler<FocusEvent>
type KeyboardEventHandler<T = Element> = EventHandler<KeyboardEvent>
type MouseEventHandler<T = Element> = EventHandler<MouseEvent>
type TouchEventHandler<T = Element> = EventHandler<TouchEvent>
type PointerEventHandler<T = Element> = EventHandler<PointerEvent>
type UIEventHandler<T = Element> = EventHandler<UIEvent>
type WheelEventHandler<T = Element> = EventHandler<WheelEvent>
type AnimationEventHandler<T = Element> = EventHandler<AnimationEvent>
type TransitionEventHandler<T = Element> = EventHandler<TransitionEvent>
interface HTMLProps<T>
extends AllHTMLAttributes<T>,
ClassAttributes<T> {}
type DetailedHTMLProps<
E extends HTMLAttributes<T>,
T
> = ClassAttributes<T> & WithObservablesInFields<E>
type SVGProps<T> = ClassAttributes<T> &
WithObservablesInFields<SVGAttributes<T>>
interface DOMAttributes<T> {
children?: ChildrenType
// Clipboard Events
onCopy?: ClipboardEventHandler<T>
onCut?: ClipboardEventHandler<T>
onPaste?: ClipboardEventHandler<T>
// Composition Events
onCompositionEnd?: CompositionEventHandler<T>
onCompositionStart?: CompositionEventHandler<T>
onCompositionUpdate?: CompositionEventHandler<T>
// Focus Events
onFocus?: FocusEventHandler<T>
onBlur?: FocusEventHandler<T>
// Form Events
onChange?: EventHandler<ChangeEvent<T>>
onInput?: EventHandler<InputEvent<T>>
onReset?: EventHandler<FormEvent<T>>
onSubmit?: EventHandler<FormEvent<T>>
onInvalid?: EventHandler<FormEvent<T>>
// Image Events
onLoad?: EventHandler<HarmajaEvent<T>>
onError?: EventHandler<HarmajaEvent<T>> // also a Media Event
// Keyboard Events
onKeyDown?: KeyboardEventHandler<T>
onKeyPress?: KeyboardEventHandler<T>
onKeyUp?: KeyboardEventHandler<T>
// Media Events
onAbort?: EventHandler<HarmajaEvent<T>>
onCanPlay?: EventHandler<HarmajaEvent<T>>
onCanPlayThrough?: EventHandler<HarmajaEvent<T>>
onDurationChange?: EventHandler<HarmajaEvent<T>>
onEmptied?: EventHandler<HarmajaEvent<T>>
onEncrypted?: EventHandler<HarmajaEvent<T>>
onEnded?: EventHandler<HarmajaEvent<T>>
onLoadedData?: EventHandler<HarmajaEvent<T>>
onLoadedMetadata?: EventHandler<HarmajaEvent<T>>
onLoadStart?: EventHandler<HarmajaEvent<T>>
onPause?: EventHandler<HarmajaEvent<T>>
onPlay?: EventHandler<HarmajaEvent<T>>
onPlaying?: EventHandler<HarmajaEvent<T>>
onProgress?: EventHandler<HarmajaEvent<T>>
onRateChange?: EventHandler<HarmajaEvent<T>>
onSeeked?: EventHandler<HarmajaEvent<T>>
onSeeking?: EventHandler<HarmajaEvent<T>>
onStalled?: EventHandler<HarmajaEvent<T>>
onSuspend?: EventHandler<HarmajaEvent<T>>
onTimeUpdate?: EventHandler<HarmajaEvent<T>>
onVolumeChange?: EventHandler<HarmajaEvent<T>>
onWaiting?: EventHandler<HarmajaEvent<T>>
// MouseEvents
onAuxClick?: MouseEventHandler<T>
onClick?: MouseEventHandler<T>
onContextMenu?: MouseEventHandler<T>
onDoubleClick?: MouseEventHandler<T>
onDrag?: DragEventHandler<T>
onDragEnd?: DragEventHandler<T>
onDragEnter?: DragEventHandler<T>
onDragExit?: DragEventHandler<T>
onDragLeave?: DragEventHandler<T>
onDragOver?: DragEventHandler<T>
onDragStart?: DragEventHandler<T>
onDrop?: DragEventHandler<T>
onMouseDown?: MouseEventHandler<T>
onMouseEnter?: MouseEventHandler<T>
onMouseLeave?: MouseEventHandler<T>
onMouseMove?: MouseEventHandler<T>
onMouseOut?: MouseEventHandler<T>
onMouseOver?: MouseEventHandler<T>
onMouseUp?: MouseEventHandler<T>
// Selection Events
onSelect?: EventHandler<HarmajaEvent<T>>
// Touch Events
onTouchCancel?: TouchEventHandler<T>
onTouchEnd?: TouchEventHandler<T>
onTouchMove?: TouchEventHandler<T>
onTouchStart?: TouchEventHandler<T>
// Pointer Events
onPointerDown?: PointerEventHandler<T>
onPointerMove?: PointerEventHandler<T>
onPointerUp?: PointerEventHandler<T>
onPointerCancel?: PointerEventHandler<T>
onPointerEnter?: PointerEventHandler<T>
onPointerLeave?: PointerEventHandler<T>
onPointerOver?: PointerEventHandler<T>
onPointerOut?: PointerEventHandler<T>
// UI Events
onScroll?: UIEventHandler<T>
// Wheel Events
onWheel?: WheelEventHandler<T>
// Animation Events
onAnimationStart?: AnimationEventHandler<T>
onAnimationEnd?: AnimationEventHandler<T>
onAnimationIteration?: AnimationEventHandler<T>
// Transition Events
onTransitionEnd?: TransitionEventHandler<T>
}
export interface CSSProperties extends CSS.Properties<string | number> {
/**
* The index signature was removed to enable closed typing for style
* using CSSType. You're able to use type assertion or module augmentation
* to add properties or an index signature of your own.
*
* For examples and more information, visit:
* https://github.com/frenic/csstype#what-should-i-do-when-i-get-type-errors
*/
}
// All the WAI-ARIA 1.1 attributes from https://www.w3.org/TR/wai-aria-1.1/
interface AriaAttributes {
/** Identifies the currently active element when DOM focus is on a composite widget, textbox, group, or application. */
"aria-activedescendant"?: string
/** Indicates whether assistive technologies will present all, or only parts of, the changed region based on the change notifications defined by the aria-relevant attribute. */
"aria-atomic"?: boolean | "false" | "true"
/**
* Indicates whether inputting text could trigger display of one or more predictions of the user's intended value for an input and specifies how predictions would be
* presented if they are made.
*/
"aria-autocomplete"?: "none" | "inline" | "list" | "both"
/** Indicates an element is being modified and that assistive technologies MAY want to wait until the modifications are complete before exposing them to the user. */
"aria-busy"?: boolean | "false" | "true"
/**
* Indicates the current "checked" state of checkboxes, radio buttons, and other widgets.
* @see aria-pressed @see aria-selected.
*/
"aria-checked"?: boolean | "false" | "mixed" | "true"
/**
* Defines the total number of columns in a table, grid, or treegrid.
* @see aria-colindex.
*/
"aria-colcount"?: number
/**
* Defines an element's column index or position with respect to the total number of columns within a table, grid, or treegrid.
* @see aria-colcount @see aria-colspan.
*/
"aria-colindex"?: number
/**
* Defines the number of columns spanned by a cell or gridcell within a table, grid, or treegrid.
* @see aria-colindex @see aria-rowspan.
*/
"aria-colspan"?: number
/**
* Identifies the element (or elements) whose contents or presence are controlled by the current element.
* @see aria-owns.
*/
"aria-controls"?: string
/** Indicates the element that represents the current item within a container or set of related elements. */
"aria-current"?:
| boolean
| "false"
| "true"
| "page"
| "step"
| "location"
| "date"
| "time"
/**
* Identifies the element (or elements) that describes the object.
* @see aria-labelledby
*/
"aria-describedby"?: string
/**
* Identifies the element that provides a detailed, extended description for the object.
* @see aria-describedby.
*/
"aria-details"?: string
/**
* Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable.
* @see aria-hidden @see aria-readonly.
*/
"aria-disabled"?: boolean | "false" | "true"
/**
* Indicates what functions can be performed when a dragged object is released on the drop target.
* @deprecated in ARIA 1.1
*/
"aria-dropeffect"?:
| "none"
| "copy"
| "execute"
| "link"
| "move"
| "popup"
/**
* Identifies the element that provides an error message for the object.
* @see aria-invalid @see aria-describedby.
*/
"aria-errormessage"?: string
/** Indicates whether the element, or another grouping element it controls, is currently expanded or collapsed. */
"aria-expanded"?: boolean | "false" | "true"
/**
* Identifies the next element (or elements) in an alternate reading order of content which, at the user's discretion,
* allows assistive technology to override the general default of reading in document source order.
*/
"aria-flowto"?: string
/**
* Indicates an element's "grabbed" state in a drag-and-drop operation.
* @deprecated in ARIA 1.1
*/
"aria-grabbed"?: boolean | "false" | "true"
/** Indicates the availability and type of interactive popup element, such as menu or dialog, that can be triggered by an element. */
"aria-haspopup"?:
| boolean
| "false"
| "true"
| "menu"
| "listbox"
| "tree"
| "grid"
| "dialog"
/**
* Indicates whether the element is exposed to an accessibility API.
* @see aria-disabled.
*/
"aria-hidden"?: boolean | "false" | "true"
/**
* Indicates the entered value does not conform to the format expected by the application.
* @see aria-errormessage.
*/
"aria-invalid"?: boolean | "false" | "true" | "grammar" | "spelling"
/** Indicates keyboard shortcuts that an author has implemented to activate or give focus to an element. */
"aria-keyshortcuts"?: string
/**
* Defines a string value that labels the current element.
* @see aria-labelledby.
*/
"aria-label"?: string
/**
* Identifies the element (or elements) that labels the current element.
* @see aria-describedby.
*/
"aria-labelledby"?: string
/** Defines the hierarchical level of an element within a structure. */
"aria-level"?: number
/** Indicates that an element will be updated, and describes the types of updates the user agents, assistive technologies, and user can expect from the live region. */
"aria-live"?: "off" | "assertive" | "polite"
/** Indicates whether an element is modal when displayed. */
"aria-modal"?: boolean | "false" | "true"
/** Indicates whether a text box accepts multiple lines of input or only a single line. */
"aria-multiline"?: boolean | "false" | "true"
/** Indicates that the user may select more than one item from the current selectable descendants. */
"aria-multiselectable"?: boolean | "false" | "true"
/** Indicates whether the element's orientation is horizontal, vertical, or unknown/ambiguous. */
"aria-orientation"?: "horizontal" | "vertical"
/**
* Identifies an element (or elements) in order to define a visual, functional, or contextual parent/child relationship
* between DOM elements where the DOM hierarchy cannot be used to represent the relationship.
* @see aria-controls.
*/
"aria-owns"?: string
/**
* Defines a short hint (a word or short phrase) intended to aid the user with data entry when the control has no value.
* A hint could be a sample value or a brief description of the expected format.
*/
"aria-placeholder"?: string
/**
* Defines an element's number or position in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM.
* @see aria-setsize.
*/
"aria-posinset"?: number
/**
* Indicates the current "pressed" state of toggle buttons.
* @see aria-checked @see aria-selected.
*/
"aria-pressed"?: boolean | "false" | "mixed" | "true"
/**
* Indicates that the element is not editable, but is otherwise operable.
* @see aria-disabled.
*/
"aria-readonly"?: boolean | "false" | "true"
/**
* Indicates what notifications the user agent will trigger when the accessibility tree within a live region is modified.
* @see aria-atomic.
*/
"aria-relevant"?:
| "additions"
| "additions text"
| "all"
| "removals"
| "text"
/** Indicates that user input is required on the element before a form may be submitted. */
"aria-required"?: boolean | "false" | "true"
/** Defines a human-readable, author-localized description for the role of an element. */
"aria-roledescription"?: string
/**
* Defines the total number of rows in a table, grid, or treegrid.
* @see aria-rowindex.
*/
"aria-rowcount"?: number
/**
* Defines an element's row index or position with respect to the total number of rows within a table, grid, or treegrid.
* @see aria-rowcount @see aria-rowspan.
*/
"aria-rowindex"?: number
/**
* Defines the number of rows spanned by a cell or gridcell within a table, grid, or treegrid.
* @see aria-rowindex @see aria-colspan.
*/
"aria-rowspan"?: number
/**
* Indicates the current "selected" state of various widgets.
* @see aria-checked @see aria-pressed.
*/
"aria-selected"?: boolean | "false" | "true"
/**
* Defines the number of items in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM.
* @see aria-posinset.
*/
"aria-setsize"?: number
/** Indicates if items in a table or grid are sorted in ascending or descending order. */
"aria-sort"?: "none" | "ascending" | "descending" | "other"
/** Defines the maximum allowed value for a range widget. */
"aria-valuemax"?: number
/** Defines the minimum allowed value for a range widget. */
"aria-valuemin"?: number
/**
* Defines the current value for a range widget.
* @see aria-valuetext.
*/
"aria-valuenow"?: number
/** Defines the human readable text alternative of aria-valuenow for a range widget. */
"aria-valuetext"?: string
}
interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> {
// Standard HTML Attributes
accessKey?: string
className?: string
contentEditable?: Booleanish | "inherit"
contextMenu?: string
dir?: string
draggable?: Booleanish
hidden?: boolean
id?: string
lang?: string
placeholder?: string
slot?: string
spellCheck?: Booleanish
style?: CSSProperties
tabIndex?: number
title?: string
translate?: "yes" | "no"
// Unknown
radioGroup?: string // <command>, <menuitem>
// WAI-ARIA
role?: string
// RDFa Attributes
about?: string
datatype?: string
inlist?: any
prefix?: string
property?: string
resource?: string
typeof?: string
vocab?: string
// Non-standard Attributes
autoCapitalize?: string
autoCorrect?: string
autoSave?: string
color?: string
itemProp?: string
itemScope?: boolean
itemType?: string
itemID?: string
itemRef?: string
results?: number
security?: string
unselectable?: "on" | "off"
// Living Standard
/**
* Hints at the type of data that might be entered by the user while editing the element or its contents
* @see https://html.spec.whatwg.org/multipage/interaction.html#input-modalities:-the-inputmode-attribute
*/
inputMode?:
| "none"
| "text"
| "tel"
| "url"
| "email"
| "numeric"
| "decimal"
| "search"
/**
* Specify that a standard HTML element should behave like a defined custom built-in element
* @see https://html.spec.whatwg.org/multipage/custom-elements.html#attr-is
*/
is?: string
}
interface AllHTMLAttributes<T> extends HTMLAttributes<T> {
// Standard HTML Attributes
accept?: string
acceptCharset?: string
action?: string
allowFullScreen?: boolean
allowTransparency?: boolean
alt?: string
as?: string
async?: boolean
autoComplete?: string
autoFocus?: boolean
autoPlay?: boolean
capture?: boolean | string
cellPadding?: number | string
cellSpacing?: number | string
charSet?: string
challenge?: string
checked?: boolean
cite?: string
classID?: string
cols?: number
colSpan?: number
content?: string
controls?: boolean
coords?: string
crossOrigin?: string
data?: string
dateTime?: string
default?: boolean
defer?: boolean
disabled?: boolean
download?: any
encType?: string
form?: string
formAction?: string
formEncType?: string
formMethod?: string
formNoValidate?: boolean
formTarget?: string
frameBorder?: number | string
headers?: string
height?: number | string
high?: number
href?: string
hrefLang?: string
htmlFor?: string
httpEquiv?: string
integrity?: string
keyParams?: string
keyType?: string
kind?: string
label?: string
list?: string
loop?: boolean
low?: number
manifest?: string
marginHeight?: number
marginWidth?: number
max?: number | string
maxLength?: number
media?: string
mediaGroup?: string
method?: string
min?: number | string
minLength?: number
multiple?: boolean
muted?: boolean
name?: string
nonce?: string
noValidate?: boolean
open?: boolean
optimum?: number
pattern?: string
placeholder?: string
playsInline?: boolean
poster?: string
preload?: string
readOnly?: boolean
rel?: string
required?: boolean
reversed?: boolean
rows?: number
rowSpan?: number
sandbox?: string
scope?: string
scoped?: boolean
scrolling?: string
seamless?: boolean
selected?: boolean
shape?: string
size?: number
sizes?: string
span?: number
src?: string
srcDoc?: string
srcLang?: string
srcSet?: string
start?: number
step?: number | string
summary?: string
target?: string
type?: string
useMap?: string
value?: string | ReadonlyArray<string> | number
width?: number | string
wmode?: string
wrap?: string
}
interface AnchorHTMLAttributes<T> extends HTMLAttributes<T> {
download?: any
href?: string
hrefLang?: string
media?: string
ping?: string
rel?: string
target?: string
type?: string
referrerPolicy?: string
}
// tslint:disable-next-line:no-empty-interface
interface AudioHTMLAttributes<T> extends MediaHTMLAttributes<T> {}
interface AreaHTMLAttributes<T> extends HTMLAttributes<T> {
alt?: string
coords?: string
download?: any
href?: string
hrefLang?: string
media?: string
rel?: string
shape?: string
target?: string
}
interface BaseHTMLAttributes<T> extends HTMLAttributes<T> {
href?: string
target?: string
}
interface BlockquoteHTMLAttributes<T> extends HTMLAttributes<T> {
cite?: string
}
interface ButtonHTMLAttributes<T> extends HTMLAttributes<T> {
autoFocus?: boolean
disabled?: boolean
form?: string
formAction?: string
formEncType?: string
formMethod?: string
formNoValidate?: boolean
formTarget?: string
name?: string
type?: "submit" | "reset" | "button"
value?: string | ReadonlyArray<string> | number
}
interface CanvasHTMLAttributes<T> extends HTMLAttributes<T> {
height?: number | string
width?: number | string
}
interface ColHTMLAttributes<T> extends HTMLAttributes<T> {
span?: number
width?: number | string
}
interface ColgroupHTMLAttributes<T> extends HTMLAttributes<T> {
span?: number
}
interface DataHTMLAttributes<T> extends HTMLAttributes<T> {
value?: string | ReadonlyArray<string> | number
}
interface DetailsHTMLAttributes<T> extends HTMLAttributes<T> {
open?: boolean
onToggle?: EventHandler<HarmajaEvent<T>>
}
interface DelHTMLAttributes<T> extends HTMLAttributes<T> {
cite?: string
dateTime?: string
}
interface DialogHTMLAttributes<T> extends HTMLAttributes<T> {
open?: boolean
}
interface EmbedHTMLAttributes<T> extends HTMLAttributes<T> {
height?: number | string
src?: string
type?: string
width?: number | string
}
interface FieldsetHTMLAttributes<T> extends HTMLAttributes<T> {
disabled?: boolean
form?: string
name?: string
}
interface FormHTMLAttributes<T> extends HTMLAttributes<T> {
acceptCharset?: string
action?: string
autoComplete?: string
encType?: string
method?: string
name?: string
noValidate?: boolean
target?: string
}
interface HtmlHTMLAttributes<T> extends HTMLAttributes<T> {
manifest?: string
}
interface IframeHTMLAttributes<T> extends HTMLAttributes<T> {
allow?: string
allowFullScreen?: boolean
allowTransparency?: boolean
frameBorder?: number | string
height?: number | string
loading?: "eager" | "lazy"
marginHeight?: number
marginWidth?: number
name?: string
referrerPolicy?: string
sandbox?: string
scrolling?: string
seamless?: boolean
src?: string
srcDoc?: string
width?: number | string
}
interface ImgHTMLAttributes<T> extends HTMLAttributes<T> {
alt?: string
crossOrigin?: "anonymous" | "use-credentials" | ""
decoding?: "async" | "auto" | "sync"
height?: number | string
loading?: "eager" | "lazy"
referrerPolicy?: "no-referrer" | "origin" | "unsafe-url"
sizes?: string
src?: string
srcSet?: string
useMap?: string
width?: number | string
}
interface InsHTMLAttributes<T> extends HTMLAttributes<T> {
cite?: string
dateTime?: string
}
interface InputHTMLAttributes<T> extends HTMLAttributes<T> {
accept?: string
alt?: string
autoComplete?: string
autoFocus?: boolean
capture?: boolean | string // https://www.w3.org/TR/html-media-capture/#the-capture-attribute
checked?: boolean
crossOrigin?: string
disabled?: boolean
form?: string
formAction?: string
formEncType?: string
formMethod?: string
formNoValidate?: boolean
formTarget?: string
height?: number | string
list?: string
max?: number | string
maxLength?: number
min?: number | string
minLength?: number
multiple?: boolean
name?: string
pattern?: string
placeholder?: string
readOnly?: boolean
required?: boolean
size?: number
src?: string
step?: number | string
type?: string
value?: string | ReadonlyArray<string> | number
width?: number | string
}
interface KeygenHTMLAttributes<T> extends HTMLAttributes<T> {
autoFocus?: boolean
challenge?: string
disabled?: boolean
form?: string
keyType?: string
keyParams?: string
name?: string
}
interface LabelHTMLAttributes<T> extends HTMLAttributes<T> {
form?: string
htmlFor?: string
}
interface LiHTMLAttributes<T> extends HTMLAttributes<T> {
value?: string | ReadonlyArray<string> | number
}
interface LinkHTMLAttributes<T> extends HTMLAttributes<T> {
as?: string
crossOrigin?: string
href?: string
hrefLang?: string
integrity?: string
media?: string
rel?: string
sizes?: string
type?: string
charSet?: string
}
interface MapHTMLAttributes<T> extends HTMLAttributes<T> {
name?: string
}
interface MenuHTMLAttributes<T> extends HTMLAttributes<T> {
type?: string
}
interface MediaHTMLAttributes<T> extends HTMLAttributes<T> {
autoPlay?: boolean
controls?: boolean
controlsList?: string
crossOrigin?: string
loop?: boolean
mediaGroup?: string
muted?: boolean
playsInline?: boolean
preload?: string
src?: string
}
interface MetaHTMLAttributes<T> extends HTMLAttributes<T> {
charSet?: string
content?: string
httpEquiv?: string
name?: string
}
interface MeterHTMLAttributes<T> extends HTMLAttributes<T> {
form?: string
high?: number
low?: number
max?: number | string
min?: number | string
optimum?: number
value?: string | ReadonlyArray<string> | number
}
interface QuoteHTMLAttributes<T> extends HTMLAttributes<T> {
cite?: string
}
interface ObjectHTMLAttributes<T> extends HTMLAttributes<T> {
classID?: string
data?: string
form?: string
height?: number | string
name?: string
type?: string
useMap?: string
width?: number | string
wmode?: string
}
interface OlHTMLAttributes<T> extends HTMLAttributes<T> {
reversed?: boolean
start?: number
type?: "1" | "a" | "A" | "i" | "I"
}
interface OptgroupHTMLAttributes<T> extends HTMLAttributes<T> {
disabled?: boolean
label?: string
}
interface OptionHTMLAttributes<T> extends HTMLAttributes<T> {
disabled?: boolean
label?: string
selected?: boolean
value?: string | ReadonlyArray<string> | number
}
interface OutputHTMLAttributes<T> extends HTMLAttributes<T> {
form?: string
htmlFor?: string
name?: string
}
interface ParamHTMLAttributes<T> extends HTMLAttributes<T> {
name?: string
value?: string | ReadonlyArray<string> | number
}
interface ProgressHTMLAttributes<T> extends HTMLAttributes<T> {
max?: number | string
value?: string | ReadonlyArray<string> | number
}
interface SlotHTMLAttributes<T> extends HTMLAttributes<T> {
name?: string
}
interface ScriptHTMLAttributes<T> extends HTMLAttributes<T> {
async?: boolean
charSet?: string
crossOrigin?: string
defer?: boolean
integrity?: string
noModule?: boolean
nonce?: string
src?: string
type?: string
}
interface SelectHTMLAttributes<T> extends HTMLAttributes<T> {
autoComplete?: string
autoFocus?: boolean
disabled?: boolean
form?: string
multiple?: boolean
name?: string
required?: boolean
size?: number
value?: string | ReadonlyArray<string> | number
}
interface SourceHTMLAttributes<T> extends HTMLAttributes<T> {
media?: string
sizes?: string
src?: string
srcSet?: string
type?: string
}
interface StyleHTMLAttributes<T> extends HTMLAttributes<T> {
media?: string
nonce?: string
scoped?: boolean
type?: string
}
interface TableHTMLAttributes<T> extends HTMLAttributes<T> {
cellPadding?: number | string
cellSpacing?: number | string
summary?: string
width?: number | string
}
interface TextareaHTMLAttributes<T> extends HTMLAttributes<T> {
autoComplete?: string
autoFocus?: boolean
cols?: number
dirName?: string
disabled?: boolean
form?: string
maxLength?: number
minLength?: number
name?: string
placeholder?: string
readOnly?: boolean
required?: boolean
rows?: number
value?: string | ReadonlyArray<string> | number
wrap?: string
}
interface TdHTMLAttributes<T> extends HTMLAttributes<T> {
align?: "left" | "center" | "right" | "justify" | "char"
colSpan?: number
headers?: string
rowSpan?: number
scope?: string
abbr?: string
height?: number | string
width?: number | string
valign?: "top" | "middle" | "bottom" | "baseline"
}
interface ThHTMLAttributes<T> extends HTMLAttributes<T> {
align?: "left" | "center" | "right" | "justify" | "char"
colSpan?: number
headers?: string
rowSpan?: number
scope?: string
abbr?: string
}
interface TimeHTMLAttributes<T> extends HTMLAttributes<T> {
dateTime?: string
}
interface TrackHTMLAttributes<T> extends HTMLAttributes<T> {
default?: boolean
kind?: string
label?: string
src?: string
srcLang?: string
}
interface VideoHTMLAttributes<T> extends MediaHTMLAttributes<T> {
height?: number | string
playsInline?: boolean
poster?: string
width?: number | string
disablePictureInPicture?: boolean
}
// this list is "complete" in that it contains every SVG attribute
// that React supports, but the types can be improved.
// Full list here: https://facebook.github.io/react/docs/dom-elements.html
//
// The three broad type categories are (in order of restrictiveness):
// - "number | string"
// - "string"
// - union of string literals
interface SVGAttributes<T> extends AriaAttributes, DOMAttributes<T> {
// Attributes which also defined in HTMLAttributes
// See comment in SVGDOMPropertyConfig.js
className?: string
color?: string
height?: number | string
id?: string
lang?: string
max?: number | string
media?: string
method?: string
min?: number | string
name?: string
style?: CSSProperties
target?: string
type?: string
width?: number | string
// Other HTML properties supported by SVG elements in browsers
role?: string
tabIndex?: number
crossOrigin?: "anonymous" | "use-credentials" | ""
// SVG Specific attributes
accentHeight?: number | string
accumulate?: "none" | "sum"
additive?: "replace" | "sum"
alignmentBaseline?:
| "auto"
| "baseline"
| "before-edge"
| "text-before-edge"
| "middle"
| "central"
| "after-edge"
| "text-after-edge"
| "ideographic"
| "alphabetic"
| "hanging"
| "mathematical"
| "inherit"
allowReorder?: "no" | "yes"
alphabetic?: number | string
amplitude?: number | string
arabicForm?: "initial" | "medial" | "terminal" | "isolated"
ascent?: number | string
attributeName?: string
attributeType?: string
autoReverse?: Booleanish
azimuth?: number | string
baseFrequency?: number | string
baselineShift?: number | string
baseProfile?: number | string
bbox?: number | string
begin?: number | string
bias?: number | string
by?: number | string
calcMode?: number | string
capHeight?: number | string
clip?: number | string
clipPath?: string
clipPathUnits?: number | string
clipRule?: number | string
colorInterpolation?: number | string
colorInterpolationFilters?:
| "auto"
| "sRGB"
| "linearRGB"
| "inherit"
colorProfile?: number | string
colorRendering?: number | string
contentScriptType?: number | string
contentStyleType?: number | string
cursor?: number | string
cx?: number | string
cy?: number | string
d?: string
decelerate?: number | string
descent?: number | string
diffuseConstant?: number | string
direction?: number | string
display?: number | string
divisor?: number | string
dominantBaseline?: number | string
dur?: number | string
dx?: number | string
dy?: number | string
edgeMode?: number | string
elevation?: number | string
enableBackground?: number | string
end?: number | string
exponent?: number | string
externalResourcesRequired?: Booleanish
fill?: string
fillOpacity?: number | string
fillRule?: "nonzero" | "evenodd" | "inherit"
filter?: string
filterRes?: number | string
filterUnits?: number | string
floodColor?: number | string
floodOpacity?: number | string
focusable?: Booleanish | "auto"
fontFamily?: string
fontSize?: number | string
fontSizeAdjust?: number | string
fontStretch?: number | string
fontStyle?: number | string
fontVariant?: number | string
fontWeight?: number | string
format?: number | string
from?: number | string
fx?: number | string
fy?: number | string
g1?: number | string
g2?: number | string
glyphName?: number | string
glyphOrientationHorizontal?: number | string
glyphOrientationVertical?: number | string
glyphRef?: number | string
gradientTransform?: string
gradientUnits?: string
hanging?: number | string
horizAdvX?: number | string
horizOriginX?: number | string
href?: string
ideographic?: number | string
imageRendering?: number | string
in2?: number | string
in?: string
intercept?: number | string
k1?: number | string
k2?: number | string
k3?: number | string
k4?: number | string
k?: number | string
kernelMatrix?: number | string
kernelUnitLength?: number | string
kerning?: number | string
keyPoints?: number | string
keySplines?: number | string
keyTimes?: number | string
lengthAdjust?: number | string
letterSpacing?: number | string
lightingColor?: number | string
limitingConeAngle?: number | string
local?: number | string
markerEnd?: string
markerHeight?: number | string
markerMid?: string
markerStart?: string
markerUnits?: number | string
markerWidth?: number | string
mask?: string
maskContentUnits?: number | string
maskUnits?: number | string
mathematical?: number | string
mode?: number | string
numOctaves?: number | string
offset?: number | string
opacity?: number | string
operator?: number | string
order?: number | string
orient?: number | string
orientation?: number | string
origin?: number | string
overflow?: number | string
overlinePosition?: number | string
overlineThickness?: number | string
paintOrder?: number | string
panose1?: number | string
path?: string
pathLength?: number | string
patternContentUnits?: string
patternTransform?: number | string
patternUnits?: string
pointerEvents?: number | string
points?: string
pointsAtX?: number | string
pointsAtY?: number | string
pointsAtZ?: number | string
preserveAlpha?: Booleanish
preserveAspectRatio?: string
primitiveUnits?: number | string
r?: number | string
radius?: number | string
refX?: number | string
refY?: number | string
renderingIntent?: number | string
repeatCount?: number | string
repeatDur?: number | string
requiredExtensions?: number | string
requiredFeatures?: number | string
restart?: number | string
result?: string
rotate?: number | string
rx?: number | string
ry?: number | string
scale?: number | string
seed?: number | string
shapeRendering?: number | string
slope?: number | string
spacing?: number | string
specularConstant?: number | string
specularExponent?: number | string
speed?: number | string
spreadMethod?: string
startOffset?: number | string
stdDeviation?: number | string
stemh?: number | string
stemv?: number | string
stitchTiles?: number | string
stopColor?: string
stopOpacity?: number | string
strikethroughPosition?: number | string
strikethroughThickness?: number | string
string?: number | string
stroke?: string
strokeDasharray?: string | number
strokeDashoffset?: string | number
strokeLinecap?: "butt" | "round" | "square" | "inherit"
strokeLinejoin?: "miter" | "round" | "bevel" | "inherit"
strokeMiterlimit?: number | string
strokeOpacity?: number | string
strokeWidth?: number | string
surfaceScale?: number | string
systemLanguage?: number | string
tableValues?: number | string
targetX?: number | string
targetY?: number | string
textAnchor?: string
textDecoration?: number | string
textLength?: number | string
textRendering?: number | string
to?: number | string
transform?: string
u1?: number | string
u2?: number | string
underlinePosition?: number | string
underlineThickness?: number | string
unicode?: number | string
unicodeBidi?: number | string
unicodeRange?: number | string
unitsPerEm?: number | string
vAlphabetic?: number | string
values?: string
vectorEffect?: number | string
version?: string
vertAdvY?: number | string
vertOriginX?: number | string
vertOriginY?: number | string
vHanging?: number | string
vIdeographic?: number | string
viewBox?: string
viewTarget?: number | string
visibility?: number | string
vMathematical?: number | string
widths?: number | string
wordSpacing?: number | string
writingMode?: number | string
x1?: number | string
x2?: number | string
x?: number | string
xChannelSelector?: string
xHeight?: number | string
xlinkActuate?: string
xlinkArcrole?: string
xlinkHref?: string
xlinkRole?: string
xlinkShow?: string
xlinkTitle?: string
xlinkType?: string
xmlBase?: string
xmlLang?: string
xmlns?: string
xmlnsXlink?: string
xmlSpace?: string
y1?: number | string
y2?: number | string
y?: number | string
yChannelSelector?: string
z?: number | string
zoomAndPan?: string
}
interface AbstractView {
styleMedia: StyleMedia
document: Document
}
type RefCallback<T> = {
bivarianceHack(instance: T): void
}["bivarianceHack"]
type Ref<T> = B.NativeAtom<T | null> | RefCallback<T> | null
interface Attributes {}
interface ClassAttributes<T> extends Attributes {
ref?: Ref<T>
}
}
} | the_stack |
declare namespace Sfdc {
function canvas(callback: () => void): void;
namespace canvas {
// see https://developer.salesforce.com/docs/atlas.en-us.platform_connect.meta/platform_connect/client_object.htm
interface Client {
readonly oauthToken?: string | null | undefined;
readonly instanceId?: string | null | undefined;
readonly instanceUrl?: string | null | undefined;
readonly targetOrigin?: string | null | undefined;
readonly refreshToken?: string | null | undefined;
}
interface Response<T> {
readonly seq: number;
readonly parentVersion: string;
readonly clientVersion: string;
readonly payload: T;
readonly status: number;
readonly statusText: string;
readonly responseHeaders: string;
readonly type: string;
readonly targetModule: string;
}
enum ApplicationOptions {
HIDE_HEADER = 'HideHeader',
HIDE_SHARE = 'HideShare',
PERSONAL_ENABLED = 'PersonalEnabled',
}
enum ApplicationAuthType {
SIGNED_REQUEST = 'SIGNED_REQUEST',
OAUTH = 'OAUTH',
}
// see https://developer.salesforce.com/docs/atlas.en-us.platform_connect.meta/platform_connect/application_object.htm;
interface Application {
readonly applicationId: string;
readonly authType: ApplicationAuthType;
readonly canvasUrl: string;
readonly developerName: string;
readonly isInstalledPersonalApp: boolean;
readonly name: string;
readonly namespace: string;
readonly options: ApplicationOptions[];
readonly referenceId: string;
readonly samlInitiationMethod: string;
readonly version: string;
}
enum UserType {
STANDARD = 'STANDARD',
}
// see https://developer.salesforce.com/docs/atlas.en-us.platform_connect.meta/platform_connect/user_object.htm
interface User {
readonly accessibilityModeEnabled: boolean;
readonly currencyISOCode: string;
readonly email: string;
readonly firstName: string;
readonly fullName: string;
readonly isDefaultNetwork: boolean;
readonly language: string;
readonly lastName: string;
readonly locale: string;
readonly networkId: string;
readonly profileId: string;
readonly profilePhotoUrl: string;
readonly profileThumbnailUrl: string;
readonly roleId: string | null;
readonly siteUrl: string;
readonly siteUrlPrefix: string;
readonly timeZone: string;
readonly userId: string;
readonly userName: string;
readonly userType: UserType;
}
// see https://developer.salesforce.com/docs/atlas.en-us.platform_connect.meta/platform_connect/dimensions_object.htm
interface EnvironmentDimensions {
readonly clientHeight: string;
readonly clientWidth: string;
readonly height: string;
readonly width: string;
readonly maxHeight: string;
readonly maxWidth: string;
}
// see https://developer.salesforce.com/docs/atlas.en-us.platform_connect.meta/platform_connect/version_object.htm
interface EnvironmentVersion {
readonly api: string;
readonly season: string;
}
enum EnvironmentDisplayLocation {
CHATTER = 'Chatter',
CHATTER_FEED = 'ChatterFeed',
MOBILE_NAV = 'MobileNav',
OPEN_CTI = 'OpenCTI',
PAGE_LAYOUT = 'PageLayout',
PUBLISHER = 'Publisher',
SERVICE_DESK = 'ServiceDesk',
VISUAL_FORCE = 'Visualforce',
NONE = 'None',
}
enum EnvironmentDisplaySubLocation {
MOBILE_CARD_FULLVIEW = 'S1MobileCardFullview',
MOBILE_CARD_PREVIEW = 'S1MobileCardPreview',
RECORD_HOME_PREVIEW = 'S1RecordHomePreview',
RECORD_HOME_FULLVIEW = 'S1RecordHomeFullview',
}
// see https://developer.salesforce.com/docs/atlas.en-us.platform_connect.meta/platform_connect/attributes_object.htm
interface EnvironmentRecordAttributes {
readonly type: string;
readonly url: string;
}
// see https://developer.salesforce.com/docs/atlas.en-us.platform_connect.meta/platform_connect/record_object.htm
interface EnvironmentRecord {
readonly attributes: EnvironmentRecordAttributes;
readonly Id: string;
[key: string]: unknown;
}
// see https://developer.salesforce.com/docs/atlas.en-us.platform_connect.meta/platform_connect/environment_object.htm
interface Environment {
readonly parameters: Record<string, unknown>;
readonly dimensions: EnvironmentDimensions;
readonly record?: EnvironmentRecord | undefined;
readonly displayLocation: EnvironmentDisplayLocation;
readonly locationUrl: string;
readonly subLocation: EnvironmentDisplaySubLocation | null;
readonly uiTheme: string;
readonly version: EnvironmentVersion;
}
// see https://developer.salesforce.com/docs/atlas.en-us.platform_connect.meta/platform_connect/organization_object.htm
interface Organization {
readonly currencyIsoCode: string;
readonly multicurrencyEnabled: boolean;
readonly name: string;
readonly namespacePrefix: string;
readonly organizationId: string;
}
// see https://developer.salesforce.com/docs/atlas.en-us.platform_connect.meta/platform_connect/links_object.htm
interface Links {
readonly chatterFeedItemsUrl: string;
readonly chatterFeedsUrl: string;
readonly chatterGroupsUrl: string;
readonly chatterUsersUrl: string;
readonly enterpriseUrl: string;
readonly loginUrl: string;
readonly metadataUrl: string;
readonly partnerUrl: string;
readonly queryUrl: string;
readonly restUrl: string;
readonly recentItemsUrl: string;
readonly searchUrl: string;
readonly sobjectUrl: string;
readonly userUrl: string;
}
// see https://developer.salesforce.com/docs/atlas.en-us.platform_connect.meta/platform_connect/context_object.htm
interface Context {
readonly application?: Application | undefined;
readonly user?: User | undefined;
readonly environment: Environment;
readonly organization?: Organization | undefined;
readonly links: Links;
}
// see https://developer.salesforce.com/docs/atlas.en-us.platform_connect.meta/platform_connect/canvas_request_object.htm
interface SignedRequest {
readonly context: Context;
readonly client: Client;
readonly algorithm: string;
readonly userId: string;
readonly issuedAt: string | null;
}
function hasOwn(obj: {}, prop: string): boolean;
function isUndefined(value: unknown): value is undefined;
function isNil(value: unknown): value is undefined | null | '';
function isNumber(value: unknown): value is number;
function isFunction(value: unknown): value is () => void;
function isArray(value: unknown): value is ArrayLike<unknown>;
function isArguments(value: unknown): boolean;
function isObject(value: unknown): value is {};
function isString(value: unknown): value is string;
function appearsJson(value: string): boolean;
function nop(): void;
function invoker(fn: () => void): void;
function identity<T>(obj: T): T;
function each<T, S = T[]>(obj: T[], it: (this: S, item: T, index: number, obj: T[]) => void, ctx?: S): void;
function each<T, S = T>(
obj: Record<string, T>,
it: (this: S, item: T, key: string, obj: Record<string, T>) => void,
ctx?: S,
): void;
function startsWithHttp(orig: string, newUrl: string): string;
function map<T, R, S = T[]>(obj: T[], it: (this: S, item: T, index: number, obj: T[]) => R, ctx?: S): R[];
function map<T, R, S = T>(
obj: Record<string, T>,
it: (this: S, item: T, key: string, obj: Record<string, T>) => R,
ctx?: S,
): R[];
function values<T>(obj: ArrayLike<T> | Record<string, T>): T[];
function slice<T>(arr: T[], begin?: number, end?: number): T[];
function toArray(iterable: null | undefined): [];
function toArray<T>(iterable: ArrayLike<T> | Record<string, T>): T[];
function size(obj: ArrayLike<unknown> | Record<string, unknown> | null | undefined): number;
function indexOf<T>(arr: ArrayLike<T>, item: T): number;
function isEmpty(obj: unknown): boolean;
function remove<T>(arr: ArrayLike<T>, item: T): T[];
function param(obj: ArrayLike<unknown> | Record<string, unknown>, encode?: boolean): string;
function objectify(q: string): Record<string, string>;
function stripUrl(url: string): string;
function query(url: string, q: string): string;
function extend<A extends Record<string, unknown>, B extends Record<string, unknown>>(a: A, b: B): A & B;
function extend<
A extends Record<string, unknown>,
B extends Record<string, unknown>,
C extends Record<string, unknown>,
>(a: A, b: B, c: C): A & B & C;
function extend<
A extends Record<string, unknown>,
B extends Record<string, unknown>,
C extends Record<string, unknown>,
D extends Record<string, unknown>,
>(a: A, b: B, c: C, d: D): A & B & C & D;
function extend<
A extends Record<string, unknown>,
B extends Record<string, unknown>,
C extends Record<string, unknown>,
D extends Record<string, unknown>,
E extends Record<string, unknown>,
>(a: A, b: B, c: C, d: D, e: E): A & B & C & D & E;
function endsWith(str: string, suffix: string): boolean;
function capitalize(str: string): string;
function uncapitalize(str: string): string;
function decode(str: string): string;
function escapeToUTF8(str: string): string;
function validEventName(name: string, res: string | string[]): number;
function prototypeOf(obj: unknown): object | null;
function module(ns: string, decl: Record<string, unknown>): typeof canvas;
function document(): Document;
function byId(id: string): HTMLElement;
function byClass(clazz: string): HTMLElement;
function attr(el: HTMLElement, name: string): string;
function onReady(callback: () => void): void;
namespace client {
interface AjaxSettings {
readonly client: Client;
readonly success: (data: Response<unknown>) => void;
readonly method?: string | undefined;
readonly async?: boolean | undefined;
readonly contentType?: string | undefined;
readonly headers?: Record<string, string> | undefined;
readonly data?: string | null | undefined;
}
interface Version {
readonly clientVersion: string;
readonly parentVersion: string;
}
interface SizeHeights {
readonly contentHeight: number;
readonly pageHeight: number;
readonly scrollTop: number;
}
interface SizeWidths {
readonly contentWidth: number;
readonly pageWidth: number;
readonly scrollLeft: number;
}
interface Size {
readonly heights: SizeHeights;
readonly widths: SizeWidths;
}
interface EventSubscriptionRef {
readonly name: string;
}
interface EventSubscription extends EventSubscriptionRef {
readonly onData: (event: unknown) => void;
}
interface StreamSubscriptionParams {
readonly topic: string;
}
interface StreamSubscriptionRef {
readonly name: 'sfdc.streamingapi';
readonly params: StreamSubscriptionParams;
}
interface StreamSubscription extends StreamSubscriptionRef {
readonly onData: (event: unknown) => void;
readonly onComplete: (event: unknown) => void;
}
type Subscription = EventSubscription | StreamSubscription;
type SubscriptionRef = string | EventSubscriptionRef | StreamSubscriptionRef;
interface Event {
readonly name: string;
readonly payload: unknown;
}
function ctx(callback: (msg: Response<Context | string>) => void, client: Client): void;
function ajax(url: string, settings: AjaxSettings): void;
function token(t?: string | null): string | null;
function version(): Version;
function resize(client: Client, size?: { height: string; width: string }): void;
function size(): Size;
function autogrow(client: Client, enabled?: boolean, interval?: number): void;
function subscribe(client: Client, subscriptions: Subscription | Subscription[]): void;
function unsubscribe(client: Client, subscriptions: SubscriptionRef | SubscriptionRef[]): void;
function publish(client: Client, event: Event): void;
function signedrequest(req?: SignedRequest): SignedRequest;
function refreshSignedRequest(cb: (data: Response<{ response: string }>) => void): void;
function repost(refresh?: boolean): void;
}
namespace console {
function enable(): void;
function disable(): void;
function log(...args: unknown[]): void;
function error(...args: unknown[]): void;
}
namespace cookies {
function set(name: string, value: string, days?: number): void;
function get(name: string): string;
function remove(name: string): void;
}
namespace oauth {
interface LoginParams {
readonly response_type: string;
readonly client_id: string;
readonly redirect_uri: string;
readonly state?: string | undefined;
readonly display?: string | undefined;
readonly scope?: string | undefined;
}
interface LoginContext {
readonly uri: string;
readonly params: LoginParams;
readonly callback?: string | undefined;
}
function init(): void;
function login(ctx: LoginContext): void;
function logout(): void;
function loggedin(): boolean;
function loginUrl(): string;
function token(t?: string | null): string | null;
function instance(t?: string | null): string | null;
function client(): Client;
/** @deprecated */
function checkChildWindowStatus(): void;
function childWindowUnloadNotification(hash: string): void;
}
namespace xd {
type Callback = (data: unknown) => void;
type OriginCheckFn = (origin: string, data: string) => boolean;
function post(message: string, targetUrl: string, target?: Window): void;
function receive(callback: Callback, sourceOrigin?: string | OriginCheckFn): void;
function remove(): void;
}
}
} | the_stack |
import fastDeepEqual from 'fast-deep-equal'
import {
AllFramePoints,
Frame,
FramePin,
FramePoint,
HorizontalFramePoints,
isHorizontalPoint,
isPercentPin,
valueToUseForPin,
VerticalFramePoints,
} from 'utopia-api'
import { getLayoutProperty } from '../../../core/layout/getLayoutProperty'
import {
createLayoutPropertyPath,
framePointForPinnedProp,
LayoutPinnedProp,
pinnedPropForFramePoint,
} from '../../../core/layout/layout-helpers-new'
import { findElementAtPath, MetadataUtils } from '../../../core/model/element-metadata-utils'
import { isLeft, right } from '../../../core/shared/either'
import {
emptyComments,
isJSXElement,
jsxAttributeValue,
} from '../../../core/shared/element-template'
import { LocalRectangle } from '../../../core/shared/math-utils'
import { ElementPath } from '../../../core/shared/project-file-types'
import * as EP from '../../../core/shared/element-path'
import Utils from '../../../utils/utils'
import { resetPins, setProp_UNSAFE, unsetProperty } from '../../editor/actions/action-creators'
import { useEditorState, useRefEditorState } from '../../editor/store/store-hook'
import { getFullFrame } from '../../frame'
import {
InspectorInfo,
useInspectorLayoutInfo,
useSelectedViews,
useRefSelectedViews,
} from './property-path-hooks'
import React from 'react'
import { CSSNumber, cssNumberToString } from './css-utils'
import { getJSXComponentsAndImportsForPathFromState } from '../../editor/store/editor-state'
const HorizontalPinPreference = [
FramePoint.Left,
FramePoint.Width,
FramePoint.Right,
FramePoint.CenterX,
]
const VerticalPinPreference = [
FramePoint.Top,
FramePoint.Height,
FramePoint.Bottom,
FramePoint.CenterY,
]
function allPinsMatch(point: FramePoint, framesToCheck: readonly Frame[]): boolean {
const firstFrame = framesToCheck[0]
if (firstFrame == null) {
return true
} else {
const firstPin = firstFrame[point]
const pinIsPercent = firstPin != null && isPercentPin(firstPin)
return (
firstPin != null &&
framesToCheck.every((frame) => {
const frameValue = frame[point]
return frameValue != null && isPercentPin(frameValue) === pinIsPercent
})
)
}
}
interface PinToSet {
path: ElementPath
pin: FramePoint
value: FramePin
}
interface PinToUnset {
path: ElementPath
pin: FramePoint
}
interface ChangePinResult {
pinsToSet: ReadonlyArray<PinToSet>
pinsToUnset: ReadonlyArray<PinToUnset>
shouldSetHorizontalPin: boolean
}
export interface ElementFrameInfo {
path: ElementPath
frame: Frame
localFrame: LocalRectangle | null
parentFrame: LocalRectangle | null
}
type PinInspectorInfo = InspectorInfo<CSSNumber | undefined>
export type PinsInfo = { [key in LayoutPinnedProp]: PinInspectorInfo }
function getOtherHorizontalPin(
newPin: LayoutPinnedProp,
lastSetPin: LayoutPinnedProp | null,
): LayoutPinnedProp | null {
if (newPin === 'PinnedCenterX') {
// When setting the CX pin, we always want to pair it with width
return 'Width'
} else if (lastSetPin === 'PinnedCenterX' && newPin !== 'Width') {
// When setting a new pin, if the last set pin was CX then replace it with width,
// unless the user is just clicking the W pin again
return 'Width'
} else {
return lastSetPin
}
}
function getOtherVerticalPin(
newPin: LayoutPinnedProp,
lastSetPin: LayoutPinnedProp | null,
): LayoutPinnedProp | null {
if (newPin === 'PinnedCenterY') {
// When setting the CY pin, we always want to pair it with height
return 'Height'
} else if (lastSetPin === 'PinnedCenterY' && newPin !== 'Height') {
// When setting a new pin, if the last set pin was CY then replace it with height,
// unless the user is just clicking the H pin again
return 'Height'
} else {
return lastSetPin
}
}
export function changePin(
newFrameProp: LayoutPinnedProp,
pinsInfo: PinsInfo,
frameInfoForElements: ReadonlyArray<ElementFrameInfo>,
lastHorizontalProp: LayoutPinnedProp | null,
lastVerticalProp: LayoutPinnedProp | null,
): ChangePinResult {
const otherHorizontalProp: LayoutPinnedProp | null = getOtherHorizontalPin(
newFrameProp,
lastHorizontalProp,
)
const otherVerticalProp: LayoutPinnedProp | null = getOtherVerticalPin(
newFrameProp,
lastVerticalProp,
)
const newFramePoint = framePointForPinnedProp(newFrameProp)
const pinInfoForProp = pinsInfo[newFrameProp]
const otherHorizontalPin = Utils.optionalMap(framePointForPinnedProp, otherHorizontalProp)
const otherVerticalPin = Utils.optionalMap(framePointForPinnedProp, otherVerticalProp)
const toggleToRelative =
pinInfoForProp.propertyStatus.identical &&
pinInfoForProp.value != null &&
pinInfoForProp.value.unit != 'px' &&
!isPercentPin(cssNumberToString(pinInfoForProp.value, true))
let pinsToSet: Array<PinToSet> = []
let pinsToUnset: Array<PinToUnset> = []
const isHorizontalPin = isHorizontalPoint(newFramePoint)
Utils.fastForEach(frameInfoForElements, (frameInfo) => {
const { path, frame, localFrame, parentFrame } = frameInfo
if (localFrame == null) {
// Can't set pins on non-layoutable elements
return
}
if (parentFrame == null) {
// Can't set pins on root level elements
return
}
const fullFrame = getFullFrame(localFrame)
const pinExists = frame[newFramePoint] != null
let pointsToDelete: Array<FramePoint> = []
if (!pinExists) {
let pointsToKeep: Array<FramePoint>
if (isHorizontalPin) {
if (otherHorizontalPin != null) {
if (frame[otherHorizontalPin] == null) {
const missingPinValue = valueToUseForPin(
otherHorizontalPin,
fullFrame[otherHorizontalPin],
false,
parentFrame,
)
pinsToSet.push({
path: path,
pin: otherHorizontalPin,
value: missingPinValue,
})
}
pointsToKeep = [newFramePoint, otherHorizontalPin, ...VerticalFramePoints]
} else {
const pinToKeep = HorizontalPinPreference.find((p) => frame[p] != null)
pointsToKeep = Utils.maybeToArray(pinToKeep).concat([
newFramePoint,
...VerticalFramePoints,
])
}
} else {
if (otherVerticalPin != null) {
if (frame[otherVerticalPin] == null) {
const missingPinValue = valueToUseForPin(
otherVerticalPin,
fullFrame[otherVerticalPin],
false,
parentFrame,
)
pinsToSet.push({
path: path,
pin: otherVerticalPin,
value: missingPinValue,
})
}
pointsToKeep = [newFramePoint, otherVerticalPin, ...HorizontalFramePoints]
} else {
const pinToKeep = VerticalPinPreference.find((p) => frame[p] != null)
pointsToKeep = Utils.maybeToArray(pinToKeep).concat([
newFramePoint,
...HorizontalFramePoints,
])
}
}
Utils.fastForEach(AllFramePoints, (framePoint) => {
if (!pointsToKeep.includes(framePoint) && frame[framePoint] !== undefined) {
pointsToDelete.push(framePoint)
}
})
}
const absoluteValue = fullFrame[newFramePoint]
const newPinValue = valueToUseForPin(
newFramePoint,
absoluteValue,
toggleToRelative,
parentFrame,
)
pinsToSet.push({
path: path,
pin: newFramePoint,
value: newPinValue,
})
Utils.fastForEach(pointsToDelete, (pointToDelete) => {
pinsToUnset.push({
path: path,
pin: pointToDelete,
})
})
})
return {
pinsToSet,
pinsToUnset,
shouldSetHorizontalPin: isHorizontalPin,
}
}
export interface FramePinInfo {
isPrimaryPosition: boolean
isRelativePosition: boolean
}
export type FramePinsInfo = { [key in FramePoint]: FramePinInfo }
export interface UsePinTogglingResult {
framePins: FramePinsInfo
togglePin: (newFrameProp: LayoutPinnedProp) => void
resetAllPins: () => void
}
export function usePinToggling(): UsePinTogglingResult {
const dispatch = useEditorState((store) => store.dispatch, 'usePinToggling dispatch')
const selectedViewsRef = useRefSelectedViews()
const jsxMetadataRef = useRefEditorState((store) => {
return store.editor.jsxMetadata
})
const elementsRef = useRefEditorState((store) =>
selectedViewsRef.current.map((e) =>
MetadataUtils.findElementByElementPath(store.editor.jsxMetadata, e),
),
)
const elementFrames = useEditorState(
(store): ReadonlyArray<Frame> => {
const jsxElements = selectedViewsRef.current.map((path) => {
const rootComponents = getJSXComponentsAndImportsForPathFromState(
path,
store.editor,
store.derived,
).components
return findElementAtPath(path, rootComponents)
})
return jsxElements.map((elem) => {
if (elem != null && isJSXElement(elem)) {
return AllFramePoints.reduce<Frame>((working, point) => {
const layoutProp = pinnedPropForFramePoint(point)
const value = getLayoutProperty(layoutProp, right(elem.props))
if (isLeft(value)) {
return working
} else {
return {
...working,
[point]: value.value,
}
}
}, {})
} else {
return {}
}
})
},
'usePinToggling elementFrames',
fastDeepEqual,
)
const framePins = React.useMemo((): FramePinsInfo => {
const allHorizontalPoints = HorizontalFramePoints.filter((p) => allPinsMatch(p, elementFrames))
const allVerticalPoints = VerticalFramePoints.filter((p) => allPinsMatch(p, elementFrames))
const framePoints = [...allHorizontalPoints, ...allVerticalPoints]
const firstFrame = elementFrames[0]
return Utils.mapArrayToDictionary(
framePoints,
(point) => point,
(point) => {
const firstFrameAtPoint = firstFrame == null ? null : firstFrame[point]
return {
isPrimaryPosition: true,
isRelativePosition: firstFrameAtPoint != null && isPercentPin(firstFrameAtPoint),
}
},
)
}, [elementFrames])
const [lastHorizontalProp, setLastHorizontalProp] = React.useState<LayoutPinnedProp | null>(null)
const [lastVerticalProp, setLastVerticalProp] = React.useState<LayoutPinnedProp | null>(null)
const Width = useInspectorLayoutInfo<LayoutPinnedProp>('Width')
const Height = useInspectorLayoutInfo<LayoutPinnedProp>('Height')
const PinnedLeft = useInspectorLayoutInfo<LayoutPinnedProp>('PinnedLeft')
const PinnedTop = useInspectorLayoutInfo<LayoutPinnedProp>('PinnedTop')
const PinnedRight = useInspectorLayoutInfo<LayoutPinnedProp>('PinnedRight')
const PinnedBottom = useInspectorLayoutInfo<LayoutPinnedProp>('PinnedBottom')
const PinnedCenterX = useInspectorLayoutInfo<LayoutPinnedProp>('PinnedCenterX')
const PinnedCenterY = useInspectorLayoutInfo<LayoutPinnedProp>('PinnedCenterY')
const togglePin = React.useCallback(
(newFrameProp: LayoutPinnedProp) => {
const frameInfo: ReadonlyArray<ElementFrameInfo> = elementFrames.map((frame, index) => {
const path = selectedViewsRef.current[index]
const parentPath = EP.parentPath(path)
const parentFrame = MetadataUtils.getFrame(parentPath, jsxMetadataRef.current)
return {
path: path,
frame: frame,
localFrame: elementsRef.current[index]?.localFrame ?? null,
parentFrame: parentFrame,
}
})
const { pinsToSet, pinsToUnset, shouldSetHorizontalPin } = changePin(
newFrameProp,
{
Width,
Height,
PinnedLeft,
PinnedTop,
PinnedRight,
PinnedBottom,
PinnedCenterX,
PinnedCenterY,
},
frameInfo,
lastHorizontalProp,
lastVerticalProp,
)
const setPinActions = pinsToSet.map(({ path, pin, value }) =>
setProp_UNSAFE(
path,
createLayoutPropertyPath(pinnedPropForFramePoint(pin)),
jsxAttributeValue(value, emptyComments),
),
)
const unsetPinActions = pinsToUnset.map(({ path, pin }) =>
unsetProperty(path, createLayoutPropertyPath(pinnedPropForFramePoint(pin))),
)
const actions = [...setPinActions, ...unsetPinActions]
dispatch(actions, 'everyone')
if (shouldSetHorizontalPin) {
setLastHorizontalProp(newFrameProp)
} else {
setLastVerticalProp(newFrameProp)
}
},
[
elementFrames,
selectedViewsRef,
elementsRef,
Width,
Height,
PinnedLeft,
PinnedTop,
PinnedRight,
PinnedBottom,
PinnedCenterX,
PinnedCenterY,
dispatch,
jsxMetadataRef,
lastHorizontalProp,
lastVerticalProp,
],
)
const resetAllPins = React.useCallback(() => {
const actions = selectedViewsRef.current.map(resetPins)
dispatch(actions, 'everyone')
}, [selectedViewsRef, dispatch])
return {
framePins: framePins,
togglePin: togglePin,
resetAllPins: resetAllPins,
}
} | the_stack |
import BinTools from "../utils/bintools"
import BN from "bn.js"
import { Buffer } from "buffer/"
import DOMPurify from "isomorphic-dompurify"
import {
NodeIDStringToBuffer,
privateKeyStringToBuffer,
bufferToNodeIDString,
bufferToPrivateKeyString
} from "./helperfunctions"
import {
CodecIdError,
TypeIdError,
TypeNameError,
UnknownTypeError
} from "../utils/errors"
import { Serialized } from "../common"
export const SERIALIZATIONVERSION: number = 0
export type SerializedType =
| "hex"
| "BN"
| "Buffer"
| "bech32"
| "nodeID"
| "privateKey"
| "cb58"
| "base58"
| "base64"
| "decimalString"
| "number"
| "utf8"
export type SerializedEncoding =
| "hex"
| "cb58"
| "base58"
| "base64"
| "decimalString"
| "number"
| "utf8"
| "display"
export abstract class Serializable {
protected _typeName: string = undefined
protected _typeID: number = undefined
protected _codecID: number = undefined
/**
* Used in serialization. TypeName is a string name for the type of object being output.
*/
getTypeName(): string {
return this._typeName
}
/**
* Used in serialization. Optional. TypeID is a number for the typeID of object being output.
*/
getTypeID(): number {
return this._typeID
}
/**
* Used in serialization. Optional. TypeID is a number for the typeID of object being output.
*/
getCodecID(): number {
return this._codecID
}
/**
* Sanitize to prevent cross scripting attacks.
*/
sanitizeObject(obj: object): object {
for (const k in obj) {
if (typeof obj[`${k}`] === "object" && obj[`${k}`] !== null) {
this.sanitizeObject(obj[`${k}`])
} else if (typeof obj[`${k}`] === "string") {
obj[`${k}`] = DOMPurify.sanitize(obj[`${k}`])
}
}
return obj
}
//sometimes the parent class manages the fields
//these are so you can say super.serialize(encoding)
serialize(encoding?: SerializedEncoding): object {
return {
_typeName: DOMPurify.sanitize(this._typeName),
_typeID: typeof this._typeID === "undefined" ? null : this._typeID,
_codecID: typeof this._codecID === "undefined" ? null : this._codecID
}
}
deserialize(fields: object, encoding?: SerializedEncoding): void {
fields = this.sanitizeObject(fields)
if (typeof fields["_typeName"] !== "string") {
throw new TypeNameError(
"Error - Serializable.deserialize: _typeName must be a string, found: " +
typeof fields["_typeName"]
)
}
if (fields["_typeName"] !== this._typeName) {
throw new TypeNameError(
"Error - Serializable.deserialize: _typeName mismatch -- expected: " +
this._typeName +
" -- received: " +
fields["_typeName"]
)
}
if (
typeof fields["_typeID"] !== "undefined" &&
fields["_typeID"] !== null
) {
if (typeof fields["_typeID"] !== "number") {
throw new TypeIdError(
"Error - Serializable.deserialize: _typeID must be a number, found: " +
typeof fields["_typeID"]
)
}
if (fields["_typeID"] !== this._typeID) {
throw new TypeIdError(
"Error - Serializable.deserialize: _typeID mismatch -- expected: " +
this._typeID +
" -- received: " +
fields["_typeID"]
)
}
}
if (
typeof fields["_codecID"] !== "undefined" &&
fields["_codecID"] !== null
) {
if (typeof fields["_codecID"] !== "number") {
throw new CodecIdError(
"Error - Serializable.deserialize: _codecID must be a number, found: " +
typeof fields["_codecID"]
)
}
if (fields["_codecID"] !== this._codecID) {
throw new CodecIdError(
"Error - Serializable.deserialize: _codecID mismatch -- expected: " +
this._codecID +
" -- received: " +
fields["_codecID"]
)
}
}
}
}
export class Serialization {
private static instance: Serialization
private constructor() {
this.bintools = BinTools.getInstance()
}
private bintools: BinTools
/**
* Retrieves the Serialization singleton.
*/
static getInstance(): Serialization {
if (!Serialization.instance) {
Serialization.instance = new Serialization()
}
return Serialization.instance
}
/**
* Convert {@link https://github.com/feross/buffer|Buffer} to [[SerializedType]]
*
* @param vb {@link https://github.com/feross/buffer|Buffer}
* @param type [[SerializedType]]
* @param ...args remaining arguments
* @returns type of [[SerializedType]]
*/
bufferToType(vb: Buffer, type: SerializedType, ...args: any[]): any {
if (type === "BN") {
return new BN(vb.toString("hex"), "hex")
} else if (type === "Buffer") {
if (args.length == 1 && typeof args[0] === "number") {
vb = Buffer.from(vb.toString("hex").padStart(args[0] * 2, "0"), "hex")
}
return vb
} else if (type === "bech32") {
return this.bintools.addressToString(args[0], args[1], vb)
} else if (type === "nodeID") {
return bufferToNodeIDString(vb)
} else if (type === "privateKey") {
return bufferToPrivateKeyString(vb)
} else if (type === "cb58") {
return this.bintools.cb58Encode(vb)
} else if (type === "base58") {
return this.bintools.bufferToB58(vb)
} else if (type === "base64") {
return vb.toString("base64")
} else if (type === "hex") {
return vb.toString("hex")
} else if (type === "decimalString") {
return new BN(vb.toString("hex"), "hex").toString(10)
} else if (type === "number") {
return new BN(vb.toString("hex"), "hex").toNumber()
} else if (type === "utf8") {
return vb.toString("utf8")
}
return undefined
}
/**
* Convert [[SerializedType]] to {@link https://github.com/feross/buffer|Buffer}
*
* @param v type of [[SerializedType]]
* @param type [[SerializedType]]
* @param ...args remaining arguments
* @returns {@link https://github.com/feross/buffer|Buffer}
*/
typeToBuffer(v: any, type: SerializedType, ...args: any[]): Buffer {
if (type === "BN") {
let str: string = (v as BN).toString("hex")
if (args.length == 1 && typeof args[0] === "number") {
return Buffer.from(str.padStart(args[0] * 2, "0"), "hex")
}
return Buffer.from(str, "hex")
} else if (type === "Buffer") {
return v
} else if (type === "bech32") {
return this.bintools.stringToAddress(v, ...args)
} else if (type === "nodeID") {
return NodeIDStringToBuffer(v)
} else if (type === "privateKey") {
return privateKeyStringToBuffer(v)
} else if (type === "cb58") {
return this.bintools.cb58Decode(v)
} else if (type === "base58") {
return this.bintools.b58ToBuffer(v)
} else if (type === "base64") {
return Buffer.from(v as string, "base64")
} else if (type === "hex") {
if ((v as string).startsWith("0x")) {
v = (v as string).slice(2)
}
return Buffer.from(v as string, "hex")
} else if (type === "decimalString") {
let str: string = new BN(v as string, 10).toString("hex")
if (args.length == 1 && typeof args[0] === "number") {
return Buffer.from(str.padStart(args[0] * 2, "0"), "hex")
}
return Buffer.from(str, "hex")
} else if (type === "number") {
let str: string = new BN(v, 10).toString("hex")
if (args.length == 1 && typeof args[0] === "number") {
return Buffer.from(str.padStart(args[0] * 2, "0"), "hex")
}
return Buffer.from(str, "hex")
} else if (type === "utf8") {
if (args.length == 1 && typeof args[0] === "number") {
let b: Buffer = Buffer.alloc(args[0])
b.write(v)
return b
}
return Buffer.from(v, "utf8")
}
return undefined
}
/**
* Convert value to type of [[SerializedType]] or [[SerializedEncoding]]
*
* @param value
* @param encoding [[SerializedEncoding]]
* @param intype [[SerializedType]]
* @param outtype [[SerializedType]]
* @param ...args remaining arguments
* @returns type of [[SerializedType]] or [[SerializedEncoding]]
*/
encoder(
value: any,
encoding: SerializedEncoding,
intype: SerializedType,
outtype: SerializedType,
...args: any[]
): any {
if (typeof value === "undefined") {
throw new UnknownTypeError(
"Error - Serializable.encoder: value passed is undefined"
)
}
if (encoding !== "display") {
outtype = encoding
}
const vb: Buffer = this.typeToBuffer(value, intype, ...args)
return this.bufferToType(vb, outtype, ...args)
}
/**
* Convert value to type of [[SerializedType]] or [[SerializedEncoding]]
*
* @param value
* @param encoding [[SerializedEncoding]]
* @param intype [[SerializedType]]
* @param outtype [[SerializedType]]
* @param ...args remaining arguments
* @returns type of [[SerializedType]] or [[SerializedEncoding]]
*/
decoder(
value: string,
encoding: SerializedEncoding,
intype: SerializedType,
outtype: SerializedType,
...args: any[]
): any {
if (typeof value === "undefined") {
throw new UnknownTypeError(
"Error - Serializable.decoder: value passed is undefined"
)
}
if (encoding !== "display") {
intype = encoding
}
const vb: Buffer = this.typeToBuffer(value, intype, ...args)
return this.bufferToType(vb, outtype, ...args)
}
serialize(
serialize: Serializable,
vm: string,
encoding: SerializedEncoding = "display",
notes: string = undefined
): Serialized {
if (typeof notes === "undefined") {
notes = serialize.getTypeName()
}
return {
vm,
encoding,
version: SERIALIZATIONVERSION,
notes,
fields: serialize.serialize(encoding)
}
}
deserialize(input: Serialized, output: Serializable) {
output.deserialize(input.fields, input.encoding)
}
} | the_stack |
declare module 'stripe' {
namespace Stripe {
namespace Issuing {
/**
* The Cardholder object.
*/
interface Cardholder {
/**
* Unique identifier for the object.
*/
id: string;
/**
* String representing the object's type. Objects of the same type share the same value.
*/
object: 'issuing.cardholder';
billing: Cardholder.Billing;
/**
* Additional information about a `company` cardholder.
*/
company: Cardholder.Company | null;
/**
* Time at which the object was created. Measured in seconds since the Unix epoch.
*/
created: number;
/**
* The cardholder's email address.
*/
email: string | null;
/**
* Additional information about an `individual` cardholder.
*/
individual: Cardholder.Individual | null;
/**
* Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode.
*/
livemode: boolean;
/**
* Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
*/
metadata: Stripe.Metadata;
/**
* The cardholder's name. This will be printed on cards issued to them.
*/
name: string;
/**
* The cardholder's phone number. This is required for all cardholders who will be creating EU cards. See the [3D Secure documentation](https://stripe.com/docs/issuing/3d-secure#when-is-3d-secure-applied) for more details.
*/
phone_number: string | null;
requirements: Cardholder.Requirements;
/**
* Rules that control spending across this cardholder's cards. Refer to our [documentation](https://stripe.com/docs/issuing/controls/spending-controls) for more details.
*/
spending_controls: Cardholder.SpendingControls | null;
/**
* Specifies whether to permit authorizations on this cardholder's cards.
*/
status: Cardholder.Status;
/**
* One of `individual` or `company`.
*/
type: Cardholder.Type;
}
namespace Cardholder {
interface Billing {
address: Stripe.Address;
}
interface Company {
/**
* Whether the company's business ID number was provided.
*/
tax_id_provided: boolean;
}
interface Individual {
/**
* The date of birth of this cardholder.
*/
dob: Individual.Dob | null;
/**
* The first name of this cardholder.
*/
first_name: string;
/**
* The last name of this cardholder.
*/
last_name: string;
/**
* Government-issued ID document for this cardholder.
*/
verification: Individual.Verification | null;
}
namespace Individual {
interface Dob {
/**
* The day of birth, between 1 and 31.
*/
day: number | null;
/**
* The month of birth, between 1 and 12.
*/
month: number | null;
/**
* The four-digit year of birth.
*/
year: number | null;
}
interface Verification {
/**
* An identifying document, either a passport or local ID card.
*/
document: Verification.Document | null;
}
namespace Verification {
interface Document {
/**
* The back of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`.
*/
back: string | Stripe.File | null;
/**
* The front of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`.
*/
front: string | Stripe.File | null;
}
}
}
interface Requirements {
/**
* If `disabled_reason` is present, all cards will decline authorizations with `cardholder_verification_required` reason.
*/
disabled_reason: Requirements.DisabledReason | null;
/**
* Array of fields that need to be collected in order to verify and re-enable the cardholder.
*/
past_due: Array<Requirements.PastDue> | null;
}
namespace Requirements {
type DisabledReason = 'listed' | 'rejected.listed' | 'under_review';
type PastDue =
| 'company.tax_id'
| 'individual.dob.day'
| 'individual.dob.month'
| 'individual.dob.year'
| 'individual.first_name'
| 'individual.last_name'
| 'individual.verification.document';
}
interface SpendingControls {
/**
* Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to allow. All other categories will be blocked. Cannot be set with `blocked_categories`.
*/
allowed_categories: Array<SpendingControls.AllowedCategory> | null;
/**
* Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to decline. All other categories will be allowed. Cannot be set with `allowed_categories`.
*/
blocked_categories: Array<SpendingControls.BlockedCategory> | null;
/**
* Limit spending with amount-based rules that apply across this cardholder's cards.
*/
spending_limits: Array<SpendingControls.SpendingLimit> | null;
/**
* Currency of the amounts within `spending_limits`.
*/
spending_limits_currency: string | null;
}
namespace SpendingControls {
type AllowedCategory =
| 'ac_refrigeration_repair'
| 'accounting_bookkeeping_services'
| 'advertising_services'
| 'agricultural_cooperative'
| 'airlines_air_carriers'
| 'airports_flying_fields'
| 'ambulance_services'
| 'amusement_parks_carnivals'
| 'antique_reproductions'
| 'antique_shops'
| 'aquariums'
| 'architectural_surveying_services'
| 'art_dealers_and_galleries'
| 'artists_supply_and_craft_shops'
| 'auto_and_home_supply_stores'
| 'auto_body_repair_shops'
| 'auto_paint_shops'
| 'auto_service_shops'
| 'automated_cash_disburse'
| 'automated_fuel_dispensers'
| 'automobile_associations'
| 'automotive_parts_and_accessories_stores'
| 'automotive_tire_stores'
| 'bail_and_bond_payments'
| 'bakeries'
| 'bands_orchestras'
| 'barber_and_beauty_shops'
| 'betting_casino_gambling'
| 'bicycle_shops'
| 'billiard_pool_establishments'
| 'boat_dealers'
| 'boat_rentals_and_leases'
| 'book_stores'
| 'books_periodicals_and_newspapers'
| 'bowling_alleys'
| 'bus_lines'
| 'business_secretarial_schools'
| 'buying_shopping_services'
| 'cable_satellite_and_other_pay_television_and_radio'
| 'camera_and_photographic_supply_stores'
| 'candy_nut_and_confectionery_stores'
| 'car_and_truck_dealers_new_used'
| 'car_and_truck_dealers_used_only'
| 'car_rental_agencies'
| 'car_washes'
| 'carpentry_services'
| 'carpet_upholstery_cleaning'
| 'caterers'
| 'charitable_and_social_service_organizations_fundraising'
| 'chemicals_and_allied_products'
| 'child_care_services'
| 'childrens_and_infants_wear_stores'
| 'chiropodists_podiatrists'
| 'chiropractors'
| 'cigar_stores_and_stands'
| 'civic_social_fraternal_associations'
| 'cleaning_and_maintenance'
| 'clothing_rental'
| 'colleges_universities'
| 'commercial_equipment'
| 'commercial_footwear'
| 'commercial_photography_art_and_graphics'
| 'commuter_transport_and_ferries'
| 'computer_network_services'
| 'computer_programming'
| 'computer_repair'
| 'computer_software_stores'
| 'computers_peripherals_and_software'
| 'concrete_work_services'
| 'construction_materials'
| 'consulting_public_relations'
| 'correspondence_schools'
| 'cosmetic_stores'
| 'counseling_services'
| 'country_clubs'
| 'courier_services'
| 'court_costs'
| 'credit_reporting_agencies'
| 'cruise_lines'
| 'dairy_products_stores'
| 'dance_hall_studios_schools'
| 'dating_escort_services'
| 'dentists_orthodontists'
| 'department_stores'
| 'detective_agencies'
| 'digital_goods_applications'
| 'digital_goods_games'
| 'digital_goods_large_volume'
| 'digital_goods_media'
| 'direct_marketing_catalog_merchant'
| 'direct_marketing_combination_catalog_and_retail_merchant'
| 'direct_marketing_inbound_telemarketing'
| 'direct_marketing_insurance_services'
| 'direct_marketing_other'
| 'direct_marketing_outbound_telemarketing'
| 'direct_marketing_subscription'
| 'direct_marketing_travel'
| 'discount_stores'
| 'doctors'
| 'door_to_door_sales'
| 'drapery_window_covering_and_upholstery_stores'
| 'drinking_places'
| 'drug_stores_and_pharmacies'
| 'drugs_drug_proprietaries_and_druggist_sundries'
| 'dry_cleaners'
| 'durable_goods'
| 'duty_free_stores'
| 'eating_places_restaurants'
| 'educational_services'
| 'electric_razor_stores'
| 'electrical_parts_and_equipment'
| 'electrical_services'
| 'electronics_repair_shops'
| 'electronics_stores'
| 'elementary_secondary_schools'
| 'employment_temp_agencies'
| 'equipment_rental'
| 'exterminating_services'
| 'family_clothing_stores'
| 'fast_food_restaurants'
| 'financial_institutions'
| 'fines_government_administrative_entities'
| 'fireplace_fireplace_screens_and_accessories_stores'
| 'floor_covering_stores'
| 'florists'
| 'florists_supplies_nursery_stock_and_flowers'
| 'freezer_and_locker_meat_provisioners'
| 'fuel_dealers_non_automotive'
| 'funeral_services_crematories'
| 'furniture_home_furnishings_and_equipment_stores_except_appliances'
| 'furniture_repair_refinishing'
| 'furriers_and_fur_shops'
| 'general_services'
| 'gift_card_novelty_and_souvenir_shops'
| 'glass_paint_and_wallpaper_stores'
| 'glassware_crystal_stores'
| 'golf_courses_public'
| 'government_services'
| 'grocery_stores_supermarkets'
| 'hardware_equipment_and_supplies'
| 'hardware_stores'
| 'health_and_beauty_spas'
| 'hearing_aids_sales_and_supplies'
| 'heating_plumbing_a_c'
| 'hobby_toy_and_game_shops'
| 'home_supply_warehouse_stores'
| 'hospitals'
| 'hotels_motels_and_resorts'
| 'household_appliance_stores'
| 'industrial_supplies'
| 'information_retrieval_services'
| 'insurance_default'
| 'insurance_underwriting_premiums'
| 'intra_company_purchases'
| 'jewelry_stores_watches_clocks_and_silverware_stores'
| 'landscaping_services'
| 'laundries'
| 'laundry_cleaning_services'
| 'legal_services_attorneys'
| 'luggage_and_leather_goods_stores'
| 'lumber_building_materials_stores'
| 'manual_cash_disburse'
| 'marinas_service_and_supplies'
| 'masonry_stonework_and_plaster'
| 'massage_parlors'
| 'medical_and_dental_labs'
| 'medical_dental_ophthalmic_and_hospital_equipment_and_supplies'
| 'medical_services'
| 'membership_organizations'
| 'mens_and_boys_clothing_and_accessories_stores'
| 'mens_womens_clothing_stores'
| 'metal_service_centers'
| 'miscellaneous'
| 'miscellaneous_apparel_and_accessory_shops'
| 'miscellaneous_auto_dealers'
| 'miscellaneous_business_services'
| 'miscellaneous_food_stores'
| 'miscellaneous_general_merchandise'
| 'miscellaneous_general_services'
| 'miscellaneous_home_furnishing_specialty_stores'
| 'miscellaneous_publishing_and_printing'
| 'miscellaneous_recreation_services'
| 'miscellaneous_repair_shops'
| 'miscellaneous_specialty_retail'
| 'mobile_home_dealers'
| 'motion_picture_theaters'
| 'motor_freight_carriers_and_trucking'
| 'motor_homes_dealers'
| 'motor_vehicle_supplies_and_new_parts'
| 'motorcycle_shops_and_dealers'
| 'motorcycle_shops_dealers'
| 'music_stores_musical_instruments_pianos_and_sheet_music'
| 'news_dealers_and_newsstands'
| 'non_fi_money_orders'
| 'non_fi_stored_value_card_purchase_load'
| 'nondurable_goods'
| 'nurseries_lawn_and_garden_supply_stores'
| 'nursing_personal_care'
| 'office_and_commercial_furniture'
| 'opticians_eyeglasses'
| 'optometrists_ophthalmologist'
| 'orthopedic_goods_prosthetic_devices'
| 'osteopaths'
| 'package_stores_beer_wine_and_liquor'
| 'paints_varnishes_and_supplies'
| 'parking_lots_garages'
| 'passenger_railways'
| 'pawn_shops'
| 'pet_shops_pet_food_and_supplies'
| 'petroleum_and_petroleum_products'
| 'photo_developing'
| 'photographic_photocopy_microfilm_equipment_and_supplies'
| 'photographic_studios'
| 'picture_video_production'
| 'piece_goods_notions_and_other_dry_goods'
| 'plumbing_heating_equipment_and_supplies'
| 'political_organizations'
| 'postal_services_government_only'
| 'precious_stones_and_metals_watches_and_jewelry'
| 'professional_services'
| 'public_warehousing_and_storage'
| 'quick_copy_repro_and_blueprint'
| 'railroads'
| 'real_estate_agents_and_managers_rentals'
| 'record_stores'
| 'recreational_vehicle_rentals'
| 'religious_goods_stores'
| 'religious_organizations'
| 'roofing_siding_sheet_metal'
| 'secretarial_support_services'
| 'security_brokers_dealers'
| 'service_stations'
| 'sewing_needlework_fabric_and_piece_goods_stores'
| 'shoe_repair_hat_cleaning'
| 'shoe_stores'
| 'small_appliance_repair'
| 'snowmobile_dealers'
| 'special_trade_services'
| 'specialty_cleaning'
| 'sporting_goods_stores'
| 'sporting_recreation_camps'
| 'sports_and_riding_apparel_stores'
| 'sports_clubs_fields'
| 'stamp_and_coin_stores'
| 'stationary_office_supplies_printing_and_writing_paper'
| 'stationery_stores_office_and_school_supply_stores'
| 'swimming_pools_sales'
| 't_ui_travel_germany'
| 'tailors_alterations'
| 'tax_payments_government_agencies'
| 'tax_preparation_services'
| 'taxicabs_limousines'
| 'telecommunication_equipment_and_telephone_sales'
| 'telecommunication_services'
| 'telegraph_services'
| 'tent_and_awning_shops'
| 'testing_laboratories'
| 'theatrical_ticket_agencies'
| 'timeshares'
| 'tire_retreading_and_repair'
| 'tolls_bridge_fees'
| 'tourist_attractions_and_exhibits'
| 'towing_services'
| 'trailer_parks_campgrounds'
| 'transportation_services'
| 'travel_agencies_tour_operators'
| 'truck_stop_iteration'
| 'truck_utility_trailer_rentals'
| 'typesetting_plate_making_and_related_services'
| 'typewriter_stores'
| 'u_s_federal_government_agencies_or_departments'
| 'uniforms_commercial_clothing'
| 'used_merchandise_and_secondhand_stores'
| 'utilities'
| 'variety_stores'
| 'veterinary_services'
| 'video_amusement_game_supplies'
| 'video_game_arcades'
| 'video_tape_rental_stores'
| 'vocational_trade_schools'
| 'watch_jewelry_repair'
| 'welding_repair'
| 'wholesale_clubs'
| 'wig_and_toupee_stores'
| 'wires_money_orders'
| 'womens_accessory_and_specialty_shops'
| 'womens_ready_to_wear_stores'
| 'wrecking_and_salvage_yards';
type BlockedCategory =
| 'ac_refrigeration_repair'
| 'accounting_bookkeeping_services'
| 'advertising_services'
| 'agricultural_cooperative'
| 'airlines_air_carriers'
| 'airports_flying_fields'
| 'ambulance_services'
| 'amusement_parks_carnivals'
| 'antique_reproductions'
| 'antique_shops'
| 'aquariums'
| 'architectural_surveying_services'
| 'art_dealers_and_galleries'
| 'artists_supply_and_craft_shops'
| 'auto_and_home_supply_stores'
| 'auto_body_repair_shops'
| 'auto_paint_shops'
| 'auto_service_shops'
| 'automated_cash_disburse'
| 'automated_fuel_dispensers'
| 'automobile_associations'
| 'automotive_parts_and_accessories_stores'
| 'automotive_tire_stores'
| 'bail_and_bond_payments'
| 'bakeries'
| 'bands_orchestras'
| 'barber_and_beauty_shops'
| 'betting_casino_gambling'
| 'bicycle_shops'
| 'billiard_pool_establishments'
| 'boat_dealers'
| 'boat_rentals_and_leases'
| 'book_stores'
| 'books_periodicals_and_newspapers'
| 'bowling_alleys'
| 'bus_lines'
| 'business_secretarial_schools'
| 'buying_shopping_services'
| 'cable_satellite_and_other_pay_television_and_radio'
| 'camera_and_photographic_supply_stores'
| 'candy_nut_and_confectionery_stores'
| 'car_and_truck_dealers_new_used'
| 'car_and_truck_dealers_used_only'
| 'car_rental_agencies'
| 'car_washes'
| 'carpentry_services'
| 'carpet_upholstery_cleaning'
| 'caterers'
| 'charitable_and_social_service_organizations_fundraising'
| 'chemicals_and_allied_products'
| 'child_care_services'
| 'childrens_and_infants_wear_stores'
| 'chiropodists_podiatrists'
| 'chiropractors'
| 'cigar_stores_and_stands'
| 'civic_social_fraternal_associations'
| 'cleaning_and_maintenance'
| 'clothing_rental'
| 'colleges_universities'
| 'commercial_equipment'
| 'commercial_footwear'
| 'commercial_photography_art_and_graphics'
| 'commuter_transport_and_ferries'
| 'computer_network_services'
| 'computer_programming'
| 'computer_repair'
| 'computer_software_stores'
| 'computers_peripherals_and_software'
| 'concrete_work_services'
| 'construction_materials'
| 'consulting_public_relations'
| 'correspondence_schools'
| 'cosmetic_stores'
| 'counseling_services'
| 'country_clubs'
| 'courier_services'
| 'court_costs'
| 'credit_reporting_agencies'
| 'cruise_lines'
| 'dairy_products_stores'
| 'dance_hall_studios_schools'
| 'dating_escort_services'
| 'dentists_orthodontists'
| 'department_stores'
| 'detective_agencies'
| 'digital_goods_applications'
| 'digital_goods_games'
| 'digital_goods_large_volume'
| 'digital_goods_media'
| 'direct_marketing_catalog_merchant'
| 'direct_marketing_combination_catalog_and_retail_merchant'
| 'direct_marketing_inbound_telemarketing'
| 'direct_marketing_insurance_services'
| 'direct_marketing_other'
| 'direct_marketing_outbound_telemarketing'
| 'direct_marketing_subscription'
| 'direct_marketing_travel'
| 'discount_stores'
| 'doctors'
| 'door_to_door_sales'
| 'drapery_window_covering_and_upholstery_stores'
| 'drinking_places'
| 'drug_stores_and_pharmacies'
| 'drugs_drug_proprietaries_and_druggist_sundries'
| 'dry_cleaners'
| 'durable_goods'
| 'duty_free_stores'
| 'eating_places_restaurants'
| 'educational_services'
| 'electric_razor_stores'
| 'electrical_parts_and_equipment'
| 'electrical_services'
| 'electronics_repair_shops'
| 'electronics_stores'
| 'elementary_secondary_schools'
| 'employment_temp_agencies'
| 'equipment_rental'
| 'exterminating_services'
| 'family_clothing_stores'
| 'fast_food_restaurants'
| 'financial_institutions'
| 'fines_government_administrative_entities'
| 'fireplace_fireplace_screens_and_accessories_stores'
| 'floor_covering_stores'
| 'florists'
| 'florists_supplies_nursery_stock_and_flowers'
| 'freezer_and_locker_meat_provisioners'
| 'fuel_dealers_non_automotive'
| 'funeral_services_crematories'
| 'furniture_home_furnishings_and_equipment_stores_except_appliances'
| 'furniture_repair_refinishing'
| 'furriers_and_fur_shops'
| 'general_services'
| 'gift_card_novelty_and_souvenir_shops'
| 'glass_paint_and_wallpaper_stores'
| 'glassware_crystal_stores'
| 'golf_courses_public'
| 'government_services'
| 'grocery_stores_supermarkets'
| 'hardware_equipment_and_supplies'
| 'hardware_stores'
| 'health_and_beauty_spas'
| 'hearing_aids_sales_and_supplies'
| 'heating_plumbing_a_c'
| 'hobby_toy_and_game_shops'
| 'home_supply_warehouse_stores'
| 'hospitals'
| 'hotels_motels_and_resorts'
| 'household_appliance_stores'
| 'industrial_supplies'
| 'information_retrieval_services'
| 'insurance_default'
| 'insurance_underwriting_premiums'
| 'intra_company_purchases'
| 'jewelry_stores_watches_clocks_and_silverware_stores'
| 'landscaping_services'
| 'laundries'
| 'laundry_cleaning_services'
| 'legal_services_attorneys'
| 'luggage_and_leather_goods_stores'
| 'lumber_building_materials_stores'
| 'manual_cash_disburse'
| 'marinas_service_and_supplies'
| 'masonry_stonework_and_plaster'
| 'massage_parlors'
| 'medical_and_dental_labs'
| 'medical_dental_ophthalmic_and_hospital_equipment_and_supplies'
| 'medical_services'
| 'membership_organizations'
| 'mens_and_boys_clothing_and_accessories_stores'
| 'mens_womens_clothing_stores'
| 'metal_service_centers'
| 'miscellaneous'
| 'miscellaneous_apparel_and_accessory_shops'
| 'miscellaneous_auto_dealers'
| 'miscellaneous_business_services'
| 'miscellaneous_food_stores'
| 'miscellaneous_general_merchandise'
| 'miscellaneous_general_services'
| 'miscellaneous_home_furnishing_specialty_stores'
| 'miscellaneous_publishing_and_printing'
| 'miscellaneous_recreation_services'
| 'miscellaneous_repair_shops'
| 'miscellaneous_specialty_retail'
| 'mobile_home_dealers'
| 'motion_picture_theaters'
| 'motor_freight_carriers_and_trucking'
| 'motor_homes_dealers'
| 'motor_vehicle_supplies_and_new_parts'
| 'motorcycle_shops_and_dealers'
| 'motorcycle_shops_dealers'
| 'music_stores_musical_instruments_pianos_and_sheet_music'
| 'news_dealers_and_newsstands'
| 'non_fi_money_orders'
| 'non_fi_stored_value_card_purchase_load'
| 'nondurable_goods'
| 'nurseries_lawn_and_garden_supply_stores'
| 'nursing_personal_care'
| 'office_and_commercial_furniture'
| 'opticians_eyeglasses'
| 'optometrists_ophthalmologist'
| 'orthopedic_goods_prosthetic_devices'
| 'osteopaths'
| 'package_stores_beer_wine_and_liquor'
| 'paints_varnishes_and_supplies'
| 'parking_lots_garages'
| 'passenger_railways'
| 'pawn_shops'
| 'pet_shops_pet_food_and_supplies'
| 'petroleum_and_petroleum_products'
| 'photo_developing'
| 'photographic_photocopy_microfilm_equipment_and_supplies'
| 'photographic_studios'
| 'picture_video_production'
| 'piece_goods_notions_and_other_dry_goods'
| 'plumbing_heating_equipment_and_supplies'
| 'political_organizations'
| 'postal_services_government_only'
| 'precious_stones_and_metals_watches_and_jewelry'
| 'professional_services'
| 'public_warehousing_and_storage'
| 'quick_copy_repro_and_blueprint'
| 'railroads'
| 'real_estate_agents_and_managers_rentals'
| 'record_stores'
| 'recreational_vehicle_rentals'
| 'religious_goods_stores'
| 'religious_organizations'
| 'roofing_siding_sheet_metal'
| 'secretarial_support_services'
| 'security_brokers_dealers'
| 'service_stations'
| 'sewing_needlework_fabric_and_piece_goods_stores'
| 'shoe_repair_hat_cleaning'
| 'shoe_stores'
| 'small_appliance_repair'
| 'snowmobile_dealers'
| 'special_trade_services'
| 'specialty_cleaning'
| 'sporting_goods_stores'
| 'sporting_recreation_camps'
| 'sports_and_riding_apparel_stores'
| 'sports_clubs_fields'
| 'stamp_and_coin_stores'
| 'stationary_office_supplies_printing_and_writing_paper'
| 'stationery_stores_office_and_school_supply_stores'
| 'swimming_pools_sales'
| 't_ui_travel_germany'
| 'tailors_alterations'
| 'tax_payments_government_agencies'
| 'tax_preparation_services'
| 'taxicabs_limousines'
| 'telecommunication_equipment_and_telephone_sales'
| 'telecommunication_services'
| 'telegraph_services'
| 'tent_and_awning_shops'
| 'testing_laboratories'
| 'theatrical_ticket_agencies'
| 'timeshares'
| 'tire_retreading_and_repair'
| 'tolls_bridge_fees'
| 'tourist_attractions_and_exhibits'
| 'towing_services'
| 'trailer_parks_campgrounds'
| 'transportation_services'
| 'travel_agencies_tour_operators'
| 'truck_stop_iteration'
| 'truck_utility_trailer_rentals'
| 'typesetting_plate_making_and_related_services'
| 'typewriter_stores'
| 'u_s_federal_government_agencies_or_departments'
| 'uniforms_commercial_clothing'
| 'used_merchandise_and_secondhand_stores'
| 'utilities'
| 'variety_stores'
| 'veterinary_services'
| 'video_amusement_game_supplies'
| 'video_game_arcades'
| 'video_tape_rental_stores'
| 'vocational_trade_schools'
| 'watch_jewelry_repair'
| 'welding_repair'
| 'wholesale_clubs'
| 'wig_and_toupee_stores'
| 'wires_money_orders'
| 'womens_accessory_and_specialty_shops'
| 'womens_ready_to_wear_stores'
| 'wrecking_and_salvage_yards';
interface SpendingLimit {
/**
* Maximum amount allowed to spend per interval.
*/
amount: number;
/**
* Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) this limit applies to. Omitting this field will apply the limit to all categories.
*/
categories: Array<SpendingLimit.Category> | null;
/**
* Interval (or event) to which the amount applies.
*/
interval: SpendingLimit.Interval;
}
namespace SpendingLimit {
type Category =
| 'ac_refrigeration_repair'
| 'accounting_bookkeeping_services'
| 'advertising_services'
| 'agricultural_cooperative'
| 'airlines_air_carriers'
| 'airports_flying_fields'
| 'ambulance_services'
| 'amusement_parks_carnivals'
| 'antique_reproductions'
| 'antique_shops'
| 'aquariums'
| 'architectural_surveying_services'
| 'art_dealers_and_galleries'
| 'artists_supply_and_craft_shops'
| 'auto_and_home_supply_stores'
| 'auto_body_repair_shops'
| 'auto_paint_shops'
| 'auto_service_shops'
| 'automated_cash_disburse'
| 'automated_fuel_dispensers'
| 'automobile_associations'
| 'automotive_parts_and_accessories_stores'
| 'automotive_tire_stores'
| 'bail_and_bond_payments'
| 'bakeries'
| 'bands_orchestras'
| 'barber_and_beauty_shops'
| 'betting_casino_gambling'
| 'bicycle_shops'
| 'billiard_pool_establishments'
| 'boat_dealers'
| 'boat_rentals_and_leases'
| 'book_stores'
| 'books_periodicals_and_newspapers'
| 'bowling_alleys'
| 'bus_lines'
| 'business_secretarial_schools'
| 'buying_shopping_services'
| 'cable_satellite_and_other_pay_television_and_radio'
| 'camera_and_photographic_supply_stores'
| 'candy_nut_and_confectionery_stores'
| 'car_and_truck_dealers_new_used'
| 'car_and_truck_dealers_used_only'
| 'car_rental_agencies'
| 'car_washes'
| 'carpentry_services'
| 'carpet_upholstery_cleaning'
| 'caterers'
| 'charitable_and_social_service_organizations_fundraising'
| 'chemicals_and_allied_products'
| 'child_care_services'
| 'childrens_and_infants_wear_stores'
| 'chiropodists_podiatrists'
| 'chiropractors'
| 'cigar_stores_and_stands'
| 'civic_social_fraternal_associations'
| 'cleaning_and_maintenance'
| 'clothing_rental'
| 'colleges_universities'
| 'commercial_equipment'
| 'commercial_footwear'
| 'commercial_photography_art_and_graphics'
| 'commuter_transport_and_ferries'
| 'computer_network_services'
| 'computer_programming'
| 'computer_repair'
| 'computer_software_stores'
| 'computers_peripherals_and_software'
| 'concrete_work_services'
| 'construction_materials'
| 'consulting_public_relations'
| 'correspondence_schools'
| 'cosmetic_stores'
| 'counseling_services'
| 'country_clubs'
| 'courier_services'
| 'court_costs'
| 'credit_reporting_agencies'
| 'cruise_lines'
| 'dairy_products_stores'
| 'dance_hall_studios_schools'
| 'dating_escort_services'
| 'dentists_orthodontists'
| 'department_stores'
| 'detective_agencies'
| 'digital_goods_applications'
| 'digital_goods_games'
| 'digital_goods_large_volume'
| 'digital_goods_media'
| 'direct_marketing_catalog_merchant'
| 'direct_marketing_combination_catalog_and_retail_merchant'
| 'direct_marketing_inbound_telemarketing'
| 'direct_marketing_insurance_services'
| 'direct_marketing_other'
| 'direct_marketing_outbound_telemarketing'
| 'direct_marketing_subscription'
| 'direct_marketing_travel'
| 'discount_stores'
| 'doctors'
| 'door_to_door_sales'
| 'drapery_window_covering_and_upholstery_stores'
| 'drinking_places'
| 'drug_stores_and_pharmacies'
| 'drugs_drug_proprietaries_and_druggist_sundries'
| 'dry_cleaners'
| 'durable_goods'
| 'duty_free_stores'
| 'eating_places_restaurants'
| 'educational_services'
| 'electric_razor_stores'
| 'electrical_parts_and_equipment'
| 'electrical_services'
| 'electronics_repair_shops'
| 'electronics_stores'
| 'elementary_secondary_schools'
| 'employment_temp_agencies'
| 'equipment_rental'
| 'exterminating_services'
| 'family_clothing_stores'
| 'fast_food_restaurants'
| 'financial_institutions'
| 'fines_government_administrative_entities'
| 'fireplace_fireplace_screens_and_accessories_stores'
| 'floor_covering_stores'
| 'florists'
| 'florists_supplies_nursery_stock_and_flowers'
| 'freezer_and_locker_meat_provisioners'
| 'fuel_dealers_non_automotive'
| 'funeral_services_crematories'
| 'furniture_home_furnishings_and_equipment_stores_except_appliances'
| 'furniture_repair_refinishing'
| 'furriers_and_fur_shops'
| 'general_services'
| 'gift_card_novelty_and_souvenir_shops'
| 'glass_paint_and_wallpaper_stores'
| 'glassware_crystal_stores'
| 'golf_courses_public'
| 'government_services'
| 'grocery_stores_supermarkets'
| 'hardware_equipment_and_supplies'
| 'hardware_stores'
| 'health_and_beauty_spas'
| 'hearing_aids_sales_and_supplies'
| 'heating_plumbing_a_c'
| 'hobby_toy_and_game_shops'
| 'home_supply_warehouse_stores'
| 'hospitals'
| 'hotels_motels_and_resorts'
| 'household_appliance_stores'
| 'industrial_supplies'
| 'information_retrieval_services'
| 'insurance_default'
| 'insurance_underwriting_premiums'
| 'intra_company_purchases'
| 'jewelry_stores_watches_clocks_and_silverware_stores'
| 'landscaping_services'
| 'laundries'
| 'laundry_cleaning_services'
| 'legal_services_attorneys'
| 'luggage_and_leather_goods_stores'
| 'lumber_building_materials_stores'
| 'manual_cash_disburse'
| 'marinas_service_and_supplies'
| 'masonry_stonework_and_plaster'
| 'massage_parlors'
| 'medical_and_dental_labs'
| 'medical_dental_ophthalmic_and_hospital_equipment_and_supplies'
| 'medical_services'
| 'membership_organizations'
| 'mens_and_boys_clothing_and_accessories_stores'
| 'mens_womens_clothing_stores'
| 'metal_service_centers'
| 'miscellaneous'
| 'miscellaneous_apparel_and_accessory_shops'
| 'miscellaneous_auto_dealers'
| 'miscellaneous_business_services'
| 'miscellaneous_food_stores'
| 'miscellaneous_general_merchandise'
| 'miscellaneous_general_services'
| 'miscellaneous_home_furnishing_specialty_stores'
| 'miscellaneous_publishing_and_printing'
| 'miscellaneous_recreation_services'
| 'miscellaneous_repair_shops'
| 'miscellaneous_specialty_retail'
| 'mobile_home_dealers'
| 'motion_picture_theaters'
| 'motor_freight_carriers_and_trucking'
| 'motor_homes_dealers'
| 'motor_vehicle_supplies_and_new_parts'
| 'motorcycle_shops_and_dealers'
| 'motorcycle_shops_dealers'
| 'music_stores_musical_instruments_pianos_and_sheet_music'
| 'news_dealers_and_newsstands'
| 'non_fi_money_orders'
| 'non_fi_stored_value_card_purchase_load'
| 'nondurable_goods'
| 'nurseries_lawn_and_garden_supply_stores'
| 'nursing_personal_care'
| 'office_and_commercial_furniture'
| 'opticians_eyeglasses'
| 'optometrists_ophthalmologist'
| 'orthopedic_goods_prosthetic_devices'
| 'osteopaths'
| 'package_stores_beer_wine_and_liquor'
| 'paints_varnishes_and_supplies'
| 'parking_lots_garages'
| 'passenger_railways'
| 'pawn_shops'
| 'pet_shops_pet_food_and_supplies'
| 'petroleum_and_petroleum_products'
| 'photo_developing'
| 'photographic_photocopy_microfilm_equipment_and_supplies'
| 'photographic_studios'
| 'picture_video_production'
| 'piece_goods_notions_and_other_dry_goods'
| 'plumbing_heating_equipment_and_supplies'
| 'political_organizations'
| 'postal_services_government_only'
| 'precious_stones_and_metals_watches_and_jewelry'
| 'professional_services'
| 'public_warehousing_and_storage'
| 'quick_copy_repro_and_blueprint'
| 'railroads'
| 'real_estate_agents_and_managers_rentals'
| 'record_stores'
| 'recreational_vehicle_rentals'
| 'religious_goods_stores'
| 'religious_organizations'
| 'roofing_siding_sheet_metal'
| 'secretarial_support_services'
| 'security_brokers_dealers'
| 'service_stations'
| 'sewing_needlework_fabric_and_piece_goods_stores'
| 'shoe_repair_hat_cleaning'
| 'shoe_stores'
| 'small_appliance_repair'
| 'snowmobile_dealers'
| 'special_trade_services'
| 'specialty_cleaning'
| 'sporting_goods_stores'
| 'sporting_recreation_camps'
| 'sports_and_riding_apparel_stores'
| 'sports_clubs_fields'
| 'stamp_and_coin_stores'
| 'stationary_office_supplies_printing_and_writing_paper'
| 'stationery_stores_office_and_school_supply_stores'
| 'swimming_pools_sales'
| 't_ui_travel_germany'
| 'tailors_alterations'
| 'tax_payments_government_agencies'
| 'tax_preparation_services'
| 'taxicabs_limousines'
| 'telecommunication_equipment_and_telephone_sales'
| 'telecommunication_services'
| 'telegraph_services'
| 'tent_and_awning_shops'
| 'testing_laboratories'
| 'theatrical_ticket_agencies'
| 'timeshares'
| 'tire_retreading_and_repair'
| 'tolls_bridge_fees'
| 'tourist_attractions_and_exhibits'
| 'towing_services'
| 'trailer_parks_campgrounds'
| 'transportation_services'
| 'travel_agencies_tour_operators'
| 'truck_stop_iteration'
| 'truck_utility_trailer_rentals'
| 'typesetting_plate_making_and_related_services'
| 'typewriter_stores'
| 'u_s_federal_government_agencies_or_departments'
| 'uniforms_commercial_clothing'
| 'used_merchandise_and_secondhand_stores'
| 'utilities'
| 'variety_stores'
| 'veterinary_services'
| 'video_amusement_game_supplies'
| 'video_game_arcades'
| 'video_tape_rental_stores'
| 'vocational_trade_schools'
| 'watch_jewelry_repair'
| 'welding_repair'
| 'wholesale_clubs'
| 'wig_and_toupee_stores'
| 'wires_money_orders'
| 'womens_accessory_and_specialty_shops'
| 'womens_ready_to_wear_stores'
| 'wrecking_and_salvage_yards';
type Interval =
| 'all_time'
| 'daily'
| 'monthly'
| 'per_authorization'
| 'weekly'
| 'yearly';
}
}
type Status = 'active' | 'blocked' | 'inactive';
type Type = 'company' | 'individual';
}
interface CardholderCreateParams {
/**
* The cardholder's billing address.
*/
billing: CardholderCreateParams.Billing;
/**
* The cardholder's name. This will be printed on cards issued to them.
*/
name: string;
/**
* One of `individual` or `company`.
*/
type: CardholderCreateParams.Type;
/**
* Additional information about a `company` cardholder.
*/
company?: CardholderCreateParams.Company;
/**
* The cardholder's email address.
*/
email?: string;
/**
* Specifies which fields in the response should be expanded.
*/
expand?: Array<string>;
/**
* Additional information about an `individual` cardholder.
*/
individual?: CardholderCreateParams.Individual;
/**
* Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`.
*/
metadata?: Stripe.MetadataParam;
/**
* The cardholder's phone number. This will be transformed to [E.164](https://en.wikipedia.org/wiki/E.164) if it is not provided in that format already. This is required for all cardholders who will be creating EU cards. See the [3D Secure documentation](https://stripe.com/docs/issuing/3d-secure#when-is-3d-secure-applied) for more details.
*/
phone_number?: string;
/**
* Rules that control spending across this cardholder's cards. Refer to our [documentation](https://stripe.com/docs/issuing/controls/spending-controls) for more details.
*/
spending_controls?: CardholderCreateParams.SpendingControls;
/**
* Specifies whether to permit authorizations on this cardholder's cards. Defaults to `active`.
*/
status?: CardholderCreateParams.Status;
}
namespace CardholderCreateParams {
interface Billing {
/**
* The cardholder's billing address.
*/
address: Billing.Address;
}
namespace Billing {
interface Address {
/**
* City, district, suburb, town, or village.
*/
city: string;
/**
* Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)).
*/
country: string;
/**
* Address line 1 (e.g., street, PO Box, or company name).
*/
line1: string;
/**
* Address line 2 (e.g., apartment, suite, unit, or building).
*/
line2?: string;
/**
* ZIP or postal code.
*/
postal_code: string;
/**
* State, county, province, or region.
*/
state?: string;
}
}
interface Company {
/**
* The entity's business ID number.
*/
tax_id?: string;
}
interface Individual {
/**
* The date of birth of this cardholder.
*/
dob?: Individual.Dob;
/**
* The first name of this cardholder.
*/
first_name: string;
/**
* The last name of this cardholder.
*/
last_name: string;
/**
* Government-issued ID document for this cardholder.
*/
verification?: Individual.Verification;
}
namespace Individual {
interface Dob {
/**
* The day of birth, between 1 and 31.
*/
day: number;
/**
* The month of birth, between 1 and 12.
*/
month: number;
/**
* The four-digit year of birth.
*/
year: number;
}
interface Verification {
/**
* An identifying document, either a passport or local ID card.
*/
document?: Verification.Document;
}
namespace Verification {
interface Document {
/**
* The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`.
*/
back?: string;
/**
* The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`.
*/
front?: string;
}
}
}
interface SpendingControls {
/**
* Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to allow. All other categories will be blocked. Cannot be set with `blocked_categories`.
*/
allowed_categories?: Array<SpendingControls.AllowedCategory>;
/**
* Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to decline. All other categories will be allowed. Cannot be set with `allowed_categories`.
*/
blocked_categories?: Array<SpendingControls.BlockedCategory>;
/**
* Limit spending with amount-based rules that apply across this cardholder's cards.
*/
spending_limits?: Array<SpendingControls.SpendingLimit>;
/**
* Currency of amounts within `spending_limits`. Defaults to your merchant country's currency.
*/
spending_limits_currency?: string;
}
namespace SpendingControls {
type AllowedCategory =
| 'ac_refrigeration_repair'
| 'accounting_bookkeeping_services'
| 'advertising_services'
| 'agricultural_cooperative'
| 'airlines_air_carriers'
| 'airports_flying_fields'
| 'ambulance_services'
| 'amusement_parks_carnivals'
| 'antique_reproductions'
| 'antique_shops'
| 'aquariums'
| 'architectural_surveying_services'
| 'art_dealers_and_galleries'
| 'artists_supply_and_craft_shops'
| 'auto_and_home_supply_stores'
| 'auto_body_repair_shops'
| 'auto_paint_shops'
| 'auto_service_shops'
| 'automated_cash_disburse'
| 'automated_fuel_dispensers'
| 'automobile_associations'
| 'automotive_parts_and_accessories_stores'
| 'automotive_tire_stores'
| 'bail_and_bond_payments'
| 'bakeries'
| 'bands_orchestras'
| 'barber_and_beauty_shops'
| 'betting_casino_gambling'
| 'bicycle_shops'
| 'billiard_pool_establishments'
| 'boat_dealers'
| 'boat_rentals_and_leases'
| 'book_stores'
| 'books_periodicals_and_newspapers'
| 'bowling_alleys'
| 'bus_lines'
| 'business_secretarial_schools'
| 'buying_shopping_services'
| 'cable_satellite_and_other_pay_television_and_radio'
| 'camera_and_photographic_supply_stores'
| 'candy_nut_and_confectionery_stores'
| 'car_and_truck_dealers_new_used'
| 'car_and_truck_dealers_used_only'
| 'car_rental_agencies'
| 'car_washes'
| 'carpentry_services'
| 'carpet_upholstery_cleaning'
| 'caterers'
| 'charitable_and_social_service_organizations_fundraising'
| 'chemicals_and_allied_products'
| 'child_care_services'
| 'childrens_and_infants_wear_stores'
| 'chiropodists_podiatrists'
| 'chiropractors'
| 'cigar_stores_and_stands'
| 'civic_social_fraternal_associations'
| 'cleaning_and_maintenance'
| 'clothing_rental'
| 'colleges_universities'
| 'commercial_equipment'
| 'commercial_footwear'
| 'commercial_photography_art_and_graphics'
| 'commuter_transport_and_ferries'
| 'computer_network_services'
| 'computer_programming'
| 'computer_repair'
| 'computer_software_stores'
| 'computers_peripherals_and_software'
| 'concrete_work_services'
| 'construction_materials'
| 'consulting_public_relations'
| 'correspondence_schools'
| 'cosmetic_stores'
| 'counseling_services'
| 'country_clubs'
| 'courier_services'
| 'court_costs'
| 'credit_reporting_agencies'
| 'cruise_lines'
| 'dairy_products_stores'
| 'dance_hall_studios_schools'
| 'dating_escort_services'
| 'dentists_orthodontists'
| 'department_stores'
| 'detective_agencies'
| 'digital_goods_applications'
| 'digital_goods_games'
| 'digital_goods_large_volume'
| 'digital_goods_media'
| 'direct_marketing_catalog_merchant'
| 'direct_marketing_combination_catalog_and_retail_merchant'
| 'direct_marketing_inbound_telemarketing'
| 'direct_marketing_insurance_services'
| 'direct_marketing_other'
| 'direct_marketing_outbound_telemarketing'
| 'direct_marketing_subscription'
| 'direct_marketing_travel'
| 'discount_stores'
| 'doctors'
| 'door_to_door_sales'
| 'drapery_window_covering_and_upholstery_stores'
| 'drinking_places'
| 'drug_stores_and_pharmacies'
| 'drugs_drug_proprietaries_and_druggist_sundries'
| 'dry_cleaners'
| 'durable_goods'
| 'duty_free_stores'
| 'eating_places_restaurants'
| 'educational_services'
| 'electric_razor_stores'
| 'electrical_parts_and_equipment'
| 'electrical_services'
| 'electronics_repair_shops'
| 'electronics_stores'
| 'elementary_secondary_schools'
| 'employment_temp_agencies'
| 'equipment_rental'
| 'exterminating_services'
| 'family_clothing_stores'
| 'fast_food_restaurants'
| 'financial_institutions'
| 'fines_government_administrative_entities'
| 'fireplace_fireplace_screens_and_accessories_stores'
| 'floor_covering_stores'
| 'florists'
| 'florists_supplies_nursery_stock_and_flowers'
| 'freezer_and_locker_meat_provisioners'
| 'fuel_dealers_non_automotive'
| 'funeral_services_crematories'
| 'furniture_home_furnishings_and_equipment_stores_except_appliances'
| 'furniture_repair_refinishing'
| 'furriers_and_fur_shops'
| 'general_services'
| 'gift_card_novelty_and_souvenir_shops'
| 'glass_paint_and_wallpaper_stores'
| 'glassware_crystal_stores'
| 'golf_courses_public'
| 'government_services'
| 'grocery_stores_supermarkets'
| 'hardware_equipment_and_supplies'
| 'hardware_stores'
| 'health_and_beauty_spas'
| 'hearing_aids_sales_and_supplies'
| 'heating_plumbing_a_c'
| 'hobby_toy_and_game_shops'
| 'home_supply_warehouse_stores'
| 'hospitals'
| 'hotels_motels_and_resorts'
| 'household_appliance_stores'
| 'industrial_supplies'
| 'information_retrieval_services'
| 'insurance_default'
| 'insurance_underwriting_premiums'
| 'intra_company_purchases'
| 'jewelry_stores_watches_clocks_and_silverware_stores'
| 'landscaping_services'
| 'laundries'
| 'laundry_cleaning_services'
| 'legal_services_attorneys'
| 'luggage_and_leather_goods_stores'
| 'lumber_building_materials_stores'
| 'manual_cash_disburse'
| 'marinas_service_and_supplies'
| 'masonry_stonework_and_plaster'
| 'massage_parlors'
| 'medical_and_dental_labs'
| 'medical_dental_ophthalmic_and_hospital_equipment_and_supplies'
| 'medical_services'
| 'membership_organizations'
| 'mens_and_boys_clothing_and_accessories_stores'
| 'mens_womens_clothing_stores'
| 'metal_service_centers'
| 'miscellaneous'
| 'miscellaneous_apparel_and_accessory_shops'
| 'miscellaneous_auto_dealers'
| 'miscellaneous_business_services'
| 'miscellaneous_food_stores'
| 'miscellaneous_general_merchandise'
| 'miscellaneous_general_services'
| 'miscellaneous_home_furnishing_specialty_stores'
| 'miscellaneous_publishing_and_printing'
| 'miscellaneous_recreation_services'
| 'miscellaneous_repair_shops'
| 'miscellaneous_specialty_retail'
| 'mobile_home_dealers'
| 'motion_picture_theaters'
| 'motor_freight_carriers_and_trucking'
| 'motor_homes_dealers'
| 'motor_vehicle_supplies_and_new_parts'
| 'motorcycle_shops_and_dealers'
| 'motorcycle_shops_dealers'
| 'music_stores_musical_instruments_pianos_and_sheet_music'
| 'news_dealers_and_newsstands'
| 'non_fi_money_orders'
| 'non_fi_stored_value_card_purchase_load'
| 'nondurable_goods'
| 'nurseries_lawn_and_garden_supply_stores'
| 'nursing_personal_care'
| 'office_and_commercial_furniture'
| 'opticians_eyeglasses'
| 'optometrists_ophthalmologist'
| 'orthopedic_goods_prosthetic_devices'
| 'osteopaths'
| 'package_stores_beer_wine_and_liquor'
| 'paints_varnishes_and_supplies'
| 'parking_lots_garages'
| 'passenger_railways'
| 'pawn_shops'
| 'pet_shops_pet_food_and_supplies'
| 'petroleum_and_petroleum_products'
| 'photo_developing'
| 'photographic_photocopy_microfilm_equipment_and_supplies'
| 'photographic_studios'
| 'picture_video_production'
| 'piece_goods_notions_and_other_dry_goods'
| 'plumbing_heating_equipment_and_supplies'
| 'political_organizations'
| 'postal_services_government_only'
| 'precious_stones_and_metals_watches_and_jewelry'
| 'professional_services'
| 'public_warehousing_and_storage'
| 'quick_copy_repro_and_blueprint'
| 'railroads'
| 'real_estate_agents_and_managers_rentals'
| 'record_stores'
| 'recreational_vehicle_rentals'
| 'religious_goods_stores'
| 'religious_organizations'
| 'roofing_siding_sheet_metal'
| 'secretarial_support_services'
| 'security_brokers_dealers'
| 'service_stations'
| 'sewing_needlework_fabric_and_piece_goods_stores'
| 'shoe_repair_hat_cleaning'
| 'shoe_stores'
| 'small_appliance_repair'
| 'snowmobile_dealers'
| 'special_trade_services'
| 'specialty_cleaning'
| 'sporting_goods_stores'
| 'sporting_recreation_camps'
| 'sports_and_riding_apparel_stores'
| 'sports_clubs_fields'
| 'stamp_and_coin_stores'
| 'stationary_office_supplies_printing_and_writing_paper'
| 'stationery_stores_office_and_school_supply_stores'
| 'swimming_pools_sales'
| 't_ui_travel_germany'
| 'tailors_alterations'
| 'tax_payments_government_agencies'
| 'tax_preparation_services'
| 'taxicabs_limousines'
| 'telecommunication_equipment_and_telephone_sales'
| 'telecommunication_services'
| 'telegraph_services'
| 'tent_and_awning_shops'
| 'testing_laboratories'
| 'theatrical_ticket_agencies'
| 'timeshares'
| 'tire_retreading_and_repair'
| 'tolls_bridge_fees'
| 'tourist_attractions_and_exhibits'
| 'towing_services'
| 'trailer_parks_campgrounds'
| 'transportation_services'
| 'travel_agencies_tour_operators'
| 'truck_stop_iteration'
| 'truck_utility_trailer_rentals'
| 'typesetting_plate_making_and_related_services'
| 'typewriter_stores'
| 'u_s_federal_government_agencies_or_departments'
| 'uniforms_commercial_clothing'
| 'used_merchandise_and_secondhand_stores'
| 'utilities'
| 'variety_stores'
| 'veterinary_services'
| 'video_amusement_game_supplies'
| 'video_game_arcades'
| 'video_tape_rental_stores'
| 'vocational_trade_schools'
| 'watch_jewelry_repair'
| 'welding_repair'
| 'wholesale_clubs'
| 'wig_and_toupee_stores'
| 'wires_money_orders'
| 'womens_accessory_and_specialty_shops'
| 'womens_ready_to_wear_stores'
| 'wrecking_and_salvage_yards';
type BlockedCategory =
| 'ac_refrigeration_repair'
| 'accounting_bookkeeping_services'
| 'advertising_services'
| 'agricultural_cooperative'
| 'airlines_air_carriers'
| 'airports_flying_fields'
| 'ambulance_services'
| 'amusement_parks_carnivals'
| 'antique_reproductions'
| 'antique_shops'
| 'aquariums'
| 'architectural_surveying_services'
| 'art_dealers_and_galleries'
| 'artists_supply_and_craft_shops'
| 'auto_and_home_supply_stores'
| 'auto_body_repair_shops'
| 'auto_paint_shops'
| 'auto_service_shops'
| 'automated_cash_disburse'
| 'automated_fuel_dispensers'
| 'automobile_associations'
| 'automotive_parts_and_accessories_stores'
| 'automotive_tire_stores'
| 'bail_and_bond_payments'
| 'bakeries'
| 'bands_orchestras'
| 'barber_and_beauty_shops'
| 'betting_casino_gambling'
| 'bicycle_shops'
| 'billiard_pool_establishments'
| 'boat_dealers'
| 'boat_rentals_and_leases'
| 'book_stores'
| 'books_periodicals_and_newspapers'
| 'bowling_alleys'
| 'bus_lines'
| 'business_secretarial_schools'
| 'buying_shopping_services'
| 'cable_satellite_and_other_pay_television_and_radio'
| 'camera_and_photographic_supply_stores'
| 'candy_nut_and_confectionery_stores'
| 'car_and_truck_dealers_new_used'
| 'car_and_truck_dealers_used_only'
| 'car_rental_agencies'
| 'car_washes'
| 'carpentry_services'
| 'carpet_upholstery_cleaning'
| 'caterers'
| 'charitable_and_social_service_organizations_fundraising'
| 'chemicals_and_allied_products'
| 'child_care_services'
| 'childrens_and_infants_wear_stores'
| 'chiropodists_podiatrists'
| 'chiropractors'
| 'cigar_stores_and_stands'
| 'civic_social_fraternal_associations'
| 'cleaning_and_maintenance'
| 'clothing_rental'
| 'colleges_universities'
| 'commercial_equipment'
| 'commercial_footwear'
| 'commercial_photography_art_and_graphics'
| 'commuter_transport_and_ferries'
| 'computer_network_services'
| 'computer_programming'
| 'computer_repair'
| 'computer_software_stores'
| 'computers_peripherals_and_software'
| 'concrete_work_services'
| 'construction_materials'
| 'consulting_public_relations'
| 'correspondence_schools'
| 'cosmetic_stores'
| 'counseling_services'
| 'country_clubs'
| 'courier_services'
| 'court_costs'
| 'credit_reporting_agencies'
| 'cruise_lines'
| 'dairy_products_stores'
| 'dance_hall_studios_schools'
| 'dating_escort_services'
| 'dentists_orthodontists'
| 'department_stores'
| 'detective_agencies'
| 'digital_goods_applications'
| 'digital_goods_games'
| 'digital_goods_large_volume'
| 'digital_goods_media'
| 'direct_marketing_catalog_merchant'
| 'direct_marketing_combination_catalog_and_retail_merchant'
| 'direct_marketing_inbound_telemarketing'
| 'direct_marketing_insurance_services'
| 'direct_marketing_other'
| 'direct_marketing_outbound_telemarketing'
| 'direct_marketing_subscription'
| 'direct_marketing_travel'
| 'discount_stores'
| 'doctors'
| 'door_to_door_sales'
| 'drapery_window_covering_and_upholstery_stores'
| 'drinking_places'
| 'drug_stores_and_pharmacies'
| 'drugs_drug_proprietaries_and_druggist_sundries'
| 'dry_cleaners'
| 'durable_goods'
| 'duty_free_stores'
| 'eating_places_restaurants'
| 'educational_services'
| 'electric_razor_stores'
| 'electrical_parts_and_equipment'
| 'electrical_services'
| 'electronics_repair_shops'
| 'electronics_stores'
| 'elementary_secondary_schools'
| 'employment_temp_agencies'
| 'equipment_rental'
| 'exterminating_services'
| 'family_clothing_stores'
| 'fast_food_restaurants'
| 'financial_institutions'
| 'fines_government_administrative_entities'
| 'fireplace_fireplace_screens_and_accessories_stores'
| 'floor_covering_stores'
| 'florists'
| 'florists_supplies_nursery_stock_and_flowers'
| 'freezer_and_locker_meat_provisioners'
| 'fuel_dealers_non_automotive'
| 'funeral_services_crematories'
| 'furniture_home_furnishings_and_equipment_stores_except_appliances'
| 'furniture_repair_refinishing'
| 'furriers_and_fur_shops'
| 'general_services'
| 'gift_card_novelty_and_souvenir_shops'
| 'glass_paint_and_wallpaper_stores'
| 'glassware_crystal_stores'
| 'golf_courses_public'
| 'government_services'
| 'grocery_stores_supermarkets'
| 'hardware_equipment_and_supplies'
| 'hardware_stores'
| 'health_and_beauty_spas'
| 'hearing_aids_sales_and_supplies'
| 'heating_plumbing_a_c'
| 'hobby_toy_and_game_shops'
| 'home_supply_warehouse_stores'
| 'hospitals'
| 'hotels_motels_and_resorts'
| 'household_appliance_stores'
| 'industrial_supplies'
| 'information_retrieval_services'
| 'insurance_default'
| 'insurance_underwriting_premiums'
| 'intra_company_purchases'
| 'jewelry_stores_watches_clocks_and_silverware_stores'
| 'landscaping_services'
| 'laundries'
| 'laundry_cleaning_services'
| 'legal_services_attorneys'
| 'luggage_and_leather_goods_stores'
| 'lumber_building_materials_stores'
| 'manual_cash_disburse'
| 'marinas_service_and_supplies'
| 'masonry_stonework_and_plaster'
| 'massage_parlors'
| 'medical_and_dental_labs'
| 'medical_dental_ophthalmic_and_hospital_equipment_and_supplies'
| 'medical_services'
| 'membership_organizations'
| 'mens_and_boys_clothing_and_accessories_stores'
| 'mens_womens_clothing_stores'
| 'metal_service_centers'
| 'miscellaneous'
| 'miscellaneous_apparel_and_accessory_shops'
| 'miscellaneous_auto_dealers'
| 'miscellaneous_business_services'
| 'miscellaneous_food_stores'
| 'miscellaneous_general_merchandise'
| 'miscellaneous_general_services'
| 'miscellaneous_home_furnishing_specialty_stores'
| 'miscellaneous_publishing_and_printing'
| 'miscellaneous_recreation_services'
| 'miscellaneous_repair_shops'
| 'miscellaneous_specialty_retail'
| 'mobile_home_dealers'
| 'motion_picture_theaters'
| 'motor_freight_carriers_and_trucking'
| 'motor_homes_dealers'
| 'motor_vehicle_supplies_and_new_parts'
| 'motorcycle_shops_and_dealers'
| 'motorcycle_shops_dealers'
| 'music_stores_musical_instruments_pianos_and_sheet_music'
| 'news_dealers_and_newsstands'
| 'non_fi_money_orders'
| 'non_fi_stored_value_card_purchase_load'
| 'nondurable_goods'
| 'nurseries_lawn_and_garden_supply_stores'
| 'nursing_personal_care'
| 'office_and_commercial_furniture'
| 'opticians_eyeglasses'
| 'optometrists_ophthalmologist'
| 'orthopedic_goods_prosthetic_devices'
| 'osteopaths'
| 'package_stores_beer_wine_and_liquor'
| 'paints_varnishes_and_supplies'
| 'parking_lots_garages'
| 'passenger_railways'
| 'pawn_shops'
| 'pet_shops_pet_food_and_supplies'
| 'petroleum_and_petroleum_products'
| 'photo_developing'
| 'photographic_photocopy_microfilm_equipment_and_supplies'
| 'photographic_studios'
| 'picture_video_production'
| 'piece_goods_notions_and_other_dry_goods'
| 'plumbing_heating_equipment_and_supplies'
| 'political_organizations'
| 'postal_services_government_only'
| 'precious_stones_and_metals_watches_and_jewelry'
| 'professional_services'
| 'public_warehousing_and_storage'
| 'quick_copy_repro_and_blueprint'
| 'railroads'
| 'real_estate_agents_and_managers_rentals'
| 'record_stores'
| 'recreational_vehicle_rentals'
| 'religious_goods_stores'
| 'religious_organizations'
| 'roofing_siding_sheet_metal'
| 'secretarial_support_services'
| 'security_brokers_dealers'
| 'service_stations'
| 'sewing_needlework_fabric_and_piece_goods_stores'
| 'shoe_repair_hat_cleaning'
| 'shoe_stores'
| 'small_appliance_repair'
| 'snowmobile_dealers'
| 'special_trade_services'
| 'specialty_cleaning'
| 'sporting_goods_stores'
| 'sporting_recreation_camps'
| 'sports_and_riding_apparel_stores'
| 'sports_clubs_fields'
| 'stamp_and_coin_stores'
| 'stationary_office_supplies_printing_and_writing_paper'
| 'stationery_stores_office_and_school_supply_stores'
| 'swimming_pools_sales'
| 't_ui_travel_germany'
| 'tailors_alterations'
| 'tax_payments_government_agencies'
| 'tax_preparation_services'
| 'taxicabs_limousines'
| 'telecommunication_equipment_and_telephone_sales'
| 'telecommunication_services'
| 'telegraph_services'
| 'tent_and_awning_shops'
| 'testing_laboratories'
| 'theatrical_ticket_agencies'
| 'timeshares'
| 'tire_retreading_and_repair'
| 'tolls_bridge_fees'
| 'tourist_attractions_and_exhibits'
| 'towing_services'
| 'trailer_parks_campgrounds'
| 'transportation_services'
| 'travel_agencies_tour_operators'
| 'truck_stop_iteration'
| 'truck_utility_trailer_rentals'
| 'typesetting_plate_making_and_related_services'
| 'typewriter_stores'
| 'u_s_federal_government_agencies_or_departments'
| 'uniforms_commercial_clothing'
| 'used_merchandise_and_secondhand_stores'
| 'utilities'
| 'variety_stores'
| 'veterinary_services'
| 'video_amusement_game_supplies'
| 'video_game_arcades'
| 'video_tape_rental_stores'
| 'vocational_trade_schools'
| 'watch_jewelry_repair'
| 'welding_repair'
| 'wholesale_clubs'
| 'wig_and_toupee_stores'
| 'wires_money_orders'
| 'womens_accessory_and_specialty_shops'
| 'womens_ready_to_wear_stores'
| 'wrecking_and_salvage_yards';
interface SpendingLimit {
/**
* Maximum amount allowed to spend per interval.
*/
amount: number;
/**
* Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) this limit applies to. Omitting this field will apply the limit to all categories.
*/
categories?: Array<SpendingLimit.Category>;
/**
* Interval (or event) to which the amount applies.
*/
interval: SpendingLimit.Interval;
}
namespace SpendingLimit {
type Category =
| 'ac_refrigeration_repair'
| 'accounting_bookkeeping_services'
| 'advertising_services'
| 'agricultural_cooperative'
| 'airlines_air_carriers'
| 'airports_flying_fields'
| 'ambulance_services'
| 'amusement_parks_carnivals'
| 'antique_reproductions'
| 'antique_shops'
| 'aquariums'
| 'architectural_surveying_services'
| 'art_dealers_and_galleries'
| 'artists_supply_and_craft_shops'
| 'auto_and_home_supply_stores'
| 'auto_body_repair_shops'
| 'auto_paint_shops'
| 'auto_service_shops'
| 'automated_cash_disburse'
| 'automated_fuel_dispensers'
| 'automobile_associations'
| 'automotive_parts_and_accessories_stores'
| 'automotive_tire_stores'
| 'bail_and_bond_payments'
| 'bakeries'
| 'bands_orchestras'
| 'barber_and_beauty_shops'
| 'betting_casino_gambling'
| 'bicycle_shops'
| 'billiard_pool_establishments'
| 'boat_dealers'
| 'boat_rentals_and_leases'
| 'book_stores'
| 'books_periodicals_and_newspapers'
| 'bowling_alleys'
| 'bus_lines'
| 'business_secretarial_schools'
| 'buying_shopping_services'
| 'cable_satellite_and_other_pay_television_and_radio'
| 'camera_and_photographic_supply_stores'
| 'candy_nut_and_confectionery_stores'
| 'car_and_truck_dealers_new_used'
| 'car_and_truck_dealers_used_only'
| 'car_rental_agencies'
| 'car_washes'
| 'carpentry_services'
| 'carpet_upholstery_cleaning'
| 'caterers'
| 'charitable_and_social_service_organizations_fundraising'
| 'chemicals_and_allied_products'
| 'child_care_services'
| 'childrens_and_infants_wear_stores'
| 'chiropodists_podiatrists'
| 'chiropractors'
| 'cigar_stores_and_stands'
| 'civic_social_fraternal_associations'
| 'cleaning_and_maintenance'
| 'clothing_rental'
| 'colleges_universities'
| 'commercial_equipment'
| 'commercial_footwear'
| 'commercial_photography_art_and_graphics'
| 'commuter_transport_and_ferries'
| 'computer_network_services'
| 'computer_programming'
| 'computer_repair'
| 'computer_software_stores'
| 'computers_peripherals_and_software'
| 'concrete_work_services'
| 'construction_materials'
| 'consulting_public_relations'
| 'correspondence_schools'
| 'cosmetic_stores'
| 'counseling_services'
| 'country_clubs'
| 'courier_services'
| 'court_costs'
| 'credit_reporting_agencies'
| 'cruise_lines'
| 'dairy_products_stores'
| 'dance_hall_studios_schools'
| 'dating_escort_services'
| 'dentists_orthodontists'
| 'department_stores'
| 'detective_agencies'
| 'digital_goods_applications'
| 'digital_goods_games'
| 'digital_goods_large_volume'
| 'digital_goods_media'
| 'direct_marketing_catalog_merchant'
| 'direct_marketing_combination_catalog_and_retail_merchant'
| 'direct_marketing_inbound_telemarketing'
| 'direct_marketing_insurance_services'
| 'direct_marketing_other'
| 'direct_marketing_outbound_telemarketing'
| 'direct_marketing_subscription'
| 'direct_marketing_travel'
| 'discount_stores'
| 'doctors'
| 'door_to_door_sales'
| 'drapery_window_covering_and_upholstery_stores'
| 'drinking_places'
| 'drug_stores_and_pharmacies'
| 'drugs_drug_proprietaries_and_druggist_sundries'
| 'dry_cleaners'
| 'durable_goods'
| 'duty_free_stores'
| 'eating_places_restaurants'
| 'educational_services'
| 'electric_razor_stores'
| 'electrical_parts_and_equipment'
| 'electrical_services'
| 'electronics_repair_shops'
| 'electronics_stores'
| 'elementary_secondary_schools'
| 'employment_temp_agencies'
| 'equipment_rental'
| 'exterminating_services'
| 'family_clothing_stores'
| 'fast_food_restaurants'
| 'financial_institutions'
| 'fines_government_administrative_entities'
| 'fireplace_fireplace_screens_and_accessories_stores'
| 'floor_covering_stores'
| 'florists'
| 'florists_supplies_nursery_stock_and_flowers'
| 'freezer_and_locker_meat_provisioners'
| 'fuel_dealers_non_automotive'
| 'funeral_services_crematories'
| 'furniture_home_furnishings_and_equipment_stores_except_appliances'
| 'furniture_repair_refinishing'
| 'furriers_and_fur_shops'
| 'general_services'
| 'gift_card_novelty_and_souvenir_shops'
| 'glass_paint_and_wallpaper_stores'
| 'glassware_crystal_stores'
| 'golf_courses_public'
| 'government_services'
| 'grocery_stores_supermarkets'
| 'hardware_equipment_and_supplies'
| 'hardware_stores'
| 'health_and_beauty_spas'
| 'hearing_aids_sales_and_supplies'
| 'heating_plumbing_a_c'
| 'hobby_toy_and_game_shops'
| 'home_supply_warehouse_stores'
| 'hospitals'
| 'hotels_motels_and_resorts'
| 'household_appliance_stores'
| 'industrial_supplies'
| 'information_retrieval_services'
| 'insurance_default'
| 'insurance_underwriting_premiums'
| 'intra_company_purchases'
| 'jewelry_stores_watches_clocks_and_silverware_stores'
| 'landscaping_services'
| 'laundries'
| 'laundry_cleaning_services'
| 'legal_services_attorneys'
| 'luggage_and_leather_goods_stores'
| 'lumber_building_materials_stores'
| 'manual_cash_disburse'
| 'marinas_service_and_supplies'
| 'masonry_stonework_and_plaster'
| 'massage_parlors'
| 'medical_and_dental_labs'
| 'medical_dental_ophthalmic_and_hospital_equipment_and_supplies'
| 'medical_services'
| 'membership_organizations'
| 'mens_and_boys_clothing_and_accessories_stores'
| 'mens_womens_clothing_stores'
| 'metal_service_centers'
| 'miscellaneous'
| 'miscellaneous_apparel_and_accessory_shops'
| 'miscellaneous_auto_dealers'
| 'miscellaneous_business_services'
| 'miscellaneous_food_stores'
| 'miscellaneous_general_merchandise'
| 'miscellaneous_general_services'
| 'miscellaneous_home_furnishing_specialty_stores'
| 'miscellaneous_publishing_and_printing'
| 'miscellaneous_recreation_services'
| 'miscellaneous_repair_shops'
| 'miscellaneous_specialty_retail'
| 'mobile_home_dealers'
| 'motion_picture_theaters'
| 'motor_freight_carriers_and_trucking'
| 'motor_homes_dealers'
| 'motor_vehicle_supplies_and_new_parts'
| 'motorcycle_shops_and_dealers'
| 'motorcycle_shops_dealers'
| 'music_stores_musical_instruments_pianos_and_sheet_music'
| 'news_dealers_and_newsstands'
| 'non_fi_money_orders'
| 'non_fi_stored_value_card_purchase_load'
| 'nondurable_goods'
| 'nurseries_lawn_and_garden_supply_stores'
| 'nursing_personal_care'
| 'office_and_commercial_furniture'
| 'opticians_eyeglasses'
| 'optometrists_ophthalmologist'
| 'orthopedic_goods_prosthetic_devices'
| 'osteopaths'
| 'package_stores_beer_wine_and_liquor'
| 'paints_varnishes_and_supplies'
| 'parking_lots_garages'
| 'passenger_railways'
| 'pawn_shops'
| 'pet_shops_pet_food_and_supplies'
| 'petroleum_and_petroleum_products'
| 'photo_developing'
| 'photographic_photocopy_microfilm_equipment_and_supplies'
| 'photographic_studios'
| 'picture_video_production'
| 'piece_goods_notions_and_other_dry_goods'
| 'plumbing_heating_equipment_and_supplies'
| 'political_organizations'
| 'postal_services_government_only'
| 'precious_stones_and_metals_watches_and_jewelry'
| 'professional_services'
| 'public_warehousing_and_storage'
| 'quick_copy_repro_and_blueprint'
| 'railroads'
| 'real_estate_agents_and_managers_rentals'
| 'record_stores'
| 'recreational_vehicle_rentals'
| 'religious_goods_stores'
| 'religious_organizations'
| 'roofing_siding_sheet_metal'
| 'secretarial_support_services'
| 'security_brokers_dealers'
| 'service_stations'
| 'sewing_needlework_fabric_and_piece_goods_stores'
| 'shoe_repair_hat_cleaning'
| 'shoe_stores'
| 'small_appliance_repair'
| 'snowmobile_dealers'
| 'special_trade_services'
| 'specialty_cleaning'
| 'sporting_goods_stores'
| 'sporting_recreation_camps'
| 'sports_and_riding_apparel_stores'
| 'sports_clubs_fields'
| 'stamp_and_coin_stores'
| 'stationary_office_supplies_printing_and_writing_paper'
| 'stationery_stores_office_and_school_supply_stores'
| 'swimming_pools_sales'
| 't_ui_travel_germany'
| 'tailors_alterations'
| 'tax_payments_government_agencies'
| 'tax_preparation_services'
| 'taxicabs_limousines'
| 'telecommunication_equipment_and_telephone_sales'
| 'telecommunication_services'
| 'telegraph_services'
| 'tent_and_awning_shops'
| 'testing_laboratories'
| 'theatrical_ticket_agencies'
| 'timeshares'
| 'tire_retreading_and_repair'
| 'tolls_bridge_fees'
| 'tourist_attractions_and_exhibits'
| 'towing_services'
| 'trailer_parks_campgrounds'
| 'transportation_services'
| 'travel_agencies_tour_operators'
| 'truck_stop_iteration'
| 'truck_utility_trailer_rentals'
| 'typesetting_plate_making_and_related_services'
| 'typewriter_stores'
| 'u_s_federal_government_agencies_or_departments'
| 'uniforms_commercial_clothing'
| 'used_merchandise_and_secondhand_stores'
| 'utilities'
| 'variety_stores'
| 'veterinary_services'
| 'video_amusement_game_supplies'
| 'video_game_arcades'
| 'video_tape_rental_stores'
| 'vocational_trade_schools'
| 'watch_jewelry_repair'
| 'welding_repair'
| 'wholesale_clubs'
| 'wig_and_toupee_stores'
| 'wires_money_orders'
| 'womens_accessory_and_specialty_shops'
| 'womens_ready_to_wear_stores'
| 'wrecking_and_salvage_yards';
type Interval =
| 'all_time'
| 'daily'
| 'monthly'
| 'per_authorization'
| 'weekly'
| 'yearly';
}
}
type Status = 'active' | 'inactive';
type Type = 'company' | 'individual';
}
interface CardholderRetrieveParams {
/**
* Specifies which fields in the response should be expanded.
*/
expand?: Array<string>;
}
interface CardholderUpdateParams {
/**
* The cardholder's billing address.
*/
billing?: CardholderUpdateParams.Billing;
/**
* Additional information about a `company` cardholder.
*/
company?: CardholderUpdateParams.Company;
/**
* The cardholder's email address.
*/
email?: string;
/**
* Specifies which fields in the response should be expanded.
*/
expand?: Array<string>;
/**
* Additional information about an `individual` cardholder.
*/
individual?: CardholderUpdateParams.Individual;
/**
* Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`.
*/
metadata?: Stripe.MetadataParam;
/**
* The cardholder's phone number. This is required for all cardholders who will be creating EU cards. See the [3D Secure documentation](https://stripe.com/docs/issuing/3d-secure) for more details.
*/
phone_number?: string;
/**
* Rules that control spending across this cardholder's cards. Refer to our [documentation](https://stripe.com/docs/issuing/controls/spending-controls) for more details.
*/
spending_controls?: CardholderUpdateParams.SpendingControls;
/**
* Specifies whether to permit authorizations on this cardholder's cards.
*/
status?: CardholderUpdateParams.Status;
}
namespace CardholderUpdateParams {
interface Billing {
/**
* The cardholder's billing address.
*/
address: Billing.Address;
}
namespace Billing {
interface Address {
/**
* City, district, suburb, town, or village.
*/
city: string;
/**
* Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)).
*/
country: string;
/**
* Address line 1 (e.g., street, PO Box, or company name).
*/
line1: string;
/**
* Address line 2 (e.g., apartment, suite, unit, or building).
*/
line2?: string;
/**
* ZIP or postal code.
*/
postal_code: string;
/**
* State, county, province, or region.
*/
state?: string;
}
}
interface Company {
/**
* The entity's business ID number.
*/
tax_id?: string;
}
interface Individual {
/**
* The date of birth of this cardholder.
*/
dob?: Individual.Dob;
/**
* The first name of this cardholder.
*/
first_name: string;
/**
* The last name of this cardholder.
*/
last_name: string;
/**
* Government-issued ID document for this cardholder.
*/
verification?: Individual.Verification;
}
namespace Individual {
interface Dob {
/**
* The day of birth, between 1 and 31.
*/
day: number;
/**
* The month of birth, between 1 and 12.
*/
month: number;
/**
* The four-digit year of birth.
*/
year: number;
}
interface Verification {
/**
* An identifying document, either a passport or local ID card.
*/
document?: Verification.Document;
}
namespace Verification {
interface Document {
/**
* The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`.
*/
back?: string;
/**
* The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`.
*/
front?: string;
}
}
}
interface SpendingControls {
/**
* Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to allow. All other categories will be blocked. Cannot be set with `blocked_categories`.
*/
allowed_categories?: Array<SpendingControls.AllowedCategory>;
/**
* Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to decline. All other categories will be allowed. Cannot be set with `allowed_categories`.
*/
blocked_categories?: Array<SpendingControls.BlockedCategory>;
/**
* Limit spending with amount-based rules that apply across this cardholder's cards.
*/
spending_limits?: Array<SpendingControls.SpendingLimit>;
/**
* Currency of amounts within `spending_limits`. Defaults to your merchant country's currency.
*/
spending_limits_currency?: string;
}
namespace SpendingControls {
type AllowedCategory =
| 'ac_refrigeration_repair'
| 'accounting_bookkeeping_services'
| 'advertising_services'
| 'agricultural_cooperative'
| 'airlines_air_carriers'
| 'airports_flying_fields'
| 'ambulance_services'
| 'amusement_parks_carnivals'
| 'antique_reproductions'
| 'antique_shops'
| 'aquariums'
| 'architectural_surveying_services'
| 'art_dealers_and_galleries'
| 'artists_supply_and_craft_shops'
| 'auto_and_home_supply_stores'
| 'auto_body_repair_shops'
| 'auto_paint_shops'
| 'auto_service_shops'
| 'automated_cash_disburse'
| 'automated_fuel_dispensers'
| 'automobile_associations'
| 'automotive_parts_and_accessories_stores'
| 'automotive_tire_stores'
| 'bail_and_bond_payments'
| 'bakeries'
| 'bands_orchestras'
| 'barber_and_beauty_shops'
| 'betting_casino_gambling'
| 'bicycle_shops'
| 'billiard_pool_establishments'
| 'boat_dealers'
| 'boat_rentals_and_leases'
| 'book_stores'
| 'books_periodicals_and_newspapers'
| 'bowling_alleys'
| 'bus_lines'
| 'business_secretarial_schools'
| 'buying_shopping_services'
| 'cable_satellite_and_other_pay_television_and_radio'
| 'camera_and_photographic_supply_stores'
| 'candy_nut_and_confectionery_stores'
| 'car_and_truck_dealers_new_used'
| 'car_and_truck_dealers_used_only'
| 'car_rental_agencies'
| 'car_washes'
| 'carpentry_services'
| 'carpet_upholstery_cleaning'
| 'caterers'
| 'charitable_and_social_service_organizations_fundraising'
| 'chemicals_and_allied_products'
| 'child_care_services'
| 'childrens_and_infants_wear_stores'
| 'chiropodists_podiatrists'
| 'chiropractors'
| 'cigar_stores_and_stands'
| 'civic_social_fraternal_associations'
| 'cleaning_and_maintenance'
| 'clothing_rental'
| 'colleges_universities'
| 'commercial_equipment'
| 'commercial_footwear'
| 'commercial_photography_art_and_graphics'
| 'commuter_transport_and_ferries'
| 'computer_network_services'
| 'computer_programming'
| 'computer_repair'
| 'computer_software_stores'
| 'computers_peripherals_and_software'
| 'concrete_work_services'
| 'construction_materials'
| 'consulting_public_relations'
| 'correspondence_schools'
| 'cosmetic_stores'
| 'counseling_services'
| 'country_clubs'
| 'courier_services'
| 'court_costs'
| 'credit_reporting_agencies'
| 'cruise_lines'
| 'dairy_products_stores'
| 'dance_hall_studios_schools'
| 'dating_escort_services'
| 'dentists_orthodontists'
| 'department_stores'
| 'detective_agencies'
| 'digital_goods_applications'
| 'digital_goods_games'
| 'digital_goods_large_volume'
| 'digital_goods_media'
| 'direct_marketing_catalog_merchant'
| 'direct_marketing_combination_catalog_and_retail_merchant'
| 'direct_marketing_inbound_telemarketing'
| 'direct_marketing_insurance_services'
| 'direct_marketing_other'
| 'direct_marketing_outbound_telemarketing'
| 'direct_marketing_subscription'
| 'direct_marketing_travel'
| 'discount_stores'
| 'doctors'
| 'door_to_door_sales'
| 'drapery_window_covering_and_upholstery_stores'
| 'drinking_places'
| 'drug_stores_and_pharmacies'
| 'drugs_drug_proprietaries_and_druggist_sundries'
| 'dry_cleaners'
| 'durable_goods'
| 'duty_free_stores'
| 'eating_places_restaurants'
| 'educational_services'
| 'electric_razor_stores'
| 'electrical_parts_and_equipment'
| 'electrical_services'
| 'electronics_repair_shops'
| 'electronics_stores'
| 'elementary_secondary_schools'
| 'employment_temp_agencies'
| 'equipment_rental'
| 'exterminating_services'
| 'family_clothing_stores'
| 'fast_food_restaurants'
| 'financial_institutions'
| 'fines_government_administrative_entities'
| 'fireplace_fireplace_screens_and_accessories_stores'
| 'floor_covering_stores'
| 'florists'
| 'florists_supplies_nursery_stock_and_flowers'
| 'freezer_and_locker_meat_provisioners'
| 'fuel_dealers_non_automotive'
| 'funeral_services_crematories'
| 'furniture_home_furnishings_and_equipment_stores_except_appliances'
| 'furniture_repair_refinishing'
| 'furriers_and_fur_shops'
| 'general_services'
| 'gift_card_novelty_and_souvenir_shops'
| 'glass_paint_and_wallpaper_stores'
| 'glassware_crystal_stores'
| 'golf_courses_public'
| 'government_services'
| 'grocery_stores_supermarkets'
| 'hardware_equipment_and_supplies'
| 'hardware_stores'
| 'health_and_beauty_spas'
| 'hearing_aids_sales_and_supplies'
| 'heating_plumbing_a_c'
| 'hobby_toy_and_game_shops'
| 'home_supply_warehouse_stores'
| 'hospitals'
| 'hotels_motels_and_resorts'
| 'household_appliance_stores'
| 'industrial_supplies'
| 'information_retrieval_services'
| 'insurance_default'
| 'insurance_underwriting_premiums'
| 'intra_company_purchases'
| 'jewelry_stores_watches_clocks_and_silverware_stores'
| 'landscaping_services'
| 'laundries'
| 'laundry_cleaning_services'
| 'legal_services_attorneys'
| 'luggage_and_leather_goods_stores'
| 'lumber_building_materials_stores'
| 'manual_cash_disburse'
| 'marinas_service_and_supplies'
| 'masonry_stonework_and_plaster'
| 'massage_parlors'
| 'medical_and_dental_labs'
| 'medical_dental_ophthalmic_and_hospital_equipment_and_supplies'
| 'medical_services'
| 'membership_organizations'
| 'mens_and_boys_clothing_and_accessories_stores'
| 'mens_womens_clothing_stores'
| 'metal_service_centers'
| 'miscellaneous'
| 'miscellaneous_apparel_and_accessory_shops'
| 'miscellaneous_auto_dealers'
| 'miscellaneous_business_services'
| 'miscellaneous_food_stores'
| 'miscellaneous_general_merchandise'
| 'miscellaneous_general_services'
| 'miscellaneous_home_furnishing_specialty_stores'
| 'miscellaneous_publishing_and_printing'
| 'miscellaneous_recreation_services'
| 'miscellaneous_repair_shops'
| 'miscellaneous_specialty_retail'
| 'mobile_home_dealers'
| 'motion_picture_theaters'
| 'motor_freight_carriers_and_trucking'
| 'motor_homes_dealers'
| 'motor_vehicle_supplies_and_new_parts'
| 'motorcycle_shops_and_dealers'
| 'motorcycle_shops_dealers'
| 'music_stores_musical_instruments_pianos_and_sheet_music'
| 'news_dealers_and_newsstands'
| 'non_fi_money_orders'
| 'non_fi_stored_value_card_purchase_load'
| 'nondurable_goods'
| 'nurseries_lawn_and_garden_supply_stores'
| 'nursing_personal_care'
| 'office_and_commercial_furniture'
| 'opticians_eyeglasses'
| 'optometrists_ophthalmologist'
| 'orthopedic_goods_prosthetic_devices'
| 'osteopaths'
| 'package_stores_beer_wine_and_liquor'
| 'paints_varnishes_and_supplies'
| 'parking_lots_garages'
| 'passenger_railways'
| 'pawn_shops'
| 'pet_shops_pet_food_and_supplies'
| 'petroleum_and_petroleum_products'
| 'photo_developing'
| 'photographic_photocopy_microfilm_equipment_and_supplies'
| 'photographic_studios'
| 'picture_video_production'
| 'piece_goods_notions_and_other_dry_goods'
| 'plumbing_heating_equipment_and_supplies'
| 'political_organizations'
| 'postal_services_government_only'
| 'precious_stones_and_metals_watches_and_jewelry'
| 'professional_services'
| 'public_warehousing_and_storage'
| 'quick_copy_repro_and_blueprint'
| 'railroads'
| 'real_estate_agents_and_managers_rentals'
| 'record_stores'
| 'recreational_vehicle_rentals'
| 'religious_goods_stores'
| 'religious_organizations'
| 'roofing_siding_sheet_metal'
| 'secretarial_support_services'
| 'security_brokers_dealers'
| 'service_stations'
| 'sewing_needlework_fabric_and_piece_goods_stores'
| 'shoe_repair_hat_cleaning'
| 'shoe_stores'
| 'small_appliance_repair'
| 'snowmobile_dealers'
| 'special_trade_services'
| 'specialty_cleaning'
| 'sporting_goods_stores'
| 'sporting_recreation_camps'
| 'sports_and_riding_apparel_stores'
| 'sports_clubs_fields'
| 'stamp_and_coin_stores'
| 'stationary_office_supplies_printing_and_writing_paper'
| 'stationery_stores_office_and_school_supply_stores'
| 'swimming_pools_sales'
| 't_ui_travel_germany'
| 'tailors_alterations'
| 'tax_payments_government_agencies'
| 'tax_preparation_services'
| 'taxicabs_limousines'
| 'telecommunication_equipment_and_telephone_sales'
| 'telecommunication_services'
| 'telegraph_services'
| 'tent_and_awning_shops'
| 'testing_laboratories'
| 'theatrical_ticket_agencies'
| 'timeshares'
| 'tire_retreading_and_repair'
| 'tolls_bridge_fees'
| 'tourist_attractions_and_exhibits'
| 'towing_services'
| 'trailer_parks_campgrounds'
| 'transportation_services'
| 'travel_agencies_tour_operators'
| 'truck_stop_iteration'
| 'truck_utility_trailer_rentals'
| 'typesetting_plate_making_and_related_services'
| 'typewriter_stores'
| 'u_s_federal_government_agencies_or_departments'
| 'uniforms_commercial_clothing'
| 'used_merchandise_and_secondhand_stores'
| 'utilities'
| 'variety_stores'
| 'veterinary_services'
| 'video_amusement_game_supplies'
| 'video_game_arcades'
| 'video_tape_rental_stores'
| 'vocational_trade_schools'
| 'watch_jewelry_repair'
| 'welding_repair'
| 'wholesale_clubs'
| 'wig_and_toupee_stores'
| 'wires_money_orders'
| 'womens_accessory_and_specialty_shops'
| 'womens_ready_to_wear_stores'
| 'wrecking_and_salvage_yards';
type BlockedCategory =
| 'ac_refrigeration_repair'
| 'accounting_bookkeeping_services'
| 'advertising_services'
| 'agricultural_cooperative'
| 'airlines_air_carriers'
| 'airports_flying_fields'
| 'ambulance_services'
| 'amusement_parks_carnivals'
| 'antique_reproductions'
| 'antique_shops'
| 'aquariums'
| 'architectural_surveying_services'
| 'art_dealers_and_galleries'
| 'artists_supply_and_craft_shops'
| 'auto_and_home_supply_stores'
| 'auto_body_repair_shops'
| 'auto_paint_shops'
| 'auto_service_shops'
| 'automated_cash_disburse'
| 'automated_fuel_dispensers'
| 'automobile_associations'
| 'automotive_parts_and_accessories_stores'
| 'automotive_tire_stores'
| 'bail_and_bond_payments'
| 'bakeries'
| 'bands_orchestras'
| 'barber_and_beauty_shops'
| 'betting_casino_gambling'
| 'bicycle_shops'
| 'billiard_pool_establishments'
| 'boat_dealers'
| 'boat_rentals_and_leases'
| 'book_stores'
| 'books_periodicals_and_newspapers'
| 'bowling_alleys'
| 'bus_lines'
| 'business_secretarial_schools'
| 'buying_shopping_services'
| 'cable_satellite_and_other_pay_television_and_radio'
| 'camera_and_photographic_supply_stores'
| 'candy_nut_and_confectionery_stores'
| 'car_and_truck_dealers_new_used'
| 'car_and_truck_dealers_used_only'
| 'car_rental_agencies'
| 'car_washes'
| 'carpentry_services'
| 'carpet_upholstery_cleaning'
| 'caterers'
| 'charitable_and_social_service_organizations_fundraising'
| 'chemicals_and_allied_products'
| 'child_care_services'
| 'childrens_and_infants_wear_stores'
| 'chiropodists_podiatrists'
| 'chiropractors'
| 'cigar_stores_and_stands'
| 'civic_social_fraternal_associations'
| 'cleaning_and_maintenance'
| 'clothing_rental'
| 'colleges_universities'
| 'commercial_equipment'
| 'commercial_footwear'
| 'commercial_photography_art_and_graphics'
| 'commuter_transport_and_ferries'
| 'computer_network_services'
| 'computer_programming'
| 'computer_repair'
| 'computer_software_stores'
| 'computers_peripherals_and_software'
| 'concrete_work_services'
| 'construction_materials'
| 'consulting_public_relations'
| 'correspondence_schools'
| 'cosmetic_stores'
| 'counseling_services'
| 'country_clubs'
| 'courier_services'
| 'court_costs'
| 'credit_reporting_agencies'
| 'cruise_lines'
| 'dairy_products_stores'
| 'dance_hall_studios_schools'
| 'dating_escort_services'
| 'dentists_orthodontists'
| 'department_stores'
| 'detective_agencies'
| 'digital_goods_applications'
| 'digital_goods_games'
| 'digital_goods_large_volume'
| 'digital_goods_media'
| 'direct_marketing_catalog_merchant'
| 'direct_marketing_combination_catalog_and_retail_merchant'
| 'direct_marketing_inbound_telemarketing'
| 'direct_marketing_insurance_services'
| 'direct_marketing_other'
| 'direct_marketing_outbound_telemarketing'
| 'direct_marketing_subscription'
| 'direct_marketing_travel'
| 'discount_stores'
| 'doctors'
| 'door_to_door_sales'
| 'drapery_window_covering_and_upholstery_stores'
| 'drinking_places'
| 'drug_stores_and_pharmacies'
| 'drugs_drug_proprietaries_and_druggist_sundries'
| 'dry_cleaners'
| 'durable_goods'
| 'duty_free_stores'
| 'eating_places_restaurants'
| 'educational_services'
| 'electric_razor_stores'
| 'electrical_parts_and_equipment'
| 'electrical_services'
| 'electronics_repair_shops'
| 'electronics_stores'
| 'elementary_secondary_schools'
| 'employment_temp_agencies'
| 'equipment_rental'
| 'exterminating_services'
| 'family_clothing_stores'
| 'fast_food_restaurants'
| 'financial_institutions'
| 'fines_government_administrative_entities'
| 'fireplace_fireplace_screens_and_accessories_stores'
| 'floor_covering_stores'
| 'florists'
| 'florists_supplies_nursery_stock_and_flowers'
| 'freezer_and_locker_meat_provisioners'
| 'fuel_dealers_non_automotive'
| 'funeral_services_crematories'
| 'furniture_home_furnishings_and_equipment_stores_except_appliances'
| 'furniture_repair_refinishing'
| 'furriers_and_fur_shops'
| 'general_services'
| 'gift_card_novelty_and_souvenir_shops'
| 'glass_paint_and_wallpaper_stores'
| 'glassware_crystal_stores'
| 'golf_courses_public'
| 'government_services'
| 'grocery_stores_supermarkets'
| 'hardware_equipment_and_supplies'
| 'hardware_stores'
| 'health_and_beauty_spas'
| 'hearing_aids_sales_and_supplies'
| 'heating_plumbing_a_c'
| 'hobby_toy_and_game_shops'
| 'home_supply_warehouse_stores'
| 'hospitals'
| 'hotels_motels_and_resorts'
| 'household_appliance_stores'
| 'industrial_supplies'
| 'information_retrieval_services'
| 'insurance_default'
| 'insurance_underwriting_premiums'
| 'intra_company_purchases'
| 'jewelry_stores_watches_clocks_and_silverware_stores'
| 'landscaping_services'
| 'laundries'
| 'laundry_cleaning_services'
| 'legal_services_attorneys'
| 'luggage_and_leather_goods_stores'
| 'lumber_building_materials_stores'
| 'manual_cash_disburse'
| 'marinas_service_and_supplies'
| 'masonry_stonework_and_plaster'
| 'massage_parlors'
| 'medical_and_dental_labs'
| 'medical_dental_ophthalmic_and_hospital_equipment_and_supplies'
| 'medical_services'
| 'membership_organizations'
| 'mens_and_boys_clothing_and_accessories_stores'
| 'mens_womens_clothing_stores'
| 'metal_service_centers'
| 'miscellaneous'
| 'miscellaneous_apparel_and_accessory_shops'
| 'miscellaneous_auto_dealers'
| 'miscellaneous_business_services'
| 'miscellaneous_food_stores'
| 'miscellaneous_general_merchandise'
| 'miscellaneous_general_services'
| 'miscellaneous_home_furnishing_specialty_stores'
| 'miscellaneous_publishing_and_printing'
| 'miscellaneous_recreation_services'
| 'miscellaneous_repair_shops'
| 'miscellaneous_specialty_retail'
| 'mobile_home_dealers'
| 'motion_picture_theaters'
| 'motor_freight_carriers_and_trucking'
| 'motor_homes_dealers'
| 'motor_vehicle_supplies_and_new_parts'
| 'motorcycle_shops_and_dealers'
| 'motorcycle_shops_dealers'
| 'music_stores_musical_instruments_pianos_and_sheet_music'
| 'news_dealers_and_newsstands'
| 'non_fi_money_orders'
| 'non_fi_stored_value_card_purchase_load'
| 'nondurable_goods'
| 'nurseries_lawn_and_garden_supply_stores'
| 'nursing_personal_care'
| 'office_and_commercial_furniture'
| 'opticians_eyeglasses'
| 'optometrists_ophthalmologist'
| 'orthopedic_goods_prosthetic_devices'
| 'osteopaths'
| 'package_stores_beer_wine_and_liquor'
| 'paints_varnishes_and_supplies'
| 'parking_lots_garages'
| 'passenger_railways'
| 'pawn_shops'
| 'pet_shops_pet_food_and_supplies'
| 'petroleum_and_petroleum_products'
| 'photo_developing'
| 'photographic_photocopy_microfilm_equipment_and_supplies'
| 'photographic_studios'
| 'picture_video_production'
| 'piece_goods_notions_and_other_dry_goods'
| 'plumbing_heating_equipment_and_supplies'
| 'political_organizations'
| 'postal_services_government_only'
| 'precious_stones_and_metals_watches_and_jewelry'
| 'professional_services'
| 'public_warehousing_and_storage'
| 'quick_copy_repro_and_blueprint'
| 'railroads'
| 'real_estate_agents_and_managers_rentals'
| 'record_stores'
| 'recreational_vehicle_rentals'
| 'religious_goods_stores'
| 'religious_organizations'
| 'roofing_siding_sheet_metal'
| 'secretarial_support_services'
| 'security_brokers_dealers'
| 'service_stations'
| 'sewing_needlework_fabric_and_piece_goods_stores'
| 'shoe_repair_hat_cleaning'
| 'shoe_stores'
| 'small_appliance_repair'
| 'snowmobile_dealers'
| 'special_trade_services'
| 'specialty_cleaning'
| 'sporting_goods_stores'
| 'sporting_recreation_camps'
| 'sports_and_riding_apparel_stores'
| 'sports_clubs_fields'
| 'stamp_and_coin_stores'
| 'stationary_office_supplies_printing_and_writing_paper'
| 'stationery_stores_office_and_school_supply_stores'
| 'swimming_pools_sales'
| 't_ui_travel_germany'
| 'tailors_alterations'
| 'tax_payments_government_agencies'
| 'tax_preparation_services'
| 'taxicabs_limousines'
| 'telecommunication_equipment_and_telephone_sales'
| 'telecommunication_services'
| 'telegraph_services'
| 'tent_and_awning_shops'
| 'testing_laboratories'
| 'theatrical_ticket_agencies'
| 'timeshares'
| 'tire_retreading_and_repair'
| 'tolls_bridge_fees'
| 'tourist_attractions_and_exhibits'
| 'towing_services'
| 'trailer_parks_campgrounds'
| 'transportation_services'
| 'travel_agencies_tour_operators'
| 'truck_stop_iteration'
| 'truck_utility_trailer_rentals'
| 'typesetting_plate_making_and_related_services'
| 'typewriter_stores'
| 'u_s_federal_government_agencies_or_departments'
| 'uniforms_commercial_clothing'
| 'used_merchandise_and_secondhand_stores'
| 'utilities'
| 'variety_stores'
| 'veterinary_services'
| 'video_amusement_game_supplies'
| 'video_game_arcades'
| 'video_tape_rental_stores'
| 'vocational_trade_schools'
| 'watch_jewelry_repair'
| 'welding_repair'
| 'wholesale_clubs'
| 'wig_and_toupee_stores'
| 'wires_money_orders'
| 'womens_accessory_and_specialty_shops'
| 'womens_ready_to_wear_stores'
| 'wrecking_and_salvage_yards';
interface SpendingLimit {
/**
* Maximum amount allowed to spend per interval.
*/
amount: number;
/**
* Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) this limit applies to. Omitting this field will apply the limit to all categories.
*/
categories?: Array<SpendingLimit.Category>;
/**
* Interval (or event) to which the amount applies.
*/
interval: SpendingLimit.Interval;
}
namespace SpendingLimit {
type Category =
| 'ac_refrigeration_repair'
| 'accounting_bookkeeping_services'
| 'advertising_services'
| 'agricultural_cooperative'
| 'airlines_air_carriers'
| 'airports_flying_fields'
| 'ambulance_services'
| 'amusement_parks_carnivals'
| 'antique_reproductions'
| 'antique_shops'
| 'aquariums'
| 'architectural_surveying_services'
| 'art_dealers_and_galleries'
| 'artists_supply_and_craft_shops'
| 'auto_and_home_supply_stores'
| 'auto_body_repair_shops'
| 'auto_paint_shops'
| 'auto_service_shops'
| 'automated_cash_disburse'
| 'automated_fuel_dispensers'
| 'automobile_associations'
| 'automotive_parts_and_accessories_stores'
| 'automotive_tire_stores'
| 'bail_and_bond_payments'
| 'bakeries'
| 'bands_orchestras'
| 'barber_and_beauty_shops'
| 'betting_casino_gambling'
| 'bicycle_shops'
| 'billiard_pool_establishments'
| 'boat_dealers'
| 'boat_rentals_and_leases'
| 'book_stores'
| 'books_periodicals_and_newspapers'
| 'bowling_alleys'
| 'bus_lines'
| 'business_secretarial_schools'
| 'buying_shopping_services'
| 'cable_satellite_and_other_pay_television_and_radio'
| 'camera_and_photographic_supply_stores'
| 'candy_nut_and_confectionery_stores'
| 'car_and_truck_dealers_new_used'
| 'car_and_truck_dealers_used_only'
| 'car_rental_agencies'
| 'car_washes'
| 'carpentry_services'
| 'carpet_upholstery_cleaning'
| 'caterers'
| 'charitable_and_social_service_organizations_fundraising'
| 'chemicals_and_allied_products'
| 'child_care_services'
| 'childrens_and_infants_wear_stores'
| 'chiropodists_podiatrists'
| 'chiropractors'
| 'cigar_stores_and_stands'
| 'civic_social_fraternal_associations'
| 'cleaning_and_maintenance'
| 'clothing_rental'
| 'colleges_universities'
| 'commercial_equipment'
| 'commercial_footwear'
| 'commercial_photography_art_and_graphics'
| 'commuter_transport_and_ferries'
| 'computer_network_services'
| 'computer_programming'
| 'computer_repair'
| 'computer_software_stores'
| 'computers_peripherals_and_software'
| 'concrete_work_services'
| 'construction_materials'
| 'consulting_public_relations'
| 'correspondence_schools'
| 'cosmetic_stores'
| 'counseling_services'
| 'country_clubs'
| 'courier_services'
| 'court_costs'
| 'credit_reporting_agencies'
| 'cruise_lines'
| 'dairy_products_stores'
| 'dance_hall_studios_schools'
| 'dating_escort_services'
| 'dentists_orthodontists'
| 'department_stores'
| 'detective_agencies'
| 'digital_goods_applications'
| 'digital_goods_games'
| 'digital_goods_large_volume'
| 'digital_goods_media'
| 'direct_marketing_catalog_merchant'
| 'direct_marketing_combination_catalog_and_retail_merchant'
| 'direct_marketing_inbound_telemarketing'
| 'direct_marketing_insurance_services'
| 'direct_marketing_other'
| 'direct_marketing_outbound_telemarketing'
| 'direct_marketing_subscription'
| 'direct_marketing_travel'
| 'discount_stores'
| 'doctors'
| 'door_to_door_sales'
| 'drapery_window_covering_and_upholstery_stores'
| 'drinking_places'
| 'drug_stores_and_pharmacies'
| 'drugs_drug_proprietaries_and_druggist_sundries'
| 'dry_cleaners'
| 'durable_goods'
| 'duty_free_stores'
| 'eating_places_restaurants'
| 'educational_services'
| 'electric_razor_stores'
| 'electrical_parts_and_equipment'
| 'electrical_services'
| 'electronics_repair_shops'
| 'electronics_stores'
| 'elementary_secondary_schools'
| 'employment_temp_agencies'
| 'equipment_rental'
| 'exterminating_services'
| 'family_clothing_stores'
| 'fast_food_restaurants'
| 'financial_institutions'
| 'fines_government_administrative_entities'
| 'fireplace_fireplace_screens_and_accessories_stores'
| 'floor_covering_stores'
| 'florists'
| 'florists_supplies_nursery_stock_and_flowers'
| 'freezer_and_locker_meat_provisioners'
| 'fuel_dealers_non_automotive'
| 'funeral_services_crematories'
| 'furniture_home_furnishings_and_equipment_stores_except_appliances'
| 'furniture_repair_refinishing'
| 'furriers_and_fur_shops'
| 'general_services'
| 'gift_card_novelty_and_souvenir_shops'
| 'glass_paint_and_wallpaper_stores'
| 'glassware_crystal_stores'
| 'golf_courses_public'
| 'government_services'
| 'grocery_stores_supermarkets'
| 'hardware_equipment_and_supplies'
| 'hardware_stores'
| 'health_and_beauty_spas'
| 'hearing_aids_sales_and_supplies'
| 'heating_plumbing_a_c'
| 'hobby_toy_and_game_shops'
| 'home_supply_warehouse_stores'
| 'hospitals'
| 'hotels_motels_and_resorts'
| 'household_appliance_stores'
| 'industrial_supplies'
| 'information_retrieval_services'
| 'insurance_default'
| 'insurance_underwriting_premiums'
| 'intra_company_purchases'
| 'jewelry_stores_watches_clocks_and_silverware_stores'
| 'landscaping_services'
| 'laundries'
| 'laundry_cleaning_services'
| 'legal_services_attorneys'
| 'luggage_and_leather_goods_stores'
| 'lumber_building_materials_stores'
| 'manual_cash_disburse'
| 'marinas_service_and_supplies'
| 'masonry_stonework_and_plaster'
| 'massage_parlors'
| 'medical_and_dental_labs'
| 'medical_dental_ophthalmic_and_hospital_equipment_and_supplies'
| 'medical_services'
| 'membership_organizations'
| 'mens_and_boys_clothing_and_accessories_stores'
| 'mens_womens_clothing_stores'
| 'metal_service_centers'
| 'miscellaneous'
| 'miscellaneous_apparel_and_accessory_shops'
| 'miscellaneous_auto_dealers'
| 'miscellaneous_business_services'
| 'miscellaneous_food_stores'
| 'miscellaneous_general_merchandise'
| 'miscellaneous_general_services'
| 'miscellaneous_home_furnishing_specialty_stores'
| 'miscellaneous_publishing_and_printing'
| 'miscellaneous_recreation_services'
| 'miscellaneous_repair_shops'
| 'miscellaneous_specialty_retail'
| 'mobile_home_dealers'
| 'motion_picture_theaters'
| 'motor_freight_carriers_and_trucking'
| 'motor_homes_dealers'
| 'motor_vehicle_supplies_and_new_parts'
| 'motorcycle_shops_and_dealers'
| 'motorcycle_shops_dealers'
| 'music_stores_musical_instruments_pianos_and_sheet_music'
| 'news_dealers_and_newsstands'
| 'non_fi_money_orders'
| 'non_fi_stored_value_card_purchase_load'
| 'nondurable_goods'
| 'nurseries_lawn_and_garden_supply_stores'
| 'nursing_personal_care'
| 'office_and_commercial_furniture'
| 'opticians_eyeglasses'
| 'optometrists_ophthalmologist'
| 'orthopedic_goods_prosthetic_devices'
| 'osteopaths'
| 'package_stores_beer_wine_and_liquor'
| 'paints_varnishes_and_supplies'
| 'parking_lots_garages'
| 'passenger_railways'
| 'pawn_shops'
| 'pet_shops_pet_food_and_supplies'
| 'petroleum_and_petroleum_products'
| 'photo_developing'
| 'photographic_photocopy_microfilm_equipment_and_supplies'
| 'photographic_studios'
| 'picture_video_production'
| 'piece_goods_notions_and_other_dry_goods'
| 'plumbing_heating_equipment_and_supplies'
| 'political_organizations'
| 'postal_services_government_only'
| 'precious_stones_and_metals_watches_and_jewelry'
| 'professional_services'
| 'public_warehousing_and_storage'
| 'quick_copy_repro_and_blueprint'
| 'railroads'
| 'real_estate_agents_and_managers_rentals'
| 'record_stores'
| 'recreational_vehicle_rentals'
| 'religious_goods_stores'
| 'religious_organizations'
| 'roofing_siding_sheet_metal'
| 'secretarial_support_services'
| 'security_brokers_dealers'
| 'service_stations'
| 'sewing_needlework_fabric_and_piece_goods_stores'
| 'shoe_repair_hat_cleaning'
| 'shoe_stores'
| 'small_appliance_repair'
| 'snowmobile_dealers'
| 'special_trade_services'
| 'specialty_cleaning'
| 'sporting_goods_stores'
| 'sporting_recreation_camps'
| 'sports_and_riding_apparel_stores'
| 'sports_clubs_fields'
| 'stamp_and_coin_stores'
| 'stationary_office_supplies_printing_and_writing_paper'
| 'stationery_stores_office_and_school_supply_stores'
| 'swimming_pools_sales'
| 't_ui_travel_germany'
| 'tailors_alterations'
| 'tax_payments_government_agencies'
| 'tax_preparation_services'
| 'taxicabs_limousines'
| 'telecommunication_equipment_and_telephone_sales'
| 'telecommunication_services'
| 'telegraph_services'
| 'tent_and_awning_shops'
| 'testing_laboratories'
| 'theatrical_ticket_agencies'
| 'timeshares'
| 'tire_retreading_and_repair'
| 'tolls_bridge_fees'
| 'tourist_attractions_and_exhibits'
| 'towing_services'
| 'trailer_parks_campgrounds'
| 'transportation_services'
| 'travel_agencies_tour_operators'
| 'truck_stop_iteration'
| 'truck_utility_trailer_rentals'
| 'typesetting_plate_making_and_related_services'
| 'typewriter_stores'
| 'u_s_federal_government_agencies_or_departments'
| 'uniforms_commercial_clothing'
| 'used_merchandise_and_secondhand_stores'
| 'utilities'
| 'variety_stores'
| 'veterinary_services'
| 'video_amusement_game_supplies'
| 'video_game_arcades'
| 'video_tape_rental_stores'
| 'vocational_trade_schools'
| 'watch_jewelry_repair'
| 'welding_repair'
| 'wholesale_clubs'
| 'wig_and_toupee_stores'
| 'wires_money_orders'
| 'womens_accessory_and_specialty_shops'
| 'womens_ready_to_wear_stores'
| 'wrecking_and_salvage_yards';
type Interval =
| 'all_time'
| 'daily'
| 'monthly'
| 'per_authorization'
| 'weekly'
| 'yearly';
}
}
type Status = 'active' | 'inactive';
}
interface CardholderListParams extends PaginationParams {
/**
* Only return cardholders that were created during the given date interval.
*/
created?: Stripe.RangeQueryParam | number;
/**
* Only return cardholders that have the given email address.
*/
email?: string;
/**
* Specifies which fields in the response should be expanded.
*/
expand?: Array<string>;
/**
* Only return cardholders that have the given phone number.
*/
phone_number?: string;
/**
* Only return cardholders that have the given status. One of `active`, `inactive`, or `blocked`.
*/
status?: CardholderListParams.Status;
/**
* Only return cardholders that have the given type. One of `individual` or `company`.
*/
type?: CardholderListParams.Type;
}
namespace CardholderListParams {
type Status = 'active' | 'blocked' | 'inactive';
type Type = 'company' | 'individual';
}
class CardholdersResource {
/**
* Creates a new Issuing Cardholder object that can be issued cards.
*/
create(
params: CardholderCreateParams,
options?: RequestOptions
): Promise<Stripe.Response<Stripe.Issuing.Cardholder>>;
/**
* Retrieves an Issuing Cardholder object.
*/
retrieve(
id: string,
params?: CardholderRetrieveParams,
options?: RequestOptions
): Promise<Stripe.Response<Stripe.Issuing.Cardholder>>;
retrieve(
id: string,
options?: RequestOptions
): Promise<Stripe.Response<Stripe.Issuing.Cardholder>>;
/**
* Updates the specified Issuing Cardholder object by setting the values of the parameters passed. Any parameters not provided will be left unchanged.
*/
update(
id: string,
params?: CardholderUpdateParams,
options?: RequestOptions
): Promise<Stripe.Response<Stripe.Issuing.Cardholder>>;
/**
* Returns a list of Issuing Cardholder objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first.
*/
list(
params?: CardholderListParams,
options?: RequestOptions
): ApiListPromise<Stripe.Issuing.Cardholder>;
list(
options?: RequestOptions
): ApiListPromise<Stripe.Issuing.Cardholder>;
}
}
}
} | the_stack |
'use strict';
import type * as nbformat from '@jupyterlab/nbformat';
import { inject, injectable, named } from 'inversify';
import { CancellationToken, Memento } from 'vscode';
import { IPythonExtensionChecker } from '../../api/types';
import { PYTHON_LANGUAGE } from '../../common/constants';
import { traceDecorators, traceError, traceInfo } from '../../common/logger';
import { GLOBAL_MEMENTO, IExtensions, IMemento, Resource } from '../../common/types';
import { IInterpreterService } from '../../interpreter/contracts';
import { captureTelemetry, sendTelemetryEvent } from '../../telemetry';
import { Telemetry } from '../constants';
import {
findPreferredKernel,
getDisplayNameOrNameOfKernelConnection,
getLanguageInNotebookMetadata
} from '../jupyter/kernels/helpers';
import { LocalKernelConnectionMetadata } from '../jupyter/kernels/types';
import { ILocalKernelFinder } from './types';
import { getResourceType } from '../common';
import { isPythonNotebook } from '../notebook/helpers/helpers';
import { getTelemetrySafeLanguage } from '../../telemetry/helpers';
import { sendKernelListTelemetry } from '../telemetry/kernelTelemetry';
import { LocalPythonAndRelatedNonPythonKernelSpecFinder } from './localPythonAndRelatedNonPythonKernelSpecFinder';
import { LocalKnownPathKernelSpecFinder } from './localKnownPathKernelSpecFinder';
import { JupyterPaths } from './jupyterPaths';
import { IFileSystem } from '../../common/platform/types';
import { noop } from '../../common/utils/misc';
import { createPromiseFromCancellation } from '../../common/cancellation';
const GlobalKernelSpecsCacheKey = 'JUPYTER_GLOBAL_KERNELSPECS';
// This class searches for a kernel that matches the given kernel name.
// First it searches on a global persistent state, then on the installed python interpreters,
// and finally on the default locations that jupyter installs kernels on.
@injectable()
export class LocalKernelFinder implements ILocalKernelFinder {
private lastFetchedKernelsWithoutCache: LocalKernelConnectionMetadata[] = [];
constructor(
@inject(IInterpreterService) private interpreterService: IInterpreterService,
@inject(IPythonExtensionChecker) private readonly extensionChecker: IPythonExtensionChecker,
@inject(IExtensions) private readonly extensions: IExtensions,
@inject(LocalKnownPathKernelSpecFinder) private readonly nonPythonkernelFinder: LocalKnownPathKernelSpecFinder,
@inject(LocalPythonAndRelatedNonPythonKernelSpecFinder)
private readonly pythonKernelFinder: LocalPythonAndRelatedNonPythonKernelSpecFinder,
@inject(JupyterPaths) private readonly jupyterPaths: JupyterPaths,
@inject(IMemento) @named(GLOBAL_MEMENTO) private readonly globalState: Memento,
@inject(IFileSystem) private readonly fs: IFileSystem
) {}
@traceDecorators.verbose('Find kernel spec')
@captureTelemetry(Telemetry.KernelFinderPerf)
public async findKernel(
resource: Resource,
notebookMetadata?: nbformat.INotebookMetadata,
cancelToken?: CancellationToken
): Promise<LocalKernelConnectionMetadata | undefined> {
const resourceType = getResourceType(resource);
const telemetrySafeLanguage =
resourceType === 'interactive'
? PYTHON_LANGUAGE
: getTelemetrySafeLanguage(getLanguageInNotebookMetadata(notebookMetadata) || '');
try {
// Get list of all of the specs
const kernels = await this.listKernels(resource, cancelToken, 'useCache');
const isPythonNbOrInteractiveWindow = isPythonNotebook(notebookMetadata) || resourceType === 'interactive';
// Always include the interpreter in the search if we can
const preferredInterpreter =
isPythonNbOrInteractiveWindow && this.extensionChecker.isPythonExtensionInstalled
? await this.interpreterService.getActiveInterpreter(resource)
: undefined;
// Find the preferred kernel index from the list.
const preferred = findPreferredKernel(
kernels,
resource,
[],
notebookMetadata,
preferredInterpreter,
undefined
);
sendTelemetryEvent(Telemetry.PreferredKernel, undefined, {
result: preferred ? 'found' : 'notfound',
resourceType,
language: telemetrySafeLanguage,
hasActiveInterpreter: !!preferredInterpreter
});
if (preferred) {
traceInfo(`findKernel found ${getDisplayNameOrNameOfKernelConnection(preferred)}`);
return preferred as LocalKernelConnectionMetadata;
}
} catch (ex) {
sendTelemetryEvent(
Telemetry.PreferredKernel,
undefined,
{
result: 'failed',
resourceType,
language: telemetrySafeLanguage
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
ex as any,
true
);
traceError(`findKernel crashed`, ex);
return undefined;
}
}
public async listNonPythonKernels(cancelToken?: CancellationToken): Promise<LocalKernelConnectionMetadata[]> {
return this.filterKernels(await this.nonPythonkernelFinder.listKernelSpecs(false, cancelToken));
}
/**
* Search all our local file system locations for installed kernel specs and return them
*/
@traceDecorators.error('List kernels failed')
public async listKernels(
resource: Resource,
cancelToken?: CancellationToken,
useCache: 'useCache' | 'ignoreCache' = 'ignoreCache'
): Promise<LocalKernelConnectionMetadata[]> {
const kernelsFromCachePromise =
useCache === 'ignoreCache' ? Promise.resolve([]) : this.listValidKernelsFromGlobalCache(cancelToken);
const kernelsWithoutCachePromise = this.listKernelsWithoutCache(resource, cancelToken);
let kernels: LocalKernelConnectionMetadata[] = [];
if (useCache === 'ignoreCache') {
kernels = await kernelsWithoutCachePromise;
} else {
let kernelsFromCache: LocalKernelConnectionMetadata[] | undefined;
kernelsFromCachePromise.then((items) => (kernelsFromCache = items)).catch(noop);
await Promise.race([kernelsFromCachePromise, kernelsWithoutCachePromise]);
// If we finish the cache first, and we don't have any items, in the cache, then load without cache.
if (Array.isArray(kernelsFromCache) && kernelsFromCache.length > 0) {
kernels = kernelsFromCache;
} else {
kernels = await kernelsWithoutCachePromise;
}
}
//
kernels = this.filterKernels(kernels);
sendKernelListTelemetry(resource, kernels);
return kernels;
}
// This should return a WRITABLE place that jupyter will look for a kernel as documented
// here: https://jupyter-client.readthedocs.io/en/stable/kernels.html#kernel-specs
public async getKernelSpecRootPath(): Promise<string | undefined> {
return this.jupyterPaths.getKernelSpecRootPath();
}
@captureTelemetry(Telemetry.KernelListingPerf, { kind: 'local' })
private async listKernelsWithoutCache(
resource: Resource,
cancelToken?: CancellationToken
): Promise<LocalKernelConnectionMetadata[]> {
let [nonPythonKernelSpecs, pythonRelatedKernelSpecs] = await Promise.all([
this.nonPythonkernelFinder.listKernelSpecs(false, cancelToken),
this.pythonKernelFinder.listKernelSpecs(resource, cancelToken)
]);
const kernels = this.filterKernels(nonPythonKernelSpecs.concat(pythonRelatedKernelSpecs));
this.lastFetchedKernelsWithoutCache = kernels;
this.globalState.update(GlobalKernelSpecsCacheKey, kernels).then(noop, (ex) => {
console.error('Failed to update global kernel cache', ex);
});
return kernels;
}
private async listValidKernelsFromGlobalCache(
cancelToken?: CancellationToken
): Promise<LocalKernelConnectionMetadata[]> {
const values = this.lastFetchedKernelsWithoutCache.length
? this.lastFetchedKernelsWithoutCache
: this.globalState.get<LocalKernelConnectionMetadata[]>(GlobalKernelSpecsCacheKey, []);
const validValues: LocalKernelConnectionMetadata[] = [];
const promise = Promise.all(
values.map(async (item) => {
let somethingIsInvalid = false;
const promises: Promise<void>[] = [];
if (item.interpreter?.path) {
// Possible the interpreter no longer exists, in such cases, exclude this cached kernel from the list.
promises.push(
this.fs
.localFileExists(item.interpreter.path)
.then((exists) => {
if (!exists) {
somethingIsInvalid = true;
}
})
.catch(noop)
);
}
if (item.kind === 'startUsingKernelSpec' && item.kernelSpec?.specFile) {
// Possible the kernelspec file no longer exists, in such cases, exclude this cached kernel from the list.
promises.push(
this.fs
.localFileExists(item.kernelSpec.specFile)
.then((exists) => {
if (!exists) {
somethingIsInvalid = true;
}
})
.catch(noop)
);
}
await Promise.all(promises);
if (!somethingIsInvalid) {
validValues.push(item);
}
})
);
if (cancelToken) {
await Promise.race([
promise,
createPromiseFromCancellation({ token: cancelToken, cancelAction: 'resolve', defaultValue: undefined })
]);
} else {
await promise;
}
return validValues;
}
private filterKernels(kernels: LocalKernelConnectionMetadata[]) {
return kernels.filter(({ kernelSpec }) => {
if (!kernelSpec) {
return true;
}
// Disable xeus python for now.
if (kernelSpec.argv[0].toLowerCase().endsWith('xpython')) {
traceInfo(`Hiding xeus kernelspec`);
return false;
}
const extensionId = kernelSpec.metadata?.vscode?.extension_id;
if (extensionId && this.extensions.getExtension(extensionId)) {
traceInfo(`Hiding kernelspec ${kernelSpec.display_name}, better support by ${extensionId}`);
return false;
}
return true;
});
}
} | the_stack |
import { ContractsAPI } from "./";
// constants
import { TERMS_CONTRACT_TYPES } from "../../utils/constants";
// libraries
import * as singleLineString from "single-line-string";
import * as Web3 from "web3";
import { BigNumber } from "../../utils/bignumber";
// utils
import { Web3Utils } from "../../utils/web3_utils";
import { Assertions } from "../invariants";
// types
import { CollateralizedSimpleInterestLoanAdapter, SimpleInterestLoanAdapter } from "../adapters";
import { DebtRegistryEntry, TxData } from "../types";
const REPAYMENT_GAS_MAXIMUM = 150000;
export const ServicingAPIErrors = {
DEBT_AGREEMENT_NONEXISTENT: (issuanceHash: string) =>
singleLineString`Debt agreement with issuance hash ${issuanceHash} could not
be found in the deployed debt registry`,
INSUFFICIENT_REPAYMENT_BALANCE: () =>
singleLineString`Payer does not have sufficient balance in the specified token
to execute this repayment.`,
INSUFFICIENT_REPAYMENT_ALLOWANCE: () =>
singleLineString`Payer has not granted the token transfer proxy a sufficient
allowance in the specified token to execute this repayment.`,
UNKNOWN_LOAN_ADAPTER: (termsContract: string) =>
singleLineString`Associated loan adapter not found for terms contract at ${termsContract}`,
};
export class ServicingAPI {
private web3: Web3;
private contracts: ContractsAPI;
private assert: Assertions;
constructor(web3: Web3, contracts: ContractsAPI) {
this.web3 = web3;
this.contracts = contracts;
this.assert = new Assertions(this.web3, this.contracts);
}
/**
* Asynchronously issue a repayment towards a debt agreement.
*
* Note that the address of whoever is making the repayment must allot a
* sufficient allowance (equal to or greater than the amount specified in
* this call) to the `tokenTransferProxy` in order for this transaction to
* succeed.
*
* @param issuanceHash the hash of the issuance to which the repayment is being made.
* @param amount the amount that is being repaid.
* @param tokenAddress the address of the token in which the repayment is being made.
* @param options any parameters necessary to modify the transaction.
* @return the hash of the resulting transaction.
*/
public async makeRepayment(
issuanceHash: string,
amount: BigNumber,
tokenAddress: string,
options?: TxData,
): Promise<string> {
const transactionOptions = await this.getTxDefaultOptions();
Object.assign(transactionOptions, options);
let {
debtToken,
repaymentRouter,
debtRegistry,
tokenTransferProxy,
} = await this.contracts.loadDharmaContractsAsync();
this.assert.schema.bytes32("issuanceHash", issuanceHash);
this.assert.schema.number("amount", amount);
this.assert.schema.address("tokenAddress", tokenAddress);
await this.assert.debtAgreement.exists(
issuanceHash,
debtToken,
ServicingAPIErrors.DEBT_AGREEMENT_NONEXISTENT(issuanceHash),
);
const repaymentToken = await this.contracts.loadERC20TokenAsync(tokenAddress);
await this.assert.token.hasSufficientBalance(
repaymentToken,
transactionOptions.from,
amount,
ServicingAPIErrors.INSUFFICIENT_REPAYMENT_BALANCE(),
);
await this.assert.token.hasSufficientAllowance(
repaymentToken,
transactionOptions.from,
tokenTransferProxy.address,
amount,
ServicingAPIErrors.INSUFFICIENT_REPAYMENT_ALLOWANCE(),
);
const entry = await debtRegistry.get.callAsync(issuanceHash);
if (entry.version !== repaymentRouter.address) {
repaymentRouter = await this.contracts.loadRepaymentRouterAtAsync(entry.version);
}
return repaymentRouter.repay.sendTransactionAsync(
issuanceHash,
amount,
tokenAddress,
transactionOptions,
);
}
/**
* Asynchronously retrieve the amount that has been repaid to date towards a
* debt agreement.
*
* @param issuanceHash the hash of the debt agreement.
* @return the amount that has been repaid to date.
*/
public async getValueRepaid(issuanceHash: string): Promise<BigNumber> {
this.assert.schema.bytes32("issuanceHash", issuanceHash);
const debtRegistry = await this.contracts.loadDebtRegistryAsync();
const [termsContractAddress] = await debtRegistry.getTerms.callAsync(issuanceHash);
const termsContract = await this.contracts.loadTermsContractAsync(termsContractAddress);
return termsContract.getValueRepaidToDate.callAsync(issuanceHash);
}
/**
* Asynchronously determine the expected value of repayments at a given
* point in time for a given debt agreement.
*
* @param issuanceHash the hash of a debt agreement.
* @param timestamp the point in time at which the expected value is to be calculated.
* @return the expected value of repayments at the point in time specified.
*/
public async getExpectedValueRepaid(
issuanceHash: string,
timestamp: number,
): Promise<BigNumber> {
this.assert.schema.bytes32("issuanceHash", issuanceHash);
const debtRegistry = await this.contracts.loadDebtRegistryAsync();
const termsContractAddress = await debtRegistry.getTermsContract.callAsync(issuanceHash);
const termsContract = await this.contracts.loadTermsContractAsync(termsContractAddress);
return termsContract.getExpectedRepaymentValue.callAsync(
issuanceHash,
new BigNumber(timestamp),
);
}
/**
* Given an issuance hash, returns the amount that is expected to be repaid
* per repayment period.
*
* @example
* const amount = await dharma.servicing.getExpectedAmountPerRepayment(
* "0x069cb8891d9dbf02d89079a77169e0dc8bacda65"
* );
* amount.toNumber();
* => 5500000000
*
* @param {string} issuanceHash
* @returns {Promise<BigNumber>}
*/
public async getExpectedAmountPerRepayment(issuanceHash: string): Promise<BigNumber> {
this.assert.schema.bytes32("issuanceHash", issuanceHash);
const totalRepayment = await this.getTotalExpectedRepayment(issuanceHash);
const debtRegistryEntry = await this.getDebtRegistryEntry(issuanceHash);
const { termsContract, termsContractParameters } = debtRegistryEntry;
const adapter = await this.adapterForTermsContract(termsContract);
const { termLength } = adapter.unpackParameters(termsContractParameters);
return new BigNumber(totalRepayment.div(termLength));
}
/**
* Given an issuanceHash, returns the total amount that the borrower is expected to
* pay by the end of the associated terms agreement.
*
* @param issuanceHash
*/
public async getTotalExpectedRepayment(issuanceHash: string): Promise<BigNumber> {
this.assert.schema.bytes32("issuanceHash", issuanceHash);
const debtToken = await this.contracts.loadDebtTokenAsync();
await this.assert.debtAgreement.exists(
issuanceHash,
debtToken,
ServicingAPIErrors.DEBT_AGREEMENT_NONEXISTENT(issuanceHash),
);
const debtRegistry = await this.contracts.loadDebtRegistryAsync();
const termsContractAddress = await debtRegistry.getTermsContract.callAsync(issuanceHash);
const termsContract = await this.contracts.loadTermsContractAsync(termsContractAddress);
const termEnd = await termsContract.getTermEndTimestamp.callAsync(issuanceHash);
return termsContract.getExpectedRepaymentValue.callAsync(issuanceHash, termEnd);
}
/**
* Asynchronously retrieve the `DebtRegistryEntry` instance mapped to the
* issuance hash specified.
*
* @param issuanceHash the id of the issuance to retrieve.
* @return the relevant `DebtRegistryEntry` instance .
*/
public async getDebtRegistryEntry(issuanceHash: string): Promise<DebtRegistryEntry> {
this.assert.schema.bytes32("issuanceHash", issuanceHash);
const debtToken = await this.contracts.loadDebtTokenAsync();
await this.assert.debtAgreement.exists(
issuanceHash,
debtToken,
ServicingAPIErrors.DEBT_AGREEMENT_NONEXISTENT(issuanceHash),
);
const debtRegistry = await this.contracts.loadDebtRegistryAsync();
return debtRegistry.get.callAsync(issuanceHash);
}
/**
* Given a debtor's account, returns a list of issuance hashes
* corresponding to debts which the debtor has issued in the past.
*
* @param account The debtor's account
* @return A list of issuance hashes of the debtor's debts
*/
public async getDebtsAsync(account: string): Promise<string[]> {
this.assert.schema.address("account", account);
const debtRegistry = await this.contracts.loadDebtRegistryAsync();
return debtRegistry.getDebtorsDebts.callAsync(account);
}
/**
* Given a creditor's account, returns a list of issuance hashes
* corresponding to debts which the creditor has invested in.
*
* @param account The creditor's account
* @return A list of issuance hashes of the creditor's investments
*/
public async getInvestmentsAsync(account: string): Promise<string[]> {
this.assert.schema.address("account", account);
const debtToken = await this.contracts.loadDebtTokenAsync();
// The ERC721-compliant token id's of debt tokens we generate
// are simply the issuance hashes of their corresponding
// debt agreements. Thus, we can retrieve a list of
// a users' debt agreements by retrieving a list of tokens
// they own.
const numInvestments = await debtToken.balanceOf.callAsync(account);
const userDebtTokenIds = [];
for (let i = 0; i < numInvestments.toNumber(); i++) {
const tokenId = await debtToken.tokenOfOwnerByIndex.callAsync(
account,
new BigNumber(i),
);
userDebtTokenIds.push(tokenId);
}
return userDebtTokenIds.map(
(tokenId: BigNumber) => `0x${tokenId.toString(16).padStart(64, "0")}`,
);
}
public async getRepaymentScheduleAsync(issuanceHash: string): Promise<number[]> {
this.assert.schema.bytes32("issuanceHash", issuanceHash);
const debtRegistryEntry = await this.getDebtRegistryEntry(issuanceHash);
const { termsContract } = debtRegistryEntry;
const adapter = await this.adapterForTermsContract(termsContract);
return adapter.getRepaymentSchedule(debtRegistryEntry);
}
private async getTxDefaultOptions(): Promise<TxData> {
const web3Utils = new Web3Utils(this.web3);
const accounts = await web3Utils.getAvailableAddressesAsync();
// TODO: Add fault tolerance to scenario in which not addresses are available
return {
from: accounts[0],
gas: REPAYMENT_GAS_MAXIMUM,
};
}
private async adapterForTermsContract(termsContract: string): Promise<any> {
const termsContractType = await this.contracts.getTermsContractType(termsContract);
switch (termsContractType) {
case TERMS_CONTRACT_TYPES.COLLATERALIZED_SIMPLE_INTEREST_LOAN:
return new CollateralizedSimpleInterestLoanAdapter(this.web3, this.contracts);
case TERMS_CONTRACT_TYPES.SIMPLE_INTEREST_LOAN:
return new SimpleInterestLoanAdapter(this.web3, this.contracts);
}
throw new Error(ServicingAPIErrors.UNKNOWN_LOAN_ADAPTER(termsContract));
}
} | the_stack |
// This is a JavaScript implementation of the Richards
// benchmark from:
//
// http://www.cl.cam.ac.uk/~mr10/Bench.html
//
// The benchmark was originally implemented in BCPL by
// Martin Richards.
/*@ type nat = {number | 0 <= v} */
/*@ type natLT[num] = {nat | v < num} */
module RichardsTYPEDVERSION {
declare type MTask = Task<Mutable>
declare type MScheduler = Scheduler<Mutable>
declare type MPacket = Packet<Mutable>
declare type MTaskControlBlock = TaskControlBlock<Mutable>
/*@ readonly COUNT :: number */
let COUNT = 1000;
/**
* These two constants specify how many times a packet is queued and
* how many times a task is put on hold in a correct run of richards.
* They don't have any meaning a such but are characteristic of a
* correct run so if the actual queue or hold count is different from
* the expected there must be a bug in the implementation.
**/
/*@ readonly */
let EXPECTED_QUEUE_COUNT = 2322;
/*@ readonly */
let EXPECTED_HOLD_COUNT = 928;
// ORIG: appeared after all IDs
/*@ readonly NUMBER_OF_IDS :: {number | v = 6} */
let NUMBER_OF_IDS = 6;
/*@ readonly */
let ID_IDLE = 0;
/*@ readonly */
let ID_WORKER = 1;
/*@ readonly */
let ID_HANDLER_A = 2;
/*@ readonly */
let ID_HANDLER_B = 3;
/*@ readonly */
let ID_DEVICE_A = 4;
/*@ readonly */
let ID_DEVICE_B = 5;
/*@ readonly */
let KIND_DEVICE = 0;
/*@ readonly */
let KIND_WORK = 1;
/*@ readonly */
let DATA_SIZE = 4;
/**
* The task is running and is currently scheduled.
*/
/*@ readonly STATE_RUNNING :: bitvector32 */
let STATE_RUNNING = 0x00000000;
/**
* The task has packets left to process.
*/
/*@ readonly STATE_RUNNABLE :: bitvector32 */
let STATE_RUNNABLE = 0x00000001;
/**
* The task is not currently running. The task is not blocked as such and may
* be started by the scheduler.
*/
/*@ readonly STATE_SUSPENDED :: bitvector32 */
let STATE_SUSPENDED = 0x00000002;
/**
* The task is blocked and cannot be run until it is explicitly released.
*/
/*@ readonly STATE_HELD :: bitvector32 */
let STATE_HELD = 0x00000004;
/*@ readonly STATE_SUSPENDED_RUNNABLE :: bitvector32 */
let STATE_SUSPENDED_RUNNABLE = STATE_SUSPENDED | STATE_RUNNABLE;
/*@ readonly STATE_NOT_HELD :: bitvector32 */
let STATE_NOT_HELD = 0xFFFFFFFB //ORIG: ~STATE_HELD;
export function testRichards() {
for (let i =0; i< 50; i++) {
runRichards();
}
}
/**
* The Richards benchmark simulates the task dispatcher of an
* operating system.
**/
function runRichards() {
let scheduler = new Scheduler(0,0,new Array<MTaskControlBlock>(NUMBER_OF_IDS),null,null,-1);
scheduler.addIdleTask(ID_IDLE, 0, null, COUNT);
let queue:MPacket = new Packet(null, ID_WORKER, KIND_WORK, 0);
queue = <MPacket>new Packet(queue, ID_WORKER, KIND_WORK, 0);
scheduler.addWorkerTask(ID_WORKER, 1000, queue);
queue = <MPacket>new Packet(null, ID_DEVICE_A, KIND_DEVICE, 0);
queue = <MPacket>new Packet(queue, ID_DEVICE_A, KIND_DEVICE, 0);
queue = <MPacket>new Packet(queue, ID_DEVICE_A, KIND_DEVICE, 0);
scheduler.addHandlerTask(ID_HANDLER_A, 2000, queue);
queue = <MPacket>new Packet(null, ID_DEVICE_B, KIND_DEVICE, 0);
queue = <MPacket>new Packet(queue, ID_DEVICE_B, KIND_DEVICE, 0);
queue = new Packet(queue, ID_DEVICE_B, KIND_DEVICE, 0);
scheduler.addHandlerTask(ID_HANDLER_B, 3000, queue);
scheduler.addDeviceTask(ID_DEVICE_A, 4000, null);
scheduler.addDeviceTask(ID_DEVICE_B, 5000, null);
scheduler.schedule();
if (scheduler.queueCount !== EXPECTED_QUEUE_COUNT ||
scheduler.holdCount !== EXPECTED_HOLD_COUNT) {
let msg =
"Error during execution: queueCount = " + scheduler.queueCount +
", holdCount = " + scheduler.holdCount + ".";
throw new Error(msg); //TODO
}
}
/**
* A scheduler can be used to schedule a set of tasks based on their relative
* priorities. Scheduling is done by maintaining a list of task control blocks
* which holds tasks and the data queue they are processing.
* @constructor
*/
class Scheduler<M extends ReadOnly> {
/*@ queueCount : number */
public queueCount = 0;
/*@ holdCount : number */
public holdCount = 0;
/*@ blocks : {IArray<MTaskControlBlock + null> | (len v) = NUMBER_OF_IDS} */
public blocks : MTaskControlBlock[] = new Array<MTaskControlBlock>(NUMBER_OF_IDS);
/*@ list : MTaskControlBlock + null */
public list : MTaskControlBlock = null;
/*@ currentTcb : MTaskControlBlock + null */
public currentTcb : MTaskControlBlock = null;
/*@ currentId : {number | -1<=v && v<NUMBER_OF_IDS} */
public currentId:number = -1;
/*@ new (queueCount:number,
holdCount:number,
blocks:{IArray<MTaskControlBlock + null> | (len v) = NUMBER_OF_IDS},
list:MTaskControlBlock + null,
currentTcb:MTaskControlBlock + null,
currentId:{number | -1<=v && v<NUMBER_OF_IDS}) : Scheduler<M> */
//\ () => Scheduler<M>
constructor(queueCount?, holdCount?, blocks?, list?, currentTcb?, currentId?) {
this.queueCount = queueCount;
this.holdCount = holdCount;
this.blocks = blocks;
this.list = list;
this.currentTcb = currentTcb;
this.currentId = currentId;
}
/**
* Add an idle task to this scheduler.
* @param {int} id the identity of the task
* @param {int} priority the task's priority
* @param {Packet} queue the queue of work to be processed by the task
* @param {int} count the number of times to schedule the task
*/
/*@ @Mutable addIdleTask (id:natLT<NUMBER_OF_IDS>,
priority:number,
queue:MPacket + null,
count:number) : void */
public addIdleTask(id: number, priority: number, queue:MPacket, count: number) {
this.addRunningTask(id, priority, queue, new IdleTask(this, 0x00000001, count));
}
/**
* Add a work task to this scheduler.
* @param {int} id the identity of the task
* @param {int} priority the task's priority
* @param {Packet} queue the queue of work to be processed by the task
*/
/*@ @Mutable addWorkerTask (id:natLT<NUMBER_OF_IDS>,
priority:number,
queue:MPacket + null) : void */
public addWorkerTask(id:number, priority:number, queue:MPacket) {
this.addTask(id, priority, queue, new WorkerTask(this, ID_HANDLER_A, 0));
}
/**
* Add a handler task to this scheduler.
* @param {int} id the identity of the task
* @param {int} priority the task's priority
* @param {Packet} queue the queue of work to be processed by the task
*/
/*@ @Mutable addHandlerTask (id:natLT<NUMBER_OF_IDS>,
priority:number,
queue:MPacket + null) : void */
public addHandlerTask(id:number, priority:number, queue:MPacket) {
this.addTask(id, priority, queue, new HandlerTask(this, null, null));
}
/**
* Add a handler task to this scheduler.
* @param {int} id the identity of the task
* @param {int} priority the task's priority
* @param {Packet} queue the queue of work to be processed by the task
*/
/*@ @Mutable addDeviceTask (id:natLT<NUMBER_OF_IDS>,
priority:number,
queue:MPacket + null) : void */
public addDeviceTask(id:number, priority:number, queue:MPacket) {
this.addTask(id, priority, queue, new DeviceTask(this, null))
}
/**
* Add the specified task and mark it as running.
* @param {int} id the identity of the task
* @param {int} priority the task's priority
* @param {Packet} queue the queue of work to be processed by the task
* @param {Task} task the task to add
*/
/*@ @Mutable addRunningTask (id:natLT<NUMBER_OF_IDS>,
priority:number,
queue:MPacket + null,
task:MTask) : void */
public addRunningTask(id:number, priority:number, queue:MPacket, task:MTask) {
this.addTask(id, priority, queue, task);
let currentTcb = this.currentTcb;
if (!currentTcb) throw new Error('This check should never fail'); // since addTask sets this.currentTcb
currentTcb.setRunning();
}
/**
* Add the specified task to this scheduler.
* @param {int} id the identity of the task
* @param {int} priority the task's priority
* @param {Packet} queue the queue of work to be processed by the task
* @param {Task} task the task to add
*/
/*@ @Mutable addTask (id:natLT<NUMBER_OF_IDS>,
priority:number,
queue:MPacket + null,
task:MTask) : {void | 0 < 1} */
public addTask(id:number, priority:number, queue:MPacket, task:MTask) {
this.currentTcb = <MTaskControlBlock> new TaskControlBlock(this.list, id, priority, queue, task);
this.list = this.currentTcb;
this.blocks[id] = this.currentTcb;
}
/**
* Execute the tasks managed by this scheduler.
*/
/*@ @Mutable schedule () : {void | 0 < 1} */
public schedule() {
this.currentTcb = this.list;
let currentTcb = this.currentTcb;
while (currentTcb) {
console.log("+");
if (currentTcb.isHeldOrSuspended()) {
this.currentTcb = currentTcb.link;
} else {
this.currentId = currentTcb.id;
this.currentTcb = currentTcb.run();
}
currentTcb = this.currentTcb;
}
}
/**
* Release a task that is currently blocked and return the next block to run.
* @param {int} id the id of the task to suspend
*/
/*@ release (id:natLT<NUMBER_OF_IDS>) : {MTaskControlBlock + null | 0 < 1} */
public release(id:number) {
let tcb = this.blocks[id];
if (!tcb) return tcb;
let currentTcb = this.currentTcb;
if (!currentTcb) throw new Error("Illegal state");
tcb.markAsNotHeld();
if (tcb.priority > currentTcb.priority) {
return tcb;
} else {
return currentTcb;
}
}
/**
* Block the currently executing task and return the next task control block
* to run. The blocked task will not be made runnable until it is explicitly
* released, even if new work is added to it.
*/
/*@ @Mutable holdCurrent () : MTaskControlBlock + null */
public holdCurrent() {
let currentTcb = this.currentTcb;
if (!currentTcb) throw new Error("Illegal state");
this.holdCount++;
currentTcb.markAsHeld();
return currentTcb.link;
}
/**
* Suspend the currently executing task and return the next task control block
* to run. If new work is added to the suspended task it will be made runnable.
*/
/*@ suspendCurrent () : MTaskControlBlock */
public suspendCurrent () {
let currentTcb = this.currentTcb;
if (!currentTcb) throw new Error("Illegal state");
currentTcb.markAsSuspended();
return currentTcb;
}
/**
* Add the specified packet to the end of the worklist used by the task
* associated with the packet and make the task runnable if it is currently
* suspended.
* @param {Packet} packet the packet to add
*/
/*@ @Mutable queue (packet: MPacket) : {MTaskControlBlock + null | 0 < 1} */
public queue(packet) {
let t = this.blocks[packet.id];
if (!t) return t;
this.queueCount++;
packet.link = null;
let currentId = this.currentId;
if (currentId === -1) throw new Error("Illegal state");
packet.id = currentId;
let currentTcb = this.currentTcb;
if (!currentTcb) throw new Error("Illegal state");
return t.checkPriorityAdd(currentTcb, packet);
}
}
class TaskControlBlock<M extends ReadOnly> {
/*@ state : bitvector32 */
private state = 0x00000000;
/*@ link : MTaskControlBlock + null */
public link;
/*@ id : natLT<NUMBER_OF_IDS> */
public id;
public priority;
/*@ queue : MPacket + null */
public queue;
/*@ task : MTask */
public task;
/**
* A task control block manages a task and the queue of work packages associated
* with it.
* @param {TaskControlBlock} link the preceding block in the linked block list
* @param {int} id the id of this block
* @param {int} priority the priority of this block
* @param {Packet} queue the queue of packages to be processed by the task
* @param {Task} task the task
* @constructor
*/
/*@ new (link:MTaskControlBlock + null,
id:natLT<NUMBER_OF_IDS>,
priority:number,
queue:MPacket + null,
task:MTask): TaskControlBlock<M> */
constructor(link, id, priority, queue, task) {
this.link = link;
this.id = id;
this.priority = priority;
this.queue = queue;
this.task = task;
//ORIG:
// if (!queue) {
this.state = STATE_SUSPENDED;
// } else {
// this.state = STATE_SUSPENDED_RUNNABLE;
// }
}
/*@ @Mutable setRunning () : {void | 0 < 1} */
public setRunning () {
this.state = STATE_RUNNING;
}
/*@ @Mutable markAsNotHeld () : {void | 0 < 1} */
public markAsNotHeld () {
this.state = this.state // PORT TODO: & STATE_NOT_HELD;
}
/*@ @Mutable markAsHeld () : {void | 0 < 1} */
public markAsHeld () {
this.state = this.state // PORT TODO: | STATE_HELD;
}
public isHeldOrSuspended () {
return true // PORT TODO: (this.state & STATE_HELD) !== 0 || (this.state === STATE_SUSPENDED);
}
/*@ @Mutable markAsSuspended () : {void | 0 < 1} */
public markAsSuspended () {
this.state = this.state // PORT TODO: | STATE_SUSPENDED;
}
/*@ @Mutable markAsRunnable () : {void | 0 < 1} */
public markAsRunnable () {
this.state = this.state // PORT TODO: | STATE_RUNNABLE;
}
/**
* Runs this task, if it is ready to be run, and returns the next task to run.
*/
/*@ @Mutable run () : {MTaskControlBlock + null | 0 < 1} */
public run () {
//ORIG:
// if (!(this.state === STATE_SUSPENDED_RUNNABLE)) {
// return this.task.run();
// }
let packet = this.queue;
if (!packet) throw new Error("Illegal state: this.queue is null yet this.state is SUSPENDED_RUNNABLE");
this.queue = packet.link;
//ORIG:
// if (!this.queue) {
// this.state = STATE_RUNNING;
// } else {
// this.state = STATE_RUNNABLE;
// }
return this.task.run(packet);
}
/**
* Adds a packet to the worklist of this block's task, marks this as runnable if
* necessary, and returns the next runnable object to run (the one
* with the highest priority).
*/
/*@ @Mutable checkPriorityAdd (task:MTaskControlBlock,
packet:MPacket) : MTaskControlBlock */
public checkPriorityAdd (task, packet) {
if (!this.queue) {
this.queue = packet;
this.markAsRunnable();
if (this.priority > task.priority) return this;
} else {
this.queue = packet.addTo(this.queue);
}
return task;
}
public toString () {
//TODO: explicit String call shouldn't be necessary
return "tcb { " + String(this.task) + "@" + String(this.state) + " }";
}
}
class Task<M extends ReadOnly> {
constructor() {}
/*@ @Mutable run (packet: MPacket) : { MTaskControlBlock + null | 0 < 1 } */
/*@ @Mutable run () : { MTaskControlBlock + null | 0 < 1 } */
public run(packet:MPacket) : MTaskControlBlock {
throw "Abstract method";
}
}
class IdleTask<M extends ReadOnly> extends Task<M> {
/*@ scheduler : MScheduler */
public scheduler;
/*@ v1 : bitvector32 */
public v1;
/*@ count : number */
public count;
/**
* An idle task doesn't do any work itself but cycles control between the two
* device tasks.
* @param {Scheduler} scheduler the scheduler that manages this task
* @param {int} v1 a seed value that controls how the device tasks are scheduled
* @param {int} count the number of times this task should be scheduled
* @constructor
*/
/*@ new (scheduler:MScheduler, v1:bitvector32, count:number) : {IdleTask<M> | 0 < 1} */
constructor(scheduler, v1, count) {
super();
this.scheduler = scheduler;
this.v1 = v1;
this.count = count;
}
/*@ @Mutable run (packet: Packet<ReadOnly>) : { MTaskControlBlock + null | 0 < 1 } */
/*@ @Mutable run () : { MTaskControlBlock + null | 0 < 1 } */
public run(packet:MPacket) : MTaskControlBlock {
this.count--;
if (this.count === 0) return this.scheduler.holdCurrent();
//ORIG:
// if ((this.v1 & 1) === 0) {
// this.v1 = this.v1 >> 1;
return this.scheduler.release(ID_DEVICE_A);
// } else {
// this.v1 = (this.v1 >> 1) ^ 0xD008;
// return this.scheduler.release(ID_DEVICE_B);
// }
}
public toString() {
return "IdleTask";
}
}
class DeviceTask<M extends ReadOnly> extends Task<M> {
/*@ scheduler : MScheduler */
public scheduler;
/*@ v1 : MPacket + null */
public v1 = null;
/**
* A task that suspends itself after each time it has been run to simulate
* waiting for data from an external device.
* @param {Scheduler} scheduler the scheduler that manages this task
* @constructor
*/
/*@ new (scheduler:MScheduler, v1:MPacket + null) : {DeviceTask<M> | 0 < 1} */
//\ (scheduler:MScheduler) => {DeviceTask<M> | 0 < 1} */
constructor(scheduler, v1?) {
super();
this.scheduler = scheduler;
this.v1 = v1;// if (arguments.length === 2) this.v1 = v1;
}
/*@ @Mutable run (packet: MPacket) : { MTaskControlBlock + null | 0 < 1 } */
/*@ @Mutable run () : { MTaskControlBlock + null | 0 < 1 } */
public run(packet:MPacket) : MTaskControlBlock {
if (!packet) {
let v1 = this.v1;
if (!v1) return this.scheduler.suspendCurrent();
let v = v1;
this.v1 = null;
return this.scheduler.queue(v);
} else {
this.v1 = packet;
return this.scheduler.holdCurrent();
}
}
public toString() {
return "DeviceTask";
}
}
class WorkerTask<M extends ReadOnly> extends Task<M> {
/*@ scheduler : MScheduler */
public scheduler;
/*@ v1 : natLT<NUMBER_OF_IDS> */
public v1;
/*@ v2 : nat */
public v2;
/**
* A task that manipulates work packets.
* @param {Scheduler} scheduler the scheduler that manages this task
* @param {int} v1 a seed used to specify how work packets are manipulated
* @param {int} v2 another seed used to specify how work packets are manipulated
* @constructor
*/
/*@ new (scheduler:MScheduler, v1:natLT<NUMBER_OF_IDS>, v2:nat) : WorkerTask<M> */
constructor(scheduler, v1, v2) {
super();
this.scheduler = scheduler;
this.v1 = v1;
this.v2 = v2;
}
/*@ @Mutable run (packet: MPacket) : { MTaskControlBlock + null | 0 < 1 } */
/*@ @Mutable run () : { MTaskControlBlock + null | 0 < 1 } */
public run(packet:MPacket) : MTaskControlBlock {
if (!packet) {
return this.scheduler.suspendCurrent();
} else {
if (this.v1 === ID_HANDLER_A) {
this.v1 = ID_HANDLER_B;
} else {
this.v1 = ID_HANDLER_A;
}
(<MPacket>packet).id = this.v1;
(<MPacket>packet).a1 = 0;
for (let i = 0; i < DATA_SIZE; i++) {
this.v2++;
if (this.v2 > 26) this.v2 = 1;
packet.a2[i] = this.v2;
}
return this.scheduler.queue(packet);
}
}
public toString() {
return "WorkerTask";
}
}
class HandlerTask<M extends ReadOnly> extends Task<M> {
/*@ scheduler : MScheduler */
public scheduler;
/*@ v1 : MPacket + null */
public v1 = null;
/*@ v2 : MPacket + null */
public v2 = null;
/**
* A task that manipulates work packets and then suspends itself.
* @param {Scheduler} scheduler the scheduler that manages this task
* @constructor
*/
/*@ new (scheduler:MScheduler, v1:MPacket + null, v2:MPacket + null) : {HandlerTask<M> | 0 < 1} */
//\ (scheduler:MScheduler) => {HandlerTask<M> | 0 < 1} */
constructor(scheduler, v1?, v2?) {
super();
this.scheduler = scheduler;
// if (arguments.length === 3) {
this.v1 = v1;
this.v2 = v2;
// }
}
/*@ @Mutable run (packet: MPacket) : { MTaskControlBlock + null | 0 < 1 } */
/*@ @Mutable run () : { MTaskControlBlock + null | 0 < 1 } */
public run(packet:MPacket) : MTaskControlBlock {
if (packet) {
if (packet.kind === KIND_WORK) {
this.v1 = packet.addTo(this.v1);
} else {
this.v2 = packet.addTo(this.v2);
}
}
let v1 = this.v1;
if (v1) {
let count = v1.a1;
if (count < DATA_SIZE) {
let v2 = this.v2;
if (v2) {
let v = v2;
this.v2 = v2.link;
(<MPacket>v).a1 = (<MPacket>v1).a2[count];
(<MPacket>v1).a1 = count + 1;
return this.scheduler.queue(v);
}
} else {
let v = v1;
this.v1 = v1.link;
return this.scheduler.queue(v);
}
}
return this.scheduler.suspendCurrent();
}
public toString() {
return "HandlerTask";
}
}
/* --- *
* P a c k e t
* --- */
class Packet<M extends ReadOnly> {
/*@ a2 : {IArray<nat> | (len v) = DATA_SIZE} */
public a2;
/*@ link : MPacket + null */
public link;
/*@ id : natLT<NUMBER_OF_IDS> */
public id;
public kind:number;
/*@ a1 : nat */
public a1 = 0;
/**
* A simple package of data that is manipulated by the tasks. The exact layout
* of the payload data carried by a packet is not importaint, and neither is the
* nature of the work performed on packets by the tasks.
*
* Besides carrying data, packets form linked lists and are hence used both as
* data and worklists.
* @param {Packet} link the tail of the linked list of packets
* @param {int} id an ID for this packet
* @param {int} kind the type of this packet
* @constructor
*/
/*@ new (link:MPacket + null, id:natLT<NUMBER_OF_IDS>, kind:number, a1:nat) : Packet<M> */
//\ (link:MPacket + null, id:natLT<NUMBER_OF_IDS>, kind:number) => Packet<M> */
constructor(link, id, kind, a1?) {
this.a2 = new Array(DATA_SIZE);
this.link = link;
this.id = id;
this.kind = kind;
this.a1 = a1;
// if (arguments.length === 4) this.a1 = a1;
}
/**
* Add this packet to the end of a worklist, and return the worklist.
* @param {Packet} queue the worklist to add this packet to
*/
/*@ @Mutable addTo (queue: MPacket + null) : MPacket */
public addTo(queue:MPacket) : MPacket {
this.link = null;
if (!queue) return this;
let next = queue;
let peek = next.link;
while (peek) {
next = peek;
peek = next.link;
}
(<MPacket>next).link = this;
return queue;
}
public toString() {
return "Packet";
}
}
} | the_stack |
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
import * as utils from "../utils/common.js";
import { adler32 } from "./adler32.js";
import { crc32 } from "./crc32.js";
import { inflate_fast } from "./inffast.js";
import { inflate_table } from "./inftrees.js";
// var utils = require('../utils/common');
// var adler32 = require('./adler32');
// var crc32 = require('./crc32');
// var inflate_fast = require('./inffast');
// var inflate_table = require('./inftrees');
var CODES = 0;
var LENS = 1;
var DISTS = 2;
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
//var Z_NO_FLUSH = 0;
//var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
//var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* The deflate compression method */
var Z_DEFLATED = 8;
/* STATES ====================================================================*/
/* ===========================================================================*/
var HEAD = 1; /* i: waiting for magic header */
var FLAGS = 2; /* i: waiting for method and flags (gzip) */
var TIME = 3; /* i: waiting for modification time (gzip) */
var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
var EXLEN = 5; /* i: waiting for extra length (gzip) */
var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
var NAME = 7; /* i: waiting for end of file name (gzip) */
var COMMENT = 8; /* i: waiting for end of comment (gzip) */
var HCRC = 9; /* i: waiting for header crc (gzip) */
var DICTID = 10; /* i: waiting for dictionary check value */
var DICT = 11; /* waiting for inflateSetDictionary() call */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
var STORED = 14; /* i: waiting for stored size (length and complement) */
var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
var COPY = 16; /* i/o: waiting for input or output to copy stored block */
var TABLE = 17; /* i: waiting for dynamic block table lengths */
var LENLENS = 18; /* i: waiting for code length code lengths */
var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
var LEN_ = 20; /* i: same as LEN below, but only first time in */
var LEN = 21; /* i: waiting for length/lit/eob code */
var LENEXT = 22; /* i: waiting for length extra bits */
var DIST = 23; /* i: waiting for distance code */
var DISTEXT = 24; /* i: waiting for distance extra bits */
var MATCH = 25; /* o: waiting for output space to copy string */
var LIT = 26; /* o: waiting for output space to write literal */
var CHECK = 27; /* i: waiting for 32-bit check value */
var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
var DONE = 29; /* finished check, done -- remain here until reset */
var BAD = 30; /* got a data error -- remain here until reset */
var MEM = 31; /* got an inflate() memory error -- remain here until reset */
var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
/* ===========================================================================*/
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_WBITS = MAX_WBITS;
function zswap32(q) {
return (((q >>> 24) & 0xff) +
((q >>> 8) & 0xff00) +
((q & 0xff00) << 8) +
((q & 0xff) << 24));
}
function InflateState() {
this.mode = 0; /* current inflate mode */
this.last = false; /* true if processing last block */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.havedict = false; /* true if dictionary provided */
this.flags = 0; /* gzip header method and flags (0 if zlib) */
this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
this.check = 0; /* protected copy of check value */
this.total = 0; /* protected copy of output count */
// TODO: may be {}
this.head = null; /* where to save gzip header information */
/* sliding window */
this.wbits = 0; /* log base 2 of requested window size */
this.wsize = 0; /* window size or zero if not using window */
this.whave = 0; /* valid bytes in the window */
this.wnext = 0; /* window write index */
this.window = null; /* allocated sliding window, if needed */
/* bit accumulator */
this.hold = 0; /* input bit accumulator */
this.bits = 0; /* number of bits in "in" */
/* for string and stored block copying */
this.length = 0; /* literal or length of data to copy */
this.offset = 0; /* distance back to copy string from */
/* for table and code decoding */
this.extra = 0; /* extra bits needed */
/* fixed and dynamic code tables */
this.lencode = null; /* starting table for length/literal codes */
this.distcode = null; /* starting table for distance codes */
this.lenbits = 0; /* index bits for lencode */
this.distbits = 0; /* index bits for distcode */
/* dynamic table building */
this.ncode = 0; /* number of code length code lengths */
this.nlen = 0; /* number of length code lengths */
this.ndist = 0; /* number of distance code lengths */
this.have = 0; /* number of code lengths in lens[] */
this.next = null; /* next available space in codes[] */
this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
this.work = new utils.Buf16(288); /* work area for code table building */
/*
because we don't have pointers in js, we use lencode and distcode directly
as buffers so we don't need codes
*/
//this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
this.distdyn = null; /* dynamic table for distance codes (JS specific) */
this.sane = 0; /* if false, allow invalid distance too far */
this.back = 0; /* bits back of last unprocessed length/lit */
this.was = 0; /* initial length of match */
}
function inflateResetKeep(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
strm.total_in = strm.total_out = state.total = 0;
strm.msg = ''; /*Z_NULL*/
if (state.wrap) { /* to support ill-conceived Java test suite */
strm.adler = state.wrap & 1;
}
state.mode = HEAD;
state.last = 0;
state.havedict = 0;
state.dmax = 32768;
state.head = null/*Z_NULL*/;
state.hold = 0;
state.bits = 0;
//state.lencode = state.distcode = state.next = state.codes;
state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
state.sane = 1;
state.back = -1;
//Tracev((stderr, "inflate: reset\n"));
return Z_OK;
}
function inflateReset(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
state.wsize = 0;
state.whave = 0;
state.wnext = 0;
return inflateResetKeep(strm);
}
function inflateReset2(strm, windowBits) {
var wrap;
var state;
/* get the state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
/* extract wrap request from windowBits parameter */
if (windowBits < 0) {
wrap = 0;
windowBits = -windowBits;
}
else {
wrap = (windowBits >> 4) + 1;
if (windowBits < 48) {
windowBits &= 15;
}
}
/* set number of window bits, free window if different */
if (windowBits && (windowBits < 8 || windowBits > 15)) {
return Z_STREAM_ERROR;
}
if (state.window !== null && state.wbits !== windowBits) {
state.window = null;
}
/* update state and reset the rest of it */
state.wrap = wrap;
state.wbits = windowBits;
return inflateReset(strm);
}
function inflateInit2(strm, windowBits) {
var ret;
var state;
if (!strm) { return Z_STREAM_ERROR; }
//strm.msg = Z_NULL; /* in case we return an error */
state = new InflateState();
//if (state === Z_NULL) return Z_MEM_ERROR;
//Tracev((stderr, "inflate: allocated\n"));
strm.state = state;
state.window = null/*Z_NULL*/;
ret = inflateReset2(strm, windowBits);
if (ret !== Z_OK) {
strm.state = null/*Z_NULL*/;
}
return ret;
}
function inflateInit(strm) {
return inflateInit2(strm, DEF_WBITS);
}
/*
Return state with length and distance decoding tables and index sizes set to
fixed code decoding. Normally this returns fixed tables from inffixed.h.
If BUILDFIXED is defined, then instead this routine builds the tables the
first time it's called, and returns those tables the first time and
thereafter. This reduces the size of the code by about 2K bytes, in
exchange for a little execution time. However, BUILDFIXED should not be
used for threaded applications, since the rewriting of the tables and virgin
may not be thread-safe.
*/
var virgin = true;
var lenfix, distfix; // We have no pointers in JS, so keep tables separate
function fixedtables(state) {
/* build fixed huffman tables if first call (may not be thread safe) */
if (virgin) {
var sym;
lenfix = new utils.Buf32(512);
distfix = new utils.Buf32(32);
/* literal/length table */
sym = 0;
while (sym < 144) { state.lens[sym++] = 8; }
while (sym < 256) { state.lens[sym++] = 9; }
while (sym < 280) { state.lens[sym++] = 7; }
while (sym < 288) { state.lens[sym++] = 8; }
inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
/* distance table */
sym = 0;
while (sym < 32) { state.lens[sym++] = 5; }
inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
/* do this just once */
virgin = false;
}
state.lencode = lenfix;
state.lenbits = 9;
state.distcode = distfix;
state.distbits = 5;
}
/*
Update the window with the last wsize (normally 32K) bytes written before
returning. If window does not exist yet, create it. This is only called
when a window is already in use, or when output has been written during this
inflate call, but the end of the deflate stream has not been reached yet.
It is also called to create a window for dictionary data when a dictionary
is loaded.
Providing output buffers larger than 32K to inflate() should provide a speed
advantage, since only the last 32K of output is copied to the sliding window
upon return from inflate(), and since all distances after the first 32K of
output will fall in the output data, making match copies simpler and faster.
The advantage may be dependent on the size of the processor's data caches.
*/
function updatewindow(strm, src, end, copy) {
var dist;
var state = strm.state;
/* if it hasn't been done already, allocate space for the window */
if (state.window === null) {
state.wsize = 1 << state.wbits;
state.wnext = 0;
state.whave = 0;
state.window = new utils.Buf8(state.wsize);
}
/* copy state->wsize or less output bytes into the circular window */
if (copy >= state.wsize) {
utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
state.wnext = 0;
state.whave = state.wsize;
}
else {
dist = state.wsize - state.wnext;
if (dist > copy) {
dist = copy;
}
//zmemcpy(state->window + state->wnext, end - copy, dist);
utils.arraySet(state.window, src, end - copy, dist, state.wnext);
copy -= dist;
if (copy) {
//zmemcpy(state->window, end - copy, copy);
utils.arraySet(state.window, src, end - copy, copy, 0);
state.wnext = copy;
state.whave = state.wsize;
}
else {
state.wnext += dist;
if (state.wnext === state.wsize) { state.wnext = 0; }
if (state.whave < state.wsize) { state.whave += dist; }
}
}
return 0;
}
function inflate(strm, flush) {
var state;
var input, output; // input/output buffers
var next; /* next input INDEX */
var put; /* next output INDEX */
var have, left; /* available input and output */
var hold; /* bit buffer */
var bits; /* bits in bit buffer */
var _in, _out; /* save starting available input and output */
var copy; /* number of stored or match bytes to copy */
var from; /* where to copy match bytes from */
var from_source;
var here = 0; /* current decoding table entry */
var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
//var last; /* parent table entry */
var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
var len; /* length to copy for repeats, bits to drop */
var ret; /* return code */
var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
var opts;
var n; // temporary var for NEED_BITS
var order = /* permutation of code lengths */
[ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
if (!strm || !strm.state || !strm.output ||
(!strm.input && strm.avail_in !== 0)) {
return Z_STREAM_ERROR;
}
state = strm.state;
if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
_in = have;
_out = left;
ret = Z_OK;
inf_leave: // goto emulation
for (;;) {
switch (state.mode) {
case HEAD:
if (state.wrap === 0) {
state.mode = TYPEDO;
break;
}
//=== NEEDBITS(16);
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
state.check = 0/*crc32(0L, Z_NULL, 0)*/;
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = FLAGS;
break;
}
state.flags = 0; /* expect zlib header */
if (state.head) {
state.head.done = false;
}
if (!(state.wrap & 1) || /* check if zlib header allowed */
(((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
strm.msg = 'incorrect header check';
state.mode = BAD;
break;
}
if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
len = (hold & 0x0f)/*BITS(4)*/ + 8;
if (state.wbits === 0) {
state.wbits = len;
}
else if (len > state.wbits) {
strm.msg = 'invalid window size';
state.mode = BAD;
break;
}
state.dmax = 1 << len;
//Tracev((stderr, "inflate: zlib header ok\n"));
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = hold & 0x200 ? DICTID : TYPE;
//=== INITBITS();
hold = 0;
bits = 0;
//===//
break;
case FLAGS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.flags = hold;
if ((state.flags & 0xff) !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
if (state.flags & 0xe000) {
strm.msg = 'unknown header flags set';
state.mode = BAD;
break;
}
if (state.head) {
state.head.text = ((hold >> 8) & 1);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = TIME;
/* falls through */
case TIME:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.time = hold;
}
if (state.flags & 0x0200) {
//=== CRC4(state.check, hold)
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
hbuf[2] = (hold >>> 16) & 0xff;
hbuf[3] = (hold >>> 24) & 0xff;
state.check = crc32(state.check, hbuf, 4, 0);
//===
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = OS;
/* falls through */
case OS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.xflags = (hold & 0xff);
state.head.os = (hold >> 8);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = EXLEN;
/* falls through */
case EXLEN:
if (state.flags & 0x0400) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length = hold;
if (state.head) {
state.head.extra_len = hold;
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
else if (state.head) {
state.head.extra = null/*Z_NULL*/;
}
state.mode = EXTRA;
/* falls through */
case EXTRA:
if (state.flags & 0x0400) {
copy = state.length;
if (copy > have) { copy = have; }
if (copy) {
if (state.head) {
len = state.head.extra_len - state.length;
if (!state.head.extra) {
// Use untyped array for more convenient processing later
state.head.extra = new Array(state.head.extra_len);
}
utils.arraySet(
state.head.extra,
input,
next,
// extra field is limited to 65536 bytes
// - no need for additional size check
copy,
/*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
len
);
//zmemcpy(state.head.extra + len, next,
// len + copy > state.head.extra_max ?
// state.head.extra_max - len : copy);
}
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
state.length -= copy;
}
if (state.length) { break inf_leave; }
}
state.length = 0;
state.mode = NAME;
/* falls through */
case NAME:
if (state.flags & 0x0800) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
// TODO: 2 or 1 bytes?
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.name_max*/)) {
state.head.name += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.name = null;
}
state.length = 0;
state.mode = COMMENT;
/* falls through */
case COMMENT:
if (state.flags & 0x1000) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.comm_max*/)) {
state.head.comment += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.comment = null;
}
state.mode = HCRC;
/* falls through */
case HCRC:
if (state.flags & 0x0200) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.check & 0xffff)) {
strm.msg = 'header crc mismatch';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
if (state.head) {
state.head.hcrc = ((state.flags >> 9) & 1);
state.head.done = true;
}
strm.adler = state.check = 0;
state.mode = TYPE;
break;
case DICTID:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
strm.adler = state.check = zswap32(hold);
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = DICT;
/* falls through */
case DICT:
if (state.havedict === 0) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
return Z_NEED_DICT;
}
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
/* falls through */
case TYPE:
if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
/* falls through */
case TYPEDO:
if (state.last) {
//--- BYTEBITS() ---//
hold >>>= bits & 7;
bits -= bits & 7;
//---//
state.mode = CHECK;
break;
}
//=== NEEDBITS(3); */
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.last = (hold & 0x01)/*BITS(1)*/;
//--- DROPBITS(1) ---//
hold >>>= 1;
bits -= 1;
//---//
switch ((hold & 0x03)/*BITS(2)*/) {
case 0: /* stored block */
//Tracev((stderr, "inflate: stored block%s\n",
// state.last ? " (last)" : ""));
state.mode = STORED;
break;
case 1: /* fixed block */
fixedtables(state);
//Tracev((stderr, "inflate: fixed codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = LEN_; /* decode codes */
if (flush === Z_TREES) {
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break inf_leave;
}
break;
case 2: /* dynamic block */
//Tracev((stderr, "inflate: dynamic codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = TABLE;
break;
case 3:
strm.msg = 'invalid block type';
state.mode = BAD;
}
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break;
case STORED:
//--- BYTEBITS() ---// /* go to byte boundary */
hold >>>= bits & 7;
bits -= bits & 7;
//---//
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
strm.msg = 'invalid stored block lengths';
state.mode = BAD;
break;
}
state.length = hold & 0xffff;
//Tracev((stderr, "inflate: stored length %u\n",
// state.length));
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = COPY_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case COPY_:
state.mode = COPY;
/* falls through */
case COPY:
copy = state.length;
if (copy) {
if (copy > have) { copy = have; }
if (copy > left) { copy = left; }
if (copy === 0) { break inf_leave; }
//--- zmemcpy(put, next, copy); ---
utils.arraySet(output, input, next, copy, put);
//---//
have -= copy;
next += copy;
left -= copy;
put += copy;
state.length -= copy;
break;
}
//Tracev((stderr, "inflate: stored end\n"));
state.mode = TYPE;
break;
case TABLE:
//=== NEEDBITS(14); */
while (bits < 14) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
//#ifndef PKZIP_BUG_WORKAROUND
if (state.nlen > 286 || state.ndist > 30) {
strm.msg = 'too many length or distance symbols';
state.mode = BAD;
break;
}
//#endif
//Tracev((stderr, "inflate: table sizes ok\n"));
state.have = 0;
state.mode = LENLENS;
/* falls through */
case LENLENS:
while (state.have < state.ncode) {
//=== NEEDBITS(3);
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
while (state.have < 19) {
state.lens[order[state.have++]] = 0;
}
// We have separate tables & no pointers. 2 commented lines below not needed.
//state.next = state.codes;
//state.lencode = state.next;
// Switch to use dynamic table
state.lencode = state.lendyn;
state.lenbits = 7;
opts = { bits: state.lenbits };
ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
state.lenbits = opts.bits;
if (ret) {
strm.msg = 'invalid code lengths set';
state.mode = BAD;
break;
}
//Tracev((stderr, "inflate: code lengths ok\n"));
state.have = 0;
state.mode = CODELENS;
/* falls through */
case CODELENS:
while (state.have < state.nlen + state.ndist) {
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_val < 16) {
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.lens[state.have++] = here_val;
}
else {
if (here_val === 16) {
//=== NEEDBITS(here.bits + 2);
n = here_bits + 2;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
if (state.have === 0) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
len = state.lens[state.have - 1];
copy = 3 + (hold & 0x03);//BITS(2);
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
}
else if (here_val === 17) {
//=== NEEDBITS(here.bits + 3);
n = here_bits + 3;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 3 + (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
else {
//=== NEEDBITS(here.bits + 7);
n = here_bits + 7;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 11 + (hold & 0x7f);//BITS(7);
//--- DROPBITS(7) ---//
hold >>>= 7;
bits -= 7;
//---//
}
if (state.have + copy > state.nlen + state.ndist) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
while (copy--) {
state.lens[state.have++] = len;
}
}
}
/* handle error breaks in while */
if (state.mode === BAD) { break; }
/* check for end-of-block code (better have one) */
if (state.lens[256] === 0) {
strm.msg = 'invalid code -- missing end-of-block';
state.mode = BAD;
break;
}
/* build code tables -- note: do not change the lenbits or distbits
values here (9 and 6) without reading the comments in inftrees.h
concerning the ENOUGH constants, which depend on those values */
state.lenbits = 9;
opts = { bits: state.lenbits };
ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.lenbits = opts.bits;
// state.lencode = state.next;
if (ret) {
strm.msg = 'invalid literal/lengths set';
state.mode = BAD;
break;
}
state.distbits = 6;
//state.distcode.copy(state.codes);
// Switch to use dynamic table
state.distcode = state.distdyn;
opts = { bits: state.distbits };
ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.distbits = opts.bits;
// state.distcode = state.next;
if (ret) {
strm.msg = 'invalid distances set';
state.mode = BAD;
break;
}
//Tracev((stderr, 'inflate: codes ok\n'));
state.mode = LEN_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case LEN_:
state.mode = LEN;
/* falls through */
case LEN:
if (have >= 6 && left >= 258) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
inflate_fast(strm, _out);
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
if (state.mode === TYPE) {
state.back = -1;
}
break;
}
state.back = 0;
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if (here_bits <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_op && (here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.lencode[last_val +
((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
state.length = here_val;
if (here_op === 0) {
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
state.mode = LIT;
break;
}
if (here_op & 32) {
//Tracevv((stderr, "inflate: end of block\n"));
state.back = -1;
state.mode = TYPE;
break;
}
if (here_op & 64) {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break;
}
state.extra = here_op & 15;
state.mode = LENEXT;
/* falls through */
case LENEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//Tracevv((stderr, "inflate: length %u\n", state.length));
state.was = state.length;
state.mode = DIST;
/* falls through */
case DIST:
for (;;) {
here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if ((here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.distcode[last_val +
((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
if (here_op & 64) {
strm.msg = 'invalid distance code';
state.mode = BAD;
break;
}
state.offset = here_val;
state.extra = (here_op) & 15;
state.mode = DISTEXT;
/* falls through */
case DISTEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//#ifdef INFLATE_STRICT
if (state.offset > state.dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
//#endif
//Tracevv((stderr, "inflate: distance %u\n", state.offset));
state.mode = MATCH;
/* falls through */
case MATCH:
if (left === 0) { break inf_leave; }
copy = _out - left;
if (state.offset > copy) { /* copy from window */
copy = state.offset - copy;
if (copy > state.whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
// (!) This block is disabled in zlib defaults,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// Trace((stderr, "inflate.c too far\n"));
// copy -= state.whave;
// if (copy > state.length) { copy = state.length; }
// if (copy > left) { copy = left; }
// left -= copy;
// state.length -= copy;
// do {
// output[put++] = 0;
// } while (--copy);
// if (state.length === 0) { state.mode = LEN; }
// break;
//#endif
}
if (copy > state.wnext) {
copy -= state.wnext;
from = state.wsize - copy;
}
else {
from = state.wnext - copy;
}
if (copy > state.length) { copy = state.length; }
from_source = state.window;
}
else { /* copy from output */
from_source = output;
from = put - state.offset;
copy = state.length;
}
if (copy > left) { copy = left; }
left -= copy;
state.length -= copy;
do {
output[put++] = from_source[from++];
} while (--copy);
if (state.length === 0) { state.mode = LEN; }
break;
case LIT:
if (left === 0) { break inf_leave; }
output[put++] = state.length;
left--;
state.mode = LEN;
break;
case CHECK:
if (state.wrap) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
// Use '|' instead of '+' to make sure that result is signed
hold |= input[next++] << bits;
bits += 8;
}
//===//
_out -= left;
strm.total_out += _out;
state.total += _out;
if (_out) {
strm.adler = state.check =
/*UPDATE(state.check, put - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
}
_out = left;
// NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
if ((state.flags ? hold : zswap32(hold)) !== state.check) {
strm.msg = 'incorrect data check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: check matches trailer\n"));
}
state.mode = LENGTH;
/* falls through */
case LENGTH:
if (state.wrap && state.flags) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.total & 0xffffffff)) {
strm.msg = 'incorrect length check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: length matches trailer\n"));
}
state.mode = DONE;
/* falls through */
case DONE:
ret = Z_STREAM_END;
break inf_leave;
case BAD:
ret = Z_DATA_ERROR;
break inf_leave;
case MEM:
return Z_MEM_ERROR;
case SYNC:
/* falls through */
default:
return Z_STREAM_ERROR;
}
}
// inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
/*
Return from inflate(), updating the total counts and the check value.
If there was no progress during the inflate() call, return a buffer
error. Call updatewindow() to create and/or update the window state.
Note: a memory error from inflate() is non-recoverable.
*/
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
(state.mode < CHECK || flush !== Z_FINISH))) {
if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
state.mode = MEM;
return Z_MEM_ERROR;
}
}
_in -= strm.avail_in;
_out -= strm.avail_out;
strm.total_in += _in;
strm.total_out += _out;
state.total += _out;
if (state.wrap && _out) {
strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
}
strm.data_type = state.bits + (state.last ? 64 : 0) +
(state.mode === TYPE ? 128 : 0) +
(state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
ret = Z_BUF_ERROR;
}
return ret;
}
function inflateEnd(strm) {
if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
return Z_STREAM_ERROR;
}
var state = strm.state;
if (state.window) {
state.window = null;
}
strm.state = null;
return Z_OK;
}
function inflateGetHeader(strm, head) {
var state;
/* check state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
/* save header structure */
state.head = head;
head.done = false;
return Z_OK;
}
function inflateSetDictionary(strm, dictionary) {
var dictLength = dictionary.length;
var state;
var dictid;
var ret;
/* check state */
if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
state = strm.state;
if (state.wrap !== 0 && state.mode !== DICT) {
return Z_STREAM_ERROR;
}
/* check for correct dictionary identifier */
if (state.mode === DICT) {
dictid = 1; /* adler32(0, null, 0)*/
/* dictid = adler32(dictid, dictionary, dictLength); */
dictid = adler32(dictid, dictionary, dictLength, 0);
if (dictid !== state.check) {
return Z_DATA_ERROR;
}
}
/* copy dictionary to window using updatewindow(), which will amend the
existing dictionary if appropriate */
ret = updatewindow(strm, dictionary, dictLength, dictLength);
if (ret) {
state.mode = MEM;
return Z_MEM_ERROR;
}
state.havedict = 1;
// Tracev((stderr, "inflate: dictionary set\n"));
return Z_OK;
}
const inflateInfo = 'pako inflate (from Nodeca project)';
export {
inflateReset,
inflateReset2,
inflateResetKeep,
inflateInit,
inflateInit2,
inflate,
inflateEnd,
inflateGetHeader,
inflateSetDictionary,
inflateInfo
};
/* Not implemented
export {
inflateCopy,
inflateGetDictionary,
inflateMark,
inflatePrime,
inflateSync,
inflateSyncPoint,
inflateUndermine
};
*/ | the_stack |
import {
ChangeDetectionStrategy,
Component,
ElementRef,
EventEmitter,
Injector,
Input,
OnDestroy,
OnInit,
Output,
Renderer2
} from '@angular/core';
import {AbstractComponent} from '@common/component/abstract.component';
import {FunctionValidator} from '@common/component/chart/option/define/common';
import {Widget} from '@domain/dashboard/widget/widget';
import {Field} from '@domain/datasource/datasource';
import {DashboardWidgetRelation} from '@domain/dashboard/dashboard';
import {PageWidgetConfiguration} from '@domain/dashboard/widget/page-widget';
import {FilterWidgetConfiguration} from '@domain/dashboard/widget/filter-widget';
import {DashboardUtil} from '../../util/dashboard.util';
declare let $;
@Component({
selector: 'app-page-relation',
templateUrl: './page-relation.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class PageRelationComponent extends AbstractComponent implements OnInit, OnDestroy {
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// 차트 기능 확인기
private _chartFuncValidator: FunctionValidator = new FunctionValidator();
// 트리 객체
private _$tree;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// 표시여부
public isShow: boolean = false;
public title: string;
public description: string;
@Output()
public changeRelation: EventEmitter<{ relations: DashboardWidgetRelation[], type: string }> = new EventEmitter();
@Input()
public hierarchyType: string;
public summary: { value: number, label: string } = {value: 0, label: ''};
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Constructor
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// 생성자
constructor(protected element: ElementRef,
protected injector: Injector,
protected renderer: Renderer2) {
super(element, injector);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Override Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 클래스 초기화
*/
public ngOnInit() {
super.ngOnInit();
} // function - ngOnInit
/**
* 클래스 제거
*/
public ngOnDestroy() {
super.ngOnDestroy();
} // function - ngOnDestroy
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
public get getNumberOfTree() {
const list = [];
for (let i = 0; i < this.summary.value; i++) {
list.push(i);
}
return list;
}
/**
* 컴포넌트 실행함수
*/
public run(initialData: { nodes: DashboardWidgetRelation[], widgets: Widget[], title?: string, description?: string }) {
this.loadingShow();
// number of widgets
this.summary.label = 'widgets';
this.summary.value = initialData.widgets.length || 0;
// set title and description
if (this.hierarchyType === 'filter') {
this.title = initialData.title;
this.description = initialData.description;
} else {
this.title = this.translateService.instant('msg.board.hierarchy.title');
this.description = this.translateService.instant('msg.board.hierarchy.desc');
}
// open popup
this.isShow = true;
// if node is empty, return
if (!initialData.nodes) {
this.loadingHide();
this.close();
return;
}
// make draggable tree sturcture
const data = this._getTreeData(initialData.nodes, initialData.widgets, this.hierarchyType);
this.safelyDetectChanges();
setTimeout(() => {
this._$tree = $('.ddp-wrap-order-setting');
this._$tree.tree({
data: data,
autoOpen: true,
dragAndDrop: true,
onCanMove: (node) => {
return (this.hierarchyType !== 'filter' || 'include' === node.type);
},
onCanMoveTo: (movedNode, targetNode, position) => {
$('.ddp-drag-enable').removeClass('ddp-drag-enable');
$('.ddp-drag-disable').removeClass('ddp-drag-disable');
if ('inside' === position && targetNode.type) {
if (movedNode.dataSource === targetNode.dataSource &&
(
this._chartFuncValidator.checkUseSelectionByTypeString(targetNode.type) ||
(this.hierarchyType === 'filter' && 'include' === targetNode.type)
)
) {
// set max depth
const maxDepth: number = this.hierarchyType === 'filter' ? 8 : 2;
if (this._getNodeDepth(targetNode) > maxDepth) {
$(targetNode.element).addClass('ddp-drag-disable');
return false
}
$(targetNode.element).addClass('ddp-drag-enable');
return true;
} else {
$(targetNode.element).addClass('ddp-drag-disable');
return false;
}
} else {
return true;
}
},
onDragStop: () => {
$('li.jqtree-element').removeClass('ddp-drag-enable').removeClass('ddp-drag-disable');
},
onCreateLi: (node, $li) => {
let html = `<div class="jqtree-title jqtree_common node-content-wrapper" role="treeitem" aria-selected="false" aria-expanded="false">
<em class="ddp-node-depth" ></em>`;
if (this.hierarchyType === 'filter') {
html += '<em class="ddp-box-type type-' + node.dimensionMeasure + '"><em class="' + node.cssClass + ' type-absolute"></em></em>'
} else {
html += '<em class="ddp-img-chart-' + node.type + '"></em>'
}
html += `<span>${node.name}</span></div>`;
$li.find('.jqtree-element').html(html);
}
});
this.loadingHide();
}, 500);
} // function - run
/**
* 컴포넌트 종료함수
*/
public close() {
this.isShow = false;
this.safelyDetectChanges();
} // function - close
/**
* 페이지 연관관계를 저장함
*/
public savePageRelation() {
const treeNodes = JSON.parse(this._$tree.tree('toJson'));
const rels: DashboardWidgetRelation[] = treeNodes.map(node => this._toBoardPageRelation(node));
this.changeRelation.emit({relations: rels, type: this.hierarchyType});
this.close();
} // function - savePageRelation
/**
* 트리 마우스 다운 이벤트
* @param {MouseEvent} event
*/
public treeMouseDown(event: MouseEvent) {
const $target = $(event.target);
if ($target.hasClass('node-content-wrapper')) {
$target.addClass('ddp-tree-drag-start');
} else if (0 < $target.closest('.node-content-wrapper').length) {
$target.closest('.node-content-wrapper').addClass('ddp-tree-drag-start');
}
} // function - treeMouseDown
/**
* 트리 마우스 업 이벤트
* @param {MouseEvent} _event
*/
public treeMouseUp(_event: MouseEvent) {
this._$tree.find('.ddp-tree-drag-start').removeClass('ddp-tree-drag-start');
} // function - treeMouseUp
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 노드 데이터를 Dashboard Page Relation 객체로 변환
* @param nodeData
* @returns {DashboardWidgetRelation}
* @private
*/
private _toBoardPageRelation(nodeData) {
const pageRel = new DashboardWidgetRelation(nodeData.id);
if (nodeData.children && 0 < nodeData.children.length) {
pageRel.children = nodeData.children.map(item => this._toBoardPageRelation(item));
}
return pageRel;
} // function - _toBoardPageRelation
/**
* Node의 Depth 를 얻는다.
* @param node
* @returns {number}
* @private
*/
private _getNodeDepth(node): number {
return (node.parent) ? 1 + this._getNodeDepth(node.parent) : 0;
} // function - _getNodeDepth
/**
* Tree Data를 위한 데이터 변환
* @param {DashboardWidgetRelation[]} nodes
* @param {Widget[]} widgets
* @param type
* @returns {any}
* @private
*/
private _getTreeData(nodes: DashboardWidgetRelation[], widgets: Widget[], type: string) {
const nodeList: any = [];
nodes.some((item) => {
const widgetInfo = widgets.find(widget => widget.id === item.ref);
if (!widgetInfo) {
return false;
}
const nodeData: any = {
id: item.ref,
label: widgetInfo.name
};
if (type === 'filter') {
const conf: FilterWidgetConfiguration = widgetInfo.configuration as FilterWidgetConfiguration;
// find field
const field = DashboardUtil.getFieldByName(widgetInfo.dashBoard, conf.filter.dataSource, conf.filter.field);
// find css class
const cssClass = Field.getDimensionTypeIconClass(field);
// find if its dimension or measure
let dimensionMeasure = field.role.toString().toLowerCase();
if (dimensionMeasure === 'timestamp') {
dimensionMeasure = 'dimension'
}
nodeData.dataSource = conf.filter.dataSource;
nodeData.type = conf.filter.type;
nodeData['cssClass'] = cssClass;
nodeData['dimensionMeasure'] = dimensionMeasure;
} else {
const conf: PageWidgetConfiguration = widgetInfo.configuration as PageWidgetConfiguration;
nodeData.dataSource = ('multi' === conf.dataSource.type) ? '' : conf.dataSource.name;
nodeData.type = conf.chart.type;
}
if (item.children && 0 < item.children.length) {
nodeData.children = this._getTreeData(item.children, widgets, type);
}
nodeList.push(nodeData);
});
return nodeList;
} // function - _getTreeData
// /**
// * 전체 노드 갯수를 반환함
// * @param {DashboardWidgetRelation[]} nodes
// * @return {number}
// * @private
// */
// private _getCntNodes(nodes: DashboardWidgetRelation[]) {
// let cntNodes: number = 0;
// nodes.forEach(item => {
// cntNodes++;
// if (item.children && 0 < item.children.length) {
// cntNodes += this._getCntNodes(item.children);
// }
// });
// return cntNodes;
// } // function - _getCntNodes
} | the_stack |
import * as typedoc from 'typedoc';
import * as fs from 'fs/promises';
import * as pathlib from 'path';
import * as sourceMap from 'source-map';
import {
ApiDocsConfig,
DeclarationReflection,
ExtendedDeclarationReflection,
SourceReference,
ExtendedSourceReference,
Location,
ExternalLocation,
} from './types.js';
const findIndexOrInfinity = <T>(
array: ReadonlyArray<T>,
match: (el: T) => boolean
) => {
const idx = array.findIndex(match);
return idx === -1 ? Infinity : idx;
};
const isType = (node: DeclarationReflection) => {
return node.kindString === 'Type alias' || node.kindString === 'Interface';
};
/**
* Mapping from symbol name to an external URL.
*/
const symbolToExternalLink = new Map([
[
'CSSStyleSheet',
'https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet',
],
[
'DocumentFragment',
'https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment',
],
['Element', 'https://developer.mozilla.org/en-US/docs/Web/API/Element'],
[
'HTMLElement',
'https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement',
],
[
'HTMLTemplateElement',
'https://developer.mozilla.org/en-US/docs/Web/API/HTMLTemplateElement',
],
['ShadowRoot', 'https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot'],
[
'ShadowRootInit',
'https://developer.mozilla.org/en-US/docs/Web/API/Element/attachShadow#parameters',
],
]);
/**
* Data consumed by lit.dev API docs Eleventy template. Each item is a separate
* page.
*/
type Pages = Array<{
slug: string;
title: string;
items: Array<DeclarationReflection>;
}>;
/**
* Map from $symbol to the location it appears in our docs. If there is more
* than one item, then the symbol is ambiguous.
*/
type SymbolMap = {
[symbol: string]: Array<Location>;
};
/**
* Transform a TypeDoc JSON project for consumption by the lit.dev API docs
* Eleventy template, and generate a symbol map that can be used to locate an
* API within our custom page structure.
*/
export class ApiDocsTransformer {
private config: ApiDocsConfig;
private project: typedoc.JSONOutput.ProjectReflection;
private symbolMap: SymbolMap = {};
/** Map from every numeric TypeDoc ID to its TypeDoc reflection object. */
private reflectionById = new Map<number, ExtendedDeclarationReflection>();
/** Cache of .d.ts -> .ts sourcemaps. */
private sourceMaps = new Map<string, sourceMap.SourceMapConsumer>();
constructor(
project: typedoc.JSONOutput.ProjectReflection,
config: ApiDocsConfig
) {
this.project = project;
this.config = config;
}
async transform(): Promise<{
symbolMap: SymbolMap;
pages: Pages;
}> {
// In the first pass, determine the page/anchor where each node should
// appear in our layout, and index all nodes by TypeDoc numeric ID.
for (const entrypoint of this.project.children ?? []) {
const ancestry: DeclarationReflection[] = [];
const firstPassVisit = async (node: DeclarationReflection) => {
// We want to generate import statement module specifiers using our
// chosen entrypoint module specifier, instead of module specifier for
// the definition of this symbol (e.g. we want "lit" instead of
// "lit-element/lit-element.js"). But since we're going to re-arrange
// items out of their original entrypoint module organization, we need
// to copy our original entrypoint source info to each node.
(node as ExtendedDeclarationReflection).entrypointSources =
entrypoint.sources;
for (const source of node.sources ?? []) {
this.makeSourceRelativeToMonorepoRoot(source);
await this.updateSourceFromDtsToTs(source);
this.setImportModuleSpecifier(source);
}
this.choosePageLocation(node, ancestry);
this.promoteVariableFunctions(node);
this.promoteAccessorTypes(node);
this.promoteSignatureComments(node);
this.reflectionById.set(node.id, node);
node.children = (node.children ?? []).filter((child) =>
this.filter(child)
);
ancestry.push(node);
for (const child of node.children) {
await firstPassVisit(child);
}
ancestry.pop();
};
await firstPassVisit(entrypoint);
}
// It's possible for the same exact export to be duplicated by TypeDoc. This
// can happen if:
//
// 1. Two entrypoints export the same symbol
// 2. A TypeScript value and type are exported as separate statements
const exportKeyToIds = new Map<string, Array<number>>();
const duplicateExportIdsToRemove = new Set<number>();
for (const entrypoint of this.project.children ?? []) {
for (const node of entrypoint.children ?? []) {
const source = node.sources?.[0];
if (!source) {
continue;
}
const exportKey = source.fileName + '#' + node.name;
let ids = exportKeyToIds.get(exportKey);
if (ids === undefined) {
ids = [];
exportKeyToIds.set(exportKey, ids);
}
ids.push(node.id);
}
}
for (const ids of exportKeyToIds.values()) {
if (ids.length <= 1) {
// No conflicts.
continue;
}
ids.sort((a, b) => {
const aReflection = this.reflectionById.get(a);
const bReflection = this.reflectionById.get(b);
// Prefer a shorter import statement.
const aImportLength =
aReflection?.entrypointSources?.[0]?.moduleSpecifier?.length ??
Infinity;
const bImportLength =
bReflection?.entrypointSources?.[0]?.moduleSpecifier?.length ??
Infinity;
if (aImportLength !== bImportLength) {
return aImportLength - bImportLength;
}
// Prefer a value to a type.
const aTypeAlias = aReflection?.kindString === 'Type alias';
const bTypeAlias = bReflection?.kindString === 'Type alias';
if (!aTypeAlias && bTypeAlias) {
return -1;
}
if (aTypeAlias && !bTypeAlias) {
return 1;
}
// Arbitrary but deterministic.
return a - b;
});
const winnerReflection = this.reflectionById.get(ids[0]);
if (!winnerReflection) {
continue;
}
for (const loserId of ids.slice(1)) {
duplicateExportIdsToRemove.add(loserId);
// Also update the id -> reflection map, so that any cross-references we
// add will point at the winner location.
this.reflectionById.set(loserId, winnerReflection);
}
}
// In the second pass, we now know the location of every node, so we can
// generate cross-references.
const secondPassVisit = (node: DeclarationReflection) => {
this.expandTransitiveHeritage(node);
this.addLocationsForAllIds(node);
this.expandAndMergeCategoryReferences(node);
this.linkifySymbolsInComments(node);
node.children = (node.children ?? []).filter(
(child) => !duplicateExportIdsToRemove.has(child.id)
);
for (const child of node.children) {
secondPassVisit(child);
}
};
secondPassVisit(this.project);
const pages = this.reorganizeExportsIntoPages();
this.prunePageData(pages);
return {
symbolMap: this.symbolMap,
pages,
};
}
/**
* Remove nodes that we don't care about documenting.
*/
private filter(node: DeclarationReflection) {
return !(
node.flags?.isPrivate ||
node.flags?.isExternal ||
node.name.startsWith('_') ||
// Reference types don't seem useful; just aliases for other nodes.
node.kindString === 'Reference'
);
}
/**
* Pick a page and anchor, and assign it to the location property.
*/
private choosePageLocation(
node: DeclarationReflection,
ancestry: Array<DeclarationReflection>
) {
if (!node.kindString || node.kindString === 'Module') {
return;
}
let nearestAncestorLocation;
for (let i = ancestry.length - 1; i >= 0; i--) {
const ancestor = ancestry[i] as ExtendedDeclarationReflection;
if (ancestor.location) {
nearestAncestorLocation = ancestor.location;
break;
}
}
const page = nearestAncestorLocation
? nearestAncestorLocation.page
: this.config.pageForSymbol(node);
const anchor = nearestAncestorLocation
? nearestAncestorLocation.anchor + '.' + node.name
: node.name;
if (page && anchor) {
const location = {page, anchor};
(node as ExtendedDeclarationReflection).location = location;
this.updateSymbolMap(node.name, location);
if (location.anchor !== node.name) {
this.updateSymbolMap(location.anchor, location);
}
}
}
/**
* Add a symbol to the symbol map.
*/
private updateSymbolMap(symbol: string, location: Location) {
// Prepend with $ so that we don't collide with builtins. We aren't using a
// Map because we need to serialize to JSON.
symbol = '$' + symbol;
let arr = this.symbolMap[symbol];
if (arr === undefined) {
arr = [];
this.symbolMap[symbol] = arr;
}
arr.push(location);
}
/**
* When a function is defined like `const fn = () => { ... }` instead of with
* the `function` keyword, TypeDoc buries things like parameters more deeply
* inside the JSON structure. Hoist up this data so that we can treat
* functions uniformly regardless of how they are defined.
*/
private promoteVariableFunctions(node: DeclarationReflection) {
if (node.kindString !== 'Variable') {
return;
}
const signatures = (node.type as {declaration?: DeclarationReflection})
?.declaration?.signatures;
if (!signatures) {
return;
}
node.kindString = 'Function';
node.signatures = signatures;
for (const sig of node.signatures ?? []) {
sig.name = node.name;
}
}
/**
* TypeDoc nests type information for getters/setters. Promote them so that
* they can be treated more uniformly with properties.
*/
private promoteAccessorTypes(node: DeclarationReflection) {
if (node.kindString !== 'Accessor') {
return;
}
if (node.getSignature?.[0]) {
node.type = node.getSignature[0].type;
}
}
/**
* For functions, TypeDoc put comments inside the signatures property, instead
* of directly in the function node. Hoist these comments up so that we can
* treat comments uniformly.
*/
private promoteSignatureComments(node: DeclarationReflection) {
if (!node.comment?.shortText && node.signatures?.[0]?.comment?.shortText) {
node.comment = node.signatures[0].comment;
}
}
/**
* Adds a "heritage" property that's similar to the existing "extendedTypes"
* property, but adds transitive heritage (e.g. adds HTMLElement to
* [LitElement -> ReactiveElement -> HTMLElement]), and adds page/anchor
* locators.
*/
private expandTransitiveHeritage(node: DeclarationReflection) {
if (!node.extendedTypes) {
// Has no heritage.
return [];
}
let heritage = (node as ExtendedDeclarationReflection).heritage;
if (heritage) {
// Already computed this heritage.
return heritage;
}
heritage = [];
(node as ExtendedDeclarationReflection).heritage = heritage;
for (const extendee of node.extendedTypes as Array<{
name: string;
id?: number;
}>) {
heritage.push(extendee);
if (extendee.id !== undefined) {
const extendeeNode = this.reflectionById.get(extendee.id);
if (extendeeNode !== undefined) {
heritage.push(...this.expandTransitiveHeritage(extendeeNode));
}
}
}
return heritage;
}
/**
* Add `location: {page, anchor}` properties to every object that looks like
* its a reference to another TypeDoc symbol. Handles nested objects and
* arrays.
*
* There are lots of places where a reference like this can appear, so we just
* use the heuristic that if any object has a numeric "id" property, and
* TypeDoc has a reflection with that id, then we should give it a location.
*/
private addLocationsForAllIds(node: unknown, isTopLevel = true) {
if (typeof node !== 'object' || node === null) {
return;
}
if (node instanceof Array) {
for (const item of node) {
this.addLocationsForAllIds(item, false);
}
return;
}
for (const [key, val] of Object.entries(node)) {
if (key === 'id' && typeof val === 'number' && !('location' in node)) {
const reflection = this.reflectionById.get(val);
if (reflection && reflection.location) {
(node as {location?: Location}).location = reflection.location;
}
} else if (
key === 'name' &&
typeof val === 'string' &&
symbolToExternalLink.has(val)
) {
(node as {externalLocation?: ExternalLocation}).externalLocation = {
url: symbolToExternalLink.get(val)!,
};
} else if (!(isTopLevel && key === 'children')) {
// We already recurse into children of top-level reflections in our main
// traversal, no need to also do it here.
this.addLocationsForAllIds(val, false);
}
}
}
/**
* Remove fields that we don't need for rendering. This makes reading diffs
* much easier, since we check the generated JSON file in.
*/
private prunePageData(node: unknown) {
if (node instanceof Array) {
for (const item of node) {
this.prunePageData(item);
}
} else if (typeof node === 'object' && node !== null) {
// Method comments are duplicated both at the root of the node, and also
// inside its signature. Remove the one from the signature.
if (
(node as ExtendedDeclarationReflection).comment &&
(node as ExtendedDeclarationReflection).signatures?.[0]?.comment
) {
delete (node as ExtendedDeclarationReflection).signatures?.[0]?.comment;
}
for (const [key, val] of Object.entries(node)) {
// Prune the child first, so that our "empty arrays and objects" check
// works more aggressively.
this.prunePageData(val);
if (
// We instead use the "location" field which tells us the page/anchor,
// instead of the internal numeric TypeDoc id. This id is
// non-deterministic, so it creates meaningless churn!
key === 'id' ||
// We do use some "children" fields, but not the ones that are just
// lists of numeric IDs.
(key === 'children' &&
val instanceof Array &&
val.every((i) => typeof i === 'number')) ||
// We only need the line number for GitHub URLs.
key === 'character' ||
// We render the readable "kindString" field instead of the numeric
// "kind" field.
key === 'kind' ||
// If we've created an "expandedCategories" field, then we don't also
// render the normal "children" field.
(key === 'children' &&
(node as ExtendedDeclarationReflection).expandedCategories) ||
// We use "groups" to generate "expandedCategories", but don't render
// it directly.
key === 'groups' ||
// Empty arrays and objects.
(typeof val === 'object' &&
val !== null &&
Object.keys(val).length === 0) ||
// We don't render JSDoc tags directly, the ones we care about are
// already extracted into e.g. "parameters".
key === 'tags'
) {
delete node[key as keyof typeof node];
}
}
}
}
/**
* The "categories" lists are just numeric reflection ID references. They're
* also divided across Property/Method/etc. groups. Create a flat list of
* mixed types, and with fully expanded reflections.
*/
private expandAndMergeCategoryReferences(
node: ExtendedDeclarationReflection
) {
for (const group of node.groups ?? []) {
for (const category of group.categories ?? []) {
const name = category.title;
// Delimit with '/' instead of '.' so that a category anchor can never
// overlap with a property/method anchor.
const anchor = node.name + '/' + name;
node.expandedCategories ??= [];
let cat = node.expandedCategories.find(
(category) => category.anchor === anchor
);
if (cat === undefined) {
cat = {
anchor,
title: name
.replace(/-/g, ' ')
// Uppercase first letter
.replace(/^./, (c) => c.toUpperCase()),
children: [],
};
node.expandedCategories.push(cat);
}
for (const id of category.children ?? []) {
const ref = this.reflectionById.get(id);
if (ref !== undefined) {
cat.children.push(ref);
}
}
}
}
if (node.expandedCategories) {
node.expandedCategories.sort(({title: a}, {title: b}) =>
a.localeCompare(b)
);
for (const category of node.expandedCategories) {
category.children.sort(this.symbolSortFn);
}
}
}
/**
* Determines order of symbols within a page, and of properties/methods appear
* within a class/interface.
*/
symbolSortFn = (
a: DeclarationReflection,
b: DeclarationReflection
): number => {
// By entrypoint (e.g. a type from a directive module should be adjacent to
// the directive function).
const aEntrypoint =
(a as ExtendedDeclarationReflection).entrypointSources?.[0]?.fileName ??
'';
const bEntrypoint =
(b as ExtendedDeclarationReflection).entrypointSources?.[0]?.fileName ??
'';
if (aEntrypoint !== bEntrypoint) {
return aEntrypoint.localeCompare(bEntrypoint);
}
// Hard-coded orderings
const idxA = findIndexOrInfinity(
this.config.symbolOrder,
(s) =>
s === (a as ExtendedDeclarationReflection).location?.anchor ?? a.name
);
const idxB = findIndexOrInfinity(
this.config.symbolOrder,
(s) =>
s === (b as ExtendedDeclarationReflection).location?.anchor ?? b.name
);
if (idxA !== idxB) {
return idxA - idxB;
}
// Types after values
if (isType(a) && !isType(b)) {
return 1;
}
if (!isType(a) && isType(b)) {
return -1;
}
// Lexicographic
return a.name.localeCompare(b.name);
};
/**
* Convert [[ symbol ]], `@link`, and `@linkcode` comments into hyperlinks.
*
* Supports the following examples:
* * Example link to {@link ApiDocsTransformer} symbol.
* * Example monospace link to {@linkcode ApiDocsTransformer}.
* * {@link ApiDocsTransformer Example labeled link.}
* * {@linkcode ApiDocsTransformer Example monospace labeled link.}
*
* Also supports these deprecated examples which don't have IDE hyperlinks:
* * [[`ApiDocsTransformer`]]
* * [[`ApiDocsTransformer`| Example labeled link.]]
*
* TODO(aomarks) This should probably technically be factored out and called
* directly from Eleventy, because the URL we generate depends on the
* configured Eleventy base URL. In practice, we always mount lit.dev to / so
* it doesn't matter.
*/
private linkifySymbolsInComments(node: DeclarationReflection) {
const replace = linkifySymbolsInCommentsBuilder({
node: node as ExtendedDeclarationReflection,
symbolMap: this.symbolMap,
locationToUrl: this.config.locationToUrl.bind(this),
});
if (node.comment?.shortText) {
node.comment.shortText = replace(node.comment.shortText);
}
if (node.comment?.text) {
node.comment.text = replace(node.comment.text);
}
}
/**
* TypeDoc sources are reported relative to the lit.dev packages/ directory,
* for some reason. Update them to be relative to the Lit monorepo root.
*/
private async makeSourceRelativeToMonorepoRoot(source: SourceReference) {
source.fileName = pathlib.relative(
this.config.gitDir,
pathlib.resolve(this.config.typedocRoot, source.fileName)
);
}
/**
* TypeDoc sources are ".d.ts" files, but we prefer the original ".ts" source
* files. Follow the corresponding ".d.ts.map" source map to find the original
* file and location.
*/
private async updateSourceFromDtsToTs(source: SourceReference) {
let consumer = this.sourceMaps.get(source.fileName);
if (!consumer) {
if (!source.fileName.endsWith('.d.ts')) {
return;
}
const mapFilename = pathlib.join(
this.config.gitDir,
source.fileName + '.map'
);
let mapStr;
try {
mapStr = await fs.readFile(mapFilename, 'utf8');
} catch (e) {
if ((e as {code: string}).code == 'ENOENT') {
return;
}
throw e;
}
consumer = await new sourceMap.SourceMapConsumer(mapStr);
this.sourceMaps.set(source.fileName, consumer);
}
const pos = consumer.originalPositionFor({
line: source.line,
column: source.character,
});
if (!pos.source) {
return;
}
// TODO(aomarks) The Lit monorepo d.ts.map files currently incorrectly have
// a sources field like "../src/source.ts" because they are copied directly
// out of the "development/" folder. We need to fix that properly the Lit
// monorepo, but temporarily fix it here too.
if (pos.source.startsWith('../')) {
pos.source = pos.source.slice('../'.length);
}
source.fileName = pathlib.join(
pathlib.dirname(source.fileName),
pos.source
);
source.line = pos.line ?? 0;
source.character = pos.column ?? 0;
}
/**
* Augment a source with its best import statement module specifier.
*/
private setImportModuleSpecifier(source: SourceReference) {
const specifier = this.config.fileToImportSpecifier(source.fileName);
if (specifier) {
(source as ExtendedSourceReference).moduleSpecifier =
this.config.fileToImportSpecifier(source.fileName);
}
}
/**
* Re-organize all module exports into our custom page structure.
*/
private reorganizeExportsIntoPages() {
const slugToPage = new Map<
string,
{
slug: string;
title: string;
anchorFilter?: (node: DeclarationReflection) => boolean;
items: Array<DeclarationReflection>;
repo: string;
commit: string;
}
>();
for (const module of this.project.children ?? []) {
for (const export_ of module.children ?? []) {
const location = (export_ as ExtendedDeclarationReflection).location;
if (!location) {
continue;
}
let page = slugToPage.get(location.page);
if (page === undefined) {
const match = this.config.pages.find(
({slug}) => slug === location.page
);
if (!match) {
throw new Error(`No page definition for ${location.page}`);
}
page = {
...match,
repo: this.config.repo,
commit: this.config.commit,
items: [],
};
slugToPage.set(location.page, page);
}
page.items.push(export_);
}
}
const pagesArray = [...slugToPage.values()];
// Sort pages
pagesArray.sort(({slug: a}, {slug: b}) => {
const idxA = findIndexOrInfinity(
this.config.pages,
({slug}) => slug === a
);
const idxB = findIndexOrInfinity(
this.config.pages,
({slug}) => slug === b
);
if (idxA !== idxB) {
return idxA - idxB;
}
return a.localeCompare(b);
});
// Sort items within pages
for (const page of pagesArray) {
page.items.sort(this.symbolSortFn);
if (page.anchorFilter) {
for (const item of page.items) {
if (!page.anchorFilter(item)) {
delete (item as ExtendedDeclarationReflection)['location'];
}
}
}
}
return pagesArray;
}
}
/**
* Returns a string replacer function that converts jsdoc links into markdown
* hyperlinks that are used in the generated API documentation.
*
* See {@linkcode ApiDocsTransformer.linkifySymbolsInComments} for more info.
*/
export function linkifySymbolsInCommentsBuilder({
node,
symbolMap,
locationToUrl,
}: {
node: {
location?: {
anchor?: string;
};
};
symbolMap: SymbolMap;
locationToUrl: (location: Location) => string;
}) {
const replacer = (from: string, symbol: string, label: string): string => {
const context =
(node as ExtendedDeclarationReflection).location?.anchor?.split('.') ??
[];
let results;
// If this node is "foo.bar", and we saw "[[ baz ]]", then look for a
// match from closest to furthest:
//
// 1. $foo.bar.baz
// 2. $foo.baz
// 3. $baz
for (let i = context.length; i >= 0; i--) {
const key = '$' + [...context.slice(0, i), symbol].join('.');
results = symbolMap[key];
if (results) {
break;
}
}
const hyperlinkTextFormat = (anchorText: string) =>
from.startsWith('{@linkcode') || from.startsWith('[[')
? `\`${anchorText}\``
: anchorText;
if (results && results.length === 1) {
return `[${hyperlinkTextFormat(label || symbol)}](${locationToUrl(
results[0]
)})`;
}
return hyperlinkTextFormat(label || symbol);
};
return (comment: string) =>
comment
.replace(/\[\[[\s`]*(.+?)(?:[\s`]*\|[\s`]*(.+?))?[\s`]*\]\]/g, replacer)
.replace(
/\{\@(?:link\b|linkcode\b)[\s`]*(.+?)(?:[\s`]*[\|\s][\s`]*(.+?))?[\s`]*\}/g,
replacer
);
} | the_stack |
import nock from "nock";
import { createJobData } from "../../src/transforms/push";
import { createWebhookApp } from "../utils/probot";
import { getLogger } from "../../src/config/logger";
import { Installation, Subscription } from "../../src/models";
import { Application } from "probot";
import { start, stop } from "../../src/worker/startup";
import waitUntil from "../utils/waitUntil";
import sqsQueues from "../../src/sqs/queues";
import {pushQueueMessageHandler, PushQueueMessagePayload} from "../../src/sqs/push";
import {Context} from "../../src/sqs/index";
import {Message} from "aws-sdk/clients/sqs";
const createMessageProcessingContext = (payload, jiraHost: string): Context<PushQueueMessagePayload> => ({
payload: createJobData(payload, jiraHost),
log: getLogger("test"),
message: {} as Message,
receiveCount: 1,
lastAttempt: false
});
describe("Push Webhook", () => {
const realDateNow = Date.now.bind(global.Date);
let app: Application;
beforeEach(async () => {
app = await createWebhookApp();
const clientKey = "client-key";
await Installation.create({
clientKey,
sharedSecret: "shared-secret",
jiraHost
});
await Subscription.create({
jiraHost,
gitHubInstallationId: 1234,
jiraClientKey: clientKey
});
});
afterEach(async () => {
await Installation.destroy({ truncate: true });
await Subscription.destroy({ truncate: true });
//We have to restore Date.now to avoid errors in SQS Client.
//SQS Client uses Date.now and fails if it is "undefined"
//Hence we mock Date with jest, it will be returning undefined when we clean all mocks
//Some async operations might still be running (like message deletion) even after the test is finished.
//TODO Instead stop the queue every time after each test. However it would be possible only when we get rid of Redis because bull queues are not restartable
global.Date.now = realDateNow;
});
// TODO: figure out how to tests with queue
describe.skip("add to push queue", () => {
beforeEach(() => {
process.env.REDIS_URL = "redis://test";
});
it("should add push event to the queue if Jira issue keys are present", async () => {
const event = require("../fixtures/push-basic.json");
await expect(app.receive(event)).toResolve();
// TODO: find a way to test queues
const queues = [];
expect(queues.push).toBeCalledWith(
{
repository: event.payload.repository,
shas: [{ id: "test-commit-id", issueKeys: ["TEST-123"] }],
jiraHost,
installationId: event.payload.installation.id
}, { removeOnFail: true, removeOnComplete: true }
);
});
it("should not add push event to the queue if there are no Jira issue keys present", async () => {
const event = require("../fixtures/push-no-issues.json");
await app.receive(event);
});
it("should handle payloads where only some commits have issue keys", async () => {
const event = require("../fixtures/push-mixed.json");
await app.receive(event);
// TODO: fix this queues.
const queues = [];
expect(queues.push).toBeCalledWith(
{
repository: event.payload.repository,
shas: [
{ id: "test-commit-id-1", issueKeys: ["TEST-123", "TEST-246"] },
{ id: "test-commit-id-2", issueKeys: ["TEST-345"] }
],
jiraHost,
installationId: event.payload.installation.id
}, { removeOnFail: true, removeOnComplete: true }
);
});
});
describe("process push payloads", () => {
beforeEach(async () => {
Date.now = jest.fn(() => 12345678);
await Subscription.create({
gitHubInstallationId: 1234,
jiraHost,
jiraClientKey: "myClientKey"
});
githubNock
.post("/app/installations/1234/access_tokens")
.optionally() // TODO: need to remove optionally and make it explicit
.reply(200, {
token: "token",
expires_at: new Date().getTime() + 1_000_000
});
});
afterEach(async () => {
await Subscription.destroy({ truncate: true });
});
it("should update the Jira issue when no username is present", async () => {
const event = require("../fixtures/push-no-username.json");
githubNock
.get("/repos/test-repo-owner/test-repo-name/commits/commit-no-username")
.reply(200, require("../fixtures/api/commit-no-username.json"));
jiraNock.post("/rest/devinfo/0.10/bulk", {
preventTransitions: false,
repositories: [
{
name: "test-repo-name",
url: "test-repo-url",
id: "test-repo-id",
commits: [
{
hash: "commit-no-username",
message: "[TEST-123] Test commit.",
author: {
name: "test-commit-name",
email: "test-email@example.com"
},
authorTimestamp: "test-commit-date",
displayId: "commit",
fileCount: 3,
files: [
{
path: "test-modified",
changeType: "MODIFIED",
linesAdded: 10,
linesRemoved: 2,
url: "https://github.com/octocat/Hello-World/blob/7ca483543807a51b6079e54ac4cc392bc29ae284/test-modified"
},
{
path: "test-added",
changeType: "ADDED",
linesAdded: 4,
linesRemoved: 0,
url: "https://github.com/octocat/Hello-World/blob/7ca483543807a51b6079e54ac4cc392bc29ae284/test-added"
},
{
path: "test-removal",
changeType: "DELETED",
linesAdded: 0,
linesRemoved: 4,
url: "https://github.com/octocat/Hello-World/blob/7ca483543807a51b6079e54ac4cc392bc29ae284/test-removal"
}
],
id: "commit-no-username",
issueKeys: ["TEST-123"],
url: "https://github.com/octokit/Hello-World/commit/commit-no-username",
updateSequenceId: 12345678
}
],
updateSequenceId: 12345678
}
],
properties: {
installationId: 1234
}
}).reply(200);
await expect(pushQueueMessageHandler(createMessageProcessingContext(event.payload, jiraHost))).toResolve();
});
it("should only send 10 files if push contains more than 10 files changed", async () => {
const event = require("../fixtures/push-multiple.json");
githubNock
.get("/repos/test-repo-owner/test-repo-name/commits/test-commit-id")
.reply(200, require("../fixtures/more-than-10-files.json"));
jiraNock.post("/rest/devinfo/0.10/bulk", {
preventTransitions: false,
repositories: [
{
name: "test-repo-name",
url: "test-repo-url",
id: "test-repo-id",
commits: [
{
hash: "test-commit-id",
message: "TEST-123 TEST-246 #comment This is a comment",
author: {
email: "test-email@example.com",
name: "test-commit-name"
},
displayId: "test-c",
fileCount: 12,
files: [
{
path: "test-modified",
changeType: "MODIFIED",
linesAdded: 10,
linesRemoved: 2,
url: "https://github.com/octocat/Hello-World/blob/7ca483543807a51b6079e54ac4cc392bc29ae284/test-modified"
},
{
path: "test-added-1",
changeType: "ADDED",
linesAdded: 4,
linesRemoved: 0,
url: "https://github.com/octocat/Hello-World/blob/7ca483543807a51b6079e54ac4cc392bc29ae284/test-added"
},
{
path: "test-added-2",
changeType: "ADDED",
linesAdded: 4,
linesRemoved: 0,
url: "https://github.com/octocat/Hello-World/blob/7ca483543807a51b6079e54ac4cc392bc29ae284/test-added"
},
{
path: "test-added-3",
changeType: "ADDED",
linesAdded: 4,
linesRemoved: 0,
url: "https://github.com/octocat/Hello-World/blob/7ca483543807a51b6079e54ac4cc392bc29ae284/test-added"
},
{
path: "test-added-4",
changeType: "ADDED",
linesAdded: 4,
linesRemoved: 0,
url: "https://github.com/octocat/Hello-World/blob/7ca483543807a51b6079e54ac4cc392bc29ae284/test-added"
},
{
path: "test-added-5",
changeType: "ADDED",
linesAdded: 4,
linesRemoved: 0,
url: "https://github.com/octocat/Hello-World/blob/7ca483543807a51b6079e54ac4cc392bc29ae284/test-added"
},
{
path: "test-added-6",
changeType: "ADDED",
linesAdded: 4,
linesRemoved: 0,
url: "https://github.com/octocat/Hello-World/blob/7ca483543807a51b6079e54ac4cc392bc29ae284/test-added"
},
{
path: "test-added-7",
changeType: "ADDED",
linesAdded: 4,
linesRemoved: 0,
url: "https://github.com/octocat/Hello-World/blob/7ca483543807a51b6079e54ac4cc392bc29ae284/test-added"
},
{
path: "test-added-8",
changeType: "ADDED",
linesAdded: 4,
linesRemoved: 0,
url: "https://github.com/octocat/Hello-World/blob/7ca483543807a51b6079e54ac4cc392bc29ae284/test-added"
},
{
path: "test-added-9",
changeType: "ADDED",
linesAdded: 4,
linesRemoved: 0,
url: "https://github.com/octocat/Hello-World/blob/7ca483543807a51b6079e54ac4cc392bc29ae284/test-added"
}
],
id: "test-commit-id",
issueKeys: ["TEST-123", "TEST-246"],
updateSequenceId: 12345678
}
],
updateSequenceId: 12345678
}
],
properties: {
installationId: 1234
}
}).reply(200);
await expect(pushQueueMessageHandler(createMessageProcessingContext(event.payload, jiraHost))).toResolve();
});
it("should not run a command without a Jira issue", async () => {
const fixture = require("../fixtures/push-no-issues.json");
const interceptor = jiraNock.post(/.*/);
const scope = interceptor.reply(200);
await expect(app.receive(fixture)).toResolve();
expect(scope).not.toBeDone();
nock.removeInterceptor(interceptor);
});
it("should not send anything to Jira if there's", async () => {
const fixture = require("../fixtures/push-no-issuekey-commits.json");
// match any post calls for jira and github
jiraNock.post(/.*/).reply(200);
githubNock.get(/.*/).reply(200);
await expect(app.receive(fixture)).toResolve();
// Since no issues keys are found, there should be no calls to github's or jira's API
expect(nock).not.toBeDone();
// Clean up all nock mocks
nock.cleanAll();
});
it("should add the MERGE_COMMIT flag when a merge commit is made", async () => {
const event = require("../fixtures/push-no-username.json");
githubNock.get("/repos/test-repo-owner/test-repo-name/commits/commit-no-username")
.reply(200, require("../fixtures/push-merge-commit.json"));
jiraNock.post("/rest/devinfo/0.10/bulk", {
preventTransitions: false,
repositories: [
{
name: "test-repo-name",
url: "test-repo-url",
id: "test-repo-id",
commits: [
{
hash: "commit-no-username",
message: "[TEST-123] Test commit.",
author: {
email: "test-email@example.com",
name: "test-commit-name"
},
authorTimestamp: "test-commit-date",
displayId: "commit",
fileCount: 3,
files: [
{
path: "test-modified",
changeType: "MODIFIED",
linesAdded: 10,
linesRemoved: 2,
url: "https://github.com/octocat/Hello-World/blob/7ca483543807a51b6079e54ac4cc392bc29ae284/test-modified"
},
{
path: "test-added",
changeType: "ADDED",
linesAdded: 4,
linesRemoved: 0,
url: "https://github.com/octocat/Hello-World/blob/7ca483543807a51b6079e54ac4cc392bc29ae284/test-added"
},
{
path: "test-removal",
changeType: "DELETED",
linesAdded: 0,
linesRemoved: 4,
url: "https://github.com/octocat/Hello-World/blob/7ca483543807a51b6079e54ac4cc392bc29ae284/test-removal"
}
],
id: "commit-no-username",
issueKeys: ["TEST-123"],
url: "https://github.com/octokit/Hello-World/commit/commit-no-username",
updateSequenceId: 12345678,
flags: ["MERGE_COMMIT"]
}
],
updateSequenceId: 12345678
}
],
properties: { installationId: 1234 }
}).reply(200);
await expect(pushQueueMessageHandler(createMessageProcessingContext(event.payload, jiraHost))).toResolve();
});
it("should not add the MERGE_COMMIT flag when a commit is not a merge commit", async () => {
const event = require("../fixtures/push-no-username.json");
githubNock.get("/repos/test-repo-owner/test-repo-name/commits/commit-no-username")
.reply(200, require("../fixtures/push-non-merge-commit"));
// flag property should not be present
jiraNock.post("/rest/devinfo/0.10/bulk", {
preventTransitions: false,
repositories: [
{
name: "test-repo-name",
url: "test-repo-url",
id: "test-repo-id",
commits: [
{
hash: "commit-no-username",
message: "[TEST-123] Test commit.",
author: {
email: "test-email@example.com",
name: "test-commit-name"
},
authorTimestamp: "test-commit-date",
displayId: "commit",
fileCount: 3,
files: [
{
path: "test-modified",
changeType: "MODIFIED",
linesAdded: 10,
linesRemoved: 2,
url: "https://github.com/octocat/Hello-World/blob/7ca483543807a51b6079e54ac4cc392bc29ae284/test-modified"
},
{
path: "test-added",
changeType: "ADDED",
linesAdded: 4,
linesRemoved: 0,
url: "https://github.com/octocat/Hello-World/blob/7ca483543807a51b6079e54ac4cc392bc29ae284/test-added"
},
{
path: "test-removal",
changeType: "DELETED",
linesAdded: 0,
linesRemoved: 4,
url: "https://github.com/octocat/Hello-World/blob/7ca483543807a51b6079e54ac4cc392bc29ae284/test-removal"
}
],
id: "commit-no-username",
issueKeys: ["TEST-123"],
url: "https://github.com/octokit/Hello-World/commit/commit-no-username",
updateSequenceId: 12345678
}
],
updateSequenceId: 12345678
}
],
properties: { installationId: 1234 }
}).reply(200);
await expect(pushQueueMessageHandler(createMessageProcessingContext(event.payload, jiraHost))).toResolve();
});
});
describe("end 2 end tests with queue", () => {
beforeEach(async () => {
Date.now = jest.fn(() => 12345678);
});
beforeAll(async () => {
Date.now = jest.fn(() => 12345678);
//Start worker node for queues processing
await start();
});
afterAll(async () => {
//Stop worker node
await stop();
await sqsQueues.push.waitUntilListenerStopped();
});
function createPushEventAndMockRestRequestsForItsProcessing() {
const event = require("../fixtures/push-no-username.json");
githubNock
.post("/app/installations/1234/access_tokens")
.optionally() // TODO: need to remove optionally and make it explicit
.reply(200, {
token: "token",
expires_at: new Date().getTime()
});
githubNock
.get(`/repos/test-repo-owner/test-repo-name/commits/commit-no-username`)
.reply(200, require("../fixtures/push-non-merge-commit"));
// flag property should not be present
jiraNock.post("/rest/devinfo/0.10/bulk", {
preventTransitions: false,
repositories: [
{
name: "test-repo-name",
url: "test-repo-url",
id: "test-repo-id",
commits: [{
hash: "commit-no-username",
message: "[TEST-123] Test commit.",
author: {
name: "test-commit-name",
email: "test-email@example.com"
},
authorTimestamp: "test-commit-date",
displayId: "commit",
fileCount: 3,
files: [
{
path: "test-modified",
changeType: "MODIFIED",
linesAdded: 10,
linesRemoved: 2,
url: "https://github.com/octocat/Hello-World/blob/7ca483543807a51b6079e54ac4cc392bc29ae284/test-modified"
},
{
path: "test-added",
changeType: "ADDED",
linesAdded: 4,
linesRemoved: 0,
url: "https://github.com/octocat/Hello-World/blob/7ca483543807a51b6079e54ac4cc392bc29ae284/test-added"
},
{
path: "test-removal",
changeType: "DELETED",
linesAdded: 0,
linesRemoved: 4,
url: "https://github.com/octocat/Hello-World/blob/7ca483543807a51b6079e54ac4cc392bc29ae284/test-removal"
}
],
id: "commit-no-username",
issueKeys: ["TEST-123"],
url: "https://github.com/octokit/Hello-World/commit/commit-no-username",
updateSequenceId: 12345678
}],
updateSequenceId: 12345678
}
],
properties: { installationId: 1234 }
}).reply(200);
return event;
}
it("should send bulk update event to Jira when push webhook received through sqs queue", async () => {
const event = createPushEventAndMockRestRequestsForItsProcessing();
await expect(app.receive(event)).toResolve();
await waitUntil(async () => {
expect(githubNock).toBeDone();
expect(jiraNock).toBeDone();
});
});
});
}); | the_stack |
import Component from '@glimmer/component';
import { TrackedArray } from 'tracked-built-ins';
import { setupRenderingTest } from 'ember-qunit';
import { module, test } from 'qunit';
import { reactivityTest } from '../helpers/reactivity';
import { eachReactivityTest, eachInReactivityTest } from '../helpers/collection-reactivity';
const ARRAY_GETTER_METHODS = [
'concat',
'entries',
'every',
'fill',
'filter',
'find',
'findIndex',
'flat',
'flatMap',
'forEach',
'includes',
'indexOf',
'join',
'keys',
'lastIndexOf',
'map',
'reduce',
'reduceRight',
'slice',
'some',
'values',
];
const ARRAY_SETTER_METHODS = [
'copyWithin',
'pop',
'push',
'reverse',
'shift',
'sort',
'splice',
'unshift',
];
module('TrackedArray', function(hooks) {
setupRenderingTest(hooks);
test('Can get values on array directly', assert => {
let arr = new TrackedArray(['foo']);
assert.equal(arr[0], 'foo');
});
test('Can get length on array directly', assert => {
let arr = new TrackedArray(['foo']);
assert.equal(arr.length, 1);
});
test('Can set values on array directly', assert => {
let arr = new TrackedArray();
arr[0] = 123;
assert.equal(arr[0], 123);
});
test('Can set length on array directly', assert => {
let arr = new TrackedArray();
arr.length = 123;
assert.equal(arr.length, 123);
});
module('methods', () => {
test('isArray', assert => {
let arr = new TrackedArray();
assert.ok(Array.isArray(arr));
});
test('length', assert => {
let arr = new TrackedArray();
assert.equal(arr.length, 0);
arr[100] = 1;
assert.equal(arr.length, 101);
});
test('concat', assert => {
let arr = new TrackedArray();
let arr2 = arr.concat([1], new TrackedArray([2]));
assert.deepEqual(arr2, [1, 2]);
assert.notOk(arr2 instanceof TrackedArray);
});
test('copyWithin', assert => {
let arr = new TrackedArray([1, 2, 3]);
arr.copyWithin(1, 0, 1);
assert.deepEqual(arr, [1, 1, 3]);
});
test('entries', assert => {
let arr = new TrackedArray([1, 2, 3]);
let iter = arr.entries();
assert.deepEqual(iter.next().value, [0, 1]);
assert.deepEqual(iter.next().value, [1, 2]);
assert.deepEqual(iter.next().value, [2, 3]);
assert.equal(iter.next().done, true);
});
test('every', assert => {
let arr = new TrackedArray([1, 2, 3]);
assert.ok(arr.every(v => typeof v === 'number'));
assert.notOk(arr.every(v => v !== 2));
});
test('fill', assert => {
let arr = new TrackedArray();
arr.length = 100;
arr.fill(123);
let count = 0;
let isCorrect = true;
for (let value of arr) {
count++;
isCorrect = isCorrect && value === 123;
}
assert.equal(count, 100);
assert.ok(isCorrect);
});
test('filter', assert => {
let arr = new TrackedArray([1, 2, 3]);
let arr2 = arr.filter(v => v > 1);
assert.deepEqual(arr2, [2, 3]);
assert.notOk(arr2 instanceof TrackedArray);
});
test('find', assert => {
let arr = new TrackedArray([1, 2, 3]);
assert.equal(arr.find(v => v > 1), 2);
});
test('findIndex', assert => {
let arr = new TrackedArray([1, 2, 3]);
assert.equal(arr.findIndex(v => v > 1), 1);
});
test('flat', assert => {
let arr = new TrackedArray([1, 2, [3]]);
assert.deepEqual(arr.flat(), [1, 2, 3]);
assert.deepEqual(arr, [1, 2, [3]]);
});
test('flatMap', assert => {
let arr = new TrackedArray([1, 2, [3]]);
assert.deepEqual(arr.flatMap(v => (typeof v === 'number' ? v + 1 : v)), [
2,
3,
3,
]);
assert.deepEqual(arr, [1, 2, [3]]);
});
test('forEach', assert => {
let arr = new TrackedArray([1, 2, 3]);
arr.forEach((v, i) => assert.equal(v, i + 1));
});
test('includes', assert => {
let arr = new TrackedArray([1, 2, 3]);
assert.equal(arr.includes(1), true);
assert.equal(arr.includes(5), false);
});
test('indexOf', assert => {
let arr = new TrackedArray([1, 2, 1]);
assert.equal(arr.indexOf(1), 0);
assert.equal(arr.indexOf(5), -1);
});
test('join', assert => {
let arr = new TrackedArray([1, 2, 3]);
assert.equal(arr.join(','), '1,2,3');
});
test('keys', assert => {
let arr = new TrackedArray([1, 2, 3]);
let iter = arr.keys();
assert.equal(iter.next().value, 0);
assert.equal(iter.next().value, 1);
assert.equal(iter.next().value, 2);
assert.equal(iter.next().done, true);
});
test('lastIndexOf', assert => {
let arr = new TrackedArray([3, 2, 3]);
assert.equal(arr.lastIndexOf(3), 2);
assert.equal(arr.lastIndexOf(5), -1);
});
test('map', assert => {
let arr = new TrackedArray([1, 2, 3]);
let arr2 = arr.map(v => v + 1);
assert.deepEqual(arr2, [2, 3, 4]);
assert.notOk(arr2 instanceof TrackedArray);
});
test('pop', assert => {
let arr = new TrackedArray([1, 2, 3]);
let val = arr.pop();
assert.deepEqual(arr, [1, 2]);
assert.equal(val, 3);
});
test('push', assert => {
let arr = new TrackedArray([1, 2, 3]);
let val = arr.push(4);
assert.deepEqual(arr, [1, 2, 3, 4]);
assert.equal(val, 4);
});
test('reduce', assert => {
let arr = new TrackedArray([1, 2, 3]);
assert.equal(arr.reduce((s, v) => s + v, ''), '123');
});
test('reduceRight', assert => {
let arr = new TrackedArray([1, 2, 3]);
assert.equal(arr.reduceRight((s, v) => s + v, ''), '321');
});
test('reverse', assert => {
let arr = new TrackedArray([1, 2, 3]);
arr.reverse();
assert.deepEqual(arr, [3, 2, 1]);
});
test('shift', assert => {
let arr = new TrackedArray([1, 2, 3]);
let val = arr.shift();
assert.deepEqual(arr, [2, 3]);
assert.equal(val, 1);
});
test('slice', assert => {
let arr = new TrackedArray([1, 2, 3]);
let arr2 = arr.slice();
assert.notEqual(arr, arr2);
assert.notOk(arr2 instanceof TrackedArray);
assert.deepEqual(arr, arr2);
});
test('some', assert => {
let arr = new TrackedArray([1, 2, 3]);
assert.ok(arr.some(v => v > 1));
assert.notOk(arr.some(v => v < 1));
});
test('sort', assert => {
let arr = new TrackedArray([3, 1, 2]);
let arr2 = arr.sort();
assert.equal(arr, arr2);
assert.deepEqual(arr, [1, 2, 3]);
});
test('sort (with method)', assert => {
let arr = new TrackedArray([3, 1, 2, 2]);
let arr2 = arr.sort((a, b) => {
if (a > b) return -1;
if (a < b) return 1;
return 0;
});
assert.equal(arr, arr2);
assert.deepEqual(arr, [3, 2, 2, 1]);
});
test('splice', assert => {
let arr = new TrackedArray([1, 2, 3]);
let arr2 = arr.splice(1, 1);
assert.notOk(arr2 instanceof TrackedArray);
assert.deepEqual(arr, [1, 3]);
assert.deepEqual(arr2, [2]);
});
test('unshift', assert => {
let arr = new TrackedArray([1, 2, 3]);
let val = arr.unshift(0);
assert.deepEqual(arr, [0, 1, 2, 3]);
assert.equal(val, 4);
});
test('values', assert => {
let arr = new TrackedArray([1, 2, 3]);
let iter = arr.values();
assert.equal(iter.next().value, 1);
assert.equal(iter.next().value, 2);
assert.equal(iter.next().value, 3);
assert.equal(iter.next().done, true);
});
test('of', assert => {
let arr = TrackedArray.of(1, 2, 3);
assert.deepEqual(arr, [1, 2, 3]);
});
test('from', assert => {
let arr = TrackedArray.from([1, 2, 3]);
assert.deepEqual(arr, [1, 2, 3]);
});
});
module('reactivity', () => {
reactivityTest(
'getting and setting an index',
class extends Component {
arr = new TrackedArray(['foo']);
get value() {
return this.arr[0];
}
update() {
this.arr[0] = 'bar';
}
}
);
eachReactivityTest(
'{{each}} works with new items',
class extends Component {
collection = new TrackedArray([1, 2, 3]);
update() {
this.collection.push(4);
}
}
);
eachReactivityTest(
'{{each}} works when updating old items',
class extends Component {
collection = new TrackedArray([1, 2, 3]);
update() {
this.collection[2] = 5;
}
}
);
eachInReactivityTest(
'{{each-in}} works with new items',
class extends Component {
collection = new TrackedArray([1, 2, 3]);
update() {
this.collection.push(4);
}
}
);
eachInReactivityTest(
'{{each-in}} works when updating old items',
class extends Component {
collection = new TrackedArray([1, 2, 3]);
update() {
this.collection[2] = 5;
}
}
);
ARRAY_GETTER_METHODS.forEach(method => {
reactivityTest(
`${method} individual index`,
class extends Component {
arr = new TrackedArray(['foo', 'bar']);
get value() {
// @ts-ignore -- this can't be represented easily in TS, and we
// don't actually care that it is; we're *just* testing reactivity.
return this.arr[method](() => {/* no op */});
}
update() {
this.arr[0] = 'bar';
}
}
);
reactivityTest(
`${method} collection tag`,
class extends Component {
arr = new TrackedArray(['foo', 'bar']);
get value() {
// @ts-ignore -- this can't be represented easily in TS, and we
// don't actually care that it is; we're *just* testing reactivity.
return this.arr[method](() => {/* no op */});
}
update() {
this.arr.sort();
}
}
);
});
ARRAY_SETTER_METHODS.forEach((method) => {
reactivityTest(
`${method} individual index`,
class extends Component {
arr = new TrackedArray(['foo', 'bar']);
get value() {
return this.arr[0];
}
update() {
// @ts-ignore -- this can't be represented easily in TS, and we
// don't actually care that it is; we're *just* testing reactivity.
this.arr[method](undefined);
}
}
);
reactivityTest(
`${method} collection tag`,
class extends Component {
arr = new TrackedArray(['foo', 'bar']);
get value() {
return this.arr.forEach(() => {/* no op */});
}
update() {
// @ts-ignore -- this can't be represented easily in TS, and we
// don't actually care that it is; we're *just* testing reactivity.
this.arr[method](undefined);
}
}
);
});
});
}); | the_stack |
import { DelimArray } from '@looker/sdk-rtl'
import { TestConfig } from './testUtils'
import { PythonGen } from './python.gen'
import type { IEnumType, IType } from './sdkModels'
import type { IMappedType } from './codeGen'
const config = TestConfig()
const apiTestModel = config.apiTestModel
const gen = new PythonGen(apiTestModel)
const indent = ''
describe('python generator', () => {
describe('comment header', () => {
it('is empty with no comment', () => {
expect(gen.commentHeader('', '')).toEqual('')
})
it('is two lines with a two line comment', () => {
const expected = `# foo
# bar
`
expect(gen.commentHeader('', 'foo\nbar')).toEqual(expected)
})
})
describe('bookends', () => {
it('has a models prologue', () => {
expect(gen.modelsPrologue('')).toEqual(`
# NOTE: Do not edit this file generated by Looker SDK Codegen
import datetime
import enum
from typing import Any, MutableMapping, Optional, Sequence
try:
from typing import ForwardRef # type: ignore
except ImportError:
from typing import _ForwardRef as ForwardRef # type: ignore
import attr
from looker_sdk.rtl import model
from looker_sdk.rtl import serialize as sr
EXPLICIT_NULL = model.EXPLICIT_NULL # type: ignore
DelimSequence = model.DelimSequence
`)
})
it('has a methods prologue', () => {
expect(gen.methodsPrologue('')).toEqual(`
# NOTE: Do not edit this file generated by Looker SDK Codegen
import datetime
from typing import Any, MutableMapping, Optional, Sequence, Union, cast
import warnings
from . import models
from looker_sdk.rtl import api_methods
from looker_sdk.rtl import transport
class LookerSDK(api_methods.APIMethods):
`)
})
it('has a models epilogue', () => {
const type = apiTestModel.types.LookmlModelExploreJoins
gen.declareType(indent, type)
expect(gen.modelsEpilogue('')).toEqual(`
# The following cattrs structure hook registrations are a workaround
# for https://github.com/Tinche/cattrs/pull/42 Once this issue is resolved
# these calls will be removed.
import functools # noqa:E402
forward_ref_structure_hook = functools.partial(sr.forward_ref_structure_hook, globals(), sr.converter)
translate_keys_structure_hook = functools.partial(sr.translate_keys_structure_hook, sr.converter)
sr.converter.register_structure_hook(
ForwardRef("LookmlModelExploreJoins"), # type: ignore
forward_ref_structure_hook # type:ignore
)
sr.converter.register_structure_hook(
LookmlModelExploreJoins, # type: ignore
translate_keys_structure_hook # type:ignore
)
`)
})
it('does not have a methods epilogue', () => {
expect(gen.methodsEpilogue('')).toEqual('')
})
})
describe('parameter declarations', () => {
it('required parameter', () => {
const method = apiTestModel.methods.run_query
const param = method.params[0]
const actual = gen.declareParameter(indent, method, param)
expect(actual).toEqual('# Id of query\nquery_id: int')
})
it('optional parameter', () => {
const method = apiTestModel.methods.run_query
const param = method.params[2]
const actual = gen.declareParameter(indent, method, param)
expect(actual).toEqual(
'# Row limit (may override the limit in the saved query).\n' +
'limit: Optional[int] = None'
)
})
it('required typed parameter', () => {
const method = apiTestModel.methods.create_query_render_task
const param = method.params[2]
const actual = gen.declareParameter(indent, method, param)
expect(actual).toEqual(`# Output width in pixels\nwidth: int`)
})
})
describe('args locations', () => {
it('path and query args', () => {
const method = apiTestModel.methods.run_query
expect(method.pathArgs).toEqual(['query_id', 'result_format'])
expect(method.bodyArg).toEqual('')
expect(method.queryArgs).toEqual([
'limit',
'apply_formatting',
'apply_vis',
'cache',
'image_width',
'image_height',
'generate_drill_links',
'force_production',
'cache_only',
'path_prefix',
'rebuild_pdts',
'server_table_calcs',
])
expect(method.headerArgs).toEqual([])
expect(method.cookieArgs).toEqual([])
})
it('body for create_query', () => {
// TODO get resolution working correctly
const method = apiTestModel.methods.create_query
expect(method.pathArgs).toEqual([])
const body = method.getParams('body')
expect(body.length).toEqual(1)
expect(body[0].type.name).toEqual('Query')
expect(method.bodyArg).toEqual('body')
expect(method.queryArgs).toEqual(['fields'])
expect(method.headerArgs).toEqual([])
expect(method.cookieArgs).toEqual([])
})
it('body for create_dashboard', () => {
// TODO get resolution working correctly
const method = apiTestModel.methods.create_dashboard
expect(method.pathArgs).toEqual([])
const body = method.getParams('body')
expect(body.length).toEqual(1)
expect(body[0].type.name).toEqual('Dashboard')
expect(method.bodyArg).toEqual('body')
expect(method.queryArgs).toEqual([])
expect(method.headerArgs).toEqual([])
expect(method.cookieArgs).toEqual([])
})
})
describe('httpArgs', () => {
it('add_group_group', () => {
const method = apiTestModel.methods.add_group_group
const args = gen.httpArgs('', method)
const expected = `
path=f"/groups/{group_id}/groups",
structure=models.Group,
body=body,
transport_options=transport_options`.replace(/^\n/, '')
expect(args).toEqual(expected)
})
it('create_query', () => {
const method = apiTestModel.methods.create_query
const args = gen.httpArgs('', method)
const expected = `
path="/queries",
structure=models.Query,
query_params={"fields": fields},
body=body,
transport_options=transport_options`.replace(/^\n/, '')
expect(args).toEqual(expected)
})
it('create_dashboard', () => {
const method = apiTestModel.methods.create_dashboard
const args = gen.httpArgs('', method)
const expected = `
path="/dashboards",
structure=models.Dashboard,
body=body,
transport_options=transport_options`.replace(/^\n/, '')
expect(args).toEqual(expected)
})
})
describe('method signature', () => {
it('no params with all_datagroups', () => {
const method = apiTestModel.methods.all_datagroups
const expected = `# ### Get information about all datagroups.
#
# GET /datagroups -> Sequence[models.Datagroup]
def all_datagroups(
self,
transport_options: Optional[transport.TransportOptions] = None,
) -> Sequence[models.Datagroup]:
`
const actual = gen.methodSignature('', method)
expect(actual).toEqual(expected)
})
it('DelimSequence with test_connection', () => {
const method = apiTestModel.methods.test_connection
const expected = `# ### Test an existing connection.
#
# Note that a connection's 'dialect' property has a 'connection_tests' property that lists the
# specific types of tests that the connection supports.
#
# This API is rate limited.
#
# Unsupported tests in the request will be ignored.
#
# PUT /connections/{connection_name}/test -> Sequence[models.DBConnectionTestResult]
def test_connection(
self,
# Name of connection
connection_name: str,
# Array of names of tests to run
tests: Optional[models.DelimSequence[str]] = None,
transport_options: Optional[transport.TransportOptions] = None,
) -> Sequence[models.DBConnectionTestResult]:
`
const actual = gen.methodSignature('', method)
expect(actual).toEqual(expected)
})
it('binary return type render_task_results', () => {
const method = apiTestModel.methods.render_task_results
const expected = `# ### Get the document or image produced by a completed render task.
#
# Note that the PDF or image result will be a binary blob in the HTTP response, as indicated by the
# Content-Type in the response headers. This may require specialized (or at least different) handling than text
# responses such as JSON. You may need to tell your HTTP client that the response is binary so that it does not
# attempt to parse the binary data as text.
#
# If the render task exists but has not finished rendering the results, the response HTTP status will be
# **202 Accepted**, the response body will be empty, and the response will have a Retry-After header indicating
# that the caller should repeat the request at a later time.
#
# Returns 404 if the render task cannot be found, if the cached result has expired, or if the caller
# does not have permission to view the results.
#
# For detailed information about the status of the render task, use [Render Task](#!/RenderTask/render_task).
# Polling loops waiting for completion of a render task would be better served by polling **render_task(id)** until
# the task status reaches completion (or error) instead of polling **render_task_results(id)** alone.
#
# GET /render_tasks/{render_task_id}/results -> bytes
def render_task_results(
self,
# Id of render task
render_task_id: str,
transport_options: Optional[transport.TransportOptions] = None,
) -> bytes:
`
const actual = gen.methodSignature('', method)
expect(actual).toEqual(expected)
})
it('noComment binary return type render_task_results', () => {
const method = apiTestModel.methods.render_task_results
const expected = `def render_task_results(
self,
render_task_id: str,
transport_options: Optional[transport.TransportOptions] = None,
) -> bytes:
`
gen.noComment = true
const actual = gen.methodSignature('', method)
gen.noComment = false
expect(actual).toEqual(expected)
})
it('binary or string return type run_url_encoded_query', () => {
const method = apiTestModel.methods.run_url_encoded_query
const expected = `# ### Run an URL encoded query.
#
# This requires the caller to encode the specifiers for the query into the URL query part using
# Looker-specific syntax as explained below.
#
# Generally, you would want to use one of the methods that takes the parameters as json in the POST body
# for creating and/or running queries. This method exists for cases where one really needs to encode the
# parameters into the URL of a single 'GET' request. This matches the way that the Looker UI formats
# 'explore' URLs etc.
#
# The parameters here are very similar to the json body formatting except that the filter syntax is
# tricky. Unfortunately, this format makes this method not currently callable via the 'Try it out!' button
# in this documentation page. But, this is callable when creating URLs manually or when using the Looker SDK.
#
# Here is an example inline query URL:
#
# \`\`\`
# https://looker.mycompany.com:19999/api/3.0/queries/models/thelook/views/inventory_items/run/json?fields=category.name,inventory_items.days_in_inventory_tier,products.count&f[category.name]=socks&sorts=products.count+desc+0&limit=500&query_timezone=America/Los_Angeles
# \`\`\`
#
# When invoking this endpoint with the Ruby SDK, pass the query parameter parts as a hash. The hash to match the above would look like:
#
# \`\`\`ruby
# query_params =
# {
# :fields => "category.name,inventory_items.days_in_inventory_tier,products.count",
# :"f[category.name]" => "socks",
# :sorts => "products.count desc 0",
# :limit => "500",
# :query_timezone => "America/Los_Angeles"
# }
# response = ruby_sdk.run_url_encoded_query('thelook','inventory_items','json', query_params)
#
# \`\`\`
#
# Again, it is generally easier to use the variant of this method that passes the full query in the POST body.
# This method is available for cases where other alternatives won't fit the need.
#
# Supported formats:
#
# | result_format | Description
# | :-----------: | :--- |
# | json | Plain json
# | json_detail | Row data plus metadata describing the fields, pivots, table calcs, and other aspects of the query
# | csv | Comma separated values with a header
# | txt | Tab separated values with a header
# | html | Simple html
# | md | Simple markdown
# | xlsx | MS Excel spreadsheet
# | sql | Returns the generated SQL rather than running the query
# | png | A PNG image of the visualization of the query
# | jpg | A JPG image of the visualization of the query
#
# GET /queries/models/{model_name}/views/{view_name}/run/{result_format} -> Union[str, bytes]
def run_url_encoded_query(
self,
# Model name
model_name: str,
# View name
view_name: str,
# Format of result
result_format: str,
transport_options: Optional[transport.TransportOptions] = None,
) -> Union[str, bytes]:
`
const actual = gen.methodSignature('', method)
expect(actual).toEqual(expected)
})
})
describe('method body', () => {
it('encodes string path params', () => {
const method = apiTestModel.methods.run_url_encoded_query
const expected = `model_name = self.encode_path_param(model_name)
view_name = self.encode_path_param(view_name)
result_format = self.encode_path_param(result_format)
`
const actual = gen.encodePathParams('', method)
expect(actual).toEqual(expected)
})
it('encodes only string path params', () => {
const method = apiTestModel.methods.run_look
// should NOT escape look_id (int)
const expected = 'result_format = self.encode_path_param(result_format)\n'
const actual = gen.encodePathParams('', method)
expect(actual).toEqual(expected)
})
it('add_group_group httpCall', () => {
const method = apiTestModel.methods.add_group_group
const expected = `
response = cast(
models.Group,
self.post(
path=f"/groups/{group_id}/groups",
structure=models.Group,
body=body,
transport_options=transport_options
)
)
return response`.replace(/^\n/, '')
const actual = gen.httpCall(indent, method)
expect(actual).toEqual(expected)
})
it('delete_group_from_group httpCall', () => {
const method = apiTestModel.methods.delete_group_from_group
const expected = `
response = cast(
None,
self.delete(
path=f"/groups/{group_id}/groups/{deleting_group_id}",
structure=None,
transport_options=transport_options
)
)
return response`.replace(/^\n/, '')
const actual = gen.httpCall(indent, method)
expect(actual).toEqual(expected)
})
it('active_themes httpCall', () => {
const method = apiTestModel.methods.active_themes
const expected = `
response = cast(
Sequence[models.Theme],
self.get(
path="/themes/active",
structure=Sequence[models.Theme],
query_params={"name": name, "ts": ts, "fields": fields},
transport_options=transport_options
)
)
return response`.replace(/^\n/, '')
const actual = gen.httpCall(indent, method)
expect(actual).toEqual(expected)
})
it('assert login_user has a warning', () => {
const method = apiTestModel.methods.login_user
const expected = `
warnings.warn("login_user behavior changed significantly in 21.4.0. See https://git.io/JOtH1")
response = cast(
models.AccessToken,
self.post(
path=f"/login/{user_id}",
structure=models.AccessToken,
query_params={"associative": associative},
transport_options=transport_options
)
)
return response`.replace(/^\n/, '')
const actual = gen.httpCall(indent, method)
expect(actual).toEqual(expected)
})
it('query_task_results httpCall', () => {
const method = apiTestModel.methods.query_task_results
const expected = `
response = cast(
str,
self.get(
path=f"/query_tasks/{query_task_id}/results",
structure=str,
transport_options=transport_options
)
)
return response`.replace(/^\n/, '')
const actual = gen.httpCall(indent, method)
expect(actual).toEqual(expected)
})
it('render_task_results httpCall', () => {
const method = apiTestModel.methods.render_task_results
const expected = `
response = cast(
bytes,
self.get(
path=f"/render_tasks/{render_task_id}/results",
structure=bytes,
transport_options=transport_options
)
)
return response`.replace(/^\n/, '')
const actual = gen.httpCall(indent, method)
expect(actual).toEqual(expected)
})
it('run_url_encoded_query httpCall', () => {
const method = apiTestModel.methods.run_url_encoded_query
const expected = `
response = cast(
Union[str, bytes],
self.get(
path=f"/queries/models/{model_name}/views/{view_name}/run/{result_format}",
structure=Union[str, bytes], # type: ignore
transport_options=transport_options
)
)
return response`.replace(/^\n/, '')
const actual = gen.httpCall(indent, method)
expect(actual).toEqual(expected)
})
})
describe('type creation', () => {
it('with arrays and hashes', () => {
const type = apiTestModel.types.Workspace
const actual = gen.declareType(indent, type)
expect(type.properties.id.type.name).toEqual('string')
expect(actual).toEqual(`
@attr.s(auto_attribs=True, init=False)
class Workspace(model.Model):
"""
Attributes:
can: Operations the current user is able to perform on this object
id: The unique id of this user workspace. Predefined workspace ids include "production" and "dev"
projects: The local state of each project in the workspace
"""
can: Optional[MutableMapping[str, bool]] = None
id: Optional[str] = None
projects: Optional[Sequence["Project"]] = None
def __init__(self, *,
can: Optional[MutableMapping[str, bool]] = None,
id: Optional[str] = None,
projects: Optional[Sequence["Project"]] = None):
self.can = can
self.id = id
self.projects = projects`)
})
it('re-orders required props to top', () => {
const type = apiTestModel.types.CreateDashboardFilter
const actual = gen.declareType(indent, type)
expect(actual).toEqual(`
@attr.s(auto_attribs=True, init=False)
class CreateDashboardFilter(model.Model):
"""
Attributes:
dashboard_id: Id of Dashboard
name: Name of filter
title: Title of filter
type: Type of filter: one of date, number, string, or field
id: Unique Id
default_value: Default value of filter
model: Model of filter (required if type = field)
explore: Explore of filter (required if type = field)
dimension: Dimension of filter (required if type = field)
field: Field information
row: Display order of this filter relative to other filters
listens_to_filters: Array of listeners for faceted filters
allow_multiple_values: Whether the filter allows multiple filter values
required: Whether the filter requires a value to run the dashboard
ui_config: The visual configuration for this filter. Used to set up how the UI for this filter should appear.
"""
dashboard_id: str
name: str
title: str
type: str
id: Optional[str] = None
default_value: Optional[str] = None
model: Optional[str] = None
explore: Optional[str] = None
dimension: Optional[str] = None
field: Optional[MutableMapping[str, Any]] = None
row: Optional[int] = None
listens_to_filters: Optional[Sequence[str]] = None
allow_multiple_values: Optional[bool] = None
required: Optional[bool] = None
ui_config: Optional[MutableMapping[str, Any]] = None
def __init__(self, *,
dashboard_id: str,
name: str,
title: str,
type: str,
id: Optional[str] = None,
default_value: Optional[str] = None,
model: Optional[str] = None,
explore: Optional[str] = None,
dimension: Optional[str] = None,
field: Optional[MutableMapping[str, Any]] = None,
row: Optional[int] = None,
listens_to_filters: Optional[Sequence[str]] = None,
allow_multiple_values: Optional[bool] = None,
required: Optional[bool] = None,
ui_config: Optional[MutableMapping[str, Any]] = None):
self.dashboard_id = dashboard_id
self.name = name
self.title = title
self.type = type
self.id = id
self.default_value = default_value
self.model = model
self.explore = explore
self.dimension = dimension
self.field = field
self.row = row
self.listens_to_filters = listens_to_filters
self.allow_multiple_values = allow_multiple_values
self.required = required
self.ui_config = ui_config`)
})
it('with translated keywords', () => {
const type = apiTestModel.types.LookmlModelExploreJoins
const actual = gen.declareType(indent, type)
// note the "from_" property
expect(actual).toEqual(`
@attr.s(auto_attribs=True, init=False)
class LookmlModelExploreJoins(model.Model):
"""
Attributes:
name: Name of this join (and name of the view to join)
dependent_fields: Fields referenced by the join
fields: Fields of the joined view to pull into this explore
foreign_key: Name of the dimension in this explore whose value is in the primary key of the joined view
from_: Name of view to join
outer_only: Specifies whether all queries must use an outer join
relationship: many_to_one, one_to_one, one_to_many, many_to_many
required_joins: Names of joins that must always be included in SQL queries
sql_foreign_key: SQL expression that produces a foreign key
sql_on: SQL ON expression describing the join condition
sql_table_name: SQL table name to join
type: The join type: left_outer, full_outer, inner, or cross
view_label: Label to display in UI selectors
"""
name: Optional[str] = None
dependent_fields: Optional[Sequence[str]] = None
fields: Optional[Sequence[str]] = None
foreign_key: Optional[str] = None
from_: Optional[str] = None
outer_only: Optional[bool] = None
relationship: Optional[str] = None
required_joins: Optional[Sequence[str]] = None
sql_foreign_key: Optional[str] = None
sql_on: Optional[str] = None
sql_table_name: Optional[str] = None
type: Optional[str] = None
view_label: Optional[str] = None
def __init__(self, *,
name: Optional[str] = None,
dependent_fields: Optional[Sequence[str]] = None,
fields: Optional[Sequence[str]] = None,
foreign_key: Optional[str] = None,
from_: Optional[str] = None,
outer_only: Optional[bool] = None,
relationship: Optional[str] = None,
required_joins: Optional[Sequence[str]] = None,
sql_foreign_key: Optional[str] = None,
sql_on: Optional[str] = None,
sql_table_name: Optional[str] = None,
type: Optional[str] = None,
view_label: Optional[str] = None):
self.name = name
self.dependent_fields = dependent_fields
self.fields = fields
self.foreign_key = foreign_key
self.from_ = from_
self.outer_only = outer_only
self.relationship = relationship
self.required_joins = required_joins
self.sql_foreign_key = sql_foreign_key
self.sql_on = sql_on
self.sql_table_name = sql_table_name
self.type = type
self.view_label = view_label`)
})
it('with refs, arrays and nullable', () => {
const type = apiTestModel.types.ApiVersion
expect(type.properties.looker_release_version.type.name).toEqual('string')
const actual = gen.declareType(indent, type)
expect(actual).toEqual(`
@attr.s(auto_attribs=True, init=False)
class ApiVersion(model.Model):
"""
Attributes:
looker_release_version: Current Looker release version number
current_version:
supported_versions: Array of versions supported by this Looker instance
"""
looker_release_version: Optional[str] = None
current_version: Optional["ApiVersionElement"] = None
supported_versions: Optional[Sequence["ApiVersionElement"]] = None
def __init__(self, *,
looker_release_version: Optional[str] = None,
current_version: Optional["ApiVersionElement"] = None,
supported_versions: Optional[Sequence["ApiVersionElement"]] = None):
self.looker_release_version = looker_release_version
self.current_version = current_version
self.supported_versions = supported_versions`)
})
function checkMappedType(
type: IType,
expectedTypeName: string,
expectedMapping: IMappedType
) {
expect(type.name).toEqual(expectedTypeName)
const mapped = gen.typeMapModels(type)
expect(mapped).toEqual(expectedMapping)
}
it('enum type', () => {
const type = apiTestModel.types.PermissionType as IEnumType
expect(type).toBeDefined()
expect(type.values).toEqual(['view', 'edit'])
const actual = gen.declareType('', type)
const expected = `
class PermissionType(enum.Enum):
"""
Type of permission: "view" or "edit" Valid values are: "view", "edit".
"""
view = "view"
edit = "edit"
invalid_api_enum_value = "invalid_api_enum_value"
# https://github.com/python/mypy/issues/2427
PermissionType.__new__ = model.safe_enum__new__ # type: ignore`
expect(actual).toEqual(expected)
})
it('needs __annotations__', () => {
const type = apiTestModel.types.RequiredResponseWithEnums
expect(type).toBeDefined()
const actual = gen.declareType('', type)
const expected = `
@attr.s(auto_attribs=True, init=False)
class RequiredResponseWithEnums(model.Model):
"""
Attributes:
query_id: Id of query to run
result_format: Desired async query result format. Valid values are: "inline_json", "json", "json_detail", "json_fe", "csv", "html", "md", "txt", "xlsx", "gsxml".
user:
an_array_of_enums: An array of user attribute types that are allowed to be used in filters on this field. Valid values are: "advanced_filter_string", "advanced_filter_number", "advanced_filter_datetime", "string", "number", "datetime", "relative_url", "yesno", "zipcode".
roles: Roles assigned to group
"""
query_id: int
result_format: "ResultFormat"
user: "UserPublic"
an_array_of_enums: Optional[Sequence["AnArrayOfEnums"]] = None
roles: Optional[Sequence["Role"]] = None
__annotations__ = {
"query_id": int,
"result_format": ForwardRef("ResultFormat"),
"user": ForwardRef("UserPublic"),
"an_array_of_enums": Optional[Sequence["AnArrayOfEnums"]],
"roles": Optional[Sequence["Role"]]
}
def __init__(self, *,
query_id: int,
result_format: "ResultFormat",
user: "UserPublic",
an_array_of_enums: Optional[Sequence["AnArrayOfEnums"]] = None,
roles: Optional[Sequence["Role"]] = None):
self.query_id = query_id
self.result_format = result_format
self.user = user
self.an_array_of_enums = an_array_of_enums
self.roles = roles`
expect(actual).toEqual(expected)
})
it('input models', () => {
// TODO this side-effect should NOT be required for the test
// type declarations should be atomic w/o side-effect requirements
// run method generation to populate inputTypes
const method = apiTestModel.methods.create_merge_query
const param = method.bodyParams[0]
gen.declareParameter(indent, method, param)
const inputType = apiTestModel.types.WriteMergeQuery
const asVal = expect.any(Function)
checkMappedType(inputType.properties.column_limit.type, 'string', {
default: gen.nullStr,
name: 'str',
asVal: asVal,
})
checkMappedType(inputType.properties.dynamic_fields.type, 'string', {
default: gen.nullStr,
name: 'str',
asVal: asVal,
})
checkMappedType(inputType.properties.pivots.type, 'string[]', {
default: gen.nullStr,
name: 'Sequence[str]',
})
const actual = gen.declareType(indent, inputType)
expect(actual).toEqual(`
@attr.s(auto_attribs=True, init=False)
class WriteMergeQuery(model.Model):
"""
Dynamic writeable type for MergeQuery removes:
can, id, result_maker_id
Attributes:
column_limit: Column Limit
dynamic_fields: Dynamic Fields
pivots: Pivots
sorts: Sorts
source_queries: Source Queries defining the results to be merged.
total: Total
vis_config: Visualization Config
"""
column_limit: Optional[str] = None
dynamic_fields: Optional[str] = None
pivots: Optional[Sequence[str]] = None
sorts: Optional[Sequence[str]] = None
source_queries: Optional[Sequence["MergeQuerySourceQuery"]] = None
total: Optional[bool] = None
vis_config: Optional[MutableMapping[str, Any]] = None
def __init__(self, *,
column_limit: Optional[str] = None,
dynamic_fields: Optional[str] = None,
pivots: Optional[Sequence[str]] = None,
sorts: Optional[Sequence[str]] = None,
source_queries: Optional[Sequence["MergeQuerySourceQuery"]] = None,
total: Optional[bool] = None,
vis_config: Optional[MutableMapping[str, Any]] = None):
self.column_limit = column_limit
self.dynamic_fields = dynamic_fields
self.pivots = pivots
self.sorts = sorts
self.source_queries = source_queries
self.total = total
self.vis_config = vis_config`)
const childInputType = apiTestModel.types.MergeQuerySourceQuery
const childActual = gen.declareType(indent, childInputType)
expect(childActual).toEqual(`
@attr.s(auto_attribs=True, init=False)
class MergeQuerySourceQuery(model.Model):
"""
Attributes:
merge_fields: An array defining which fields of the source query are mapped onto fields of the merge query
name: Display name
query_id: Id of the query to merge
"""
merge_fields: Optional[Sequence["MergeFields"]] = None
name: Optional[str] = None
query_id: Optional[int] = None
def __init__(self, *,
merge_fields: Optional[Sequence["MergeFields"]] = None,
name: Optional[str] = None,
query_id: Optional[int] = None):
self.merge_fields = merge_fields
self.name = name
self.query_id = query_id`)
const grandChildInputType = apiTestModel.types.MergeFields
const grandChildActual = gen.declareType(indent, grandChildInputType)
expect(grandChildActual).toEqual(`
@attr.s(auto_attribs=True, init=False)
class MergeFields(model.Model):
"""
Attributes:
field_name: Field name to map onto in the merged results
source_field_name: Field name from the source query
"""
field_name: Optional[str] = None
source_field_name: Optional[str] = None
def __init__(self, *,
field_name: Optional[str] = None,
source_field_name: Optional[str] = None):
self.field_name = field_name
self.source_field_name = source_field_name`)
})
})
describe('makeTheCall', () => {
const fields = 'id,user_id,title,description'
it('handles no params', () => {
const inputs = {}
const method = apiTestModel.methods.run_look
const actual = gen.makeTheCall(method, inputs)
const expected = 'response = sdk.run_look()'
expect(actual).toEqual(expected)
})
it('assigns single param', () => {
const inputs = { look_id: 17 }
const method = apiTestModel.methods.look
const actual = gen.makeTheCall(method, inputs)
const expected = `response = sdk.look(look_id=17)`
expect(actual).toEqual(expected)
})
it('assigns simple params', () => {
const inputs = { look_id: 17, fields }
const method = apiTestModel.methods.look
const actual = gen.makeTheCall(method, inputs)
const expected = `response = sdk.look(
look_id=17,
fields="${fields}")`
expect(actual).toEqual(expected)
})
it('assigns a body param', () => {
const body = {
title: 'test title',
description: 'gen test',
query: {
model: 'the_look',
view: 'users',
total: true,
},
}
const inputs = { look_id: 17, body, fields }
const method = apiTestModel.methods.update_look
const actual = gen.makeTheCall(method, inputs)
const expected = `response = sdk.update_look(
look_id=17,
body=models.WriteLookWithQuery(
title="test title",
description="gen test",
query=models.WriteQuery(
model="the_look",
view="users",
total=true
)
),
fields="id,user_id,title,description")`
expect(actual).toEqual(expected)
})
it('assigns an enum', () => {
const inputs = {
body: {
query_id: 1,
result_format: 'csv',
},
}
const method = apiTestModel.methods.create_query_task
const actual = gen.makeTheCall(method, inputs)
const expected = `response = sdk.create_query_task(
body=models.WriteCreateQueryTask(
query_id=1,
result_format=models.ResultFormat.csv
))`
expect(actual).toEqual(expected)
})
it('assigns a DelimArray', () => {
const inputs = {
ids: new DelimArray<number>([1, 2, 3]),
}
const method = apiTestModel.methods.all_users
const actual = gen.makeTheCall(method, inputs)
const expected = `response = sdk.all_users(
ids=models.DelimSequence([1,2,3]))`
expect(actual).toEqual(expected)
})
it('assigns a DelimArray', () => {
const inputs = {
ids: new DelimArray<number>([1, 2, 3]),
}
const method = apiTestModel.methods.all_users
const actual = gen.makeTheCall(method, inputs)
const expected = `response = sdk.all_users(
ids=models.DelimSequence([1,2,3]))`
expect(actual).toEqual(expected)
})
it('assigns simple and complex arrays', () => {
const body = {
column_limit: '5',
pivots: ['one', 'two', 'three'],
sorts: ['a'],
source_queries: [
{
name: 'first query',
query_id: 1,
merge_fields: [
{
field_name: 'merge_1',
source_field_name: 'source_1',
},
],
},
{
name: 'second query',
query_id: 2,
merge_fields: [
{
field_name: 'merge_2',
source_field_name: 'source_2',
},
],
},
],
}
const inputs = { body, fields }
const method = apiTestModel.methods.create_merge_query
const actual = gen.makeTheCall(method, inputs)
const expected = `response = sdk.create_merge_query(
body=models.WriteMergeQuery(
column_limit="5",
pivots=[
"one",
"two",
"three"
],
sorts=["a"],
source_queries=[
models.MergeQuerySourceQuery(
merge_fields=[
models.MergeFields(
field_name="merge_1",
source_field_name="source_1"
)
],
name="first query",
query_id=1
),
models.MergeQuerySourceQuery(
merge_fields=[
models.MergeFields(
field_name="merge_2",
source_field_name="source_2"
)
],
name="second query",
query_id=2
)
]
),
fields="id,user_id,title,description")`
expect(actual).toEqual(expected)
})
it('assigns dictionaries', () => {
const query = {
connection_name: 'looker',
model_name: 'the_look',
vis_config: { first: 1, second: 'two' },
}
const inputs = { body: query }
const method = apiTestModel.methods.create_sql_query
const expected = `response = sdk.create_sql_query(
body=models.SqlQueryCreate(
connection_name="looker",
model_name="the_look",
vis_config={
"first": 1,
"second": "two"
}
))`
const actual = gen.makeTheCall(method, inputs)
expect(actual).toEqual(expected)
})
describe('hashValue', () => {
it('assigns a hash with heterogeneous values', () => {
const token = {
access_token: 'backstage',
token_type: 'test',
expires_in: 10,
}
const oneItem = [1]
const threeItems = ['Abe', 'Zeb', token]
const inputs = {
/**
* The below key is quoted in the generated dictionary. This is a bug
* that might need addressing later on.
*/
1: 'one',
'2': 'two',
item: oneItem,
items: threeItems,
first: 1,
second: 'two',
third: false,
token,
'foo.bar': 'foobar',
}
const expected = `{
"1": "one",
"2": "two",
"item": [1],
"items": [
"Abe",
"Zeb",
{
"access_token": "backstage",
"token_type": "test",
"expires_in": 10
}
],
"first": 1,
"second": "two",
"third": false,
"token": {
"access_token": "backstage",
"token_type": "test",
"expires_in": 10
},
"foo.bar": "foobar"
}`
const actual = gen.hashValue('', inputs)
expect(actual).toEqual(expected)
})
})
describe('assignType', () => {
it('assigns a complex type', () => {
const inputs = {
name: 'first query',
query_id: 1,
merge_fields: [
{
field_name: 'merge_1',
source_field_name: 'source_1',
},
],
}
const type = apiTestModel.types.MergeQuerySourceQuery
expect(type).toBeDefined()
const expected = `models.MergeQuerySourceQuery(
merge_fields=[
models.MergeFields(
field_name="merge_1",
source_field_name="source_1"
)
],
name="first query",
query_id=1
)`
const actual = gen.assignType(gen.indentStr, type, inputs)
expect(actual).toEqual(expected)
})
})
})
}) | the_stack |
// IMPORTANT
// This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually.
// In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator
// Generated from: https://testing.googleapis.com/$discovery/rest?version=v1
/// <reference types="gapi.client" />
declare namespace gapi.client {
/** Load Google Cloud Testing API v1 */
function load(name: "testing", version: "v1"): PromiseLike<void>;
function load(name: "testing", version: "v1", callback: () => any): void;
const projects: testing.ProjectsResource;
const testEnvironmentCatalog: testing.TestEnvironmentCatalogResource;
namespace testing {
interface Account {
/** An automatic google login account */
googleAuto?: any;
}
interface AndroidDevice {
/**
* The id of the Android device to be used.
* Use the EnvironmentDiscoveryService to get supported options.
* Required
*/
androidModelId?: string;
/**
* The id of the Android OS version to be used.
* Use the EnvironmentDiscoveryService to get supported options.
* Required
*/
androidVersionId?: string;
/**
* The locale the test device used for testing.
* Use the EnvironmentDiscoveryService to get supported options.
* Required
*/
locale?: string;
/**
* How the device is oriented during the test.
* Use the EnvironmentDiscoveryService to get supported options.
* Required
*/
orientation?: string;
}
interface AndroidDeviceCatalog {
/**
* The set of supported Android device models.
* @OutputOnly
*/
models?: AndroidModel[];
/**
* The set of supported runtime configurations.
* @OutputOnly
*/
runtimeConfiguration?: AndroidRuntimeConfiguration;
/**
* The set of supported Android OS versions.
* @OutputOnly
*/
versions?: AndroidVersion[];
}
interface AndroidDeviceList {
/**
* A list of Android devices
* Required
*/
androidDevices?: AndroidDevice[];
}
interface AndroidInstrumentationTest {
/**
* The APK for the application under test.
* Required
*/
appApk?: FileReference;
/**
* The java package for the application under test.
* Optional, default is determined by examining the application's manifest.
*/
appPackageId?: string;
/**
* The option of whether running each test within its own invocation of
* instrumentation with Android Test Orchestrator or not.
* ** Orchestrator is only compatible with AndroidJUnitRunner version 1.0 or
* higher! **
* Orchestrator offers the following benefits:
* - No shared state
* - Crashes are isolated
* - Logs are scoped per test
*
* See
* <https://developer.android.com/training/testing/junit-runner.html#using-android-test-orchestrator>
* for more information about Android Test Orchestrator.
*
* Optional, if empty, test will be run without orchestrator.
*/
orchestratorOption?: string;
/**
* The APK containing the test code to be executed.
* Required
*/
testApk?: FileReference;
/**
* The java package for the test to be executed.
* Optional, default is determined by examining the application's manifest.
*/
testPackageId?: string;
/**
* The InstrumentationTestRunner class.
* Optional, default is determined by examining the application's manifest.
*/
testRunnerClass?: string;
/**
* Each target must be fully qualified with the package name or class name,
* in one of these formats:
* - "package package_name"
* - "class package_name.class_name"
* - "class package_name.class_name#method_name"
*
* Optional, if empty, all targets in the module will be run.
*/
testTargets?: string[];
}
interface AndroidMatrix {
/**
* The ids of the set of Android device to be used.
* Use the EnvironmentDiscoveryService to get supported options.
* Required
*/
androidModelIds?: string[];
/**
* The ids of the set of Android OS version to be used.
* Use the EnvironmentDiscoveryService to get supported options.
* Required
*/
androidVersionIds?: string[];
/**
* The set of locales the test device will enable for testing.
* Use the EnvironmentDiscoveryService to get supported options.
* Required
*/
locales?: string[];
/**
* The set of orientations to test with.
* Use the EnvironmentDiscoveryService to get supported options.
* Required
*/
orientations?: string[];
}
interface AndroidModel {
/**
* The company that this device is branded with.
* Example: "Google", "Samsung"
* @OutputOnly
*/
brand?: string;
/**
* The name of the industrial design.
* This corresponds to android.os.Build.DEVICE
* @OutputOnly
*/
codename?: string;
/**
* Whether this device is virtual or physical.
* @OutputOnly
*/
form?: string;
/**
* The unique opaque id for this model.
* Use this for invoking the TestExecutionService.
* @OutputOnly
*/
id?: string;
/**
* The manufacturer of this device.
* @OutputOnly
*/
manufacturer?: string;
/**
* The human-readable marketing name for this device model.
* Examples: "Nexus 5", "Galaxy S5"
* @OutputOnly
*/
name?: string;
/**
* Screen density in DPI.
* This corresponds to ro.sf.lcd_density
* @OutputOnly
*/
screenDensity?: number;
/**
* Screen size in the horizontal (X) dimension measured in pixels.
* @OutputOnly
*/
screenX?: number;
/**
* Screen size in the vertical (Y) dimension measured in pixels.
* @OutputOnly
*/
screenY?: number;
/**
* The list of supported ABIs for this device.
* This corresponds to either android.os.Build.SUPPORTED_ABIS (for API level
* 21 and above) or android.os.Build.CPU_ABI/CPU_ABI2.
* The most preferred ABI is the first element in the list.
*
* Elements are optionally prefixed by "version_id:" (where version_id is
* the id of an AndroidVersion), denoting an ABI that is supported only on
* a particular version.
* @OutputOnly
*/
supportedAbis?: string[];
/**
* The set of Android versions this device supports.
* @OutputOnly
*/
supportedVersionIds?: string[];
/**
* Tags for this dimension.
* Examples: "default", "preview", "deprecated"
*/
tags?: string[];
}
interface AndroidRoboTest {
/**
* The APK for the application under test.
* Required
*/
appApk?: FileReference;
/**
* The initial activity that should be used to start the app.
* Optional
*/
appInitialActivity?: string;
/**
* The java package for the application under test.
* Optional, default is determined by examining the application's manifest.
*/
appPackageId?: string;
/**
* The max depth of the traversal stack Robo can explore. Needs to be at least
* 2 to make Robo explore the app beyond the first activity.
* Default is 50.
* Optional
*/
maxDepth?: number;
/**
* The max number of steps Robo can execute.
* Default is no limit.
* Optional
*/
maxSteps?: number;
/**
* A set of directives Robo should apply during the crawl.
* This allows users to customize the crawl. For example, the username and
* password for a test account can be provided.
* Optional
*/
roboDirectives?: RoboDirective[];
}
interface AndroidRuntimeConfiguration {
/**
* The set of available locales.
* @OutputOnly
*/
locales?: Locale[];
/**
* The set of available orientations.
* @OutputOnly
*/
orientations?: Orientation[];
}
interface AndroidTestLoop {
/**
* The APK for the application under test.
* Required
*/
appApk?: FileReference;
/**
* The java package for the application under test.
* Optional, default is determined by examining the application's manifest.
*/
appPackageId?: string;
/**
* The list of scenario labels that should be run during the test.
* The scenario labels should map to labels defined in the application's
* manifest. For example, player_experience and
* com.google.test.loops.player_experience add all of the loops labeled in the
* manifest with the com.google.test.loops.player_experience name to the
* execution.
* Optional. Scenarios can also be specified in the scenarios field.
*/
scenarioLabels?: string[];
/**
* The list of scenarios that should be run during the test.
* Optional, default is all test loops, derived from the application's
* manifest.
*/
scenarios?: number[];
}
interface AndroidVersion {
/**
* The API level for this Android version.
* Examples: 18, 19
* @OutputOnly
*/
apiLevel?: number;
/**
* The code name for this Android version.
* Examples: "JellyBean", "KitKat"
* @OutputOnly
*/
codeName?: string;
/**
* Market share for this version.
* @OutputOnly
*/
distribution?: Distribution;
/**
* An opaque id for this Android version.
* Use this id to invoke the TestExecutionService.
* @OutputOnly
*/
id?: string;
/**
* The date this Android version became available in the market.
* @OutputOnly
*/
releaseDate?: Date;
/**
* Tags for this dimension.
* Examples: "default", "preview", "deprecated"
*/
tags?: string[];
/**
* A string representing this version of the Android OS.
* Examples: "4.3", "4.4"
* @OutputOnly
*/
versionString?: string;
}
interface CancelTestMatrixResponse {
/**
* The current rolled-up state of the test matrix.
* If this state is already final, then the cancelation request will
* have no effect.
*/
testState?: string;
}
interface ClientInfo {
/** The list of detailed information about client. */
clientInfoDetails?: ClientInfoDetail[];
/**
* Client name, such as gcloud.
* Required
*/
name?: string;
}
interface ClientInfoDetail {
/**
* The key of detailed client information.
* Required
*/
key?: string;
/**
* The value of detailed client information.
* Required
*/
value?: string;
}
interface Date {
/**
* Day of month. Must be from 1 to 31 and valid for the year and month, or 0
* if specifying a year/month where the day is not significant.
*/
day?: number;
/** Month of year. Must be from 1 to 12. */
month?: number;
/**
* Year of date. Must be from 1 to 9999, or 0 if specifying a date without
* a year.
*/
year?: number;
}
interface DeviceFile {
/** A reference to an opaque binary blob file */
obbFile?: ObbFile;
}
interface Distribution {
/**
* The estimated fraction (0-1) of the total market with this configuration.
* @OutputOnly
*/
marketShare?: number;
/**
* The time this distribution was measured.
* @OutputOnly
*/
measurementTime?: string;
}
interface Environment {
/** An Android device which must be used with an Android test. */
androidDevice?: AndroidDevice;
}
interface EnvironmentMatrix {
/**
* A list of Android devices; the test will be run only on the specified
* devices.
*/
androidDeviceList?: AndroidDeviceList;
/** A matrix of Android devices. */
androidMatrix?: AndroidMatrix;
}
interface EnvironmentVariable {
/** Key for the environment variable */
key?: string;
/** Value for the environment variable */
value?: string;
}
interface FileReference {
/**
* A path to a file in Google Cloud Storage.
* Example: gs://build-app-1414623860166/app-debug-unaligned.apk
*/
gcsPath?: string;
}
interface GoogleCloudStorage {
/**
* The path to a directory in GCS that will
* eventually contain the results for this test.
* The requesting user must have write access on the bucket in the supplied
* path.
* Required
*/
gcsPath?: string;
}
interface Locale {
/**
* The id for this locale.
* Example: "en_US"
* @OutputOnly
*/
id?: string;
/**
* A human-friendly name for this language/locale.
* Example: "English"
* @OutputOnly
*/
name?: string;
/**
* A human-friendy string representing the region for this locale.
* Example: "United States"
* Not present for every locale.
* @OutputOnly
*/
region?: string;
/**
* Tags for this dimension.
* Examples: "default"
*/
tags?: string[];
}
interface NetworkConfiguration {
/** The emulation rule applying to the download traffic */
downRule?: TrafficRule;
/**
* The unique opaque id for this network traffic configuration
* @OutputOnly
*/
id?: string;
/** The emulation rule applying to the upload traffic */
upRule?: TrafficRule;
}
interface NetworkConfigurationCatalog {
configurations?: NetworkConfiguration[];
}
interface ObbFile {
/**
* Opaque Binary Blob (OBB) file(s) to install on the device
* Required
*/
obb?: FileReference;
/**
* OBB file name which must conform to the format as specified by
* Android
* e.g. [main|patch].0300110.com.example.android.obb
* which will be installed into
* <shared-storage>/Android/obb/<package-name>/
* on the device
* Required
*/
obbFileName?: string;
}
interface Orientation {
/**
* The id for this orientation.
* Example: "portrait"
* @OutputOnly
*/
id?: string;
/**
* A human-friendly name for this orientation.
* Example: "portrait"
* @OutputOnly
*/
name?: string;
/**
* Tags for this dimension.
* Examples: "default"
*/
tags?: string[];
}
interface ResultStorage {
/** Required. */
googleCloudStorage?: GoogleCloudStorage;
/**
* The tool results execution that results are written to.
* @OutputOnly
*/
toolResultsExecution?: ToolResultsExecution;
/**
* The tool results history that contains the tool results execution that
* results are written to.
*
* Optional, if not provided the service will choose an appropriate value.
*/
toolResultsHistory?: ToolResultsHistory;
}
interface RoboDirective {
/**
* The type of action that Robo should perform on the specified element.
* Required.
*/
actionType?: string;
/**
* The text that Robo is directed to set. If left empty, the directive will be
* treated as a CLICK on the element matching the resource_name.
* Optional
*/
inputText?: string;
/**
* The android resource name of the target UI element
* For example,
* in Java: R.string.foo
* in xml: @string/foo
* Only the “foo” part is needed.
* Reference doc:
* https://developer.android.com/guide/topics/resources/accessing-resources.html
* Required
*/
resourceName?: string;
}
interface TestDetails {
/**
* If the TestState is ERROR, then this string will contain human-readable
* details about the error.
* @OutputOnly
*/
errorMessage?: string;
/**
* Human-readable, detailed descriptions of the test's progress.
* For example: "Provisioning a device", "Starting Test".
*
* During the course of execution new data may be appended
* to the end of progress_messages.
* @OutputOnly
*/
progressMessages?: string[];
}
interface TestEnvironmentCatalog {
/** Android devices suitable for running Android Instrumentation Tests. */
androidDeviceCatalog?: AndroidDeviceCatalog;
/** Supported network configurations */
networkConfigurationCatalog?: NetworkConfigurationCatalog;
}
interface TestExecution {
/**
* How the host machine(s) are configured.
* @OutputOnly
*/
environment?: Environment;
/**
* Unique id set by the backend.
* @OutputOnly
*/
id?: string;
/**
* Id of the containing TestMatrix.
* @OutputOnly
*/
matrixId?: string;
/**
* The cloud project that owns the test execution.
* @OutputOnly
*/
projectId?: string;
/**
* Indicates the current progress of the test execution (e.g., FINISHED).
* @OutputOnly
*/
state?: string;
/**
* Additional details about the running test.
* @OutputOnly
*/
testDetails?: TestDetails;
/**
* How to run the test.
* @OutputOnly
*/
testSpecification?: TestSpecification;
/**
* The time this test execution was initially created.
* @OutputOnly
*/
timestamp?: string;
/**
* Where the results for this execution are written.
* @OutputOnly
*/
toolResultsStep?: ToolResultsStep;
}
interface TestMatrix {
/**
* Information about the client which invoked the test.
* Optional
*/
clientInfo?: ClientInfo;
/**
* How the host machine(s) are configured.
* Required
*/
environmentMatrix?: EnvironmentMatrix;
/**
* Describes why the matrix is considered invalid.
* Only useful for matrices in the INVALID state.
* @OutputOnly
*/
invalidMatrixDetails?: string;
/**
* The cloud project that owns the test matrix.
* @OutputOnly
*/
projectId?: string;
/**
* Where the results for the matrix are written.
* Required
*/
resultStorage?: ResultStorage;
/**
* Indicates the current progress of the test matrix (e.g., FINISHED)
* @OutputOnly
*/
state?: string;
/**
* The list of test executions that the service creates for this matrix.
* @OutputOnly
*/
testExecutions?: TestExecution[];
/**
* Unique id set by the service.
* @OutputOnly
*/
testMatrixId?: string;
/**
* How to run the test.
* Required
*/
testSpecification?: TestSpecification;
/**
* The time this test matrix was initially created.
* @OutputOnly
*/
timestamp?: string;
}
interface TestSetup {
/**
* The device will be logged in on this account for the duration of the test.
* Optional
*/
account?: Account;
/**
* The directories on the device to upload to GCS at the end of the test;
* they must be absolute, whitelisted paths.
* Refer to RegularFile for whitelisted paths.
* Optional
*/
directoriesToPull?: string[];
/**
* Environment variables to set for the test (only applicable for
* instrumentation tests).
*/
environmentVariables?: EnvironmentVariable[];
/** Optional */
filesToPush?: DeviceFile[];
/**
* The network traffic profile used for running the test.
* Optional
*/
networkProfile?: string;
}
interface TestSpecification {
/** An Android instrumentation test. */
androidInstrumentationTest?: AndroidInstrumentationTest;
/** An Android robo test. */
androidRoboTest?: AndroidRoboTest;
/** An Android Application with a Test Loop */
androidTestLoop?: AndroidTestLoop;
/**
* Enables automatic Google account login.
* If set, the service will automatically generate a Google test account and
* add it to the device, before executing the test. Note that test accounts
* might be reused.
* Many applications show their full set of functionalities when an account is
* present on the device. Logging into the device with these generated
* accounts allows testing more functionalities.
* Default is false.
* Optional
*/
autoGoogleLogin?: boolean;
/** Disables performance metrics recording; may reduce test latency. */
disablePerformanceMetrics?: boolean;
/** Disables video recording; may reduce test latency. */
disableVideoRecording?: boolean;
/**
* Test setup requirements e.g. files to install, bootstrap scripts
* Optional
*/
testSetup?: TestSetup;
/**
* Max time a test execution is allowed to run before it is
* automatically cancelled.
* Optional, default is 5 min.
*/
testTimeout?: string;
}
interface ToolResultsExecution {
/**
* A tool results execution ID.
* @OutputOnly
*/
executionId?: string;
/**
* A tool results history ID.
* @OutputOnly
*/
historyId?: string;
/**
* The cloud project that owns the tool results execution.
* @OutputOnly
*/
projectId?: string;
}
interface ToolResultsHistory {
/**
* A tool results history ID.
* Required
*/
historyId?: string;
/**
* The cloud project that owns the tool results history.
* Required
*/
projectId?: string;
}
interface ToolResultsStep {
/**
* A tool results execution ID.
* @OutputOnly
*/
executionId?: string;
/**
* A tool results history ID.
* @OutputOnly
*/
historyId?: string;
/**
* The cloud project that owns the tool results step.
* @OutputOnly
*/
projectId?: string;
/**
* A tool results step ID.
* @OutputOnly
*/
stepId?: string;
}
interface TrafficRule {
/** Bandwidth in kbits/second */
bandwidth?: number;
/** Burst size in kbits */
burst?: number;
/** Packet delay, must be >= 0 */
delay?: string;
/** Packet duplication ratio (0.0 - 1.0) */
packetDuplicationRatio?: number;
/** Packet loss ratio (0.0 - 1.0) */
packetLossRatio?: number;
}
interface TestMatricesResource {
/**
* Cancels unfinished test executions in a test matrix.
* This call returns immediately and cancellation proceeds asychronously.
* If the matrix is already final, this operation will have no effect.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to read project
* - INVALID_ARGUMENT - if the request is malformed
* - NOT_FOUND - if the Test Matrix does not exist
*/
cancel(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Cloud project that owns the test. */
projectId: string;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Test matrix that will be canceled. */
testMatrixId: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<CancelTestMatrixResponse>;
/**
* Request to run a matrix of tests according to the given specifications.
* Unsupported environments will be returned in the state UNSUPPORTED.
* Matrices are limited to at most 200 supported executions.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to write to project
* - INVALID_ARGUMENT - if the request is malformed or if the matrix expands
* to more than 200 supported executions
*/
create(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** The GCE project under which this job will run. */
projectId: string;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/**
* A string id used to detect duplicated requests.
* Ids are automatically scoped to a project, so
* users should ensure the ID is unique per-project.
* A UUID is recommended.
*
* Optional, but strongly recommended.
*/
requestId?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<TestMatrix>;
/**
* Check the status of a test matrix.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to read project
* - INVALID_ARGUMENT - if the request is malformed
* - NOT_FOUND - if the Test Matrix does not exist
*/
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Cloud project that owns the test matrix. */
projectId: string;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Unique test matrix id which was assigned by the service. */
testMatrixId: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<TestMatrix>;
}
interface ProjectsResource {
testMatrices: TestMatricesResource;
}
interface TestEnvironmentCatalogResource {
/**
* Get the catalog of supported test environments.
*
* May return any of the following canonical error codes:
*
* - INVALID_ARGUMENT - if the request is malformed
* - NOT_FOUND - if the environment type does not exist
* - INTERNAL - if an internal error occurred
*/
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/**
* The type of environment that should be listed.
* Required
*/
environmentType: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* For authorization, the cloud project requesting the TestEnvironmentCatalog.
* Optional
*/
projectId?: string;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<TestEnvironmentCatalog>;
}
}
} | the_stack |
interface JQuery {
dropdown: SemanticUI.Dropdown;
}
declare namespace SemanticUI {
// TODO: Should 'value'/'values' parameters be of type 'string' instead of 'any'?
interface Dropdown {
settings: DropdownSettings;
/**
* Recreates dropdown menu from select option values.
*/
(behavior: 'setup menu'): JQuery;
/**
* Refreshes all cached selectors and data
*/
(behavior: 'refresh'): JQuery;
/**
* Toggles current visibility of dropdown
*/
(behavior: 'toggle'): JQuery;
/**
* Shows dropdown
*/
(behavior: 'show'): JQuery;
/**
* Hides dropdown
*/
(behavior: 'hide'): JQuery;
/**
* Clears dropdown of selection
*/
(behavior: 'clear'): JQuery;
/**
* Hides all other dropdowns that is not current dropdown
*/
(behavior: 'hide others'): JQuery;
/**
* Restores dropdown text and value to its value on page load
*/
(behavior: 'restore defaults'): JQuery;
/**
* Restores dropdown text to its value on page load
*/
(behavior: 'restore default text'): JQuery;
/**
* Restores dropdown text to its prompt, placeholder text
*/
(behavior: 'restore placeholder text'): JQuery;
/**
* Restores dropdown value to its value on page load
*/
(behavior: 'restore default value'): JQuery;
/**
* Saves current text and value as new defaults (for use with restore)
*/
(behavior: 'save defaults'): JQuery;
/**
* Sets value as selected
*/
(behavior: 'set selected', value: any): JQuery;
/**
* Remove value from selected
*/
(behavior: 'remove selected', value: any): JQuery;
/**
* Adds a group of values as selected
*/
(behavior: 'set selected', values: any[]): JQuery;
/**
* Sets selected values to exactly specified values, removing current selection
*/
(behavior: 'set exactly', values: any[]): JQuery;
/**
* Sets dropdown text to a value
*/
(behavior: 'set text', text: string): JQuery;
/**
* Sets dropdown input to value (does not update display state)
*/
(behavior: 'set value', value: any): JQuery;
/**
* Returns current dropdown text
*/
(behavior: 'get text'): string;
/**
* Returns current dropdown input value
*/
(behavior: 'get value'): any;
/**
* Returns DOM element that matches a given input value
*/
(behavior: 'get item', value: any): JQuery;
/**
* Adds touch events to element
*/
(behavior: 'bind touch events'): JQuery;
/**
* Adds mouse events to element
*/
(behavior: 'bind mouse events'): JQuery;
/**
* Binds a click to document to determine if you click away from a dropdown
*/
(behavior: 'bind intent'): JQuery;
/**
* Unbinds document intent click
*/
(behavior: 'unbind intent'): JQuery;
/**
* Returns whether event occurred inside dropdown
*/
(behavior: 'determine intent'): boolean;
/**
* Triggers preset item selection action based on settings passing text/value
*/
(behavior: 'determine select action', text: string, value: any): JQuery;
/**
* Sets dropdown to active state
*/
(behavior: 'set active'): JQuery;
/**
* Sets dropdown to visible state
*/
(behavior: 'set visible'): JQuery;
/**
* Removes dropdown active state
*/
(behavior: 'remove active'): JQuery;
/**
* Removes dropdown visible state
*/
(behavior: 'remove visible'): JQuery;
/**
* Returns whether dropdown is a selection dropdown
*/
(behavior: 'is selection'): boolean;
/**
* Returns whether dropdown is animated
*/
(behavior: 'is animated'): boolean;
/**
* Returns whether dropdown is visible
*/
(behavior: 'is visible'): boolean;
/**
* Returns whether dropdown is hidden
*/
(behavior: 'is hidden'): boolean;
/**
* Returns dropdown value as set on page load
*/
(behavior: 'get default text'): string;
/**
* Returns placeholder text
*/
(behavior: 'get placeholder text'): string;
(behavior: 'destroy'): JQuery;
<K extends keyof DropdownSettings>(behavior: 'setting', name: K, value?: undefined): DropdownSettings._Impl[K];
<K extends keyof DropdownSettings>(behavior: 'setting', name: K, value: DropdownSettings._Impl[K]): JQuery;
(behavior: 'setting', value: DropdownSettings): JQuery;
(settings?: DropdownSettings): JQuery;
}
/**
* @see {@link http://semantic-ui.com/modules/dropdown.html#/settings}
*/
type DropdownSettings = DropdownSettings.Param;
namespace DropdownSettings {
type Param = (Pick<_Impl, 'on'> |
Pick<_Impl, 'values'> |
Pick<_Impl, 'allowReselection'> |
Pick<_Impl, 'allowAdditions'> |
Pick<_Impl, 'hideAdditions'> |
Pick<_Impl, 'action'> |
Pick<_Impl, 'minCharacters'> |
Pick<_Impl, 'match'> |
Pick<_Impl, 'selectOnKeydown'> |
Pick<_Impl, 'forceSelection'> |
Pick<_Impl, 'allowCategorySelection'> |
Pick<_Impl, 'placeholder'> |
Pick<_Impl, 'apiSettings'> |
Pick<_Impl, 'fields'> |
Pick<_Impl, 'saveRemoteData'> |
Pick<_Impl, 'filterRemoteData'> |
Pick<_Impl, 'useLabels'> |
Pick<_Impl, 'maxSelections'> |
Pick<_Impl, 'glyphWidth'> |
Pick<_Impl, 'label'> |
Pick<_Impl, 'direction'> |
Pick<_Impl, 'keepOnScreen'> |
Pick<_Impl, 'context'> |
Pick<_Impl, 'fullTextSearch'> |
Pick<_Impl, 'preserveHTML'> |
Pick<_Impl, 'sortSelect'> |
Pick<_Impl, 'showOnFocus'> |
Pick<_Impl, 'allowTab'> |
Pick<_Impl, 'transition'> |
Pick<_Impl, 'duration'> |
Pick<_Impl, 'keys'> |
Pick<_Impl, 'delay'> |
Pick<_Impl, 'onChange'> |
Pick<_Impl, 'onAdd'> |
Pick<_Impl, 'onRemove'> |
Pick<_Impl, 'onLabelCreate'> |
Pick<_Impl, 'onLabelRemove'> |
Pick<_Impl, 'onLabelSelect'> |
Pick<_Impl, 'onNoResults'> |
Pick<_Impl, 'onShow'> |
Pick<_Impl, 'onHide'> |
Pick<_Impl, 'message'> |
Pick<_Impl, 'selector'> |
Pick<_Impl, 'regExp'> |
Pick<_Impl, 'metadata'> |
Pick<_Impl, 'className'> |
Pick<_Impl, 'error'> |
Pick<_Impl, 'namespace'> |
Pick<_Impl, 'name'> |
Pick<_Impl, 'silent'> |
Pick<_Impl, 'debug'> |
Pick<_Impl, 'performance'> |
Pick<_Impl, 'verbose'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
// region Frequently Used Settings
/**
* Event used to trigger dropdown (Hover, Click, Custom Event)
*
* @default 'click'
*/
on: string;
/**
* When specified allows you to initialize dropdown with specific values. See usage guide for details.
*
* @default false
*/
values: any;
/**
* When set to true will fire onChange even when the value a user select matches the currently selected value.
*
* @default false
*/
allowReselection: boolean;
/**
* Whether search selection should allow users to add their own selections, works for single or multi-select.
*
* @default false
*/
allowAdditions: boolean;
/**
* When disabled user additions will appear in the results menu using a specially formatted selection item formatted by templates.addition.
*
* @default true
*/
hideAdditions: boolean;
/**
* Sets a default action to occur. (See usage guide)
*
* @default 'activate'
* @see {@link http://semantic-ui.com/modules/dropdown.html#/usage}
*/
action: 'activate' | 'select' | 'combo' | 'nothing' | 'hide' | ((this: JQuery, text: string, value: string | false, element: JQuery) => void);
/**
* The minimum characters for a search to begin showing results
*
* @default 1
*/
minCharacters: number;
/**
* When using search selection specifies how to match values.
*
* @default 'both'
*/
match: 'both' | 'value' | 'text';
/**
* Whether dropdown should select new option when using keyboard shortcuts. Setting to false will require enter or left click to confirm a choice.
*
* @default true
*/
selectOnKeydown: boolean;
/**
* Whether search selection will force currently selected choice when element is blurred.
*
* @default true
*/
forceSelection: boolean;
/**
* Whether menu items with sub-menus (categories) should be selectable
*
* @default false
*/
allowCategorySelection: boolean;
/**
* @default 'auto'
*/
placeholder: 'auto' | 'value' | false;
// endregion
// region Remote Settings
/**
* Can be set to an object to specify API settings for retrieving remote selection menu content from an API endpoint
*
* @default false
* @see {@link http://semantic-ui.com/behaviors/api.html}
*/
apiSettings: false | ApiSettings;
/**
* List mapping dropdown content to JSON Property when using API
*/
fields: Dropdown.FieldsSettings;
/**
* When enabled will automatically store selected name/value pairs in sessionStorage to preserve user selection on page refresh. Disabling will clear remote dropdown values on refresh.
*
* @default true
*/
saveRemoteData: boolean;
/**
* When set to true API will be expected to return the complete result set, which will then be filtered clientside to only display matching results.
*
* @default false
* @since 2.2.8
*/
filterRemoteData: boolean;
// endregion
// region Multiple Select Settings
/**
* Whether multiselect should use labels. Must be set to true when allowAdditions is true
*
* @default true
*/
useLabels: boolean;
/**
* When set to a number, sets the maximum number of selections
*
* @default false
*/
maxSelections: false | number;
/**
* Maximum glyph width, used to calculate search size. This is usually size of a "W" in your font in em
*
* @default 1.0714
*/
glyphWidth: number;
/**
* Allows customization of multi-select labels
*/
label: Dropdown.LabelSettings;
// endregion
// region Additional Settings
/**
* When set to auto determines direction based on whether dropdown can fit on screen. Set to upward or downward to always force a direction.
*
* @default 'auto'
*/
direction: 'auto' | 'upward' | 'downward';
/**
* Whether dropdown should try to keep itself on screen by checking whether menus display position in its context (Default context is page).
*
* @default true
*/
keepOnScreen: boolean;
/**
* Element context to use when checking whether can show when keepOnScreen: true
*
* @default 'window'
*/
context: string | JQuery;
/**
* Specifying to "true" will use a fuzzy full text search, setting to "exact" will force the exact search to be matched somewhere in the string
*
* @default false
*/
fullTextSearch: boolean | 'exact';
/**
* Whether HTML included in dropdown values should be preserved. (Allows icons to show up in selected value)
*
* @default true
*/
preserveHTML: boolean;
/**
* Whether to sort values when creating a dropdown automatically from a select element.
*
* @default false
*/
sortSelect: boolean;
/**
* Whether to show dropdown menu automatically on element focus.
*
* @default true
*/
showOnFocus: boolean;
/**
* Whether to allow the element to be navigable by keyboard, by automatically creating a tabindex
*
* @default true
*/
allowTab: boolean;
/**
* Named transition to use when animating menu in and out.
* Defaults to slide down or slide up depending on dropdown direction.
* Fade and slide down are available without including ui transitions
*
* @default 'auto'
* @see {@link http://semantic-ui.com/modules/transition.html}
*/
transition: 'auto' | string;
/**
* Duration of animation events
*
* @default 200
*/
duration: number;
/**
* The keycode used to represent keyboard shortcuts. To avoid issues with some foreign languages, you can pass false for comma delimiter's value
*/
keys: Dropdown.KeySettings;
/**
* Time in milliseconds to debounce show or hide behavior when on: hover is used, or when touch is used.
*/
delay: Dropdown.DelaySettings;
// endregion
// region Callbacks
/**
* Is called after a dropdown value changes. Receives the name and value of selection and the active menu element
*/
onChange(this: JQuery, value: any, text: string, $choice: JQuery): void;
/**
* Is called after a dropdown selection is added using a multiple select dropdown, only receives the added value
*/
onAdd(this: JQuery, addedValue: any, addedText: string, $addedChoice: JQuery): void;
/**
* Is called after a dropdown selection is removed using a multiple select dropdown, only receives the removed value
*/
onRemove(this: JQuery, removedValue: any, removedText: string, $removedChoice: JQuery): void;
/**
* Allows you to modify a label before it is added. Expects the jQ DOM element for a label to be returned.
*/
onLabelCreate(this: JQuery, value: any, text: string): JQuery;
/**
* Called when a label is remove, return false; will prevent the label from being removed.
*/
onLabelRemove(this: JQuery, value: any): false | void;
/**
* Is called after a label is selected by a user
*/
onLabelSelect(this: JQuery, $selectedLabels: JQuery): void;
/**
* Is called after a dropdown is searched with no matching values
*/
onNoResults(this: JQuery, searchValue: any): void;
/**
* Is called before a dropdown is shown. If false is returned, dropdown will not be shown.
*/
onShow(this: JQuery): false | void;
/**
* Is called before a dropdown is hidden. If false is returned, dropdown will not be hidden.
*/
onHide(this: JQuery): false | void;
// endregion
// region DOM Settings
/**
* You can specify site wide messages by modifying $.fn.dropdown.settings.message that will apply on any dropdown if it appears in the page.
*/
message: Dropdown.MessageSettings;
selector: Dropdown.SelectorSettings;
regExp: Dropdown.RegExpSettings;
metadata: Dropdown.MetadataSettings;
className: Dropdown.ClassNameSettings;
// endregion
// region Debug Settings
error: Dropdown.ErrorSettings;
// endregion
// region Component Settings
// region DOM Settings
/**
* Event namespace. Makes sure module teardown does not effect other events attached to an element.
*/
namespace: string;
// endregion
// region Debug Settings
/**
* Name used in log statements
*/
name: string;
/**
* Silences all console output including error messages, regardless of other debug settings.
*/
silent: boolean;
/**
* Debug output to console
*/
debug: boolean;
/**
* Show console.table output with performance metrics
*/
performance: boolean;
/**
* Debug output includes all internal behaviors
*/
verbose: boolean;
// endregion
// endregion
}
}
namespace Dropdown {
type FieldsSettings = FieldsSettings.Param;
namespace FieldsSettings {
type Param = (Pick<_Impl, 'remoteValues'> |
Pick<_Impl, 'values'> |
Pick<_Impl, 'name'> |
Pick<_Impl, 'value'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* grouping for api results
*
* @default 'results'
*/
remoteValues: string;
/**
* grouping for all dropdown values
*
* @default 'values'
*/
values: string;
/**
* displayed dropdown text
*
* @default 'name'
*/
name: string;
/**
* actual dropdown value
*
* @default 'value'
*/
value: string;
}
}
type LabelSettings = LabelSettings.Param;
namespace LabelSettings {
type Param = (Pick<_Impl, 'transition'> |
Pick<_Impl, 'duration'> |
Pick<_Impl, 'variation'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default 'horizontal flip'
*/
transition: string;
/**
* @default 200
*/
duration: number;
/**
* @default false
*/
variation: false | string;
}
}
type KeySettings = KeySettings.Param;
namespace KeySettings {
type Param = (Pick<_Impl, 'backspace'> |
Pick<_Impl, 'delimiter'> |
Pick<_Impl, 'deleteKey'> |
Pick<_Impl, 'enter'> |
Pick<_Impl, 'escape'> |
Pick<_Impl, 'pageUp'> |
Pick<_Impl, 'pageDown'> |
Pick<_Impl, 'leftArrow'> |
Pick<_Impl, 'upArrow'> |
Pick<_Impl, 'rightArrow'> |
Pick<_Impl, 'downArrow'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default 8
*/
backspace: number;
/**
* @default 188
*/
delimiter: number | false;
/**
* @default 46
*/
deleteKey: number;
/**
* @default 13
*/
enter: number;
/**
* @default 27
*/
escape: number;
/**
* @default 33
*/
pageUp: number;
/**
* @default 34
*/
pageDown: number;
/**
* @default 37
*/
leftArrow: number;
/**
* @default 38
*/
upArrow: number;
/**
* @default 39
*/
rightArrow: number;
/**
* @default 40
*/
downArrow: number;
}
}
type DelaySettings = DelaySettings.Param;
namespace DelaySettings {
type Param = (Pick<_Impl, 'hide'> |
Pick<_Impl, 'show'> |
Pick<_Impl, 'search'> |
Pick<_Impl, 'touch'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default 300
*/
hide: number;
/**
* @default 200
*/
show: number;
/**
* @default 50
*/
search: number;
/**
* @default 50
*/
touch: number;
}
}
type MessageSettings = MessageSettings.Param;
namespace MessageSettings {
type Param = (Pick<_Impl, 'addResult'> |
Pick<_Impl, 'count'> |
Pick<_Impl, 'maxSelections'> |
Pick<_Impl, 'noResults'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default 'Add <b>{term}</b>'
*/
addResult: string;
/**
* @default '{count} selected'
*/
count: string;
/**
* @default 'Max {maxCount} selections'
*/
maxSelections: string;
/**
* 'No results found.'
*/
noResults: string;
}
}
type SelectorSettings = SelectorSettings.Param;
namespace SelectorSettings {
type Param = (Pick<_Impl, 'addition'> |
Pick<_Impl, 'dropdown'> |
Pick<_Impl, 'icon'> |
Pick<_Impl, 'input'> |
Pick<_Impl, 'item'> |
Pick<_Impl, 'label'> |
Pick<_Impl, 'remove'> |
Pick<_Impl, 'siblingLabel'> |
Pick<_Impl, 'menu'> |
Pick<_Impl, 'message'> |
Pick<_Impl, 'menuIcon'> |
Pick<_Impl, 'search'> |
Pick<_Impl, 'text'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default '.addition'
*/
addition: string;
/**
* @default '.ui.dropdown'
*/
dropdown: string;
/**
* @default '> .dropdown.icon'
*/
icon: string;
/**
* @default '> input[type="hidden"], > select'
*/
input: string;
/**
* @default '.item'
*/
item: string;
/**
* @default '> .label'
*/
label: string;
/**
* @default '> .label > .delete.icon'
*/
remove: string;
/**
* @default '.label'
*/
siblingLabel: string;
/**
* @default '.menu'
*/
menu: string;
/**
* @default '.message'
*/
message: string;
/**
* @default '.dropdown.icon'
*/
menuIcon: string;
/**
* @default 'input.search, .menu > .search > input'
*/
search: string;
/**
* @default '> .text:not(.icon)'
*/
text: string;
}
}
type RegExpSettings = RegExpSettings.Param;
namespace RegExpSettings {
type Param = (Pick<_Impl, 'escape'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default /[-[\]{}()*+?.,\\^$|#\s]/g
*/
escape: RegExp;
}
}
type MetadataSettings = MetadataSettings.Param;
namespace MetadataSettings {
type Param = (Pick<_Impl, 'defaultText'> |
Pick<_Impl, 'defaultValue'> |
Pick<_Impl, 'placeholderText'> |
Pick<_Impl, 'text'> |
Pick<_Impl, 'value'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default 'defaultText'
*/
defaultText: string;
/**
* @default 'defaultValue'
*/
defaultValue: string;
/**
* @default 'placeholderText'
*/
placeholderText: string;
/**
* @default 'text'
*/
text: string;
/**
* @default 'value'
*/
value: string;
}
}
type ClassNameSettings = ClassNameSettings.Param;
namespace ClassNameSettings {
type Param = (Pick<_Impl, 'active'> |
Pick<_Impl, 'addition'> |
Pick<_Impl, 'animating'> |
Pick<_Impl, 'disabled'> |
Pick<_Impl, 'dropdown'> |
Pick<_Impl, 'filtered'> |
Pick<_Impl, 'hidden'> |
Pick<_Impl, 'item'> |
Pick<_Impl, 'label'> |
Pick<_Impl, 'loading'> |
Pick<_Impl, 'menu'> |
Pick<_Impl, 'message'> |
Pick<_Impl, 'multiple'> |
Pick<_Impl, 'placeholder'> |
Pick<_Impl, 'search'> |
Pick<_Impl, 'selected'> |
Pick<_Impl, 'selection'> |
Pick<_Impl, 'upward'> |
Pick<_Impl, 'visible'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default 'active'
*/
active: string;
/**
* @default 'addition'
*/
addition: string;
/**
* @default 'animating'
*/
animating: string;
/**
* @default 'disabled'
*/
disabled: string;
/**
* @default 'ui dropdown'
*/
dropdown: string;
/**
* @default 'filtered'
*/
filtered: string;
/**
* @default 'hidden transition'
*/
hidden: string;
/**
* @default 'item'
*/
item: string;
/**
* @default 'ui label'
*/
label: string;
/**
* @default 'loading'
*/
loading: string;
/**
* @default 'menu'
*/
menu: string;
/**
* @default 'message'
*/
message: string;
/**
* @default 'multiple'
*/
multiple: string;
/**
* @default 'default'
*/
placeholder: string;
/**
* @default 'search'
*/
search: string;
/**
* @default 'selected'
*/
selected: string;
/**
* @default 'selection'
*/
selection: string;
/**
* @default 'upward'
*/
upward: string;
/**
* @default 'visible'
*/
visible: string;
}
}
type ErrorSettings = ErrorSettings.Param;
namespace ErrorSettings {
type Param = (Pick<_Impl, 'action'> |
Pick<_Impl, 'alreadySetup'> |
Pick<_Impl, 'labels'> |
Pick<_Impl, 'method'> |
Pick<_Impl, 'noTransition'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default 'You called a dropdown action that was not defined'
*/
action: string;
/**
* @default 'Once a select has been initialized behaviors must be called on the created ui dropdown'
*/
alreadySetup: string;
/**
* @default 'Allowing user additions currently requires the use of labels.'
*/
labels: string;
/**
* @default 'The method you called is not defined.'
*/
method: string;
/**
* @default 'This module requires ui transitions <https: github.com="" semantic-org="" ui-transition="">'
*/
noTransition: string;
}
}
}
} | the_stack |
import { Component, Input, Output, EventEmitter, OnDestroy, AfterViewInit } from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import { AssetTilesService } from '../../core/services/asset-tiles.service';
import { AssetGroupObservableService } from '../../core/services/asset-group-observable.service';
import { UpdateRecentAGService } from './../common/services/update-recent-ag.service';
import { Subscription } from 'rxjs/Subscription';
import { AutorefreshService } from '../../pacman-features/services/autorefresh.service';
import { environment } from './../../../environments/environment';
import { ErrorHandlingService } from '../../shared/services/error-handling.service';
import { DataCacheService } from '../../core/services/data-cache.service';
import { LoggerService } from '../../shared/services/logger.service';
import { UtilsService } from '../../shared/services/utils.service';
@Component({
selector: 'app-asset-groups',
templateUrl: './asset-groups.component.html',
styleUrls: ['./asset-groups.component.css'],
providers: [AssetTilesService, AutorefreshService, LoggerService, ErrorHandlingService, UpdateRecentAGService]
})
export class AssetGroupsComponent implements AfterViewInit, OnDestroy {
constructor(private router: Router,
private dataStore: DataCacheService,
private assetGroupsService: AssetTilesService,
private assetGroupObservableService: AssetGroupObservableService,
private updateRecentAGService: UpdateRecentAGService,
private activatedRoute: ActivatedRoute,
private errorHandlingService: ErrorHandlingService,
private logger: LoggerService,
private utils: UtilsService) {
this.subscriptionToAssetGroup = this.assetGroupObservableService.getAssetGroup().subscribe(
assetGroupName => {
this.thisAssetTile = assetGroupName;
this.selectedGroup = assetGroupName;
this.assetTileClicked(this.thisAssetTile);
});
}
@Input() clickedVal = false;
@Input() hideCloseButton;
@Input() notLoadedAsModel;
@Output() closeAssetGroup = new EventEmitter();
assetTabName: any;
selectedTab = 0;
selectedTabName;
returnedSearch = '';
assetTiles;
loaded: boolean;
thisAssetTile: string;
selectedGroup: string;
assetDetailTiles: any;
recentTiles: any = [];
userDetails: any;
assetGroup: any = {};
showError = false;
assetDetailsState = 0;
private subscriptionToAssetGroup: Subscription;
private assetDetailsSubscription: Subscription;
private assetTilesSubscription: Subscription;
private updateRecentAGSubscription: Subscription;
ngAfterViewInit() {
try {
if (this.subscriptionToAssetGroup) {
this.subscriptionToAssetGroup.unsubscribe();
}
this.loaded = false;
this.retrieveFragment();
this.getAssetTiles();
} catch (error) {
this.errorHandlingService.handleJavascriptError(error);
this.logger.log('error', error);
}
}
retrieveFragment() {
this.activatedRoute.fragment.subscribe((fragment: string) => {
this.selectedTabName = fragment;
});
}
getSearch(search) {
this.returnedSearch = search;
}
getAssetTiles(): void {
this.showError = false;
const assetGroupList = this.dataStore.getListOfAssetGroups();
if (!assetGroupList || assetGroupList === 'undefined') {
const assetUrl = environment.assetTiles.url;
const assetMethod = environment.assetTiles.method;
this.assetTilesSubscription = this.assetGroupsService.getAssetTiles(assetUrl, assetMethod).subscribe(
response => {
this.assetTiles = response[0];
this.dataStore.setListOfAssetGroups(JSON.stringify(this.assetTiles));
this.processData();
},
error => {
this.loaded = true;
this.showError = true;
this.logger.log('error', error);
});
} else {
this.assetTiles = JSON.parse(assetGroupList);
this.processData();
}
}
getCurrentAssetInfo(assetInfo) {
}
assetTileClicked(tile) {
this.thisAssetTile = tile;
this.getAssetDetailTiles(tile);
this.updateRecentAssetGroup(tile);
}
setDefault() {
try {
this.instructParentToCloseAssetGroup(this.thisAssetTile);
const userDefaultAssetGroup = this.dataStore.getUserDefaultAssetGroup();
if (this.thisAssetTile !== userDefaultAssetGroup) {
this.updateDefaultAssetGroupForUser(this.thisAssetTile);
}
} catch (error) {
this.errorHandlingService.handleJavascriptError(error);
this.logger.log('error', error);
}
}
selectAsset(assetGroup) {
try {
this.instructParentToCloseAssetGroup(assetGroup.name);
if (assetGroup.name !== this.selectedGroup) {
this.selectedGroup = assetGroup.name;
this.assetTileClicked(assetGroup.name);
}
} catch (error) {
this.errorHandlingService.handleJavascriptError(error);
this.logger.log('error', error);
}
}
updateDefaultAssetGroupForUser(assetGroup) {
try {
const updateAssetGroupUrl = environment.saveDefaultAssetGroup.url;
const updateAssetGroupMethod = environment.saveDefaultAssetGroup.method;
const userId = this.dataStore.getUserDetailsValue().getUserId();
this.assetTilesSubscription = this.assetGroupsService.updateDefaultAssetGroupForUser(updateAssetGroupUrl, updateAssetGroupMethod, assetGroup, userId).subscribe(
response => {
this.dataStore.setUserDefaultAssetGroup(assetGroup);
},
error => {
});
} catch (error) {
this.errorHandlingService.handleJavascriptError(error);
}
}
processData() {
try {
const typeObj = {
'all': 'typeVal',
'recently viewed': 'typeVal'
};
for ( let i = 0 ; i < this.assetTiles.length; i++) {
typeObj[this.assetTiles[i].type.toLowerCase()] = 'typeVal';
}
delete typeObj[''];
let typeArr = [];
typeArr = Object.keys(typeObj);
this.assetTabName = typeArr;
/* Bottom line is not required */
// this.selectedTabName = this.assetTabName[this.selectedTab];
this.loaded = true;
} catch (error) {
this.errorHandlingService.handleJavascriptError(error);
this.logger.log('error', error);
}
}
updateTab(newTab) {
this.selectedTabName = newTab.toLowerCase();
}
getAssetDetailTiles(groupName) {
const assetDetailUrl = environment.assetTilesdata.url;
const assetDetailMethod = environment.assetTilesdata.method;
const queryParams = {
'ag': groupName
};
this.assetDetailsState = 0;
if (queryParams['ag'] !== undefined) {
this.assetDetailsSubscription = this.assetGroupsService.getAssetdetailTiles(queryParams, assetDetailUrl, assetDetailMethod).subscribe(
response => {
this.assetDetailsState = 1;
this.assetDetailTiles = response[0];
},
error => {
this.assetDetailsState = -1;
});
}
}
updateRecentAssetGroup(groupName) {
const updateRecentAGUrl = environment.updateRecentAG.url;
const updateRecentAGMethod = environment.updateRecentAG.method;
const userId = this.dataStore.getUserDetailsValue().getUserId();
const queryParams = {
'ag': groupName,
'userId': userId
};
if (queryParams['ag'] !== undefined) {
this.updateRecentAGSubscription = this.updateRecentAGService.updateRecentlyViewedAG(queryParams, updateRecentAGUrl, updateRecentAGMethod).subscribe(
response => {
this.recentTiles = response.data.response[0].recentlyViewedAg;
},
error => {
});
}
}
instructParentToCloseAssetGroup (assetGroupName) {
this.closeAssetGroup.emit(assetGroupName);
}
checkRecentlyViewed(name) {
if (!name || !this.selectedTabName) {
return false;
}
const tiles = this.recentTiles.map(item => {
return item['ag'];
});
if (this.selectedTabName.toLowerCase() === 'recently viewed') {
if (tiles.includes(name.name.toLowerCase())) {
return true;
} else {
return false;
}
} else {
return false;
}
}
/**
* This function navigates the page mentioned with a ruleID
*/
navigatePage(data1, data2) {
/**
* selectAsset function closes the modal window and update the asset group
* after that router.navigate is used to navigate
*/
try {
const clickText = data1;
const apiTarget = {'TypeAsset' : 'TotalAsset'};
/**
* Router navigation is not working , need to check --> Trinanjan
*/
if (clickText.toLowerCase() === 'total asset' ) {
/**
* This router.navigate function is added By Trinanjan on 31.01.2018
* This router.navigate function first closes the modal window and then navigates to the path specified
*/
const eachParams = {};
let newParams = this.utils.makeFilterObj(eachParams);
newParams = Object.assign(newParams, apiTarget);
newParams['ag'] = data2;
this.router.navigate([{
outlets: {
modal: null
}
}],
{
relativeTo: this.activatedRoute.parent,
queryParamsHandling: 'merge'
}).then(() => this.router.navigate(['pl', 'assets' , 'asset-list' ], {queryParams: newParams, queryParamsHandling: 'merge'}));
}
} catch (error) {
this.logger.log('error', error);
}
}
ngOnDestroy() {
try {
this.subscriptionToAssetGroup.unsubscribe();
} catch (error) {
}
}
} | the_stack |
import type { NodePath } from '@babel/traverse';
import type * as Babel from '@babel/core';
import type { types as t } from '@babel/core';
import State, { owningPackage } from './state';
import dependencySatisfies from './dependency-satisfies';
import moduleExists from './module-exists';
import getConfig from './get-config';
type OpValue = string | boolean | number;
const binops: { [operator: string]: any } = {
'||': function (a: OpValue, b: OpValue) {
return a || b;
},
'&&': function (a: OpValue, b: OpValue) {
return a && b;
},
'|': function (a: any, b: any) {
return a | b;
},
'^': function (a: any, b: any) {
return a ^ b;
},
'&': function (a: any, b: any) {
return a & b;
},
'==': function (a: OpValue, b: OpValue) {
// eslint-disable-next-line eqeqeq
return a == b;
},
'!=': function (a: OpValue, b: OpValue) {
// eslint-disable-next-line eqeqeq
return a != b;
},
'===': function (a: OpValue, b: OpValue) {
return a === b;
},
'!==': function (a: OpValue, b: OpValue) {
return a !== b;
},
'<': function (a: OpValue, b: OpValue) {
return a < b;
},
'>': function (a: OpValue, b: OpValue) {
return a > b;
},
'<=': function (a: OpValue, b: OpValue) {
return a <= b;
},
'>=': function (a: OpValue, b: OpValue) {
return a >= b;
},
'<<': function (a: any, b: any) {
return a << b;
},
'>>': function (a: any, b: any) {
return a >> b;
},
'>>>': function (a: any, b: any) {
return a >>> b;
},
'+': function (a: any, b: any) {
return a + b;
},
'-': function (a: any, b: any) {
return a - b;
},
'*': function (a: any, b: any) {
return a * b;
},
'/': function (a: any, b: any) {
return a / b;
},
'%': function (a: any, b: any) {
return a % b;
},
'??': function (a: any, b: any) {
if (a === null || a === undefined) {
return b;
}
return a;
},
};
const unops: { [operator: string]: any } = {
'-': function (a: OpValue) {
return -a;
},
'+': function (a: OpValue) {
return +a;
},
'~': function (a: OpValue) {
return ~a;
},
'!': function (a: OpValue) {
return !a;
},
void: function () {
return undefined;
},
};
export interface ConfidentResult {
confident: true;
value: any;
}
export interface UnknownResult {
confident: false;
}
export type EvaluateResult = ConfidentResult | UnknownResult;
// this is needed to make our strict types work when inter-operating with
// babel's own built-in evaluator
function isConfidentResult(result: { confident: boolean; value: any }): result is ConfidentResult {
return result.confident;
}
export interface EvaluationEnv {
knownPaths?: Map<NodePath, EvaluateResult>;
locals?: { [localVar: string]: any };
state?: State;
}
export class Evaluator {
private knownPaths: Map<NodePath, EvaluateResult>;
private locals: { [localVar: string]: any };
private state: State | undefined;
constructor(env: EvaluationEnv = {}) {
this.knownPaths = env.knownPaths || new Map();
this.locals = env.locals || {};
this.state = env.state;
}
evaluateMember(
path: NodePath<t.MemberExpression | t.OptionalMemberExpression>,
optionalChain: boolean
): EvaluateResult {
let propertyPath = assertNotArray(path.get('property'));
let property: EvaluateResult;
if (path.node.computed) {
property = this.evaluate(propertyPath);
} else {
property = this.evaluateKey(propertyPath);
}
if (property.confident) {
let objectPath = path.get('object');
let object = this.evaluate(objectPath);
if (object.confident) {
let confidentObject = object;
let confidentProperty = property;
return {
confident: true,
get value() {
if (optionalChain) {
return confidentObject.value != null
? confidentObject.value[confidentProperty.value]
: confidentObject.value;
} else {
return confidentObject.value[confidentProperty.value];
}
},
};
}
}
return { confident: false };
}
evaluateKey(path: NodePath): EvaluateResult {
let first = this.evaluate(path);
if (first.confident) {
return first;
}
if (path.isIdentifier()) {
return { confident: true, value: path.node.name };
}
return { confident: false };
}
evaluate(path: NodePath): EvaluateResult {
let known = this.knownPaths.get(path);
if (known) {
return known;
}
let result = this.realEvaluate(path);
return result;
}
private realEvaluate(path: NodePath): EvaluateResult {
let builtIn = path.evaluate();
if (isConfidentResult(builtIn)) {
return builtIn;
}
if (path.isMemberExpression()) {
return this.evaluateMember(path, false);
}
// Here we are glossing over the lack of a real OptionalMemberExpression type
// in our @babel/traverse typings.
if (path.node.type === 'OptionalMemberExpression') {
return this.evaluateMember(path as NodePath<t.OptionalMemberExpression>, true);
}
if (path.isStringLiteral()) {
return { confident: true, value: path.node.value };
}
if (path.isNumericLiteral()) {
return { confident: true, value: path.node.value };
}
if (path.isBooleanLiteral()) {
return { confident: true, value: path.node.value };
}
if (path.isNullLiteral()) {
return { confident: true, value: null };
}
if (path.isObjectExpression()) {
let props = assertArray(path.get('properties')).map(p => {
let key = assertNotArray(p.get('key'));
let keyEvalValue = this.evaluateKey(key);
let value = assertNotArray(p.get('value'));
let valueEvalValue = this.evaluate(value);
return [keyEvalValue, valueEvalValue];
});
for (let [k, v] of props) {
if (!k.confident || !v.confident) {
return { confident: false };
}
}
let confidentProps = props as ConfidentResult[][];
return {
confident: true,
get value() {
let result: any = {};
for (let [k, v] of confidentProps) {
result[k.value] = v.value;
}
return result;
},
};
}
if (path.isArrayExpression()) {
let elements = path.get('elements').map(element => {
return this.evaluate(element as NodePath);
});
if (elements.every(element => element.confident)) {
let confidentElements = elements as ConfidentResult[];
return {
confident: true,
get value() {
return confidentElements.map(element => element.value);
},
};
}
}
if (path.isAssignmentExpression()) {
let leftPath = path.get('left');
if (leftPath.isIdentifier()) {
let rightPath = path.get('right');
let right = this.evaluate(rightPath);
if (right.confident) {
this.locals[leftPath.node.name] = right.value;
return right;
}
}
}
if (path.isCallExpression()) {
let result = this.maybeEvaluateRuntimeConfig(path);
if (result.confident) {
return result;
}
result = this.evaluateMacroCall(path);
if (result.confident) {
return result;
}
}
if (path.isLogicalExpression() || path.isBinaryExpression()) {
let operator = path.node.operator as string;
if (binops[operator]) {
let leftOperand = this.evaluate(path.get('left') as NodePath<t.Expression>);
if (leftOperand.confident) {
let rightOperand = this.evaluate(path.get('right') as NodePath<t.Expression>);
if (leftOperand.confident && rightOperand.confident) {
let value = binops[operator](leftOperand.value, rightOperand.value);
return { confident: true, value };
}
}
}
return { confident: false };
}
if (path.isConditionalExpression()) {
let test = this.evaluate(path.get('test'));
if (test.confident) {
let result = test.value ? this.evaluate(path.get('consequent')) : this.evaluate(path.get('alternate'));
if (result.confident) {
return result;
}
}
}
if (path.isUnaryExpression()) {
let operator = path.node.operator as string;
if (unops[operator]) {
let operand = this.evaluate(path.get('argument') as NodePath<t.Expression>);
if (operand.confident) {
let value = unops[operator](operand.value);
return { confident: true, value };
}
}
return { confident: false };
}
if (path.isIdentifier()) {
if (!this.locals.hasOwnProperty(path.node.name)) {
return { confident: false };
}
return { confident: true, value: this.locals[path.node.name] };
}
return { confident: false };
}
// This handles the presence of our runtime-mode getConfig functions. We want
// to designate them as { confident: true }, because it's important that we
// give feedback even in runtime-mode if the developer is trying to pass
// non-static arguments somewhere they're not supposed to. But we don't
// actually want to calculate their value here because that has been deferred
// to runtime. That's why we've made `value` lazy. It lets us check the
// confidence without actually forcing the value.
private maybeEvaluateRuntimeConfig(path: NodePath<t.CallExpression>): EvaluateResult {
let callee = path.get('callee');
if (callee.isIdentifier()) {
let { name } = callee.node;
// Does the identifier refer to our runtime config?
if (this.state?.neededRuntimeImports.get(name) === 'config') {
return {
confident: true,
get value() {
throw new Error(`bug in @embroider/macros: didn't expect to need to evaluate this value`);
},
};
}
}
return { confident: false };
}
evaluateMacroCall(path: NodePath<t.CallExpression>): EvaluateResult {
if (!this.state) {
return { confident: false };
}
let callee = path.get('callee');
if (callee.referencesImport('@embroider/macros', 'dependencySatisfies')) {
return { confident: true, value: dependencySatisfies(path, this.state) };
}
if (callee.referencesImport('@embroider/macros', 'moduleExists')) {
return { confident: true, value: moduleExists(path, this.state) };
}
if (callee.referencesImport('@embroider/macros', 'getConfig')) {
return { confident: true, value: getConfig(path, this.state, 'package') };
}
if (callee.referencesImport('@embroider/macros', 'getOwnConfig')) {
return { confident: true, value: getConfig(path, this.state, 'own') };
}
if (callee.referencesImport('@embroider/macros', 'getGlobalConfig')) {
return { confident: true, value: getConfig(path, this.state, 'getGlobalConfig') };
}
if (callee.referencesImport('@embroider/macros', 'isDevelopingApp')) {
return {
confident: true,
value: Boolean(
this.state.opts.appPackageRoot &&
this.state.opts.isDevelopingPackageRoots.includes(this.state.opts.appPackageRoot)
),
};
}
if (callee.referencesImport('@embroider/macros', 'isDevelopingThisPackage')) {
return {
confident: true,
value: this.state.opts.isDevelopingPackageRoots.includes(owningPackage(path, this.state).root),
};
}
if (callee.referencesImport('@embroider/macros', 'isTesting')) {
let g = getConfig(path, this.state, 'getGlobalConfig') as any;
let e = g && g['@embroider/macros'];
let value = Boolean(e && e.isTesting);
return { confident: true, value };
}
return { confident: false };
}
}
// these next two functions are here because the type definitions we're using
// don't seem to know exactly which NodePath properties are arrays and which
// aren't.
export function assertNotArray<T>(input: T | T[]): T {
if (Array.isArray(input)) {
throw new Error(`bug: not supposed to be an array`);
}
return input;
}
export function assertArray<T>(input: T | T[]): T[] {
if (!Array.isArray(input)) {
throw new Error(`bug: supposed to be an array`);
}
return input;
}
export function buildLiterals(
value: unknown | undefined,
babelContext: typeof Babel
): t.Identifier | t.ObjectExpression {
if (typeof value === 'undefined') {
return babelContext.types.identifier('undefined');
}
let statement = babelContext.parse(`a(${JSON.stringify(value)})`) as t.File;
let expression = (statement.program.body[0] as t.ExpressionStatement).expression as t.CallExpression;
return expression.arguments[0] as t.ObjectExpression;
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.